Java Code Examples for org.eclipse.xtext.nodemodel.ICompositeNode#getGrammarElement()

The following examples show how to use org.eclipse.xtext.nodemodel.ICompositeNode#getGrammarElement() . 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: BaseContentAssistParser.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected AbstractElement getEntryGrammarElement(ICompositeNode entryPoint) {
	EObject grammarElement = entryPoint.getGrammarElement();
	if (grammarElement instanceof RuleCall) {
		AbstractRule rule = ((RuleCall) grammarElement).getRule();
		if (rule instanceof ParserRule) {
			if (!GrammarUtil.isMultipleCardinality(rule.getAlternatives())) {
				grammarElement = rule.getAlternatives();
			}
		}
	} else if (grammarElement instanceof ParserRule) {
		grammarElement = ((ParserRule) grammarElement).getAlternatives();
	} else if (grammarElement instanceof CrossReference) {
		grammarElement = GrammarUtil.containingAssignment(grammarElement);
	}
	AbstractElement result = (AbstractElement) grammarElement;
	if (result instanceof Action) {
		return getEntryGrammarElement((ICompositeNode) entryPoint.getFirstChild());
	}
	return result;
}
 
Example 2
Source File: EntryPointFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean shouldUseParent(ICompositeNode result, int offset, ILeafNode leaf) {
	if (leaf.getTotalEndOffset() == offset) {
		return true;
	}
	if (result.getGrammarElement() instanceof RuleCall) {
		RuleCall rc = (RuleCall) result.getGrammarElement();
		if (!rc.getArguments().isEmpty()) {
			return true;
		}
		Assignment assignment = GrammarUtil.containingAssignment(rc);
		if (assignment != null
				&& (GrammarUtil.isMultipleCardinality(assignment) || (assignment.eContainer() instanceof AbstractElement && GrammarUtil
						.isMultipleCardinality((AbstractElement) assignment.eContainer())))) {
			return true;
		}
	}
	return false;
}
 
Example 3
Source File: EntryPointFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public ICompositeNode findEntryPoint(IParseResult parseResult, int offset) {
	ICompositeNode rootNode = parseResult.getRootNode();
	if (rootNode.getTotalLength() == offset) {
		return null;
	}
	ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset);
	ICompositeNode parent = leafNode.getParent();
	ICompositeNode result = findEntryPoint(parent, offset);
	if (result != null) {
		EObject grammarElement = result.getGrammarElement();
		if (grammarElement instanceof AbstractElement) {
			return result;
		}
	}
	return null;
}
 
Example 4
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Investigates the composite nodes containing the changed region and collects a list of nodes which could possibly
 * replaced by a partial parse. Such a node has a parent that consumes all his current lookahead tokens and all of
 * these tokens are located before the changed region.
 */
protected List<ICompositeNode> internalFindValidReplaceRootNodeForChangeRegion(List<ICompositeNode> nodesEnclosingRegion) {
	List<ICompositeNode> result = new ArrayList<ICompositeNode>();
	boolean mustSkipNext = false;
	for (int i = 0; i < nodesEnclosingRegion.size(); i++) {
		ICompositeNode node = nodesEnclosingRegion.get(i);
		if (node.getGrammarElement() != null) {
			if (!mustSkipNext) {
				result.add(node);
				if (isActionNode(node)) {
					mustSkipNext = true;
				}
			} else {
				mustSkipNext = isActionNode(node);
			}
		}
	}
	return result;
}
 
Example 5
Source File: Bug480686Test.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testAllGrammarElementsUnique() throws Exception {
	ContentAssistFragmentTestLanguageRoot result = parseHelper.parse("newArrayList()");
	XtextResource res = (XtextResource) result.eResource();
	ICompositeNode root = res.getParseResult().getRootNode();
	new InvariantChecker().checkInvariant(root);
	Set<EObject> set = new HashSet<>();
	for (INode node : root.getAsTreeIterable()) {
		if (node instanceof ICompositeNode) {
			ICompositeNode compositeNode = (ICompositeNode) node;
			if (compositeNode.getGrammarElement() != null) {
				Assert.assertTrue(compositeNode.getGrammarElement().toString(),
						set.add(compositeNode.getGrammarElement()));
			} else {
				Assert.fail("node without grammar element");
			}
		}
	}
}
 
