我试图创建一个非常简单的DSL,它采用格式化为
的字符串GET /endpoint controller.action1 |> controller.action2
然后将其转换为
的内容{"GET", "/endpoint", [{controller.action1}, {controller.action2}]}
我的Leex文件是:
Definitions.
Rules.
GET|PUT|POST|DELETE|PATCH : {token, {method, TokenLine, TokenChars}}.
/[A-Za-z_]+ : {token, {endpoint, TokenLine, TokenChars}}.
[A-Za-z0-9_]+\.[A-Za-z0-9_]+ : {token, {function, TokenLine, splitControllerAction(TokenChars)}}.
\|\> : {token, {pipe, TokenLine}}.
[\s\t\n\r]+ : skip_token.
Erlang code.
splitControllerAction(A) ->
[Controller, Action] = string:tokens(A, "."),
{list_to_atom(Controller), list_to_atom(Action)}.
我的Yecc文件看起来像这样:
Nonterminals route actionlist elem.
Terminals function endpoint method pipe.
Rootsymbol route.
route -> method endpoint actionlist : {$1, $2, $3}.
actionlist -> elem : [$1].
actionlist -> elem 'pipe' actionlist : [$1 | $3].
elem -> function : $1.
Erlang code.
extract_token({_Token, _Line, Value}) -> _Token;
我得到的输出:
2> {ok, Fart, _} = blah:string("GET /asdfdsf dasfadsf.adsfasdf |> adsfsdf.adsfdf").
{ok,[{method,1,"GET"},
{endpoint,1,"/asdfdsf"},
{function,1,{dasfadsf,adsfasdf}},
{pipe,1},
{function,1,{adsfsdf,adsfdf}}],
1}
3> blah_parser:parse(Fart).
{ok,{49,50,51}}
答案 0 :(得分:1)
原来你需要用单引号括起$1
,否则它只会尝试并成为ASCII值。
-Thomas Gebert。