Java Code Examples for org.antlr.runtime.tree.CommonTree#getChildren()

The following examples show how to use org.antlr.runtime.tree.CommonTree#getChildren() . 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: UnaryIntegerParser.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Parses an unary integer (dec, hex or oct).
 *
 * @param unaryInteger
 *            An unary integer node.
 *
 * @return The integer value.
 * @throws ParseException
 *             on an invalid integer format ("bob" for example)
 */
@Override
public Long parse(CommonTree unaryInteger, ICommonTreeParserParameter notUsed) throws ParseException {
    List<CommonTree> children = unaryInteger.getChildren();
    CommonTree value = children.get(0);
    String strval = value.getText();

    long intval;
    try {
        intval = Long.decode(strval);
    } catch (NumberFormatException e) {
        throw new ParseException("Invalid integer format: " + strval, e); //$NON-NLS-1$
    }

    /* The rest of children are sign */
    if ((children.size() % 2) == 0) {
        return -intval;
    }
    return intval;
}
 
Example 2
Source File: QueryParserUtils.java    From spork with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
static void replaceNodeWithNodeList(Tree oldNode, CommonTree newTree,
        String fileName) {
    int idx = oldNode.getChildIndex();

    CommonTree parent = (CommonTree) oldNode.getParent();
    int count = parent.getChildCount();

    List childList = new ArrayList(parent.getChildren());
    List macroList = newTree.getChildren();

    while (parent.getChildCount() > 0) {
        parent.deleteChild(0);
    }

    for (int i = 0; i < count; i++) {
        if (i == idx) {
            // add only there is something to add
            if (macroList != null) {
                parent.addChildren(macroList);
            }
        } else {
            parent.addChild((Tree) childList.get(i));
        }
    }
}
 
Example 3
Source File: CtfParserTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
void matches(CommonTree tree) {
    if (fType == -1) {
        return;
    }
    if (tree.getType() != fType) {
        fail("Type mismatch!" +
                " expected:" + fType +
                " actual:" + tree.getType());
    }

    if (fText != null) {
        if (!fText.equals(tree.getText())) {
            fail("Text mismatch!" +
                    " expected:" + fText +
                    " actual:" + tree.getText());
        }
    }

    if (fChild != null) {
        int size = fChild.length;
        if (tree.getChildren() == null) {
            if (size != 0) {
                fail("Invalid children!"
                        + "Expect: " + size + "child");
            }
        } else {
            if (tree.getChildren().size() != size) {
                fail("Invalid number of childs!"
                        + " expected:" + size
                        + " actual:" + tree.getChildren().size());
            }

            for (int i = 0; i < size; ++i) {
                fChild[i].matches((CommonTree) tree.getChild(i));
            }
        }
    }
}
 
Example 4
Source File: FTSQueryParser.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static boolean isAutoPhrasable(CommonTree node, boolean defaultConjunction) {
	if((node.getType() == FTSParser.CONJUNCTION) && (node.getChildCount() > 1))
	{
		int simpleTermCount = 0;
		for (Object current : node.getChildren())
		{
			CommonTree child = (CommonTree) current;
			if((child.getType() ==  FTSParser.MANDATORY) || (child.getType() ==  FTSParser.DEFAULT))
			{
				if(child.getChildCount() > 0)
				{
					CommonTree item = (CommonTree)child.getChild(0);
					if((item.getType() == FTSParser.TERM) && (item.getChildCount() == 1))
					{
						simpleTermCount++;
					}
				}
			}
			else
			{
				return false;
			}
		}
		return simpleTermCount > 1;
	}

	return false;

}
 
Example 5
Source File: CallSiteParser.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public @NonNull CTFCallsite parse(CommonTree tree, ICommonTreeParserParameter param)  {
    /*
     * this is to replace the previous quotes with nothing...
     * effectively deleting them
     */
    final String emptyString = ""; //$NON-NLS-1$

    /* this is a regex to find the leading and trailing quotes */
    final String regex = "^\"|\"$"; //$NON-NLS-1$

    String fileName = null;
    String funcName = null;
    String name = null;
    long lineNumber =-1;
    long ip = -1;

    List<CommonTree> children = tree.getChildren();
    for (CommonTree child : children) {
        String left = child.getChild(0).getChild(0).getChild(0).getText();
        if (left.equals(NAME)) {
            name = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString);
        } else if (left.equals(FUNC)) {
            funcName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString);
        } else if (left.equals(IP)) {
            ip = Long.decode(child.getChild(1).getChild(0).getChild(0).getText());
        } else if (left.equals(FILE)) {
            fileName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString);
        } else if (left.equals(LINE)) {
            lineNumber = Long.parseLong(child.getChild(1).getChild(0).getChild(0).getText());
        }
    }

    if (name == null || funcName == null || fileName == null) {
        throw new NullPointerException("CTFCallsite parameters shouldn't be null!"); //$NON-NLS-1$
    }

    return new CTFCallsite(name, funcName, ip, fileName, lineNumber);
}
 
Example 6
Source File: TypedefParser.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Parses a typedef node. This creates and registers a new declaration for
 * each declarator found in the typedef.
 *
 * @param typedef
 *            A TYPEDEF node.
 *
 * @return map of type name to type declaration
 * @throws ParseException
 *             If there is an error creating the declaration.
 */
@Override
public Map<String, IDeclaration> parse(CommonTree typedef, ICommonTreeParserParameter param) throws ParseException {
    if (!(param instanceof Param)) {
        throw new IllegalArgumentException("Param must be a " + Param.class.getCanonicalName()); //$NON-NLS-1$
    }
    DeclarationScope scope = ((Param) param).fDeclarationScope;

    CommonTree typeDeclaratorListNode = (CommonTree) typedef.getFirstChildWithType(CTFParser.TYPE_DECLARATOR_LIST);
    if (typeDeclaratorListNode == null) {
        throw new ParseException("Cannot have a typedef without a declarator"); //$NON-NLS-1$
    }
    CommonTree typeSpecifierListNode = (CommonTree) typedef.getFirstChildWithType(CTFParser.TYPE_SPECIFIER_LIST);
    if (typeSpecifierListNode == null) {
        throw new ParseException("Cannot have a typedef without specifiers"); //$NON-NLS-1$
    }
    List<CommonTree> typeDeclaratorList = typeDeclaratorListNode.getChildren();

    Map<String, IDeclaration> declarations = new HashMap<>();

    for (CommonTree typeDeclaratorNode : typeDeclaratorList) {
        StringBuilder identifierSB = new StringBuilder();
        CTFTrace trace = ((Param) param).fTrace;
        IDeclaration typeDeclaration = TypeDeclaratorParser.INSTANCE.parse(typeDeclaratorNode, new TypeDeclaratorParser.Param(trace, typeSpecifierListNode, scope, identifierSB));

        if ((typeDeclaration instanceof VariantDeclaration)
                && !((VariantDeclaration) typeDeclaration).isTagged()) {
            throw new ParseException("Typealias of untagged variant is not permitted"); //$NON-NLS-1$
        }

        scope.registerType(identifierSB.toString(), typeDeclaration);

        declarations.put(identifierSB.toString(), typeDeclaration);
    }
    return declarations;
}
 
Example 7
Source File: VariantBodyParser.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Parse the variant body, fills the variant with the results.
 *
 * @param variantBody
 *            the variant body AST node
 * @param param
 *            the {@link Param} parameter object
 * @return a populated {@link VariantDeclaration}
 * @throws ParseException
 *             if the AST is malformed
 */
@Override
public VariantDeclaration parse(CommonTree variantBody, ICommonTreeParserParameter param) throws ParseException {
    if (!(param instanceof Param)) {
        throw new IllegalArgumentException("Param must be a " + Param.class.getCanonicalName()); //$NON-NLS-1$
    }

    String variantName = ((Param) param).fName;
    VariantDeclaration variantDeclaration = ((Param) param).fVariantDeclaration;
    List<CommonTree> variantDeclarations = variantBody.getChildren();

    final DeclarationScope scope = new DeclarationScope(((Param) param).fDeclarationScope, variantName == null ? MetadataStrings.VARIANT : variantName);
    CTFTrace trace = ((Param) param).fTrace;
    for (CommonTree declarationNode : variantDeclarations) {
        switch (declarationNode.getType()) {
        case CTFParser.TYPEALIAS:
            TypeAliasParser.INSTANCE.parse(declarationNode, new TypeAliasParser.Param(trace, scope));
            break;
        case CTFParser.TYPEDEF:
            Map<String, IDeclaration> decs = TypedefParser.INSTANCE.parse(declarationNode, new TypedefParser.Param(trace, scope));
            for (Entry<String, IDeclaration> declarationEntry : decs.entrySet()) {
                variantDeclaration.addField(declarationEntry.getKey(), declarationEntry.getValue());
            }
            break;
        case CTFParser.SV_DECLARATION:
            VariantDeclarationParser.INSTANCE.parse(declarationNode, new VariantDeclarationParser.Param(variantDeclaration, trace, scope));
            break;
        default:
            throw childTypeError(declarationNode);
        }
    }

    return variantDeclaration;
}
 
Example 8
Source File: IOStructGen.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private void parseTrace(CommonTree traceNode) throws ParseException {

        CTFTrace trace = fTrace;
        List<CommonTree> children = traceNode.getChildren();
        if (children == null) {
            throw new ParseException("Trace block is empty"); //$NON-NLS-1$
        }

        for (CommonTree child : children) {
            switch (child.getType()) {
            case CTFParser.TYPEALIAS:
                TypeAliasParser.INSTANCE.parse(child, new TypeAliasParser.Param(trace, fRoot));
                break;
            case CTFParser.TYPEDEF:
                TypedefParser.INSTANCE.parse(child, new TypedefParser.Param(trace, fRoot));
                break;
            case CTFParser.CTF_EXPRESSION_TYPE:
            case CTFParser.CTF_EXPRESSION_VAL:
                TraceDeclarationParser.INSTANCE.parse(child, new TraceDeclarationParser.Param(fTrace, fRoot));
                break;
            default:
                throw childTypeError(child);
            }
        }

        /*
         * If trace byte order was not specified and not using packet based
         * metadata
         */
        if (fTrace.getByteOrder() == null) {
            throw new ParseException("Trace byte order not set"); //$NON-NLS-1$
        }
    }
 
Example 9
Source File: EnvironmentParser.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Map<String, String> parse(CommonTree environment, ICommonTreeParserParameter param) {

    ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();
    List<CommonTree> children = environment.getChildren();
    for (CommonTree child : children) {
        String left;
        String right;
        left = child.getChild(0).getChild(0).getChild(0).getText();
        right = child.getChild(1).getChild(0).getChild(0).getText();
        builder.put(left, right);
    }
    return builder.build();
}
 
Example 10
Source File: CFilterRuleParser.java    From binnavi with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an ANTRL OR AST into a filter OR AST.
 * 
 * @param ast The AST to convert.
 * 
 * @return The converted AST.
 * 
 * @throws RecognitionException Thrown if the AST could not be converted.
 */
private static IAbstractNode convertOr(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 CAbstractOrExpression(children);
}
 
Example 11
Source File: HintProvider.java    From cuba with Apache License 2.0 5 votes vote down vote up
private List<String> prepareErrorMessages(List<ErrorRec> errorRecs) {
    List<String> errorMessages = new ArrayList<>();
    for (ErrorRec errorRec : errorRecs) {
        CommonTree errorNode = errorRec.node;
        StringBuilder b = new StringBuilder();
        for (Object child : errorNode.getChildren()) {
            CommonTree childNode = (CommonTree) child;
            b.append(childNode.getText());
        }
        String errorMessage = "Error near: \"" + b + "\"";
        errorMessages.add(errorMessage);
    }
    return errorMessages;
}
 
Example 12
Source File: IdentificationVariableNode.java    From cuba with Apache License 2.0 5 votes vote down vote up
public void deductFields(QueryVariableContext queryVC, CommonTree node, DomainModel model) {
    List children = node.getChildren();
    CommonTree T_SELECTED_ITEMS_NODE = (CommonTree) children.get(0);
    for (Object o : T_SELECTED_ITEMS_NODE.getChildren()) {
        o = ((SelectedItemNode) o).getChild(0);
        if (!(o instanceof PathNode)) {
            throw new RuntimeException("Not a path node");
        }

        PathNode pathNode = (PathNode) o;
        Pointer pointer = pathNode.resolvePointer(model, queryVC);

        if (pointer instanceof NoPointer) {
            queryVC.setEntity(NoJpqlEntityModel.getInstance());
            return;
        }

        if (pointer instanceof SimpleAttributePointer) {
            SimpleAttributePointer saPointer = (SimpleAttributePointer) pointer;
            queryVC.getEntity().addAttributeCopy(saPointer.getAttribute());
        } else if (pointer instanceof EntityPointer) {
            if (T_SELECTED_ITEMS_NODE.getChildren().size() != 1) {
                //todo implement
                throw new UnsupportedOperationException("Unimplemented variant with returned array");
            } else {
                queryVC.setEntity(((EntityPointer) pointer).getEntity());
            }
        }
    }
}
 
Example 13
Source File: WhereCompiler.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void print(CommonTree tree, int level) {
	//indent level
	for (int i = 0; i < level; i++)
		logger.debug("--");

	//print node description: type code followed by token text
	logger.debug(" " + tree.getType() + " " + tree.getText());
	
	//print all children
	if (tree.getChildren() != null)
		for (Object ie : tree.getChildren()) {
			print((CommonTree) ie, level + 1);
		}
}
 
Example 14
Source File: FloatDeclarationParser.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Parses a float node and returns a floating point declaration of the
 * type @link {@link FloatDeclaration}.
 *
 * @param floatingPoint
 *            AST node of type FLOAT
 * @param param
 *            parameter containing the trace
 * @return the float declaration
 * @throws ParseException
 *             if a float AST is malformed
 */
@Override
public FloatDeclaration parse(CommonTree floatingPoint, ICommonTreeParserParameter param) throws ParseException {
    if (!(param instanceof Param)) {
        throw new IllegalArgumentException("Param must be a " + Param.class.getCanonicalName()); //$NON-NLS-1$
    }
    CTFTrace trace = ((Param) param).fTrace;
    List<CommonTree> children = floatingPoint.getChildren();

    /*
     * If the integer has no attributes, then it is missing the size
     * attribute which is required
     */
    if (children == null) {
        throw new ParseException(FLOAT_MISSING_SIZE_ATTRIBUTE);
    }

    /* The return value */
    ByteOrder byteOrder = trace.getByteOrder();
    long alignment = 0;

    int exponent = DEFAULT_FLOAT_EXPONENT;
    int mantissa = DEFAULT_FLOAT_MANTISSA;

    /* Iterate on all integer children */
    for (CommonTree child : children) {
        switch (child.getType()) {
        case CTFParser.CTF_EXPRESSION_VAL:
            /*
             * An assignment expression must have 2 children, left and right
             */

            CommonTree leftNode = (CommonTree) child.getChild(0);
            CommonTree rightNode = (CommonTree) child.getChild(1);

            List<CommonTree> leftStrings = leftNode.getChildren();

            if (!isAnyUnaryString(leftStrings.get(0))) {
                throw new ParseException(IDENTIFIER_MUST_BE_A_STRING);
            }
            String left = concatenateUnaryStrings(leftStrings);

            if (left.equals(MetadataStrings.EXP_DIG)) {
                exponent = UnaryIntegerParser.INSTANCE.parse((CommonTree) rightNode.getChild(0), null).intValue();
            } else if (left.equals(MetadataStrings.BYTE_ORDER)) {
                byteOrder = ByteOrderParser.INSTANCE.parse(rightNode, new ByteOrderParser.Param(trace));
            } else if (left.equals(MetadataStrings.MANT_DIG)) {
                mantissa = UnaryIntegerParser.INSTANCE.parse((CommonTree) rightNode.getChild(0), null).intValue();
            } else if (left.equals(MetadataStrings.ALIGN)) {
                alignment = AlignmentParser.INSTANCE.parse(rightNode, null);
            } else {
                throw new ParseException(FLOAT_UNKNOWN_ATTRIBUTE + left);
            }

            break;
        default:
            throw childTypeError(child);
        }
    }
    int size = mantissa + exponent;
    if (size == 0) {
        throw new ParseException(FLOAT_MISSING_SIZE_ATTRIBUTE);
    }

    if (alignment == 0) {
        alignment = 1;
    }

    return new FloatDeclaration(exponent, mantissa, byteOrder, alignment);

}
 
Example 15
Source File: VariantDeclarationParser.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Parses the variant declaration and gets a {@link VariantDeclaration}
 * back.
 *
 * @param declaration
 *            the variant declaration AST node
 * @param param
 *            the {@link Param} parameter object
 * @return the {@link VariantDeclaration}
 * @throws ParseException
 *             if the AST is malformed
 */
@Override
public VariantDeclaration parse(CommonTree declaration, ICommonTreeParserParameter param) throws ParseException {
    if (!(param instanceof Param)) {
        throw new IllegalArgumentException("Param must be a " + Param.class.getCanonicalName()); //$NON-NLS-1$
    }
    VariantDeclaration variant = ((Param) param).fVariant;
    final DeclarationScope scope = ((Param) param).fDeclarationScope;
    /* Get the type specifier list node */
    CommonTree typeSpecifierListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_SPECIFIER_LIST);
    if (typeSpecifierListNode == null) {
        throw new ParseException("Variant need type specifiers"); //$NON-NLS-1$
    }

    /* Get the type declarator list node */
    CommonTree typeDeclaratorListNode = (CommonTree) declaration.getFirstChildWithType(CTFParser.TYPE_DECLARATOR_LIST);
    if (typeDeclaratorListNode == null) {
        throw new ParseException("Cannot have empty variant"); //$NON-NLS-1$
    }
    /* Get the type declarator list */
    List<CommonTree> typeDeclaratorList = typeDeclaratorListNode.getChildren();

    /*
     * For each type declarator, parse the declaration and add a field to
     * the variant
     */
    for (CommonTree typeDeclaratorNode : typeDeclaratorList) {

        StringBuilder identifierSB = new StringBuilder();
        CTFTrace trace = ((Param) param).fTrace;
        IDeclaration decl = TypeDeclaratorParser.INSTANCE.parse(typeDeclaratorNode,
                new TypeDeclaratorParser.Param(trace, typeSpecifierListNode, scope, identifierSB));

        String name = identifierSB.toString();

        if (variant.hasField(name)) {
            throw new ParseException("variant: duplicate field " //$NON-NLS-1$
                    + name);
        }

        scope.registerIdentifier(name, decl);

        variant.addField(name, decl);
    }
    return variant;
}
 
Example 16
Source File: EnumeratorParser.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Parses an enumerator node and adds an enumerator declaration to an
 * enumeration declaration.
 *
 * The high value of the range of the last enumerator is needed in case the
 * current enumerator does not specify its value.
 *
 * @param enumerator
 *            An ENUM_ENUMERATOR node.
 * @param param
 *            an enumeration declaration to which will be added the
 *            enumerator.
 * @return The high value of the value range of the current enumerator.
 * @throws ParseException
 *             if the element failed to add
 */
@Override
public Long parse(CommonTree enumerator, ICommonTreeParserParameter param) throws ParseException {
    if (!(param instanceof Param)) {
        throw new IllegalArgumentException("Param must be a " + Param.class.getCanonicalName()); //$NON-NLS-1$
    }
    EnumDeclaration enumDeclaration = ((Param) param).fEnumDeclaration;

    List<CommonTree> children = enumerator.getChildren();

    long low = 0, high = 0;
    boolean valueSpecified = false;
    String label = null;

    for (CommonTree child : children) {
        if (isAnyUnaryString(child)) {
            label = UnaryStringParser.INSTANCE.parse(child, null);
        } else if (child.getType() == CTFParser.ENUM_VALUE) {

            valueSpecified = true;

            low = UnaryIntegerParser.INSTANCE.parse((CommonTree) child.getChild(0), null);
            high = low;
        } else if (child.getType() == CTFParser.ENUM_VALUE_RANGE) {

            valueSpecified = true;

            low = UnaryIntegerParser.INSTANCE.parse((CommonTree) child.getChild(0), null);
            high = UnaryIntegerParser.INSTANCE.parse((CommonTree) child.getChild(1), null);
        } else {
            throw childTypeError(child);
        }
    }

    if (low > high) {
        throw new ParseException("enum low value greater than high value"); //$NON-NLS-1$
    }
    if (valueSpecified && !enumDeclaration.add(low, high, label)) {
        Activator.log(IStatus.WARNING, "enum declarator values overlap. " + enumDeclaration.getLabels() + " and " + label); //$NON-NLS-1$ //$NON-NLS-2$
    } else if (!valueSpecified && !enumDeclaration.add(label)) {
        throw new ParseException("enum cannot add element " + label); //$NON-NLS-1$
    }

    if (valueSpecified && (BigInteger.valueOf(low).compareTo(enumDeclaration.getContainerType().getMinValue()) < 0 ||
            BigInteger.valueOf(high).compareTo(enumDeclaration.getContainerType().getMaxValue()) > 0)) {
        throw new ParseException("enum value is not in range"); //$NON-NLS-1$
    }

    return high;
}
 
