org.antlr.runtime.tree.CommonTree Java Examples

The following examples show how to use org.antlr.runtime.tree.CommonTree. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void refAttr(Token templateToken, CommonTree id) {
    String name = id.getText();
    if ( impl.formalArguments!=null && impl.formalArguments.get(name)!=null ) {
        FormalArgument arg = impl.formalArguments.get(name);
        int index = arg.index;
        emit1(id, Bytecode.INSTR_LOAD_LOCAL, index);
    }
    else {
        if ( Interpreter.predefinedAnonSubtemplateAttributes.contains(name) ) {
            errMgr.compileTimeError(ErrorType.REF_TO_IMPLICIT_ATTRIBUTE_OUT_OF_SCOPE, templateToken, id.token);
            emit(id, Bytecode.INSTR_NULL);
        }
        else {
            emit1(id, Bytecode.INSTR_LOAD_ATTR, name);
        }
    }
}
 
Example #2
Source File: WhereTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Use by the inClauseTest
 * @param theQuery Query
 * @param propName String
 * @param values String...
 */
private void inChecks(Query theQuery, final String propName, final String... values) {
    assertNotNull(theQuery);
    CommonTree tree = theQuery.getTree();
    assertNotNull(tree);
	assertEquals(WhereClauseParser.IN, tree.getType());
	assertEquals(WhereClauseParser.PROPERTYNAME, tree.getChild(0).getType());
	assertTrue(propName.equals(tree.getChild(0).getText()));
	QueryHelper.walk(theQuery, new WalkerCallbackAdapter(){
		@Override
		public void in(String property, boolean negated, String... propertyValues) {
			assertTrue("Property name should be "+propName,propName.equals(property));
			for (int i = 0; i < values.length; i++) {
				assertTrue("Value must match:"+values[i],values[i].equals(propertyValues[i]));				
			}
		}
		
	});
}
 
Example #3
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void refAttr(Token templateToken, CommonTree id) {
    String name = id.getText();
    if ( impl.formalArguments!=null && impl.formalArguments.get(name)!=null ) {
        FormalArgument arg = impl.formalArguments.get(name);
        int index = arg.index;
        emit1(id, Bytecode.INSTR_LOAD_LOCAL, index);
    }
    else {
        if ( Interpreter.predefinedAnonSubtemplateAttributes.contains(name) ) {
            errMgr.compileTimeError(ErrorType.REF_TO_IMPLICIT_ATTRIBUTE_OUT_OF_SCOPE, templateToken, id.token);
            emit(id, Bytecode.INSTR_NULL);
        }
        else {
            emit1(id, Bytecode.INSTR_LOAD_ATTR, name);
        }
    }
}
 
Example #4
Source File: FTSQueryParser.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static boolean hasOptionalFieldReference(CommonTree node)
{
    switch (node.getType())
    {
    case FTSParser.TERM:
    case FTSParser.EXACT_TERM:
    case FTSParser.PHRASE:
    case FTSParser.EXACT_PHRASE:
    case FTSParser.SYNONYM:
    case FTSParser.PROXIMITY:
    case FTSParser.RANGE:
        return true;
    default:
        return false;
    }
}
 
Example #5
Source File: WhereTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Used by the matchesClauseTest
 * @param theQuery Query
 * @param propName String
 * @param propVal String
 */
private void matchesChecks(Query theQuery, final String propName, final String propVal) {
    assertNotNull(theQuery);
    CommonTree tree = theQuery.getTree();
    assertNotNull(tree);
	assertEquals(WhereClauseParser.PROPERTYNAME, tree.getChild(0).getType());
	assertTrue(propName.equals(tree.getChild(0).getText()));
	assertEquals(WhereClauseParser.PROPERTYVALUE, tree.getChild(1).getType());
	QueryHelper.walk(theQuery, new WalkerCallbackAdapter(){
		@Override
		public void matches(String propertyName, String propertyValue, boolean negated) {
			assertTrue("Property name should be "+propName,propName.equals(propertyName));
			assertTrue("Property value should be "+propVal,propVal.equals(propertyValue));
		}
		
	});
}
 
Example #6
Source File: AbstractCobolTester.java    From legstar-core2 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Starting from a COBOL source fragment translates to XML Schema.
 * @param source COBOL source fragment.
 * @return an XML Schema
 * @throws RecognizerException if emit fails
 */
public String emit(final String source)  throws RecognizerException {
    try {
        CommonTree ast = parse(source);
        if (_log.isDebugEnabled()) {
            _log.debug(ast.toStringTree());
        }
        TreeNodeStream nodes = new CommonTreeNodeStream(ast);
        CobolStructureEmitter emitter = new CobolStructureEmitterImpl(
                nodes, getErrorHandler());
        List < CobolDataItem > dataEntries = new ArrayList < CobolDataItem >();
        emitter.cobdata(dataEntries);
        return dataEntries.toString();
    } catch (RecognitionException e) {
        throw new RecognizerException(e);
    }
}
 
Example #7
Source File: IdVarSelector.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public Object pre(Object t) {
    if (!(t instanceof CommonTree))
        return t;

    if (t instanceof CommonErrorNode) {
        return t;
    }

    CommonTree node = (CommonTree) t;

    if (node instanceof QueryNode) {
        QueryVariableContext newCurrent = new QueryVariableContext(model, (QueryNode) node);
        if (root == null) {
            root = newCurrent;
        }
        QueryVariableContext last = stack.peekLast();
        if (last != null) {
            last.addChild(newCurrent);
        }
        stack.addLast(newCurrent);
    }
    return t;
}
 
Example #8
Source File: EventIDParser.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Long parse(CommonTree tree, ICommonTreeParserParameter param) throws ParseException {

    CommonTree firstChild = (CommonTree) tree.getChild(0);

    if (isUnaryInteger(firstChild)) {
        if (tree.getChildCount() > 1) {
            throw new ParseException(INVALID_VALUE_ERROR);
        }
        long intval = UnaryIntegerParser.INSTANCE.parse(firstChild, null);
        if (intval > Integer.MAX_VALUE) {
            throw new ParseException("Event id larger than int.maxvalue, something is amiss"); //$NON-NLS-1$
        }
        return intval;
    }
    throw new ParseException(INVALID_VALUE_ERROR);
}
 
Example #9
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void refAttr(Token templateToken, CommonTree id) {
    String name = id.getText();
    if ( impl.formalArguments!=null && impl.formalArguments.get(name) !=null ) {
        FormalArgument arg = impl.formalArguments.get(name);
        int index = arg.index;
        emit1(id, Bytecode.INSTR_LOAD_LOCAL, index);
    }
    else {
        if ( Interpreter.predefinedAnonSubtemplateAttributes.contains(name) ) {
            errMgr.compileTimeError(ErrorType.REF_TO_IMPLICIT_ATTRIBUTE_OUT_OF_SCOPE, templateToken, id.token);
            emit(id, Bytecode.INSTR_NULL);
        } else {
            emit1(id, Bytecode.INSTR_LOAD_ATTR, name);
        }
    }
}
 
Example #10
Source File: CMISQueryParser.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @param orNode CommonTree
 * @param factory QueryModelFactory
 * @param functionEvaluationContext FunctionEvaluationContext
 * @param selectors Map<String, Selector>
 * @param columnMap HashMap<String, Column>
 * @return Constraint
 */
private Constraint buildDisjunction(CommonTree orNode, QueryModelFactory factory,
        FunctionEvaluationContext functionEvaluationContext, Map<String, Selector> selectors,
        HashMap<String, Column> columnMap)
{
    List<Constraint> constraints = new ArrayList<Constraint>(orNode.getChildCount());
    for (int i = 0; i < orNode.getChildCount(); i++)
    {
        CommonTree andNode = (CommonTree) orNode.getChild(i);
        Constraint constraint = buildConjunction(andNode, factory, functionEvaluationContext, selectors, columnMap);
        constraints.add(constraint);
    }
    if (constraints.size() == 1)
    {
        return constraints.get(0);
    } else
    {
        return factory.createDisjunction(constraints);
    }
}
 
Example #11
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void refAttr(Token templateToken, CommonTree id) {
    String name = id.getText();
    if ( impl.formalArguments!=null && impl.formalArguments.get(name) !=null ) {
        FormalArgument arg = impl.formalArguments.get(name);
        int index = arg.index;
        emit1(id, Bytecode.INSTR_LOAD_LOCAL, index);
    }
    else {
        if ( Interpreter.predefinedAnonSubtemplateAttributes.contains(name) ) {
            errMgr.compileTimeError(ErrorType.REF_TO_IMPLICIT_ATTRIBUTE_OUT_OF_SCOPE, templateToken, id.token);
            emit(id, Bytecode.INSTR_NULL);
        } else {
            emit1(id, Bytecode.INSTR_LOAD_ATTR, name);
        }
    }
}
 