Example 6
Source File: Bug480686Test.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testAllGrammarElementsUniqueAfterReparse() throws Exception {
	ContentAssistFragmentTestLanguageRoot result = parseHelper.parse("");
	XtextResource res = (XtextResource) result.eResource();
	res.update(0, 0, "newArrayList()");
	ICompositeNode root = res.getParseResult().getRootNode();
	Set<EObject> set = new HashSet<>();
	for (INode node : root.getAsTreeIterable()) {
		if (node instanceof ICompositeNode) {
			ICompositeNode compositeNode = (ICompositeNode) node;
			if (compositeNode.getGrammarElement() != null) {
				Assert.assertTrue(compositeNode.getGrammarElement().toString(),
						set.add(compositeNode.getGrammarElement()));
			} else {
				Assert.fail("node without grammar element");
			}
		}
	}
}
 
Example 7
Source File: AbstractCleaningLinker.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @return true, if the parent node could contain cross references to the same semantic element as the given node.
 */
protected boolean shouldCheckParentNode(INode node) {
	EObject grammarElement = node.getGrammarElement();
	if (grammarElement instanceof AbstractElement) {
		ICompositeNode parent = node.getParent();
		if (parent != null) {
			if (!parent.hasDirectSemanticElement()) {
				if (isContainedInFragmentRule(grammarElement)) {
					return false;
				}
				Assignment assignment = GrammarUtil.containingAssignment(grammarElement);
				if (assignment == null) {
					return true;
				}
			}
			if (grammarElement instanceof Action) {
				if (isContainedInFragmentRule(grammarElement)) {
					return parent.getGrammarElement() instanceof RuleCall;
				}
			}
		}
	}
	return false;
}
 
Example 8
Source File: NodeModelUtils.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public static ParserRule getEntryParserRule(INode node) {
	ICompositeNode root = node.getRootNode();
	EObject ge1 = root.getGrammarElement();
	if (ge1 instanceof ParserRule) {
		return (ParserRule) ge1;
	} else if (ge1 instanceof Action) {
		INode firstChild = root.getFirstChild();
		while (firstChild.getGrammarElement() instanceof Action && firstChild instanceof CompositeNode) {
			firstChild = ((CompositeNode)firstChild).getFirstChild();
		}
		EObject ge2 = firstChild.getGrammarElement();
		if (ge2 instanceof ParserRule) {
			return (ParserRule) ge2;
		}
	}
	throw new IllegalStateException("No Root Parser Rule found; The Node Model is broken.");
}
 
Example 9
Source File: PartialParsingHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isInvalidRootNode(ICompositeNode rootNode, ICompositeNode candidate) {
	int endOffset = candidate.getTotalEndOffset();
	if (candidate instanceof SyntheticCompositeNode)
		return true;
	if (candidate.getGrammarElement() instanceof RuleCall) {
		AbstractRule rule = ((RuleCall) candidate.getGrammarElement()).getRule();
		if (!(rule instanceof ParserRule))
			return true;
		ParserRule casted = (ParserRule) rule;
		if (GrammarUtil.isDatatypeRule(casted) || casted.isFragment() || !casted.getParameters().isEmpty()) {
			return true;
		}
		if (isInvalidDueToPredicates((AbstractElement) candidate.getGrammarElement()))
			return true;
	}
	if (candidate.getGrammarElement() instanceof Action) {
		return true;
	}
	if (endOffset == rootNode.getTotalEndOffset()) {
		INode lastChild = getLastChild(candidate);
		if (lastChild instanceof ICompositeNode) {
			INode lastLeaf = getLastLeaf(candidate);
			if (isInvalidLastChildNode(candidate, lastLeaf)) {
				return true;
			}
		}
		if (isInvalidLastChildNode(candidate, lastChild)) {
			return true;
		}
	}
	return false;
}
 
