使用 Ruby 解析 Tcl DSL
我希望能够解析一些参数没有被字符串包围的 Tcl 代码。
考虑这个 tcl 代码:
proc foo {name} {
puts "Foo --> $name"
}
foo bar
对于那些不熟悉 Tcl 的人来说,foo
是方法名称,bar
是参数(引号在 Tcl 中是可选的)。
前面的代码将输出:
Foo --> bar
Is it possible to parse exactly using ruby (bar
still unquoted)?
等效的 ruby 代码是:
def foo(name)
puts "Foo --> #{name}"
end
tcl = <<-TCL.gsub(/^\s+/, "").chop
foo bar
TCL
instance_eval(tcl)
当然,当它到达 bar
时会失败,因为它预计会被引用。
我尝试过修改 method_missing
def method_missing(meth, *args)
puts meth.to_s + " --> args.to_s
end
但它以相反的顺序解析:
to_hash --> []
bar --> []
foo --> [nil]
是否有人对此类问题有一个干净的解决方案。我想避免对字符串进行标记,因为与词法分析相比,通过调用方法读取数据所需的工作量最少。但如果我想做一些不可能的事情,我想知道。谢谢。
I would like to be able to parse some Tcl code where arguments are not surrounded by strings.
Consider this tcl code:
proc foo {name} {
puts "Foo --> $name"
}
foo bar
For those unfamiliar with Tcl, foo
is the method name and bar
is the argument (quotes are optional in Tcl).
The previous code will output:
Foo --> bar
Is it possible to parse exactly the same input using ruby (bar
remains unquoted)?
The equivalent ruby code is:
def foo(name)
puts "Foo --> #{name}"
end
tcl = <<-TCL.gsub(/^\s+/, "").chop
foo bar
TCL
instance_eval(tcl)
Of course that fails when it reaches bar
since it's expected it to be quoted.
I've tried tinkering with method_missing
def method_missing(meth, *args)
puts meth.to_s + " --> args.to_s
end
but it parses in reverse order:
to_hash --> []
bar --> []
foo --> [nil]
Does anyone have a clean solution to this type of problem. I'd like to avoid tokenizing the strings since reading the data in by calling a method requires minimal work compared to lexical analysis. But if I'm trying to do something that's not possible, I'd like to know. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它对你不起作用,因为
.puts
方法返回nil
而不是字符串:我真的不知道为什么
to_hash
出现在这个 < code>method_missing 但它有效:It's doesn't work for you because
.puts
method returnsnil
instead of string:I really don't know why
to_hash
appears in thismethod_missing
but it works:这是一个尝试使语法接近TCL语法的实现。
This is an implementation that try to make the syntax near to the TCL syntax.