Crystal: Define a class in begin/end block

Created on 31 Jul 2020  路  3Comments  路  Source: crystal-lang/crystal

This program compiles fine:

begin
  class Foo
  end
end

Should it? It doesn't seem to make sense to define a class in a begin/end block.
As soon as you add a rescue clause for example, it no longer compiles:

begin
  class Foo # Error: can't declare class dynamically
  end
rescue
end
bug invalid lang

Most helpful comment

A begin end is just another way to write parentheses. I don't mind being able to define classes and methods inside groupings of expressions. So I would personally close this issue as invalid.

All 3 comments

No, it should not compile.

So this is a bit more complicated than it seems.

A macro block is not dynamic, so we want the following to work:

macro foo
  {{yield}}
end

foo do
  class Foo; end
end

The problem is: MacroInterpreter wraps {{ yield }} expression in begin ... end. I presume this is to restrict variable scope in the block?

This doesn't seem to be correctly implemented though, because simply wrapping the yield in parenthesis ({{ (yield) }}) avoids the begin ... end wrapper.
Removing that wrapper however doesn't seem to break any specs, so maybe we could just go with that?

A begin end is just another way to write parentheses. I don't mind being able to define classes and methods inside groupings of expressions. So I would personally close this issue as invalid.

Was this page helpful?
0 / 5 - 0 ratings