Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mirah Scoping

Mirah Scoping and control structures

If statements

If statements don't introduce a new scope, like ruby, but they are a little tricky.

For example, if b is false in the following, what would a be?

if b
  a = 1
end
puts a

In some dynamic languages, a would be undefined, but Mirah can't do that. It's a staticly typed language without an undefined value. Mirah's options are either make a = null, 0 (aka default int val) or consider the above a compiler error.

In Ruby, a is nil.

In addition to values, Mirah, as a staticly typed language, must* give a a type. Ideally, we'd use primitives wherever possible. But, if you have an expression like this, that would force a to equal 0, which in my opinion is worse than anything.

a Type: Integer a Value: 1 or null if b is false

What about

if b
  a = 1
else
  a = 2
end
puts a

Super cool would be to figure out that a can be primitive. a Type: int a Value: 1 or 2 if b is false

Rescue

a = 1
begin
  raise "wut"
rescue => a
end
puts a

Due to types, this should be a compile error. A's assigned Numeric and Exception.

begin
  raise "wut"
rescue
  b = 1
end
puts b

b should be 1

begin ; rescue => e; end
puts e

following Ruby's behavior, this should print null, but this would introduce interesting behavior in the following.

begin ; rescue Ex1 => e; e.ex1_msg; end
begin ; rescue Ex1 => e; e.ex1_msg; end
begin ; rescue Ex2 => e; e.ex2_msg; end

If e is the same e for each rescue, then the above will be a compile error. :sadface:

And what about

begin 
  # cool stuff that might blow up
rescue Ex1 => e
  # handle Ex1
rescue Ex2 => e
  # handle Ex2
end

Or

begin 
  # cool stuff that might blow up
rescue Ex1 => e
  # handle Ex1
rescue Ex2 => e
  # handle Ex2
end
puts e

Blocks

These should be true regardless of whether the block is a macro block or a closure.

Argument variables should only live inside the block.

[1, 2, 3].each do |i|
end
puts i

compile error on puts i

Argument variables that shadow outer variables, could be a warning, but shouldn't be considered the same variable.

i = "cool beginnings"
[1, 2, 3].each do |i|
end
puts i

prints cool beginnings

Variables that are defined in blocks should not be referenceable outside the block.

[1, 2, 3].each do
  x = 1
end
puts x

compile error on puts i

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment