Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Macros 晶体中的Tmp宏变量_Macros_Metaprogramming_Crystal Lang - Fatal编程技术网

Macros 晶体中的Tmp宏变量

Macros 晶体中的Tmp宏变量,macros,metaprogramming,crystal-lang,Macros,Metaprogramming,Crystal Lang,如何使用宏中的临时变量在Crystal Lang中构建代码。例如,我有: module Rule macro included {% rules = [] of TypeDeclaration %} macro rule(declaration) raise("Should be TypeDeclaration") unless \{{declaration.is_a?(TypeDeclaration)}} \{

如何使用宏中的临时变量在Crystal Lang中构建代码。例如,我有:

module Rule
  macro included
    {% rules = [] of TypeDeclaration %}
    
    macro rule(declaration)
        raise("Should be TypeDeclaration") unless \{{declaration.is_a?(TypeDeclaration)}}

        \{% {{rules}} << declaration %}
    end

    macro finished
        \{% for declaration in rules %}
            puts \{{declaration}}
        \{% end %}
    end

  end
end



class StringRule
    include Rule

    rule min : Int32 = 0
    rule max : Int32 = 255
end

模块规则
宏包括
{%rules=[]的类型声明%}
宏规则(声明)
raise(“应该是类型声明”),除非\{declaration.is_a?(类型声明)}

\{%{{rules}}6{%[]宏表达式中的变量的作用域为相应的宏上下文。因此,在包含的
宏中定义的变量在
宏规则中不可见

但您可以为此使用常量:
RULES=[]of
\u
下划线使数组不类型化,它仅在编译期间使用,不用于实际代码。如果在宏表达式外部引用
RULES
,编译器将抱怨

module Rule
  macro included
    RULES = [] of _
    
    macro rule(declaration)
      \{% raise("Should be TypeDeclaration") unless declaration.is_a?(TypeDeclaration) %}

      \{% RULES << declaration %}
    end

    macro finished
      \{% for declaration in RULES %}
      puts \{{ declaration.stringify }}
      \{% end %}
    end
  end
end

class StringRule
    include Rule

    rule min : Int32 = 0
    rule max : Int32 = 255
end
模块规则
宏包括
规则=[]共_
宏规则(声明)
\{%raise(“应该是类型声明”),除非声明.is_a?(类型声明)%}

\{%谢谢,这对我来说太好了。
module Rule
  macro included
    RULES = [] of _
    
    macro rule(declaration)
      \{% raise("Should be TypeDeclaration") unless declaration.is_a?(TypeDeclaration) %}

      \{% RULES << declaration %}
    end

    macro finished
      \{% for declaration in RULES %}
      puts \{{ declaration.stringify }}
      \{% end %}
    end
  end
end

class StringRule
    include Rule

    rule min : Int32 = 0
    rule max : Int32 = 255
end