gpt4 book ai didi

ANTLR 字符串插值

转载 作者:行者123 更新时间:2023-12-02 17:27:04 25 4
gpt4 key购买 nike

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

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

我得到的错误是:

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

Output from ANTLR IntelliJ Plugin

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:

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 ;

像下面这样的表达式可以正常工作:

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

知道我可能做错了什么吗?

最佳答案

代替:

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 字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37916661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com