Java Code Examples for org.eclipse.emf.common.util.TreeIterator#prune()

The following examples show how to use org.eclipse.emf.common.util.TreeIterator#prune() . 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: TranspilerUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Search entire containment tree below 'root' for objects of type 'cls'. If last argument is <code>false</code>,
 * then sub trees below a matching node won't be searched.
 */
public static final <T extends EObject> List<T> collectNodes(EObject root, Class<T> cls,
		boolean searchForNestedNodes) {
	final List<T> result = new ArrayList<>();
	final TreeIterator<EObject> iter = root.eAllContents();
	while (iter.hasNext()) {
		final EObject obj = iter.next();
		if (cls.isAssignableFrom(obj.getClass())) {
			@SuppressWarnings("unchecked")
			final T objCasted = (T) obj;
			result.add(objCasted);
			if (!searchForNestedNodes)
				iter.prune();
		}
	}
	return result;
}
 
Example 2
Source File: TranspilerUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * root usually a function or other ThisProviding environment.
 *
 * @param root
 *            function or method.
 * @param cls
 *            Type of element to report.
 * @return nodes of (sub-)type cls in the same this-environment
 */
public static final <T extends EObject> List<T> collectNodesWithinSameThisEnvironment(EObject root, Class<T> cls) {
	final List<T> result = new ArrayList<>();
	final TreeIterator<EObject> iter = root.eAllContents();
	while (iter.hasNext()) {
		final EObject obj = iter.next();
		if (cls.isAssignableFrom(obj.getClass())) {
			@SuppressWarnings("unchecked")
			final T objCasted = (T) obj;
			result.add(objCasted);
		}
		// check for same environment
		if (obj instanceof ThisArgProvider) {
			iter.prune();
		}
	}
	return result;
}
 
Example 3
Source File: GlobalObjectScope.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void buildMap(Resource resource, Map<QualifiedName, IEObjectDescription> elements) {
	IDefaultResourceDescriptionStrategy strategy = ((XtextResource) resource).getResourceServiceProvider()
			.get(IDefaultResourceDescriptionStrategy.class);
	TreeIterator<EObject> allProperContents = EcoreUtil.getAllProperContents(resource, false);
	IAcceptor<IEObjectDescription> acceptor = new IAcceptor<>() {
		@Override
		public void accept(IEObjectDescription description) {
			elements.put(description.getQualifiedName(), description);
		}
	};
	while (allProperContents.hasNext()) {
		EObject content = allProperContents.next();
		if (!strategy.createEObjectDescriptions(content, acceptor)) {
			allProperContents.prune();
		}
	}
}
 
Example 4
Source File: SolidityImportedNamespaceAwareLocalScopeProvider.java    From solidity-ide with Eclipse Public License 1.0 6 votes vote down vote up
protected List<ImportNormalizer> getSuperTypeImports(Resource res, EReference reference) {
	List<ImportNormalizer> result = Lists.newArrayList();
	TreeIterator<EObject> allContents = res.getAllContents();
	while (allContents.hasNext()) {
		EObject next = allContents.next();
		if (next instanceof ContractDefinition) {
			ContractDefinition contract = (ContractDefinition) next;
			EList<TypeSpecifier> superTypes = contract.getSuperTypes();
			for (TypeSpecifier superType : superTypes) {
				ImportNormalizer resolver = createImportedNamespaceResolver(superType.getType().getName() + ".*", false);
				result.add(resolver);
			}
			allContents.prune();
		}
	}
	return result;
}
 
