Skip to content

Instantly share code, notes, and snippets.

@enebo
Created June 5, 2019 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enebo/59dae5d15c909b7902c97e2eb920b4c9 to your computer and use it in GitHub Desktop.
Save enebo/59dae5d15c909b7902c97e2eb920b4c9 to your computer and use it in GitHub Desktop.
# Thought experiment: 'for' loops have almost zero real world usage and removing
# them as an internal implementation detail from our IR (Internal
# Representation) would simplify our code.
#
# The idea is at build time to replace 'for' with a 'while' and an enumerator.
# This should be semantically equivalent?
#
# The main challenge of 'for' loops is they contain blocks which do not actually
# have their own local variable scope (similar to while loops) but that they
# do call the 'in' exprs .each method. So they need to be passed as blocks
# but scope in a "special" way. IR analysis acknowledges this specialness.
# Also note this is coded out as Ruby but this internally would mostly be
# our internal Ruby instructions and some Java code.
require 'enumerator'
a = [1, 2, 3, 4, 5]
def for_normal(a)
c = 10 # defined in base scope
for i in a do
puts i + c # can see c
b = i # assign to be which is base scope
end
puts b # so we can see it here
end
def for_replaced(a)
c = 10
# begin for replacement
enumerator = Enumerator.new a
done = false
while !done # While consumes no scope like 'for' # BNil
begin
i = enumerator.next
# original code as instrs (begin)
puts i + c
b = i
# originalk code as instrs (end)
rescue StopIteration # Probably won't require catching in IR but done value.
done = true
end
end # Jump to while
# end for replacement
puts b
end
for_normal(a)
for_replaced(a)
# A java Enumeration implementation with machinery for calling through our
# block dispatch code could possibly even be as fast as our for. The other
# unknown is emitting a simple loop in IR is like inlining the loop into
# where it is used.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment