Example usage for org.antlr.v4.runtime.tree TerminalNode getSymbol

List of usage examples for org.antlr.v4.runtime.tree TerminalNode getSymbol

Introduction

In this page you can find the example usage for org.antlr.v4.runtime.tree TerminalNode getSymbol.

Prototype

Token getSymbol();

Source Link

Usage

From source file:FullFormEmitter.java

License:Open Source License

/**
 * {@inheritDoc}//w  w w  .j  ava2s .co m
 *
 * <p>The default implementation returns the result of calling
 * {@link #visitChildren} on {@code ctx}.</p>
 */
@Override
public String visitComparison(FoxySheepParser.ComparisonContext ctx) {
    /*
     * This is a rather complicated construct, because:
     *       "x==y"       -> Equal[x,y]
     *       "x==y>z"    -> Inequality[x, Equal, y, Greater, z]
     *       "x==y==z      -> Equal[x,y,z]
     *       "x>y>z"      -> Greater[x,y,z]
     * So we need to flatten many different operators at once
     * if necessary.
     * 
     * We solve this problem by postprocessing the syntax tree
     * to flatten the tree where appropriate.  
     */

    HashMap<Integer, String> opText = new HashMap<Integer, String>(6);
    opText.put(FoxySheepParser.EqualSymbol, "Equal");
    opText.put(FoxySheepParser.NotEqualSymbol, "Unequal");
    opText.put(FoxySheepParser.GREATER, "Greater");
    opText.put(FoxySheepParser.GreaterEqualSymbol, "GreaterEqual");
    opText.put(FoxySheepParser.LESS, "Less");
    opText.put(FoxySheepParser.LessEqualSymbol, "LessEqual");

    boolean allSame = true;
    int opType = ((TerminalNode) ctx.getChild(1)).getSymbol().getType();
    for (int i = 3; i < ctx.getChildCount(); i += 2) {
        allSame = allSame && (opType == ((TerminalNode) ctx.getChild(i)).getSymbol().getType());
    }

    //If all operators are the same, make a "head" with that operator. 
    if (allSame) {
        return makeHeadList((String) opText.get(opType), ctx.expr());
    }

    //All operators are not the same. We need to create an Inequality[].
    TerminalNode op;
    StringBuilder val = new StringBuilder("Inequality[");
    val.append(getFullForm(ctx.expr(0)));
    for (int i = 1; i < ctx.getChildCount(); i += 2) {
        val.append(",");
        op = (TerminalNode) ctx.getChild(i);
        val.append((String) opText.get(op.getSymbol().getType()));
        val.append(",");
        val.append(getFullForm(ctx.getChild(i + 1)));
    }
    val.append("]");
    return val.toString();
}

From source file:ai.grakn.graql.internal.parser.QueryVisitor.java

License:Open Source License

private Var getVariable(TerminalNode variable) {
    return getVariable(variable.getSymbol());
}

From source file:ai.grakn.graql.internal.template.TemplateVisitor.java

License:Open Source License

@Override
public String visitTerminal(TerminalNode node) {
    int index = node.getSymbol().getTokenIndex();
    String lws = tokens.getHiddenTokensToLeft(index) != null
            ? tokens.getHiddenTokensToLeft(index).stream().map(Token::getText).collect(joining())
            : "";
    String rws = tokens.getHiddenTokensToRight(index) != null
            ? tokens.getHiddenTokensToRight(index).stream().map(Token::getText).collect(joining())
            : "";
    return lws + node.getText() + rws;
}

From source file:android.databinding.tool.ExpressionVisitor.java

License:Apache License

@Override
public Expr visitTerminal(@NotNull TerminalNode node) {
    try {/*  w  w  w  .j a v  a2  s. c om*/
        onEnter((ParserRuleContext) node.getParent().getRuleContext());
        final int type = node.getSymbol().getType();
        Class classType;
        switch (type) {
        case BindingExpressionParser.IntegerLiteral:
            classType = int.class;
            break;
        case BindingExpressionParser.FloatingPointLiteral:
            classType = float.class;
            break;
        case BindingExpressionParser.BooleanLiteral:
            classType = boolean.class;
            break;
        case BindingExpressionParser.CharacterLiteral:
            classType = char.class;
            break;
        case BindingExpressionParser.SingleQuoteString:
        case BindingExpressionParser.DoubleQuoteString:
            classType = String.class;
            break;
        case BindingExpressionParser.NullLiteral:
            classType = Object.class;
            break;
        default:
            throw new RuntimeException("cannot create expression from terminal node " + node.toString());
        }
        return mModel.symbol(node.getText(), classType);
    } finally {
        onExit((ParserRuleContext) node.getParent().getRuleContext());
    }
}

