首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaCC语法-适当的词法分析

JavaCC语法-适当的词法分析
EN

Stack Overflow用户
提问于 2014-02-21 22:57:45
回答 2查看 256关注 0票数 0

我有一个具有以下定义的JavaCC语法:

代码语言:javascript
复制
<REGULAR_IDENTIFIER : (["A"-"Z"])+ > // simple identifier like say "DODGE"
<_LABEL : (["A"-"Z"])+ (":") > // label, eg "DODGE:"
<DOUBLECOLON : "::">
<COLON : ":">

现在"DODGE::“lexed as <_LABEL> <COLON> ("DODGE:”“:”“),但我需要将它作为<REGULAR_IDENTIFIER> <DOUBLECOLON> ("DODGE”"::")

EN

回答 2

Stack Overflow用户

发布于 2014-02-26 01:41:02

我认为下面的方法将会奏效

代码语言:javascript
复制
MORE: { < (["A"-"Z"])+ :S0 > } // Could be identifier or label.
<S0> TOKEN: { <LABEL : ":" : DEFAULT> } // label, eg "DODGE:"
<S0> TOKEN: { <IDENTIFIER : "" : DEFAULT > } // simple identifier like say "DODGE"
<S0> TOKEN: { <IDENTIFIER : "::" { matchedToken.image = image.substring(0,image.size()-2) ; } : S1 > }
<S1> TOKEN: { <DOUBLECOLON : "" { matchedToken.image =  "::" ; } : DEFAULT> }
<DOUBLECOLON : "::">
<COLON : ":">

请注意,“DODGE:”是三个标记,而不是两个。

票数 1
EN

Stack Overflow用户

发布于 2014-02-24 18:15:55

在javacc中,使用最大匹配规则(最长前缀匹配规则)请参阅:http://www.engr.mun.ca/~theo/JavaCC-FAQ/javacc-faq-moz.htm#more-than-one

这意味着_LABEL令牌将在REGULAR_IDENTIFIER令牌之前匹配,因为_LABEL令牌将包含更多字符。这意味着您尝试做的事情不应该在记号赋予器中完成。

我已经写了一个正确识别语法的解析器,我使用解析器来识别_LABEL,而不是标记器:

代码语言:javascript
复制
options {
    STATIC = false;
}

PARSER_BEGIN(Parser)

import java.io.StringReader;

public class Parser {

    //Main method, parses the first argument to the program
    public static void main(String[] args) throws ParseException {
        System.out.println("Parseing: " + args[0]);
        Parser parser = new Parser(new StringReader(args[0]));
        parser.Start();
    }
}

PARSER_END(Parser)

//The _LABEL will be recognized by the parser, not the tokenizer
TOKEN :
{
    <DOUBLECOLON : "::"> //The double token will be preferred to the single colon due to the maximal munch rule
    |
    <COLON : ":">
    |
    <REGULAR_IDENTIFIER : (["A"-"Z"])+ > // simple identifier like say "DODGE"
}

/** Root production. */
void Start() :
{}
{
    ( 
        LOOKAHEAD(2) //We need a lookahead of two, to see if this is a label or not
        <REGULAR_IDENTIFIER> <COLON> { System.err.println("label"); } //Labels, should probably be put in it's own production
        | <REGULAR_IDENTIFIER> { System.err.println("reg_id"); }  //Regulair identifiers
        | <DOUBLECOLON> { System.err.println("DC"); } 
        | <COLON> { System.err.println("C"); } 
    )+
}

在实际中,您理所当然应该将<REGULAR_IDENTIFIER> <COLON>移到_label生产环境中。

希望能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21937764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档