在javacc的某些位置跳过声明的令牌

时间:2014-05-16 04:53:31

标签: lexical-analysis javacc

我宣布了一个令牌<VOTE>。我想使用此标记来匹配由大括号分隔的块内。如果它出现在阻止之外,我想跳过它。目前,令牌匹配相同,无论它是在块内还是在外部,这使得解析块外的东西成为问题。

  TOKEN: { < VOTE: " vote" > }

  TOKEN: { < #STRING_LITERAL: ["a" - "z", "A" - "Z", "0" - "9", ".", "_", "-", "!","`", "*", "@", "#", "$", "%", ":", "[", "]", "\"", "^", ";", "\\", "<", ">", "/", ",", "?", "=", "&","(",")","+","|"] >}

  TOKEN: { < DATA: < STRING_LITERAL > ( < STRING_LITERAL > ) * >
    | < OPEN_BRACE: "{" >
    | < CLOSE_BRACE: "}" >}

   **Production:**

   void test():{}
   {
      (<OPEN_BRACE>
          <VOTE>{System.out.println("Voted");}
          <CLOSE_BRACE>)
      |
      <DATA>{System.out.println("Skipped"+token.image);}
   }

上述生产适用于块

hi i am { vote }

但它会引发跟随块

的异常
hi i vote am { vote }

因为“投票”不在括号内。请告诉我如何跳过大括号外的“投票”。

我可以像生产中那样提及<VOTE>

   void test():{}
   {
      (<OPEN_BRACE>
          <VOTE>{System.out.println("VOted");}
          <CLOSE_BRACE>)
      |
      (<DATA>|<VOTE>){System.out.println("Skipped"+token.image);}
   }

但是我不想这样做,因为我有很多令牌,所以当我在全尺寸系统中应用这个修复时,它很难维护。

1 个答案:

答案 0 :(得分:2)

你需要使用的是词汇状态。这将在常见问题解答和文档中介绍,您应阅读相关部分。

基本上你想要做的就是这样的事情

<DEFAULT> TOKEN:{
        < #STRING_LITERAL: ["a" - "z", "A" - "Z", "0" - "9", ".", "_", "-", "!","`", "*", "@", "#", "$", "%", ":", "[", "]", "\"", "^", ";", "\\", "<", ">", "/", ",", "?", "=", "&","(",")","+","|"] >
    |   < DATA: < STRING_LITERAL > ( < STRING_LITERAL > ) * > }

<DEFAULT, INBRACES> TOKEN : {
        < OPEN_BRACE: "{" > : INBRACES
    |   < CLOSE_BRACE: "}" > : DEFAULT }

<INBRACES> TOKEN: {
        < VOTE: "vote" > }

<DEFAULT, INBRACES> SKIP { " " | "\r" | "\n" }

现在在括号之间,&#34;投票&#34;将是一个投票,但在外面,它将是一个数据。无论它们在何处,大括号和空格都被视为相同。