From source file:br.beholder.memelang.model.visitor.SemanticVisitor.java

@Override
public Object visitDeclaracoes(MemelangParser.DeclaracoesContext ctx) {
    visitTipo(ctx.tipo());//from w  ww .  ja v a  2  s .c o m
    for (MemelangParser.DeclaracaoContext declaracaoContext : ctx.declaracao()) {
        multidimensional = 0;
        qtdMultidimensional = 1;
        TerminalNode id = declaracaoContext.ID();
        if (declaracaoContext.multidimensional() != null) {
            visitMultidimensional(declaracaoContext.multidimensional());
        }
        boolean inicializada;
        if (declaracaoContext.IGUAL() != null) {
            inicializada = true;
        } else {
            inicializada = false;
        }
        if (Escopo.verificaSeExisteNoEscopo(id.getSymbol().getText(), tabelaSimbolos, escopoAtual)) {
            this.semanticErrors.add(new ParseCancellationException(
                    "Declarao de Vriavel " + declaracaoContext.ID() + " j existe neste escopo Linha: "
                            + ctx.start.getLine() + " Coluna: " + ctx.start.getCharPositionInLine()));
        }
        Identificador ident = new Identificador(id.getSymbol().getText(), tipoAtual, inicializada, false,
                escopoAtual, false, false, 0, multidimensional, qtdMultidimensional, false);
        tabelaSimbolos.add(ident);
        visitChildren(ctx);
        System.out.println(ident.getTipo());
        if (inicializada) {
            verificarCompatibilidadeAtribuicao(ident.getTipo(), ctx);
        }
    }

    return null;
}

From source file:br.edu.ifrn.potigol.Listener.java

License:Open Source License

@Override
public void visitTerminal(TerminalNode node) {
    final String s;
    switch (node.getSymbol().getType()) {
    case potigolLexer.ID:
        s = escapeID(node.getText());//  www .j ava2  s.  c o  m
        break;
    default:
        s = node.getText();
    }
    setValue(node, s);
}

From source file:ch.raffael.contracts.devtools.ast.AstInspector.java

License:Apache License

public void parse(final String source) {
    final StringBuilder errors = new StringBuilder();
    final StringBuilder trace = new StringBuilder("Log:\n");
    ANTLRErrorListener errorListener = new BaseErrorListener() {
        @Override//from   w  w w.ja v a  2s.  c o  m
        public void syntaxError(Recognizer<?, ?> recognizer, @Nullable Object offendingSymbol, int line,
                int charPositionInLine, String msg, @Nullable RecognitionException e) {
            errors.append("Line ").append(line).append(':').append(charPositionInLine).append(": ").append(msg)
                    .append('\n');
        }
    };
    final CelLexer lexer = new CelLexer(new ANTLRInputStream(source));
    final CelParser parser = new CelParser(new CommonTokenStream(lexer));
    lexer.addErrorListener(errorListener);
    parser.addErrorListener(errorListener);
    parser.addParseListener(new ParseTreeListener() {
        @Override
        public void enterEveryRule(ParserRuleContext ctx) {
            trace.append("    enter\t").append(parser.getRuleNames()[ctx.getRuleIndex()]).append(", LT(1)=")
                    .append(parser.getTokenStream().LT(1).getText()).append('\n');
        }

        @Override
        public void visitTerminal(TerminalNode node) {
            trace.append("    consume\t").append(node.getSymbol()).append(" rule ")
                    .append(parser.getRuleNames()[parser.getContext().getRuleIndex()]).append('\n');
        }

        @Override
        public void visitErrorNode(ErrorNode node) {
        }

        @Override
        public void exitEveryRule(ParserRuleContext ctx) {
            trace.append("    exit\t").append(parser.getRuleNames()[ctx.getRuleIndex()]).append(", LT(1)=")
                    .append(parser.getTokenStream().LT(1).getText()).append('\n');
        }
    });
    parser.setBuildParseTree(true);
    AstBuilder builder = new AstBuilder();
    builder.install(parser);
    final CelParser.ClauseContext rootContext = parser.clause();
    if (errors.length() != 0) {
        errors.append('\n');
    }
    Runnable guiUpdate = new Runnable() {
        @Override
        public void run() {
            log.setText(errors.toString() + trace.toString());
            log.setSelectionStart(0);
            log.setSelectionEnd(0);
            if (rootContext == null || rootContext.node == null) {
                syntaxTree.setModel(new DefaultTreeModel(AstTreeNode.empty()));
                updateParseTree(null);
            } else {
                syntaxTree.setModel(new DefaultTreeModel(AstTreeNode.from(rootContext.node)));
                updateParseTree(new TreeViewer(Arrays.asList(parser.getRuleNames()), rootContext));
            }
            for (int i = 0; i < syntaxTree.getRowCount(); i++) {
                syntaxTree.expandRow(i);
            }
        }
    };
    if (SwingUtilities.isEventDispatchThread()) {
        guiUpdate.run();
    } else {
        SwingUtilities.invokeLater(guiUpdate);
    }
}