Example 10
Source File: ContentAssistContextFactory.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Multimap<EObject, AbstractElement> computeCurrentModel(EObject currentModel, INode lastCompleteNode,
		Collection<AbstractElement> followElements) {
	Multimap<EObject, AbstractElement> result = LinkedHashMultimap.create();
	ICompositeNode currentParserNode = NodeModelUtils.getNode(currentModel);
	if (currentParserNode == null) {
		result.putAll(currentModel, followElements);
		return result;
	}
	EObject currentGrammarElement = currentParserNode.getGrammarElement();
	AbstractRule currentRule = getRule(currentGrammarElement);
	for (AbstractElement grammarElement : followElements) {
		AbstractRule rule = currentRule;
		ICompositeNode loopParserNode = currentParserNode;
		EObject loopLastGrammarElement = lastCompleteNode.getGrammarElement();
		while (!canBeCalledAfter(rule, loopLastGrammarElement, lastCompleteNode.getText(), grammarElement) && loopParserNode.getParent() != null) {
			loopLastGrammarElement = loopParserNode.getGrammarElement();
			loopParserNode = loopParserNode.getParent();
			while (loopParserNode.getGrammarElement() == null && loopParserNode.getParent() != null)
				loopParserNode = loopParserNode.getParent();
			EObject loopGrammarElement = loopParserNode.getGrammarElement();
			rule = getRule(loopGrammarElement);
		}
		EObject context = loopParserNode.getSemanticElement();
		result.put(context, grammarElement);
	}
	return result;
}
 
Example 11
Source File: PartialParsingPointers.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return either a RuleCall or a ParserRule
 */
public EObject findEntryRuleOrRuleCall(ICompositeNode replaceRootNode) {
	EObject grammarElement = replaceRootNode.getGrammarElement();
	if (grammarElement instanceof CrossReference) {
		grammarElement = ((CrossReference) grammarElement).getTerminal();
	}
	if (GrammarUtil.isParserRuleCall(grammarElement)) {
		return grammarElement;
	}
	else if (grammarElement instanceof ParserRule) {
		return grammarElement;
	}
	else if (grammarElement instanceof Action) {
		BidiIterator<INode> iterator = replaceRootNode.getChildren().iterator();
		while(iterator.hasNext()) {
			INode next = iterator.next();
			if (next instanceof ICompositeNode) {
				return findEntryRuleOrRuleCall((ICompositeNode) next);
			}
		}
		throw new IllegalArgumentException("Invalid parsetree: Action node does not have a Composite child");
	}
	else
		throw new IllegalArgumentException(
				"Entry rule can only be resolved for parser rules, rule calls, cross-references or actions, but tried to resolve for: "
				+ replaceRootNode.getGrammarElement().eClass().getName());
}
 
Example 12
Source File: ParamAwareEntryPointFinder.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean shouldUseParent(ICompositeNode result, int offset, ILeafNode leaf) {
	if (leaf.getTotalEndOffset() >= offset) {
		return true;
	}
	if (result.getGrammarElement() instanceof RuleCall) {
		RuleCall rc = (RuleCall) result.getGrammarElement();
		if (isMultipleCardinality(rc)) {
			return true;
		}
	}
	return false;
}
 
Example 13
Source File: ParserBasedContentAssistContextFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected Multimap<EObject, AbstractElement> computeCurrentModel(EObject currentModel, INode lastCompleteNode,
		Collection<AbstractElement> followElements) {
	Multimap<EObject, AbstractElement> result = LinkedHashMultimap.create();
	ICompositeNode currentParserNode = NodeModelUtils.getNode(currentModel);
	if (currentParserNode == null) {
		result.putAll(currentModel, followElements);
		return result;
	}
	EObject currentGrammarElement = currentParserNode.getGrammarElement();
	AbstractRule currentRule = getRule(currentGrammarElement);
	for (AbstractElement grammarElement : followElements) {
		AbstractRule rule = currentRule;
		ICompositeNode loopParserNode = currentParserNode;
		EObject loopLastGrammarElement = lastCompleteNode.getGrammarElement();
		while (!canBeCalledAfter(rule, loopLastGrammarElement, lastCompleteNode.getText(), grammarElement) && loopParserNode.getParent() != null) {
			loopLastGrammarElement = loopParserNode.getGrammarElement();
			loopParserNode = loopParserNode.getParent();
			while (loopParserNode.getGrammarElement() == null && loopParserNode.getParent() != null)
				loopParserNode = loopParserNode.getParent();
			EObject loopGrammarElement = loopParserNode.getGrammarElement();
			rule = getRule(loopGrammarElement);
		}
		EObject context = loopParserNode.getSemanticElement();
		result.put(context, grammarElement);
	}
	return result;
}
 