Example 5
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void checkIsValidConstructorArgument(XExpression argument, JvmType containerType) {
	TreeIterator<EObject> iterator = EcoreUtil2.eAll(argument);
	while(iterator.hasNext()) {
		EObject partOfArgumentExpression = iterator.next();
		if (partOfArgumentExpression instanceof XFeatureCall || partOfArgumentExpression instanceof XMemberFeatureCall) {				
			XAbstractFeatureCall featureCall = (XAbstractFeatureCall) partOfArgumentExpression;
			XExpression actualReceiver = featureCall.getActualReceiver();
			if(actualReceiver instanceof XFeatureCall && ((XFeatureCall)actualReceiver).getFeature() == containerType) {
				JvmIdentifiableElement feature = featureCall.getFeature();
				if (feature != null && !feature.eIsProxy()) {
					if (feature instanceof JvmField) {
						if (!((JvmField) feature).isStatic())
							error("Cannot refer to an instance field " + feature.getSimpleName() + " while explicitly invoking a constructor", 
									partOfArgumentExpression, null, INVALID_CONSTRUCTOR_ARGUMENT);
					} else if (feature instanceof JvmOperation) {
						if (!((JvmOperation) feature).isStatic())
							error("Cannot refer to an instance method while explicitly invoking a constructor", 
									partOfArgumentExpression, null, INVALID_CONSTRUCTOR_ARGUMENT);	
					}
				}
			}
		} else if(isLocalClassSemantics(partOfArgumentExpression)) {
			iterator.prune();
		}
	}
}
 
Example 6
Source File: ClosureWithExpectationHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isImplicitReturn(ITypeComputationResult expressionResult) {
	int flags = expressionResult.getConformanceFlags();
	if ((ConformanceFlags.NO_IMPLICIT_RETURN & flags) != 0) {
		return false;
	}
	XExpression expression = expressionResult.getExpression();
	if (expression == null) {
		return true;
	}
	if (expression.eClass() == XbasePackage.Literals.XRETURN_EXPRESSION) {
		return false;
	}
	TreeIterator<EObject> contents = expression.eAllContents();
	while (contents.hasNext()) {
		EObject next = contents.next();
		if (next.eClass() == XbasePackage.Literals.XRETURN_EXPRESSION) {
			return false;
		}
		if (next.eClass() == XbasePackage.Literals.XCLOSURE) {
			contents.prune();
		}
	}
	return true;
}
 
Example 7
Source File: AbstractElementFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> List<T> findByNestedRuleCall(Class<T> clazz, AbstractRule... rule) {
	Set<AbstractRule> rls = new HashSet<AbstractRule>(Arrays.asList(rule));
	ArrayList<T> r = new ArrayList<T>();
	for (AbstractRule ar : getRules()) {
		TreeIterator<EObject> i = ar.eAllContents();
		while (i.hasNext()) {
			EObject o = i.next();
			if (clazz.isInstance(o)) {
				TreeIterator<EObject> ct = o.eAllContents();
				while (ct.hasNext()) {
					EObject cto = ct.next();
					if (cto instanceof RuleCall && rls.contains(((RuleCall) cto).getRule())) {
						r.add((T) o);
						break;
					}
				}
				i.prune();
			}
		}
	}
	return r;
}
 
Example 8
Source File: XtendCompiler.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected boolean needSyntheticSelfVariable(XClosure closure, LightweightTypeReference typeRef) {
	JvmType jvmType = typeRef.getType();
	TreeIterator<EObject> closureIterator = closure.eAllContents();
	while (closureIterator.hasNext()) {
		EObject obj1 = closureIterator.next();
		if (obj1 instanceof XClosure) {
			closureIterator.prune();
		} else if (obj1 instanceof XtendTypeDeclaration) {
			TreeIterator<EObject> typeIterator = obj1.eAllContents();
			while (typeIterator.hasNext()) {
				EObject obj2 = typeIterator.next();
				if (obj2 instanceof XClosure) {
					typeIterator.prune();
				} else if (obj2 instanceof XFeatureCall && isReferenceToSelf((XFeatureCall) obj2, jvmType)) {
					return true;
				}
			}
			closureIterator.prune();
		}
	}
	return false;
}
 
Example 9
Source File: DotFoldingRegionProvider.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
protected void computeObjectFolding(XtextResource xtextResource,
		IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor) {
	acceptedRegions.clear();

	IParseResult parseResult = xtextResource.getParseResult();
	if (parseResult != null) {
		EObject rootASTElement = parseResult.getRootASTElement();
		if (rootASTElement != null) {
			TreeIterator<EObject> allContents = rootASTElement
					.eAllContents();
			while (allContents.hasNext()) {
				EObject eObject = allContents.next();
				if (isHandled(eObject)) {
					computeObjectFolding(eObject, foldingRegionAcceptor);
				}
				if (eObject instanceof Attribute) {
					computeDotAttributeValueFolding((Attribute) eObject,
							foldingRegionAcceptor);
				}
				if (!shouldProcessContent(eObject)) {
					allContents.prune();
				}
			}
		}
	}
}
 
