gpt4 book ai didi

java - 使用自定义 AST 节点类型进行树过滤时,如何避免抛出 ClassCastException?

转载 作者:行者123 更新时间:2023-12-01 05:30:08 27 4
gpt4 key购买 nike

我使用派生自 CommonTree 的自定义 AST 节点类型构建了 AST。

这似乎工作正常,直到我使用包含 * 通配符的树过滤语法。

this的评论页面表明这是由代码必须执行的操作引起的:

(MyCustomType)input.LT(1);

当遇到 UP 或 DOWN 节点时会抛出此异常,因为它们属于 CommonTree 类。评论中的解决方案是针对可选 (?) 元素,但我确实需要一种使用 * 通配符来捕获事物列表的方法,而不会抛出异常。

编辑:

这是一个小例子,说明了我遇到的问题。

source.txt 显示了我需要能够解析的一些示例。当我使用树遍历器将任何数组赋值(第 3 行 source.txt)重写为对数组对象上的 push 函数的调用时,问题就出现了。

使用 source.txt 运行以下代码会导致节点类型之间出现 ClassCastException。

Scee.g:

grammar Sscce;

options
{
output = AST;
ASTLabelType = SscceAST;
}

tokens
{
ASSIGN;
ARGS;
FUNCCALL;
REF;
INDEXOP;
}


@lexer::header
{
package com.dummyco.dummypack;
}

@parser::header
{
package com.dummyco.dummypack;
}

stmts: singleStatement+
;

singleStatement
: memberExpression '=' (expr | listAssignment) ->
^(ASSIGN '=' memberExpression expr? listAssignment?)
;

expr
: memberExpression
| functionCall
;

functionCall
: memberExpression args -> ^(FUNCCALL args)
;

args
: '(' memberExpression? (',' memberExpression)* ')' ->
^(ARGS memberExpression*)
;

indexSuffix:
'[' ID? ']' -> ^(INDEXOP ID?)
;

memberExpression
: ID ('.' ID)* indexSuffix? -> ^(REF ID+ indexSuffix?)
;

idList
: memberExpression (',' memberExpression)* -> memberExpression+
;

listAssignment
: '{' idList '}' -> ^(ARGS idList)
;

assignmentOperator
: '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '>>>=' | '&=' | '^=' | '|='
;

ID : ('a'..'z'|'A'..'Z'|'_')*emphasized text* ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* { setText(getText().toLowerCase()); }
;

WS : (' ' | '\t' | '\r' | '\n') {$channel=HIDDEN;}
;

SscceWalker.g:

tree grammar SscceWalker;

options
{
output = AST;
ASTLabelType = SscceAST;
tokenVocab = Sscce;
filter = true;
}

@header
{
package com.dummyco.dummypack;
}

topdown
: arrayAssignment
;

arrayAssignment
: ^(ASSIGN '=' ^(REF memexp+=.* INDEXOP) ^(ARGS args+=.*)) ->
^(FUNCCALL ^(REF $memexp*) ID["push"] ^(ARGS $args*))
;

Main.java:

package com.dummyco.dummypack;

import java.io.*;
import java.util.*;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;

public class Main
{

private static final TreeAdaptor sscceAdaptor = new CommonTreeAdaptor()
{
@Override
public Object create(Token token)
{
return new SscceAST(token);
}

@Override
public Object dupNode(Object t)
{
if(t == null)
return null;

return create(((SscceAST)t).token);
}

@Override
public Object errorNode(TokenStream input, Token start, Token stop, RecognitionException e)
{
return new SscceASTErrorNode(input, start, stop, e);
}
};

public static void main(String[] args) throws IOException
{

SscceLexer lexer = null;
try
{
lexer = new SscceLexer(
new ANTLRFileStream("source.txt", "UTF8"));
}
catch(IOException e)
{
System.err.println("Can't open the specified file.");
System.exit(1);
}

CommonTokenStream tokens = new CommonTokenStream(lexer);
SscceParser parser = new SscceParser(tokens);
parser.setTreeAdaptor(sscceAdaptor);
SscceParser.stmts_return r = null;
try
{
r = parser.stmts();
}
catch(RecognitionException e)
{
System.err.println("Parser exception.");
System.exit(1);
}

SscceAST t = (SscceAST)r.getTree();
CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
nodes.setTokenStream(tokens);
SscceWalker walker = new SscceWalker(nodes);
walker.setTreeAdaptor(sscceAdaptor);
t = (SscceAST)walker.downup(t, false);
System.out.println(t.toStringTree());
}
}

SscceAST.java:

package com.dummyco.dummypack;

import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
import org.antlr.runtime.tree.CommonTree;

public class SscceAST extends CommonTree
{
public SscceAST()
{
super();
}

public SscceAST(Token t)
{
super(t);
}

public SscceAST(SscceAST tree)
{
super(tree);
}

@Override
public Tree dupNode()
{
return new SscceAST(this);
}
}

SscceeASTErrorNode.java:

package com.dummyco.dummypack;

import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;

public class SscceASTErrorNode extends SscceAST {
public IntStream input;
public Token start;
public Token stop;
public RecognitionException trappedException;

public SscceASTErrorNode(TokenStream input, Token start, Token stop,
RecognitionException e)
{
//System.out.println("start: "+start+", stop: "+stop);
if ( stop==null ||
(stop.getTokenIndex() < start.getTokenIndex() &&
stop.getType()!=Token.EOF) )
{
// sometimes resync does not consume a token (when LT(1) is
// in follow set. So, stop will be 1 to left to start. adjust.
// Also handle case where start is the first token and no token
// is consumed during recovery; LT(-1) will return null.
stop = start;
}
this.input = input;
this.start = start;
this.stop = stop;
this.trappedException = e;
}

public boolean isNil() {
return false;
}

public int getType() {
return Token.INVALID_TOKEN_TYPE;
}

public String getText() {
String badText = null;
if ( start instanceof Token ) {
int i = ((Token)start).getTokenIndex();
int j = ((Token)stop).getTokenIndex();
if ( ((Token)stop).getType() == Token.EOF ) {
j = ((TokenStream)input).size();
}
badText = ((TokenStream)input).toString(i, j);
}
else if ( start instanceof Tree ) {
badText = ((TreeNodeStream)input).toString(start, stop);
}
else {
// people should subclass if they alter the tree type so this
// next one is for sure correct.
badText = "<unknown>";
}
return badText;
}

public String toString() {
if ( trappedException instanceof MissingTokenException ) {
return "<missing type: "+
((MissingTokenException)trappedException).getMissingType()+
">";
}
else if ( trappedException instanceof UnwantedTokenException ) {
return "<extraneous: "+
((UnwantedTokenException)trappedException).getUnexpectedToken()+
", resync="+getText()+">";
}
else if ( trappedException instanceof MismatchedTokenException ) {
return "<mismatched token: "+trappedException.token+", resync="+getText()+">";
}
else if ( trappedException instanceof NoViableAltException ) {
return "<unexpected: "+trappedException.token+
", resync="+getText()+">";
}
return "<error: "+getText()+">";
}
}

来源.txt:

this.something = this.somecall(someparam, anotherparam)
this.dummy1 = this.dummy2
this.control[]={this.control1, this.control2, this.control3}

最佳答案

使用instanceof运算符?它用于确定给定对象是否属于某种类型,并防止在运行时引发 ClassCastExceptions

Object object = input.LT(1);
if (object instanceof MyCustomType){
MyCustomType type = (MyCustomType)object;
}

关于java - 使用自定义 AST 节点类型进行树过滤时,如何避免抛出 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9114023/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com