Example 17
Source File: EventParser.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Parses an enum declaration and returns the corresponding declaration.
 *
 * @param eventNode
 *            An event node.
 * @param param
 *            the parameter object
 *
 * @return The corresponding enum declaration.
 * @throws ParseException
 *             event stream was badly defined
 */
@Override
public EventDeclaration parse(CommonTree eventNode, ICommonTreeParserParameter param) throws ParseException {
    if (!(param instanceof Param)) {
        throw new IllegalArgumentException("Param must be a " + Param.class.getCanonicalName()); //$NON-NLS-1$
    }
    Param parameter = (Param) param;
    CTFTrace trace = ((Param) param).fTrace;
    List<CommonTree> children = eventNode.getChildren();
    if (children == null) {
        throw new ParseException("Empty event block"); //$NON-NLS-1$
    }

    EventDeclaration event = new EventDeclaration();

    DeclarationScope scope = new DeclarationScope(parameter.fCurrentScope, MetadataStrings.EVENT);

    for (CommonTree child : children) {
        switch (child.getType()) {
        case CTFParser.TYPEALIAS:
            TypeAliasParser.INSTANCE.parse(child, new TypeAliasParser.Param(trace, scope));
            break;
        case CTFParser.TYPEDEF:
            TypedefParser.INSTANCE.parse(child, new TypedefParser.Param(trace, scope));
            break;
        case CTFParser.CTF_EXPRESSION_TYPE:
        case CTFParser.CTF_EXPRESSION_VAL:
            EventDeclarationParser.INSTANCE.parse(child, new EventDeclarationParser.Param(trace, event, scope));
            break;
        default:
            throw childTypeError(child);
        }
    }

    if (!event.nameIsSet()) {
        throw new ParseException("Event name not set"); //$NON-NLS-1$
    }

    /*
     * If the event did not specify a stream, then the trace must be single
     * stream
     */
    if (!event.streamIsSet()) {
        if (trace.nbStreams() > 1) {
            throw new ParseException("Event without stream_id with more than one stream"); //$NON-NLS-1$
        }

        /*
         * If the event did not specify a stream, the only existing stream
         * must not have an id. Note: That behavior could be changed, it
         * could be possible to just get the only existing stream, whatever
         * is its id.
         */
        ICTFStream iStream = trace.getStream(null);
        if (iStream instanceof CTFStream) {
            CTFStream ctfStream = (CTFStream) iStream;
            event.setStream(ctfStream);
        } else {
            throw new ParseException("Event without stream_id, but there is no stream without id"); //$NON-NLS-1$
        }
    }

    /*
     * Add the event to the stream.
     */
    event.getStream().addEvent(event);

    return event;
}
 
Example 18
Source File: RecognizedParamsExtractor.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Gets the clause specificed in paramName
 *
 * @param param
 * @param paramName
 * @return bean property names potentially using JSON Pointer syntax
 */
default List<String> getClause(String param, String paramName)
{
    if (param == null)
        return Collections.emptyList();

    try
    {
        CommonTree selectedPropsTree = WhereCompiler.compileSelectClause(param);
        if (selectedPropsTree instanceof CommonErrorNode)
        {
            rpeLogger().debug("Error parsing the " + paramName + " clause " + selectedPropsTree);
            throw new InvalidSelectException(paramName, selectedPropsTree);
        }
        if (selectedPropsTree.getChildCount() == 0 && !selectedPropsTree.getText().isEmpty())
        {
            return Arrays.asList(selectedPropsTree.getText());
        }
        List<Tree> children = (List<Tree>) selectedPropsTree.getChildren();
        if (children != null && !children.isEmpty())
        {
            List<String> properties = new ArrayList<String>(children.size());
            for (Tree child : children)
            {
                properties.add(child.getText());
            }
            return properties;
        }
    }
    catch (RewriteCardinalityException re)
    {
        //Catch any error so it doesn't get thrown up the stack
        rpeLogger().debug("Unhandled Error parsing the " + paramName + " clause: " + re);
    }
    catch (RecognitionException e)
    {
        rpeLogger().debug("Error parsing the \"+paramName+\" clause: " + param);
    }
    catch (InvalidQueryException iqe)
    {
        throw new InvalidSelectException(paramName, iqe.getQueryParam());
    }
    //Default to throw out an invalid query
    throw new InvalidSelectException(paramName, param);
}
 