Example 14
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isInvalidRootNode(ICompositeNode candidate) {
	if (candidate instanceof SyntheticCompositeNode)
		return true;
	if (candidate.getGrammarElement() instanceof RuleCall) {
		AbstractRule rule = ((RuleCall) candidate.getGrammarElement()).getRule();
		if (!(rule instanceof ParserRule) || GrammarUtil.isDatatypeRule((ParserRule) rule))
			return true;
	}
	if (candidate.getGrammarElement() instanceof Action) {
		return true;
	}
	return false;
}
 
Example 15
Source File: CustomN4JSParser.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private String getRuleName(ICompositeNode entryPoint) {
	// This does not work well from Xpect since Xpect messes with the injectors and
	// thereby causes trouble with object identities of the grammar access.
	EObject grammarElement = entryPoint.getGrammarElement();
	if (grammarElement instanceof RuleCall) {
		RuleCall rc = (RuleCall) grammarElement;
		AbstractRule rule = rc.getRule();
		if (rule instanceof ParserRule) {
			if (!GrammarUtil.isMultipleCardinality(rule.getAlternatives())) {
				grammarElement = rule.getAlternatives();
				String[][] names = getRequiredRuleNames(getRuleName((AbstractElement) grammarElement),
						Ints.asList(getParamConfig(entryPoint)),
						(AbstractElement) grammarElement);
				if (names.length > 0) {
					return names[0][0];
				}
			}
		}
	}
	if (grammarElement instanceof ParserRule) {
		return getRuleName(((ParserRule) grammarElement).getAlternatives());
	}
	AbstractElement result = (AbstractElement) grammarElement;
	if (result instanceof Action) {
		return getRuleName((ICompositeNode) entryPoint.getFirstChild());
	}
	return getRuleName(result);
}
 
Example 16
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
protected boolean isActionNode(final ICompositeNode node) {
  return node.getGrammarElement() != null && node.getGrammarElement().eClass() == XtextPackage.Literals.ACTION;
}
 
Example 17
Source File: PartialParsingHelper.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected boolean isActionNode(ICompositeNode node) {
	return node.getGrammarElement() != null && node.getGrammarElement().eClass() == XtextPackage.Literals.ACTION;
}
 
Example 18
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected boolean isActionNode(ICompositeNode node) {
	return node.getGrammarElement() != null && node.getGrammarElement().eClass() == XtextPackage.Literals.ACTION;
}
 
Example 19
Source File: NodeModelTokenSource.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Filter the nodes from the iterator that do not have any impact on the parse result.
 *
 * For now we filter mostly regions that do have lookahead 1 and are closed before the requested region starts.
 */