Example #12
Source File: JoinVariableNode.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public CommonTree treeToQueryPre(QueryBuilder sb, List<ErrorRec> invalidNodes) {
    int childCount = getChildCount();
    if (childCount == 0) {
        invalidNodes.add(new ErrorRec(this, "No children found"));
        return null;
    }
    sb.appendSpace();
    sb.appendString(joinSpec);
    sb.appendSpace();
    sb.appendString(toQuery(getChild(0)));
    sb.appendSpace();
    sb.appendString(variableName);
    if (childCount > 1) {
        sb.appendSpace();
        sb.appendString("on");
        for (int idx = 1; idx < childCount; idx++) {
            sb.appendSpace();
            sb.appendString(toQuery(getChild(idx)));
        }
    }
    return null;
}
 
Example #13
Source File: TypeDeclarationStringParser.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates the string representation of a type specifier.
 *
 * @param typeSpecifierList
 *            A TYPE_SPECIFIER node.
 *
 * @return A StringBuilder to which will be appended the string.
 * @throws ParseException
 *             invalid node
 */
@Override
public String parse(CommonTree typeSpecifierList, ICommonTreeParserParameter param) throws ParseException {
    if (!(param instanceof Param)) {
        throw new IllegalArgumentException("Param must be a " + Param.class.getCanonicalName()); //$NON-NLS-1$
    }
    List<CommonTree> pointers = ((Param) param).fList;
    StringBuilder sb = new StringBuilder();
    sb.append(TypeSpecifierListStringParser.INSTANCE.parse(typeSpecifierList, null));
    if (pointers != null) {
        CommonTree temp = new CommonTree();
        for (CommonTree pointer : pointers) {
            temp.addChild(pointer);
        }
        sb.append(PointerListStringParser.INSTANCE.parse(temp, null));
    }
    return sb.toString();
}
 
Example #14
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void refAttr(Token templateToken, CommonTree id) {
    String name = id.getText();
    if ( impl.formalArguments !=null && impl.formalArguments.get(name)!=null ) {
        FormalArgument arg = impl.formalArguments.get(name);
        int index = arg.index;
        emit1(id, Bytecode.INSTR_LOAD_LOCAL, index);
    }
    else {
        if ( Interpreter.predefinedAnonSubtemplateAttributes.contains(name) ) {
            errMgr.compileTimeError(ErrorType.REF_TO_IMPLICIT_ATTRIBUTE_OUT_OF_SCOPE,
                                    templateToken,
                                    id.token);
            emit(id, Bytecode.INSTR_NULL);
        }
        else {
            emit1(id, Bytecode.INSTR_LOAD_ATTR, name);
        }
    }
}
 
Example #15
Source File: WhereTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Used by ComparisonClauseTest, validates the clause
 * @param theQuery Query
 * @param comparisonOperator One of EQUALS LESSTHAN GREATERTHAN LESSTHANOREQUALS GREATERTHANOREQUALS
    * @param propName String
    * @param propVal String
    */
private void comparisonChecks(Query theQuery, final int comparisonOperator, final String propName, final String propVal) {
    assertNotNull(theQuery);
    CommonTree tree = theQuery.getTree();
    assertNotNull(tree);
	assertEquals(comparisonOperator, tree.getType());
	assertEquals(WhereClauseParser.PROPERTYNAME, tree.getChild(0).getType());
	assertTrue(propName.equals(tree.getChild(0).getText()));
	assertEquals(WhereClauseParser.PROPERTYVALUE, tree.getChild(1).getType());
	QueryHelper.walk(theQuery, new WalkerCallbackAdapter(){
		@Override
		public void comparison(int comparisonType, String propertyName, String propertyValue, boolean negated) {
			assertTrue("Property name should be "+propName,propName.equals(propertyName));
			assertTrue(comparisonOperator == comparisonType);
			assertTrue("Property value should be "+propVal,propVal.equals(propertyValue));
		}
		
	});
}
 
