Search code examples
macroscrystal-lang

How to extend Crystal language syntax?


For example, i want to get looks-like-native "for" loop, which was implemented in crystal's embedded macro language, but it is absent (for reasons of principle) in main, "runtime" language:

for i in list do
end

for k, v in hash do
end

(Here "{}" is a simple block. I cant use do .. end syntax here anyway (maybe not)). Will be very good to implement multi-inlcude directive, such as:

includes MixinX, MixinY, MixinZ

and so on... As i know, macro (named "for" and "includes" in the provided snippets) can't accept "i in list" without double-quoting. So... is there only one way to do so - extending crystal's syntax/lexical parser and analyzer itself?


Solution

  • Maybe, you could use something like this:

    module Foo
      def foo
        "foo"
      end
    end
    
    module Bar
      def bar
        "bar"
      end
    end
    
    class Object
      macro includes(*mods)
        {% for mod in mods %}
          include  {{ mod }}
          {% end %}
      end
    end
    
    class Baz
      includes Foo, Bar
    end
    
    Baz.new.foo # => "foo"
    Baz.new.bar # => "bar"