private Iterator<INode> filterIterator(TreeIterator<AbstractNode> iterator) {
	return new AbstractIterator<>() {
		@Override
		protected INode computeNext() {
			if (iterator.hasNext()) {
				INode result = iterator.next();
				if (result instanceof ICompositeNode) {
					ICompositeNode casted = (ICompositeNode) result;
					if (casted.getTotalEndOffset() < endOffset - 1) {
						if (casted.hasChildren() && casted.getLookAhead() == 1) {
							AbstractElement grammarElement = (AbstractElement) casted.getGrammarElement();
							// Filter script elements and member declarations to the left of the cursor position.
							if (grammarElement == scriptElementCall || grammarElement == memberDeclarationCall) {
								INode sibling = casted.getNextSibling();
								while (sibling instanceof ILeafNode) {
									ILeafNode siblingLeaf = (ILeafNode) sibling;
									if (siblingLeaf.isHidden()) {
										if (siblingLeaf.getTotalEndOffset() >= endOffset) {
											return result;
										}
									} else {
										break;
									}
									sibling = siblingLeaf.getNextSibling();
								}
								iterator.prune();

								// filter statements that are completed before the cursor position and are not
								// part of the lookahead
							} else if (grammarElement == statementsCall) {
								// check if this is in the parents lookAhead to disambiguate block from object
								// literal
								ICompositeNode parent = casted.getParent();
								if (parent.getLookAhead() > 1) {
									ILeafNode firstLeaf = Iterables.get(casted.getLeafNodes(), 0);
									int remainingLA = parent.getLookAhead();
									Iterator<ILeafNode> parentLeafs = parent.getLeafNodes().iterator();
									while (parentLeafs.hasNext() && remainingLA > 0) {
										ILeafNode leafNode = parentLeafs.next();
										if (leafNode == firstLeaf) {
											break;
										}
										if (!leafNode.isHidden()) {
											remainingLA--;
											if (remainingLA == 0) {
												iterator.prune();
											}
										}
									}
								}

								// Reduce the size of object literals.
							} else if (grammarElement == propertyAssignmentCall1
									|| grammarElement == propertyAssignmentCall2) {
								iterator.prune();
								Iterator<ILeafNode> localLeafs = casted.getLeafNodes().iterator();
								while (localLeafs.hasNext()) {
									ILeafNode leaf = localLeafs.next();
									if (!leaf.isHidden()) {
										return leaf;
									}
								}
							}
						}
					}
				}
				return result;
			}
			return endOfData();
		}
	};

}
 
Example 20
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Investigates the composite nodes containing the changed region and collects a list of nodes which could possibly
 * replaced by a partial parse. Such a node has a parent that consumes all his current lookahead tokens and all of
 * these tokens are located before the changed region.
 */
private List<ICompositeNode> internalFindValidReplaceRootNodeForChangeRegion(final List<ICompositeNode> nodesEnclosingRegion, final Range range) {
  List<ICompositeNode> result = new ArrayList<ICompositeNode>();
  boolean mustSkipNext = false;
  ICompositeNode previous = null;
  /*
   * set to 'true' as soon as the lookahead of an enclosing
   * exceeds the given range
   */
  boolean done = false;
  for (int i = 0; i < nodesEnclosingRegion.size() && !done; i++) {
    ICompositeNode node = nodesEnclosingRegion.get(i);
    if (node.getGrammarElement() != null) {
      if (!mustSkipNext) {
        boolean process = true;
        if (previous != null && !node.hasNextSibling()) {
          if (previous.getLookAhead() == node.getLookAhead() && previous.getLookAhead() == 0) {
            process = false;
          }
        }
        EObject semanticElement = NodeModelUtils.findActualSemanticObjectFor(node);
        if (semanticElement != null) {
          ICompositeNode actualNode = NodeModelUtils.findActualNodeFor(semanticElement);
          if (actualNode != null && (actualNode.getTotalOffset() < node.getTotalOffset() || actualNode.getTotalEndOffset() > node.getTotalEndOffset())) {
            mustSkipNext = isActionNode(node);
            process = false;
          }
        }
        if (process) {
          int remainingLookAhead = node.getLookAhead();
          if (remainingLookAhead != 0) {
            Iterator<ILeafNode> iterator = node.getLeafNodes().iterator();
            while (iterator.hasNext() && remainingLookAhead > 0) {
              ILeafNode leaf = iterator.next();
              if (!leaf.isHidden()) {
                if (remainingLookAhead > 0) {
                  remainingLookAhead--;
                }
                if (remainingLookAhead == 0) {
                  if (leaf.getTotalEndOffset() <= range.getOffset()) {
                    result.add(node);
                    previous = node;
                    if (isActionNode(node)) {
                      mustSkipNext = true;
                    }
                    break;
                  } else {
                    // lookahead ends left of the range, don't dive into child nodes
                    done = true;
                  }
                }
              }
            }
            if (remainingLookAhead != 0) {
              done = true;
            }
          } else {
            result.add(node);
            previous = node;
            if (isActionNode(node)) {
              mustSkipNext = true;
            }
          }
        }
      } else { // !mustSkipNext
        mustSkipNext = isActionNode(node);
      }
    }
  }
  return result;
}