Crystal: Multi-line macros with `for`

Created on 2 Sep 2018  路  4Comments  路  Source: crystal-lang/crystal

Currently this code:

{%
  for a in [1]
    do_something
  end
%}

Does not compile (even the formatter doesn't like it):

Syntax error in temp.cr:3: expecting token '%}', not 'do_something'

    do_something
    ^

The code would be cleaner if I could do that.

help-wanted feature topicparser topicmacros

Most helpful comment

WARNING: it is too general opinion than this issue. I'll open a new issue if needed.


Conversely, when do .. end block with macro literals like the macro for and if is allowed and add ArrayLiteral#each method, we can write such a iteration in both styles:

{%
  [1].each do |a|
    do_something
  end
%}
{% [1].each do |a| %}
  {% do_something %}
{% end %}

And now, we can deprecate the macro for syntax from language. We can rewrite for a in [1] with [1].each do |a|.

I think the macro for is one of the bad parts of Crystal. Because it can be used only under macros, and its raison d'etre is only for limitations in the parser implementation. It seems natural that do ... end block accepts macro literals.

All 4 comments

That's not how for works. This is how it works:

{% for a in [1] %}
    {% do_something %}
{% end %}

Because you can do the above, I consider this feature enhancement super low priority right now.

WARNING: it is too general opinion than this issue. I'll open a new issue if needed.


Conversely, when do .. end block with macro literals like the macro for and if is allowed and add ArrayLiteral#each method, we can write such a iteration in both styles:

{%
  [1].each do |a|
    do_something
  end
%}
{% [1].each do |a| %}
  {% do_something %}
{% end %}

And now, we can deprecate the macro for syntax from language. We can rewrite for a in [1] with [1].each do |a|.

I think the macro for is one of the bad parts of Crystal. Because it can be used only under macros, and its raison d'etre is only for limitations in the parser implementation. It seems natural that do ... end block accepts macro literals.

If someone can implement that, please go ahead. There was a closed issue recently about this: https://github.com/crystal-lang/crystal/issues/5506

I actually prefer macro expressions being different from regular code. That helps understanding that they are on a different level. The macro language has many similarities with template languages like Jinja or Liquid which communicates conceptual similarities and even newcomers can easily grasp the concept.

That being said, we can obviously discuss the proposal to make the macro language more similar to regular code. But that's really a different issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lbguilherme picture lbguilherme  路  3Comments

RX14 picture RX14  路  3Comments

Papierkorb picture Papierkorb  路  3Comments

asterite picture asterite  路  3Comments

costajob picture costajob  路  3Comments