From source file:ch.raffael.contracts.processor.cel.parser.AstBuilder.java

License:Apache License

@Override
public void exitExpression(ExpressionContext ctx) {
    TerminalNode operator;
    if (ctx.unary() != null) {
        ctx.node = ctx.unary().node;//from   w ww .jav  a 2  s  .  co m
    } else if ((operator = first(ctx.MUL(), ctx.DIV(), ctx.MOD(), ctx.ADD(), ctx.SUB())) != null) {
        ctx.node = Nodes.arithmeticOp(operator.getSymbol(), ctx.expression(0).node, ctx.expression(1).node);
    } else if ((operator = first(ctx.LEFT_SHIFT(), ctx.RIGHT_SHIFT(), ctx.URIGHT_SHIFT())) != null) {
        ctx.node = Nodes.shiftOp(operator.getSymbol(), ctx.expression(0).node, ctx.expression(1).node);
    } else if (ctx.INSTANCEOF() != null) {
        /*FIXME:*/throw new NotImplementedException("instanceof");
    } else if ((operator = first(ctx.GT(), ctx.GE(), ctx.LT(), ctx.LE())) != null) {
        ctx.node = Nodes.relationalOp(operator.getSymbol(), ctx.expression(0).node, ctx.expression(1).node);
    } else if ((operator = first(ctx.BITWISE_AND(), ctx.BITWISE_OR(), ctx.BITWISE_XOR())) != null) {
        ctx.node = Nodes.bitwiseOp(operator.getSymbol(), ctx.expression(0).node, ctx.expression(1).node);
    } else if ((operator = first(ctx.LOGICAL_AND(), ctx.LOGICAL_OR())) != null) {
        ctx.node = Nodes.logicalOp(operator.getSymbol(), ctx.expression(0).node, ctx.expression(1).node);
    } else if (ctx.CONDITIONAL() != null) {
        ctx.node = Nodes.conditionalOp(ctx.CONDITIONAL().getSymbol(), ctx.expression(0).node,
                ctx.expression(1).node, ctx.expression(2).node);
    } else {
        throw new UnreachableCodeException();
    }
}

From source file:com.antsdb.saltedfish.sql.mysql.ExprGenerator.java

License:Open Source License

