忽略令牌字符中的令牌?

时间:2011-05-18 15:21:28

标签: parsing antlr antlr3

我的词法分析器中定义了一个CharacterString(例如'abcd'),我有以下标记定义:

CharacterString:
  Apostrophe
  (Alphanumeric)*
  Apostrophe
;

是否可以忽略两个撇号,然后才能在词法分析器中获取没有它们的标记字符串(通过$ CharacterString.text->字符)?

我试过......

CharacterString:
  Apostrophe { $channel = HIDDEN; }
  (Alphanumeric)*
  Apostrophe { $channel = HIDDEN; }
;

...没有成功......这个案例甚至不再匹配我的字符串了(例如'oiu'将在解析器中失败 - Missmatched Set Exception)。

谢谢:)

2 个答案:

答案 0 :(得分:2)

内联代码{$channel=HIDDEN;}会影响整个CharacterString,因此您无法像尝试的那样执行此操作。

您需要添加一些自定义代码并自行删除引号。这是一个小C演示:

grammar T;

options {
  language=C;
}

parse
  :  (t=. {printf(">\%s<\n", $t.text->chars);})+ EOF
  ;

CharacterString
  :  '\'' ~'\''* '\''
     {
       pANTLR3_STRING quoted = GETTEXT();
       SETTEXT(quoted->subString(quoted, 1, quoted->len-1));
     }
  ;

Any
  :  .
  ;

和一点测试功能:

#include "TLexer.h"
#include "TParser.h"

int main(int argc, char *argv[])
{
  pANTLR3_UINT8 fName = (pANTLR3_UINT8)"input.txt";
  pANTLR3_INPUT_STREAM input = antlr3AsciiFileStreamNew(fName);

  if(input == NULL)
  {
    fprintf(stderr, "Failed to open file %s\n", (char *)fName);
    exit(1);
  }

  pTLexer lexer = TLexerNew(input);

  if(lexer == NULL)
  {
    fprintf(stderr, "Unable to create the lexer due to malloc() failure1\n");
    exit(1);
  }

  pANTLR3_COMMON_TOKEN_STREAM tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));

  if(tstream == NULL)
  {
    fprintf(stderr, "Out of memory trying to allocate token stream\n");
    exit(1);
  }

  pTParser parser = TParserNew(tstream);

  if(parser == NULL)
  {
    fprintf(stderr, "Out of memory trying to allocate parser\n");
    exit(ANTLR3_ERR_NOMEM);
  }

  parser->parse(parser);

  parser->free(parser);   parser = NULL;
  tstream->free(tstream); tstream = NULL;
  lexer->free(lexer);     lexer = NULL;
  input->close(input);    input = NULL;

  return 0;
}

并且测试input.txt文件包含:

'abc'

如果您现在1)生成词法分析器和解析器,2)编译所有.c源文件,3)运行main

# 1
java -cp antlr-3.3.jar org.antlr.Tool T.g

# 2
gcc -Wall main.c TLexer.c TParser.c -l antlr3c -o main

# 3
./main

你会看到abc(没有引号)正在打印到控制台。

答案 1 :(得分:1)

您可以通过词法分析器的RecognizerSharedState state属性影响令牌构造:

CharacterString:
  Apostrophe
  CharSequence
  Apostrophe
  { state.text = $CharSequence.text; }
;

fragment CharSequence:
  Alphanumeric+
;