Example #16
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void emit(CommonTree opAST, short opcode) {
    ensureCapacity(1);
    if ( opAST !=null ) {
        int i = opAST.getTokenStartIndex();
        int j = opAST.getTokenStopIndex();
        int p = ((CommonToken)tokens.get(i)).getStartIndex();
        int q = ((CommonToken)tokens.get(j)).getStopIndex();
        if ( !(p<0 || q<0) ) impl.sourceMap[ip] = new Interval(p, q);
    }
    impl.instrs[ip++] = (byte)opcode;
}
 
Example #17
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void emit2(CommonTree opAST, short opcode, int arg, int arg2) {
    emit(opAST, opcode);
    ensureCapacity(Bytecode.OPND_SIZE_IN_BYTES*2);
    writeShort(impl.instrs, ip, (short)arg);
    ip += Bytecode.OPND_SIZE_IN_BYTES;
    writeShort(impl.instrs, ip, (short)arg2);
    ip += Bytecode.OPND_SIZE_IN_BYTES;
}
 
Example #18
Source File: TypeSpecifierListNameParser.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private static void parseVariant(CommonTree typeSpecifier, StringBuilder sb) throws ParseException {
    CommonTree variantName = (CommonTree) typeSpecifier.getFirstChildWithType(CTFParser.VARIANT_NAME);
    if (variantName == null) {
        throw new ParseException("nameless variant found in createTypeSpecifierString"); //$NON-NLS-1$
    }

    CommonTree variantNameIdentifier = (CommonTree) variantName.getChild(0);

    parseSimple(variantNameIdentifier, sb);
}
 
Example #19
Source File: CFilterRuleParser.java    From binnavi with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an ANTRL AND AST into a filter AND AST.
 * 
 * @param ast The AST to convert.
 * 
 * @return The converted AST.
 * 
 * @throws RecognitionException Thrown if the AST could not be converted.
 */
private static IAbstractNode convertAnd(final CommonTree ast) throws RecognitionException {
  final List<IAbstractNode> children = new ArrayList<IAbstractNode>();

  for (final Object childObject : ast.getChildren()) {
    children.add(convert((CommonTree) childObject));
  }

  return new CAbstractAndExpression(children);
}
 
Example #20
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void emit2(CommonTree opAST, short opcode, int arg, int arg2) {
    emit(opAST, opcode);
    ensureCapacity(Bytecode.OPND_SIZE_IN_BYTES*2);
    writeShort(impl.instrs, ip, (short)arg);
    ip += Bytecode.OPND_SIZE_IN_BYTES;
    writeShort(impl.instrs, ip, (short)arg2);
    ip += Bytecode.OPND_SIZE_IN_BYTES;
}
 
Example #21
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void emit(CommonTree opAST, short opcode) {
    ensureCapacity(1);
    if ( opAST!=null ) {
        int i = opAST.getTokenStartIndex();
        int j = opAST.getTokenStopIndex();
        int p = ((CommonToken)tokens.get(i)).getStartIndex();
        int q = ((CommonToken)tokens.get(j)).getStopIndex();
        if ( !(p<0 || q<0) ) impl.sourceMap[ip] = new Interval(p, q);
    }
    impl.instrs[ip++] = (byte)opcode;
}
 
Example #22
Source File: QueryTransformerAstBased.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected CommonTree parseWhereCondition(String whereCondition) {
    try {
        return Parser.parseWhereClause("where " + whereCondition);
    } catch (RecognitionException | JPA2RecognitionException e) {
        throw new JpqlSyntaxException(format("Errors found while parsing where condition:[%s] for query:[%s]\n%s",
                StringUtils.strip(whereCondition), StringUtils.strip(query), e.getMessage()));
    }
}
 
Example #23
Source File: SemanticException.java    From AppTroy with Apache License 2.0 5 votes vote down vote up
SemanticException(IntStream input, CommonTree tree, String errorMessage, Object... messageArguments) {
    super();
    this.input = input;
    this.token = tree.getToken();
    this.index = tree.getTokenStartIndex();
    this.line = token.getLine();
 this.charPositionInLine = token.getCharPositionInLine();
    this.errorMessage = String.format(errorMessage, messageArguments);
}
 
Example #24
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void func(Token templateToken, CommonTree id) {
    Short funcBytecode = Compiler.funcs.get(id.getText());
    if ( funcBytecode==null ) {
        errMgr.compileTimeError(ErrorType.NO_SUCH_FUNCTION, templateToken, id.token);
        emit(id, Bytecode.INSTR_POP);
    }
    else {
        emit(id, funcBytecode);
    }
}
 