Example 19
Source File: IntegerDeclarationParser.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Parses an integer declaration node.
 *
 * @param parameter
 *            parent trace, for byte orders
 *
 * @return The corresponding integer declaration.
 */
@Override
public IntegerDeclaration parse(CommonTree integer, ICommonTreeParserParameter parameter) throws ParseException {
    if (!(parameter instanceof Param)) {
        throw new IllegalArgumentException("Param must be a " + Param.class.getCanonicalName()); //$NON-NLS-1$
    }
    CTFTrace trace = ((Param) parameter).fTrace;
    List<CommonTree> children = integer.getChildren();

    /*
     * If the integer has no attributes, then it is missing the size
     * attribute which is required
     */
    if (children == null) {
        throw new ParseException("integer: missing size attribute"); //$NON-NLS-1$
    }

    /* The return value */
    IntegerDeclaration integerDeclaration = null;
    boolean signed = false;
    ByteOrder byteOrder = trace.getByteOrder();
    long size = 0;
    long alignment = 0;
    int base = DEFAULT_INT_BASE;
    @NonNull
    String clock = EMPTY_STRING;

    Encoding encoding = Encoding.NONE;

    /* Iterate on all integer children */
    for (CommonTree child : children) {
        switch (child.getType()) {
        case CTFParser.CTF_EXPRESSION_VAL:
            /*
             * An assignment expression must have 2 children, left and right
             */

            CommonTree leftNode = (CommonTree) child.getChild(0);
            CommonTree rightNode = (CommonTree) child.getChild(1);

            List<CommonTree> leftStrings = leftNode.getChildren();

            if (!isAnyUnaryString(leftStrings.get(0))) {
                throw new ParseException("Left side of ctf expression must be a string"); //$NON-NLS-1$
            }
            String left = concatenateUnaryStrings(leftStrings);

            switch (left) {
            case SIGNED:
                signed = SignedParser.INSTANCE.parse(rightNode, null);
                break;
            case MetadataStrings.BYTE_ORDER:
                byteOrder = ByteOrderParser.INSTANCE.parse(rightNode, new ByteOrderParser.Param(trace));
                break;
            case SIZE:
                size = SizeParser.INSTANCE.parse(rightNode, null);
                break;
            case MetadataStrings.ALIGN:
                alignment = AlignmentParser.INSTANCE.parse(rightNode, null);
                break;
            case BASE:
                base = BaseParser.INSTANCE.parse(rightNode, null);
                break;
            case ENCODING:
                encoding = EncodingParser.INSTANCE.parse(rightNode, null);
                break;
            case MAP:
                clock = ClockMapParser.INSTANCE.parse(rightNode, null);
                break;
            default:
                Activator.log(IStatus.WARNING, Messages.IOStructGen_UnknownIntegerAttributeWarning + " " + left); //$NON-NLS-1$
                break;
            }

            break;
        default:
            throw childTypeError(child);
        }
    }

    if (size <= 0) {
        throw new ParseException("Invalid size attribute in Integer: " + size); //$NON-NLS-1$
    }

    if (alignment == 0) {
        alignment = 1;
    }

    integerDeclaration = IntegerDeclaration.createDeclaration((int) size, signed, base,
            byteOrder, encoding, clock, alignment);

    return integerDeclaration;
}
 
Example 20
Source File: BreakpointConditionParser.java    From binnavi with Apache License 2.0 3 votes vote down vote up
/**
 * Converts the children of an n-ary operator node.
 *
 * @param ast The root node of the n-ary operator.
 *
 * @return The converted child nodes.
 *
 * @throws RecognitionException Thrown if any of the children could not be converted.
 */
private static List<ConditionNode> createOperator(final CommonTree ast)
    throws RecognitionException {
  final List<ConditionNode> children = new ArrayList<>();
  for (final Object child : ast.getChildren()) {
    children.add(convert((CommonTree) child));
  }
  return children;
}