0

我一直在寻找一种方法来让命名函数参数/参数以任何顺序出现在 ANTLR 中。有谁知道在 ANTLR 解析器表达式中是否存在忽略顺序的语法?

假设foo语言中有一个函数可以接受两个命名参数:xy. 由于它们是命名参数,我希望它们能够以任何顺序传递到函数中:

foo(x=1, y=2)

foo(y=2, x=1)

两者都应该是合法的。

我可以只列出 ANTLR 中的所有参数排列,但我希望有一个更优雅的解决方案,特别是因为我有一些可以接受 5 个参数的函数。

任何帮助将不胜感激!

4

2 回答 2

1

明白了...

如果您想在语法中硬连线“foo”、“x”和“y”,请执行以下操作(未编译/测试,但应该给出想法)

foo :
    { SomeType x=null, y=null; }
    'foo' '('
      (     'x' '=' {if (x != null) throw ...;} x=value
      |     'y' '=' {if (y != null) throw ...;} y=value
      )*
    ')'
    { if (x = null || y == null) throw ...; }
    ;

如果您想要更大的灵活性(以支持其他功能),请执行 Bart 的建议。

于 2009-12-08T22:49:43.333 回答
1

我很确定 ANTLR 没有内置任何东西来处理这个问题。但是你可以简单地在你的语法中添加一些常规的编程逻辑来重新组织参数。

这是一个小演示语法:

grammar NF;

@parser::header {
    package antlrdemo;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Arrays;
}

@lexer::header {
    package antlrdemo;
}

parse   :   concat+
        ;

concat  :   'concat' '(' k1=Key '=' v1=Value ',' k2=Key '=' v2=Value ',' k3=Key '=' v3=Value ')' {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put($k1.text, $v1.text);
                params.put($k2.text, $v2.text);
                params.put($k3.text, $v3.text);
                HashSet<String> expected = new HashSet<String>(Arrays.asList(new String[]{"a", "b", "c"}));
                if(!params.keySet().equals(expected)) {
                    throw new RuntimeException("No soup for you!");
                }
                System.out.println(params.get("a")+params.get("b")+ params.get("c"));
            }
        ;

Key     :   ('a'..'z')+
        ;

Value   :   ('a'..'z' | 'A'..'Z' | '0'..'9')+
        ;

Space   :   (' ' | '\t' | '\r' | '\n'){$channel = HIDDEN;}
        ;

还有一个小课来测试它:

package antlrdemo;

import org.antlr.runtime.*;

public class NFDemo {

    static void test(String source) throws RecognitionException {
        ANTLRStringStream in = new ANTLRStringStream(source);
        NFLexer lexer = new NFLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        NFParser parser = new NFParser(tokens);
        System.out.print(source+" -> ");
        parser.parse();
    }

    public static void main(String[] args) throws RecognitionException {
        test("concat(a=1, b=2, c=3)");
        test("concat(b=2, c=3, a=1)");
        test("concat(c=3, a=1, b=2)");
        test("concat(c=3, a=1, x=2)");
    }
}

产生输出:

concat(a=1, b=2, c=3) -> 123
concat(b=2, c=3, a=1) -> 123
concat(c=3, a=1, b=2) -> 123
concat(c=3, a=1, x=2) -> Exception in thread "main" java.lang.RuntimeException: No soup for you!
    at antlrdemo.NFParser.concat(NFParser.java:137)
    at antlrdemo.NFParser.parse(NFParser.java:70)
    at antlrdemo.NFDemo.test(NFDemo.java:13)
    at antlrdemo.NFDemo.main(NFDemo.java:20)
于 2009-12-08T19:43:13.700 回答