使用Ruby解析Tcl DSL [英] Use Ruby to parse a Tcl DSL
问题描述
我希望能够解析一些参数不被字符串包围的Tcl代码.
I would like to be able to parse some Tcl code where arguments are not surrounded by strings.
考虑以下tcl代码:
proc foo {name} {
puts "Foo --> $name"
}
foo bar
对于那些不熟悉Tcl的人,foo
是方法名称,而bar
是参数(在Tcl中引号是可选的).
For those unfamiliar with Tcl, foo
is the method name and bar
is the argument (quotes are optional in Tcl).
先前的代码将输出:
Foo --> bar
是否可以使用ruby准确解析 相同的输入(bar
保持未引用)?
Is it possible to parse exactly the same input using ruby (bar
remains unquoted)?
等效的红宝石代码为:
def foo(name)
puts "Foo --> #{name}"
end
tcl = <<-TCL.gsub(/^\s+/, "").chop
foo bar
TCL
instance_eval(tcl)
当然,它到达bar
时失败,因为期望它被引用.
Of course that fails when it reaches bar
since it's expected it to be quoted.
我尝试过修改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.
推荐答案
它对您不起作用,因为.puts
方法返回nil
而不是字符串:
It's doesn't work for you because .puts
method returns nil
instead of string:
irb(main):003:0> puts "42"
42
=> nil
我真的不知道为什么to_hash
出现在此method_missing
中,但是它可以工作:
I really don't know why to_hash
appears in this method_missing
but it works:
def foo(name)
puts "Foo --> #{name}"
end
def method_missing(meth, *args)
meth.to_s unless meth.to_s == "to_hash"
end
tcl = <<-TCL.gsub(/^\s+/, "").chop
foo bar
TCL
instance_eval(tcl)
=> Foo --> bar
这篇关于使用Ruby解析Tcl DSL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!