首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正确设置Cup/JLex解析

正确设置Cup/JLex解析
EN

Stack Overflow用户
提问于 2013-06-09 09:09:32
回答 1查看 8.3K关注 0票数 3

我这里有一个非常基本的词汇:

代码语言:javascript
复制
import java_cup.runtime.*;
import java.io.IOException;

%%

%class AnalyzerLex

%function next_token
%type java_cup.runtime.Symbol

%unicode
//%line
//%column

// %public
%final
// %abstract

%cupsym sym
%cup
%cupdebug

%eofval{
  return sym(sym.EOF);
%eofval}

%init{
    // TODO: code that goes to constructor
%init}

%{
    private Symbol sym(int type)
    {
        return sym(type, yytext());
    }

    private Symbol sym(int type, Object value)
    {
        return new Symbol(type, yyline, yycolumn, value);
    }

    private void error()
    throws IOException
    {
        throw new IOException("Illegal text at line = "+yyline+", column = "+yycolumn+", text = '"+yytext()+"'");
    }
%}

ANY = .

%%

{ANY}       { return sym(sym.ANY); }
"\n" { }

这是我最基本的解析器:

代码语言:javascript
复制
import java_cup.runtime.*;

parser code
{:

    public void syntax_error(Symbol cur_token) {
        System.err.println("syntax_error " + cur_token );
    }

:}

action code
{:
:}

terminal        ANY;

non terminal    grammar;

grammar         ::= ANY : a
                {:
                //System.out.println(a);
                :}
                ;

我正在尝试解析一个示例文件。我做了一个这样的方法:

代码语言:javascript
复制
AnalyzerLex scanner = null;
        ParserCup pc = null;
        try {
          scanner = new AnalyzerLex( new java.io.FileReader(argv[i]) );
          pc = new ParserCup(scanner);
          while ( !scanner.zzAtEOF ){
              pc.parse_debug();
          }
        }

但是上面的代码会引发一个错误:

代码语言:javascript
复制
    #2
Unexpected exception:
# Initializing parser
# Current Symbol is #2
# Shift under term #2 to state #2
# Current token is #2
syntax_error #2
# Attempting error recovery
# Finding recovery state on stack
# Pop stack by one, state was # 2
# Pop stack by one, state was # 0
# No recovery state found on stack
# Error recovery fails
Couldn't repair and continue parse at character 0 of input
java.lang.Exception: Can't recover from previous error(s)
    at java_cup.runtime.lr_parser.report_fatal_error(lr_parser.java:375)
    at java_cup.runtime.lr_parser.unrecovered_syntax_error(lr_parser.java:424)
    at java_cup.runtime.lr_parser.debug_parse(lr_parser.java:816)
    at AnalyzerLex.main(AnalyzerLex.java:622)

我认为我设置的lexer/解析器不正确。

EN

回答 1

Stack Overflow用户

发布于 2013-09-25 22:57:34

我不是专家,但我可以建议你采取以下行动:

  1. 您可能必须指定从哪个非终端开始,例如: 从compilation_unit开始;
  2. 您可以通过添加行和列来增强语法错误方法,这样错误所在的位置就更清楚了。 Syntax_error(符号s){ System.out.println(“编译器在”+ s.left +“列”+s.right行检测到语法错误);}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17008139

复制
相关文章

相似问题

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