Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当使用自定义AST节点类型进行树筛选时,如何避免抛出ClassCastException?_Java_Antlr - Fatal编程技术网

Java 当使用自定义AST节点类型进行树筛选时,如何避免抛出ClassCastException?

Java 当使用自定义AST节点类型进行树筛选时,如何避免抛出ClassCastException?,java,antlr,Java,Antlr,我使用从CommonTree派生的自定义AST节点类型构建了一个AST 在我使用包含*通配符的树过滤语法之前,这似乎还可以 页面上的注释表明,这是由于代码必须执行以下操作造成的: (MyCustomType)input.LT(1); 当遇到上下节点时抛出,因为它们属于CommonTree类。 注释中的解决方案是针对可选的(?)元素,但我确实需要一种使用*通配符捕获事物列表的方法,而不必抛出它 编辑: 这是一个小例子,说明了我的问题 这个source.txt展示了一些我需要能够解析的示例。 当我

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

在我使用包含*通配符的树过滤语法之前,这似乎还可以

页面上的注释表明,这是由于代码必须执行以下操作造成的:

(MyCustomType)input.LT(1);
当遇到上下节点时抛出,因为它们属于CommonTree类。 注释中的解决方案是针对可选的(?)元素,但我确实需要一种使用*通配符捕获事物列表的方法,而不必抛出它

编辑:

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

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

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

Sccee.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;}
    ;
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()+">";
        }
}

是否使用
instanceof
运算符?它用于确定给定对象是否属于特定类型,并防止运行时抛出
ClassCastExceptions

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

谢谢你的建议,但是上面的一行出现在生成的代码中。我真的在寻找一个选项或方法来指定语法,以避免出现这种情况。你能发布一个演示CCE的示例吗?我一直在尝试为你组合一个,但我无法像我预期的那样在示例中复制问题。我将继续工作,并在我到达某处后发布。我添加了一些代码。很抱歉,它不是非常紧凑,但我似乎只有在中添加了一些基本内容之后才能演示这个问题。如果你还需要什么,请告诉我。谢谢,不管它没有那么短。最重要的是复制粘贴,并查看SSCCE的问题方面。稍后我会看一看。唉,我无法使用自定义的
ASTLabelType
。但我必须承认,我对ANTLR的树模式重写相当陌生:我自己从未使用过。我通常倾向于使用
CommonTree
,通过手动遍历AST或在整个语法上使用树遍历器来创建自定义节点(也可能进行重写)。你可以试试。祝你好运!
this.something = this.somecall(someparam, anotherparam)
this.dummy1 = this.dummy2
this.control[]={this.control1, this.control2, this.control3}
Object object = input.LT(1);
if (object instanceof MyCustomType){
   MyCustomType type = (MyCustomType)object;
}