crystal icon indicating copy to clipboard operation
crystal copied to clipboard

Execute while and until inside macros

Open Blacksmoke16 opened this issue 4 years ago • 6 comments

Resolves https://github.com/crystal-lang/crystal/pull/9091#discussion_r667633119

Blacksmoke16 avatar Jul 17 '21 15:07 Blacksmoke16

Note that I excluded these from the macro language because they allow the compiler to hang. I'm not sure we should add this.

asterite avatar Jul 17 '21 15:07 asterite

At some point I was experimenting with a macro that could generate SQL from almost arbitrary expressions and on a part of it I ended up with this piece of code:

  {%
    stack = ...
    forever = [nil] of NilLiteral
    forever.each do
      forever << nil
      top = stack.last
      if top.is_a?(NilLiteral)
        forever.clear
      else
        # do stuff that might involve pushing to "stack"
      end
    end
  %}

Yeah, it hurts my eyes too. But the point is: it is already possible to make infinite loops and consume unrestricted memory from macros. This PR doesn't make things worse, just cleaner and more obvious.

lbguilherme avatar Jul 18 '21 10:07 lbguilherme

It's true

asterite avatar Jul 18 '21 10:07 asterite

This should be good for review.

Blacksmoke16 avatar Sep 05 '22 01:09 Blacksmoke16

I'm not sure about this. For example, I would expect such macro loops to have a block macro body similar to the for loop:

{% while v < 5 %}
  {% v += 5 %}
{% end %}

That doesn't exclude the inline syntax implemented in this PR. But it's definitely more limiting in what can be expressed.

I'd rather look at the bigger picture with a focus on implementing loops with a block body. The short form might be an enhancement, but it's not a priority.

straight-shoota avatar Sep 05 '22 18:09 straight-shoota

I have a working prototype of a MacroWhile node here: https://github.com/beta-ziliani/crystal/tree/feat/macro-while

At the moment, I was just playing with this small thing, but at some point I'll make a proper PR with everything that is missing (until and specs).

beta-ziliani avatar May 20 '24 19:05 beta-ziliani