Example #25
Source File: CompilationState.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void emit(CommonTree opAST, short opcode) {
    ensureCapacity(1);
    if ( opAST !=null ) {
        int i = opAST.getTokenStartIndex();
        int j = opAST.getTokenStopIndex();
        int p = ((CommonToken)tokens.get(i)).getStartIndex();
        int q = ((CommonToken)tokens.get(j)).getStopIndex();
        if ( !(p<0 || q<0) ) impl.sourceMap[ip] = new Interval(p, q);
    }
    impl.instrs[ip++] = (byte)opcode;
}
 
Example #26
Source File: AbstractHiveQLProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void findTableNames(final Object obj, final Set<TableName> tableNames) {
    if (!(obj instanceof CommonTree)) {
        return;
    }
    final CommonTree tree = (CommonTree) obj;
    final int childCount = tree.getChildCount();
    if ("TOK_TABNAME".equals(tree.getText())) {
        final TableName tableName;
        final boolean isInput = "TOK_TABREF".equals(tree.getParent().getText());
        switch (childCount) {
            case 1 :
                tableName = new TableName(null, tree.getChild(0).getText(), isInput);
                break;
            case 2:
                tableName = new TableName(tree.getChild(0).getText(), tree.getChild(1).getText(), isInput);
                break;
            default:
                throw new IllegalStateException("TOK_TABNAME does not have expected children, childCount=" + childCount);
        }
        // If parent is TOK_TABREF, then it is an input table.
        tableNames.add(tableName);
        return;
    }
    for (int i = 0; i < childCount; i++) {
        findTableNames(tree.getChild(i), tableNames);
    }
}
 
Example #27
Source File: Parser.java    From cuba with Apache License 2.0 5 votes vote down vote up
public static CommonTree parseSelectionSource(String input) throws RecognitionException {
    JPA2Parser parser = createParser(input);
    JPA2Parser.identification_variable_declaration_or_collection_member_declaration_return aReturn =
            parser.identification_variable_declaration_or_collection_member_declaration();
    CommonTree tree = (CommonTree) aReturn.getTree();
    checkTreeForExceptions(input, tree);
    return tree;
}
 
Example #28
Source File: BaseCustomNode.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void dupChildren(CommonTree result) {
    for (Object child : children) {
        CommonTree t = (CommonTree) child;
        Tree copy = t.dupNode();
        result.addChild(copy);
    }
}
 
Example #29
Source File: CFAssignmentExpression.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private CFExpression reparse( cfStringData _string, CFContext _context )
    throws cfmRunTimeException {
	// note, the fact that calling leftVal.getString() will not include the
	// pound signs is what's req'd
	// note addition of ';' at end of expression to make it parsable
	try {
		ANTLRNoCaseReaderStream input = new ANTLRNoCaseReaderStream(
		    new poundSignFilterStream(new StringReader(_string.getString())));

		CFMLLexer lexer = new CFMLLexer(input);
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		CFMLParser parser = new CFMLParser(tokens);
		parser.scriptMode = false;
		CFMLParser.expression_return r = parser.expression();
		CommonTree tree = (CommonTree) r.getTree();

		CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
		nodes.setTokenStream(tokens);
		CFMLTree p2 = new CFMLTree(nodes);
		p2.scriptMode = false;
		return p2.expression();
	} catch (IOException ioe) { // shouldn't happen
		throw new CFException("Invalid expression : " + left.Decompile(0),
		    _context);
	} catch (RecognitionException pe) {
		throw new CFException("Invalid expression : " + left.Decompile(0),
		    _context);
	} catch (poundSignFilterStreamException e) {
		throw new CFException("Invalid expression : " + left.Decompile(0),
		    _context);
	}

}
 
Example #30
Source File: AbstractAntlrTester.java    From legstar-core2 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * A generic test helper that takes a source fragment and checks the result.
 * 
 * @param source the source fragment
 * @param expected the expected sub graph
 */
public void parseAndCheck(final String source, final String expected) {
    try {
        CommonTree ast = parse(source);
        assertEquals(expected, (ast == null) ? "" : ast.toStringTree());
        if (_log.isDebugEnabled()) {
            _log.debug(getGraph(ast).toString());
        }
    } catch (RecognizerException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}