Example 10
Source File: ResourceDescription2.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected List<IReferenceDescription> computeReferenceDescriptions() {
  final ImmutableList.Builder<IReferenceDescription> referenceDescriptions = ImmutableList.builder();
  EcoreUtil2.resolveLazyCrossReferences(getResource(), CancelIndicator.NullImpl);
  Map<EObject, IEObjectDescription> eObject2exportedEObjects = createEObject2ExportedEObjectsMap(getExportedObjects());
  TreeIterator<EObject> contents = EcoreUtil.getAllProperContents(getResource(), true);
  while (contents.hasNext()) {
    EObject eObject = contents.next();
    URI exportedContainerURI = findExportedContainerURI(eObject, eObject2exportedEObjects);
    if (!strategy.createReferenceDescriptions(eObject, exportedContainerURI, referenceDescriptions::add)) {
      contents.prune();
    }
  }
  if (strategy instanceof AbstractResourceDescriptionStrategy) {
    ((AbstractResourceDescriptionStrategy) strategy).createImplicitReferenceDescriptions(getResource(), referenceDescriptions::add);
  }
  return referenceDescriptions.build();
}
 
Example 11
Source File: ConcreteSyntaxConstraintProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean ruleContainsRecursiveUnassignedRuleCall(AbstractRule rule, Set<AbstractRule> visited) {
	if (!visited.add(rule))
		return true;
	TreeIterator<EObject> i = rule.eAllContents();
	while (i.hasNext()) {
		EObject o = i.next();
		if (o instanceof Assignment)
			i.prune();
		else if (o instanceof RuleCall && isParserRule(((RuleCall) o).getRule())) {
			if (ruleContainsRecursiveUnassignedRuleCall(((RuleCall) o).getRule(), visited))
				return true;
		}
	}
	return false;
}
 
Example 12
Source File: EcoreUtilN4.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> List<T> getAllContentsOfTypeStopAt(boolean findFirst, EObject eobj, final Class<T> filterType,
		final EReference... stopReferences) {

	if (eobj == null) {
		return Collections.EMPTY_LIST;
	}

	List<EReference> stopReferencesL = Arrays.asList(stopReferences);
	List<T> contentList = new LinkedList<>();
	TreeIterator<EObject> tIter = eobj.eAllContents();

	while (tIter.hasNext()) {
		EObject eObj = tIter.next();
		EReference eRef = eObj.eContainmentFeature();
		if (stopReferencesL != null && stopReferencesL.contains(eRef)) {
			tIter.prune();
		} else {
			if (filterType.isInstance(eObj)) {
				contentList.add((T) eObj);
				if (findFirst) {
					return contentList;
				}
			}
		}
	}

	return contentList;
}
 
Example 13
Source File: ResourceDescription2.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create EObjectDescriptions for exported objects.
 *
 * @param resource
 *          LazyLinkingResource
 * @return list of object descriptions
 */
protected List<IEObjectDescription> createDescriptions(final LazyLinkingResource resource) {
  final ImmutableList.Builder<IEObjectDescription> exportedEObjects = ImmutableList.builder();
  IAcceptor<IEObjectDescription> acceptor = decorateExportedObjectsAcceptor(exportedEObjects::add);
  TreeIterator<EObject> allProperContents = EcoreUtil.getAllProperContents(resource, false);
  while (allProperContents.hasNext()) {
    EObject content = allProperContents.next();
    if (!strategy.createEObjectDescriptions(content, acceptor)) {
      allProperContents.prune();
    }
  }
  return exportedEObjects.build();
}
 
Example 14
Source File: XtendJvmModelInferrer.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
private void initializeLocalTypes(JvmFeature feature, XExpression expression) {
	if (expression != null) {
		TreeIterator<EObject> iterator = EcoreUtil2.getAllNonDerivedContents(expression, true);
		String nameStub = "__" + feature.getDeclaringType().getSimpleName();
		while(iterator.hasNext()) {
			EObject next = iterator.next();
			if (next.eClass() == XtendPackage.Literals.ANONYMOUS_CLASS) {
				inferLocalClass((AnonymousClass) next, nameStub, feature);
				iterator.prune();
			}
		}
	}
}
 
