本文介绍了ANTLR字符串插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写ANTLR语法来解析字符串插值表达式,例如:

I'm trying to write an ANTLR grammar that parses string interpolation expressions such as:

my.greeting = "hello ${your.name}"

我得到的错误是:

line 1:31 token recognition error at: 'e'
line 1:34 no viable alternative at input '<EOF>'

MyParser.g4:

MyParser.g4:

parser grammar MyParser;

options { tokenVocab=MyLexer; }

program: variable EQ expression EOF;
expression: (string | variable);
variable: (VAR DOT)? VAR;
string: (STRING_SEGMENT_END expression)* STRING_END;

MyLexer.g4:

MyLexer.g4:

lexer grammar MyLexer;

START_STR: '"' -> more, pushMode(STRING_MODE) ;
VAR: (UPPERCASE|LOWERCASE) ANY_CHAR*;
EQ: '=';
DOT: '.';

WHITE_SPACE: (SPACE | NEW_LINE | TAB)+ -> skip;

fragment DIGIT: '0'..'9';
fragment LOWERCASE: 'a'..'z';
fragment UPPERCASE: 'A'..'Z';
fragment ANY_CHAR: LOWERCASE | UPPERCASE | DIGIT;
fragment NEW_LINE: '\n' | '\r' | '\r\n';
fragment SPACE: ' ';
fragment TAB: '\t';

mode INTERPOLATION_MODE;

STRING_SEGMENT_START: '}' -> more, popMode;

mode STRING_MODE;

STRING_END: '"' -> popMode;
STRING_SEGMENT_END: '${' -> pushMode(INTERPOLATION_MODE);
TEXT : ~["$]+ -> more ;

类似以下的表达式可以正常工作:

Expressions like the following work fine:

my.greeting = "hello"
my.greeting = "hello ${} world"

有什么想法我可能做错了吗?

Any ideas what I might be doing wrong?

推荐答案

而不是:

mode INTERPOLATION_MODE;

STRING_SEGMENT_START: '}' -> more, popMode;
I_VAR: (UPPERCASE|LOWERCASE) ANY_CHAR*;
I_DOT: '.';

...

variable: ((VAR|I_VAR) (DOT|I_DOT))? (VAR|I_VAR);

您可以尝试:

mode INTERPOLATION_MODE;

STRING_SEGMENT_START: '}' -> more, popMode;
I_VAR: (UPPERCASE|LOWERCASE) ANY_CHAR* -> type(VAR);
I_DOT: '.' -> type(DOT);

...

variable: (VAR DOT)? VAR;

这篇关于ANTLR字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:28