static Operator gen_(GeneratorContext ctx, Planner cursorMeta, ExprContext rule) throws OrcaException {
    if (rule.getChildCount() == 1) {
        return gen_sinlge_node(ctx, cursorMeta, rule);
    } else if (rule.expr_in_values() != null) {
        Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
        return gen_in_values(ctx, cursorMeta, rule.expr_in_values(), left);
    } else if (rule.expr_in_select() != null) {
        Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
        return gen_in_select(ctx, cursorMeta, rule.expr_in_select(), left);
    } else if (rule.unary_operator() != null) {
        Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(1));
        return gen_unary(ctx, cursorMeta, rule.unary_operator(), right);
    } else if (rule.K_REGEXP() != null) {
        // REGEXP operator
        Operator expr = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
        String text = rule.literal_value().getText();
        text = text.substring(1, text.length() - 1);
        return new OpRegexp(expr, text);
    } else if (rule.K_BETWEEN() != null) {
        Operator expr = gen(ctx, cursorMeta, rule.expr(0));
        Operator from = gen(ctx, cursorMeta, rule.expr(1));
        Operator to = gen(ctx, cursorMeta, rule.expr(2));
        return new OpBetween(expr, from, to);
    } else if (rule.getChild(1) instanceof TerminalNode) {
        String op = rule.getChild(1).getText();
        if ("=".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpEqual(left, right);
        } else if ("==".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpEqualNull(left, right);
        } else if ("+".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            if ((left instanceof OpInterval) || (right instanceof OpInterval)) {
                return new OpAddTime(left, right);
            } else {
                return new OpAdd(left, right);
            }//  w  w  w  .  j a v  a  2 s  .c om
        } else if ("-".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            if ((left instanceof OpInterval) || (right instanceof OpInterval)) {
                return new OpMinusTime(left, right);
            } else {
                return new OpAdd(left, new OpNegate(right));
            }
        } else if ("*".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpMultiply(left, right);
        } else if (">".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpLarger(left, right);
        } else if (">=".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpLargerEqual(left, right);
        } else if ("<".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpLess(left, right);
        } else if ("<=".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpLessEqual(left, right);
        } else if ("!=".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpNot(new OpEqual(left, right));
        } else if ("<>".equals(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpNot(new OpEqual(left, right));
        } else if ("like".equalsIgnoreCase(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpLike(left, right);
        } else if ("or".equalsIgnoreCase(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpOr(left, right);
        } else if ("and".equalsIgnoreCase(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpAnd(left, right);
        } else if ("||".equalsIgnoreCase(op)) {
            Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
            Operator right = gen(ctx, cursorMeta, (ExprContext) rule.getChild(2));
            return new OpConcat(left, right);
        } else if ("is".equalsIgnoreCase(op)) {
            if (rule.getChild(2) instanceof ExprContext) {
                Operator upstream = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
                return new OpIsNull(upstream);
            } else if (rule.getChild(2) instanceof TerminalNode) {
                // IS NOT
                Operator upstream = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
                return new OpNot(new OpIsNull(upstream));
            } else {
                throw new NotImplementedException();
            }
        } else if ("not".equalsIgnoreCase(op)) {
            if (rule.getChild(2) instanceof TerminalNode) {
                TerminalNode node = (TerminalNode) rule.getChild(2);
                if (node.getSymbol().getType() == MysqlParser.K_LIKE) {
                    Operator left = gen(ctx, cursorMeta, (ExprContext) rule.getChild(0));
                    Operator right = genLiteralValue(ctx, cursorMeta, (Literal_valueContext) rule.getChild(3));
                    return new OpNot(new OpLike(left, right));
                }
            }
            throw new NotImplementedException();
        } else {
            throw new NotImplementedException();
        }
    } else if (rule.K_DISTINCT() != null) {
        Operator op = gen(ctx, cursorMeta, rule.expr(0));
        return new FuncDistinct(op, ctx.allocVariable());
    } else {
        String text = rule.getText();
        throw new NotImplementedException(text);
    }
}

From source file:com.antsdb.saltedfish.sql.mysql.ExprGenerator.java

License:Open Source License

private static Operator gen_unary(GeneratorContext ctx, Planner cursorMeta, Unary_operatorContext rule,
        Operator right) {/*from w  w  w. j  a  va 2s  .  c o  m*/
    TerminalNode token = (TerminalNode) rule.getChild(0);
    if (token.getSymbol().getType() == MysqlParser.K_NOT) {
        return new OpNot(right);
    } else if (token.getSymbol().getType() == MysqlParser.MINUS) {
        return new OpNegate(right);
    } else if (token.getSymbol().getType() == MysqlParser.K_BINARY) {
        return new OpBinary(right);
    } else {
        throw new NotImplementedException();
    }
}