Example 15
Source File: TypeDeclarationAwareBatchTypeResolver.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Collects all Xtend type declarations and adds them to the list. The types are added
 * from the innermost to the outermost type declaration. That is, nested classes are 
 * added before their declarators are added. This greatly simplifies the implementation of
 * {@code isHandled} in the concrete {@link org.eclipse.xtext.xbase.typesystem.internal.AbstractRootedReentrantTypeResolver}.
 */
private void addXtendTypes(XtendTypeDeclaration declaration, List<EObject> result) {
	for(XtendMember member: declaration.getMembers()) {
		TreeIterator<EObject> iterator = EcoreUtil2.getAllNonDerivedContents(member, true);
		while(iterator.hasNext()) {
			EObject next = iterator.next();
			if (next instanceof XtendTypeDeclaration) {
				addXtendTypes((XtendTypeDeclaration) next, result);
				iterator.prune();
			}
		}
	}
	result.add(declaration);
}
 
Example 16
Source File: XtendHighlightingCalculator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void highlightRichStrings(XExpression expression, IHighlightedPositionAcceptor acceptor) {
	if (expression != null) {
		TreeIterator<EObject> iterator = EcoreUtil2.eAll(expression);
		while (iterator.hasNext()) {
			EObject object = iterator.next();
			if (object instanceof RichString) {
				RichStringHighlighter highlighter = createRichStringHighlighter(acceptor);
				processor.process((RichString) object, highlighter, indentationHandlerProvider.get());
				iterator.prune();
			}
		}
	}
}
 
Example 17
Source File: DefaultFoldingRegionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void computeObjectFolding(XtextResource xtextResource, IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor) {
	IParseResult parseResult = xtextResource.getParseResult();
	if(parseResult != null){
		EObject rootASTElement = parseResult.getRootASTElement();
		if(rootASTElement != null){
			if (cancelIndicator.isCanceled())
				throw new OperationCanceledException();
			if (isHandled(rootASTElement)) {
				computeObjectFolding(rootASTElement, foldingRegionAcceptor);
			}
			if (shouldProcessContent(rootASTElement)) {
				TreeIterator<EObject> allContents = rootASTElement.eAllContents();
				while (allContents.hasNext()) {
					if (cancelIndicator.isCanceled())
						throw new OperationCanceledException();
					EObject eObject = allContents.next();
					if (isHandled(eObject)) {
						computeObjectFolding(eObject, foldingRegionAcceptor);
					}
					if (!shouldProcessContent(eObject)) {
						allContents.prune();
					}
				}
			}
		}
	}
}
 
Example 18
Source File: DefaultSemanticHighlightingCalculator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void highlightElementRecursively(EObject element, IHighlightedPositionAcceptor acceptor,
		CancelIndicator cancelIndicator) {
	TreeIterator<EObject> iterator = EcoreUtil2.eAll(element);
	while (iterator.hasNext()) {
		EObject object = iterator.next();
		if (highlightElement(object, acceptor, cancelIndicator)) {
			iterator.prune();
		}
	}
}
 
Example 19
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkNoForwardReferences(XExpression fieldInitializer) {
	JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer);
	if (container instanceof JvmField) {
		JvmField field = (JvmField) container;
		boolean staticField = field.isStatic();
		JvmDeclaredType declaredType = field.getDeclaringType();
		if (declaredType == null) {
			return;
		}
		Collection<JvmField> illegalFields = Sets.newHashSet();
		for(int i = declaredType.getMembers().size() - 1; i>=0; i--) {
			JvmMember member = declaredType.getMembers().get(i);
			if (member instanceof JvmField) {
				if (((JvmField) member).isStatic() == staticField) {
					illegalFields.add((JvmField) member);
				}
			}
			if (member == field)
				break;
		}
		TreeIterator<EObject> iterator = EcoreUtil2.eAll(fieldInitializer);
		while(iterator.hasNext()) {
			EObject object = iterator.next();
			if (object instanceof XFeatureCall) {
				JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature();
				if (illegalFields.contains(((XFeatureCall) object).getFeature())) {
					error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", 
							object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE);
				}
			} else if (isLocalClassSemantics(object)) {
				iterator.prune();
			}
		}
	}
}
 
Example 20
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();
		}
	};

}