0

我已经有一个 DSL 并且想为它构建 ANTLR4 语法。

这是该 DSL 的一个例子:

rule isC {
    true  when O_M in [5, 6, 17, 34]
    false in other cases
}

rule isContract {
    true  when O_C in ['XX','XY','YY']
    false in other cases
}

rule isFixed {
    true  when F3 ==~ '.*/.*/.*-F.*/.*'
    false in other cases
}

rule temp[1].future {
    false when O_OF in ['C','P']
    true  in other cases
}

rule temp[0].scale {
    10 when O_M == 5 && O_C in ['YX']
    1  in other cases 
}

DSL是如何简单地通过使用已经变得一团糟的正则表达式来解析的——因此需要一种语法。

它的工作方式如下:它提取左侧(之前when)和右侧部分,并由 Groovy 评估。

我仍然希望它由 Groovy 评估,但通过使用语法来组织解析过程。所以,本质上,我需要的是使用某种通配符提取这些左右部分。

不幸的是,我无法弄清楚如何做到这一点。这是我到目前为止所拥有的:

grammar RuleDSL;

rules: basic_rule+ EOF;

basic_rule: 'rule' rule_name '{' condition_expr+ '}';

name: CHAR+;
list_index: '[' DIGIT+ ']';
name_expr: name list_index*;
rule_name: name_expr ('.' name_expr)*;

condition_expr: when_condition_expr | otherwise_condition_expr;

condition: .*?;
result: .*?;
when_condition_expr: result WHEN condition;

otherwise_condition_expr: result IN_OTHER_CASES;

WHEN: 'when';
IN_OTHER_CASES: 'in other cases';


DIGIT: '0'..'9';
CHAR: 'a'..'z' | 'A'..'Z';
SYMBOL: '?' | '!' | '&' | '.' | ',' | '(' | ')' | '[' | ']' | '\\' | '/' | '%' 
      | '*' | '-' | '+' | '=' | '<' | '>' | '_' | '|' | '"' | '\'' | '~';


// Whitespace and comments

WS: [ \t\r\n\u000C]+ -> skip;
COMMENT: '/*' .*? '*/' -> skip;

这个语法“太”贪心了,只处理一条规则。我的意思是,如果我听解析

@Override
public void enterBasic_rule(Basic_ruleContext ctx) {
    System.out.println("ENTERING RULE");
}

@Override
public void exitBasic_rule(Basic_ruleContext ctx) {
    System.out.println(ctx.getText());
    System.out.println("LEAVING RULE");
}

我有以下输出

ENTERING RULE
-- tons of text
LEAVING RULE

我怎样才能让它不那么贪婪,所以如果我解析这个给定的输入,我会得到 5 条规则?condition贪婪来自result我想。


更新: 事实证明,跳过空格并不是最好的主意,所以过了一会儿我得到了以下结果:link to gist

感谢 280Z28 的提示!

4

1 回答 1

2

不要.*?在解析器规则中使用,而是尝试使用~'}'*以确保这些规则不会尝试读取超出规则末尾的内容。

此外,您在词法分析器中跳过空格,但在解析器规则中使用CHAR+和。DIGIT+这意味着以下是等价的:

  1. rule temp[1].future
  2. rule t e m p [ 1 ] . f u t u r e

除此之外,您制作in other cases了一个令牌而不是 3 个,因此以下内容等价:

true  in other cases
true  in  other cases

您可能应该首先制定以下词法分析器规则,然后制定CHARandDIGIT规则fragment

ID : CHAR+;
INT : DIGIT+;
于 2013-07-18T11:20:44.197 回答