Crystal: Errors of macro def variables

Created on 29 Jan 2018  路  5Comments  路  Source: crystal-lang/crystal

Hello everyone! I faced such behavior, is this normal?

Syntax error in eval:5: expecting token 'CONST', not '{{'

module Asd::But::Me::Ar
  class Test
    def remote_api
      Other::{{@type.name.split("::").last.capitalize.id}}.new
    end
  end
end

module Other
  class Test
    def hi
      pp "hi"
    end
  end
end

Asd::But::Me::Ar::Test.new.remote_api.hi

Working example

module Asd::But::Me::Ar
  class Test
    def remote_api
      {{("Other::" + (@type.name.split("::").last.capitalize)).id}}.new
    end
  end
end

module Other
  class Test
    def hi
      pp "hi"
    end
  end
end

Asd::But::Me::Ar::Test.new.remote_api.hi

=> "hi" # => "hi"

Other problems:

Error in line 18: instantiating 'Asd::But::Me::Ar::Test#remote_api()'
in line 5: expanding macro
in line 5: undefined macro variable 'name'

module Asd::But::Me::Ar
  class Test
    def remote_api
      {% name = @type.name.split("::").last %}
      "{{name.capitalize.id}}"
    end
  end
end

module Other
  class Test
    def hi
      pp "hi"
    end
  end
end

Asd::But::Me::Ar::Test.new.remote_api

Thanks for your help in advance!

Crystal 0.24.1 (2017-12-26)

LLVM: 5.0.1
Default target: x86_64-apple-macosx

All 5 comments

Other:{{...}} is invalid syntax. You can't just stick macros there. They must appear where a single expression appears (not in the middle of an identifier).

If you need that, you can wrap everything in a macro:

{% begin %}
  # your code here
{% end %}

Note that {{...}}.new is valid, because exp.new is valid. However, Foo::{{bar}} is not, because the parser consumes Foo::Bar::... as a single expression (a Path in ASTNode terms), not as a composition of several expressions.

Thanks

{% name = @type.name.split("::").last %}
"{{name.capitalize.id}}"

why name is undefined macro variable?

Because those are two, unrelated macro expansions.

To make them related, wrap both in a single {% begin %} ...{% end %}.

Thank you

Was this page helpful?
0 / 5 - 0 ratings

Related issues

malte-v picture malte-v  路  77Comments

asterite picture asterite  路  139Comments

RX14 picture RX14  路  62Comments

chocolateboy picture chocolateboy  路  87Comments

stugol picture stugol  路  70Comments