开发者

Format ParseException with JavaCC

I was wondering how could it be possible to format in a human-readable format a ParseException thrown by JavaCC: in fact it includes fields such asbeginLine, beginColumn, endColumn, endLine in the token reference of the exception, b开发者_如何学编程ut not the reference to the source parsed.

Thanks! :)


The problem is that, by default, JavaCC doesn't retain the raw source data. So unless you keep a reference to the tokens somehow, they're not held in memory. And even if you did hang onto all the regular tokens, you'd need to add special handling for any SKIP tokens that you'd defined - e.g., for discarding whitespace and comments. The reason JavaCC doesn't retain all this stuff is that it would use a lot more memory.

Keeping all the token images is definitely doable... just takes some semi-manual intervention.


I don't know if it is enough, but you can use property currentToken from catched ParseException object:

try {
parser.Start();
    }
    catch(ParseException e){
        System.out.println("Problem with code!");
        System.out.println("Unknown symbol >> " 
            + e.currentToken.image 
            + " << Line:" + e.currentToken.beginLine 
            + ", column:" + e.currentToken.beginColumn);
        //e.printStackTrace();
    }


Just keep the filename before calling the parser. Then when you catch ParseException, reread the file and, using beginLine, skip to the right line. Alternatively, instead of the filename, keep the original source text yourself.

I recently used javacc and did exactly that. Also had to handle include-like files recursively so I had the parser build a stack of included source files. Upon catching ParseException, it was a simple matter to walk the stack so the user could see the context (i.e. line number in the parent) where each file was included.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