我正在写令牌器。我有Token
struct:
defmodule Token do
defstruct type: :text, str: ""
end
我想定义一些在函数模式匹配中使用的公共标记常量(Tokens.double_quote
):
defmodule Tokenizer do
require Tokens
#def tokenize(<<char>> <> buf, %Token{type: :double_quote, str: "\""} = current_token, acc) do
def tokenize(<<char>> <> buf, Tokens.double_quote = current_token, acc) do
# ...
end
def tokenize("\"" <> buf, current_token, acc) do
# ...
end
def tokenize(<<char>> <> buf, current_token, acc) do
# ...
end
end
我决定使用宏,因为我不能使用函数(不匹配期间)或模块属性(模块外部不可见)。
宏返回struct常量:
defmodule Tokens do
import TokenMacro
# This works
#defmacro double_quote, do: quote do: %Token{type: :double_quote, str: "\""}
# This doesn't work
token double_quote, :double_quote, "\""
end
定义宏返回结构常量的宏不起作用:
defmodule TokenMacro do
defmacro token(name, type, str) do
quote do
defmacro unquote(name), do: %Token{type: unquote(type), str: unquote(str)}
end
end
end
我得到CompileError
:
tokenizer.ex: invalid quoted expression: %Token{str: "\"", type: :double_quote}
expanding macro: Tokens.double_quote/0
令牌宏有什么问题?
是否有更简单的解决方案?