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

The following examples show how to use org.eclipse.emf.common.util.TreeIterator#hasNext() . 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: IndexTestLanguageGenerator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doGenerate(Resource input, IFileSystemAccess2 fsa, IGeneratorContext context) {
	TreeIterator<EObject> iter = input.getAllContents();
	while (iter.hasNext()) {
		EObject e = iter.next();
		if (e instanceof Entity) {
			Entity entity = (Entity) e;
			StringConcatenation builder = new StringConcatenation();
			builder.append("Hello ");
			builder.append(entity.getName());
			builder.append("!");
			builder.newLineIfNotEmpty();
			fsa.generateFile(entity.getName() + ".txt", builder);
		}
	}
}
 
Example 2
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 3
Source File: DefaultResourceDescription.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected List<IReferenceDescription> computeReferenceDescriptions() {
	final List<IReferenceDescription> referenceDescriptions = Lists.newArrayList();
	IAcceptor<IReferenceDescription> acceptor = new IAcceptor<IReferenceDescription>() {
		@Override
		public void accept(IReferenceDescription referenceDescription) {
			referenceDescriptions.add(referenceDescription);
		}
	};
	EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl);
	Map<EObject, IEObjectDescription> eObject2exportedEObjects = createEObject2ExportedEObjectsMap(getExportedObjects());
	TreeIterator<EObject> contents = EcoreUtil.getAllProperContents(this.resource, true);
	while (contents.hasNext()) {
		EObject eObject = contents.next();
		URI exportedContainerURI = findExportedContainerURI(eObject, eObject2exportedEObjects);
		if (!strategy.createReferenceDescriptions(eObject, exportedContainerURI, acceptor))
			contents.prune();
	}
	return referenceDescriptions;
}
 
Example 4
Source File: AbstractElementFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public List<Keyword> findKeywords(String... keywords) {
	Set<String> kwds = new HashSet<String>(Arrays.asList(keywords));
	ArrayList<Keyword> r = new ArrayList<Keyword>();
	for (AbstractRule ar : getRules()) {
		TreeIterator<EObject> i = ar.eAllContents();
		while (i.hasNext()) {
			EObject o = i.next();
			if (o instanceof Keyword) {
				Keyword k = (Keyword) o;
				if (kwds.contains(k.getValue()))
					r.add(k);
			}
		}
	}
	return r;
}
 
Example 5
Source File: DefaultResourceDescription.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected List<IEObjectDescription> computeExportedObjects() {
	if (!getResource().isLoaded()) {
		try {
			getResource().load(null);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return Collections.<IEObjectDescription> emptyList();
		}
	}
	final List<IEObjectDescription> exportedEObjects = newArrayList();
	IAcceptor<IEObjectDescription> acceptor = new IAcceptor<IEObjectDescription>() {
		@Override
		public void accept(IEObjectDescription eObjectDescription) {
			exportedEObjects.add(eObjectDescription);
		}
	};
	TreeIterator<EObject> allProperContents = EcoreUtil.getAllProperContents(getResource(), false);
	while (allProperContents.hasNext()) {
		EObject content = allProperContents.next();
		if (!strategy.createEObjectDescriptions(content, acceptor))
			allProperContents.prune();
	}
	return exportedEObjects;
}
 
Example 6
Source File: AbstractElementFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public List<Pair<Keyword, Keyword>> findKeywordPairs(String leftKw, String rightKw) {
	ArrayList<Pair<Keyword, Keyword>> pairs = new ArrayList<Pair<Keyword, Keyword>>();
	for (AbstractRule ar : getRules())
		if (ar instanceof ParserRule && !GrammarUtil.isDatatypeRule((ParserRule) ar)) {
			Stack<Keyword> openings = new Stack<Keyword>();
			TreeIterator<EObject> i = ar.eAllContents();
			while (i.hasNext()) {
				EObject o = i.next();
				if (o instanceof Keyword) {
					Keyword k = (Keyword) o;
					if (leftKw.equals(k.getValue()))
						openings.push(k);
					else if (rightKw.equals(k.getValue())) {
						if (openings.size() > 0)
							pairs.add(Tuples.create(openings.pop(), k));
					}
				}
			}
		}
	return pairs;
}
 
Example 7
Source File: GrammarElementDeclarationOrder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected GrammarElementDeclarationOrder(Grammar grammar) {
	elementIDCache = Maps.newHashMap();
	List<Grammar> grammars = Lists.newArrayList(grammar);
	grammars.addAll(GrammarUtil.allUsedGrammars(grammar));
	int counter = 0;
	for (Grammar g : grammars) {
		elementIDCache.put(g, counter++);
		for (AbstractRule rule : g.getRules()) {
			elementIDCache.put(rule, counter++);
			TreeIterator<EObject> iterator = rule.eAllContents();
			while (iterator.hasNext()) {
				elementIDCache.put(iterator.next(), counter++);
			}
		}
	}
}
 
Example 8
Source File: N4JSPostProcessor.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private static void exposeTypesReferencedBy(EObject root) {
	final TreeIterator<EObject> i = root.eAllContents();
	while (i.hasNext()) {
		final EObject object = i.next();
		for (EReference currRef : object.eClass().getEAllReferences()) {
			if (!currRef.isContainment() && !currRef.isContainer()) {
				final Object currTarget = object.eGet(currRef);
				if (currTarget instanceof Collection<?>) {
					for (Object currObj : (Collection<?>) currTarget) {
						exposeType(currObj);
					}
				} else {
					exposeType(currTarget);
				}
			}
		}
	}
}
 
Example 9
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 10
Source File: Oven.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void fireproof(String input) throws Exception {
	try {
		EObject file = parseHelper.parse(input);
		IResolvedTypes resolvedTypes = typeResolver.resolveTypes(file);
		Assert.assertNotNull(resolvedTypes);
		if (file != null) {
			TreeIterator<EObject> allContents = file.eAllContents();
			while (allContents.hasNext()) {
				EObject content = allContents.next();
				if (content instanceof XAbstractFeatureCall) {
					assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
					XAbstractFeatureCall abstractFeatureCall = (XAbstractFeatureCall) content;
					if (abstractFeatureCall.getImplicitReceiver() != null) {
						assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitReceiver(), resolvedTypes);
					}
					if (abstractFeatureCall.getImplicitFirstArgument() != null) {
						assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitFirstArgument(), resolvedTypes);
					}
				} else if (content instanceof XClosure) {
					assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
					for (JvmFormalParameter p : ((XClosure) content).getImplicitFormalParameters()) {
						assertIdentifiableTypeIsResolved(p, resolvedTypes);
					}
				} else if (content instanceof XExpression) {
					assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
				} else if (content instanceof JvmIdentifiableElement) {
					assertIdentifiableTypeIsResolved((JvmIdentifiableElement) content, resolvedTypes);
				}
			}
		}
	} catch (Throwable e) {
		ComparisonFailure error = new ComparisonFailure(e.getMessage(), input, "");
		error.setStackTrace(e.getStackTrace());
		throw error;
	}
}
 
Example 11
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 12
Source File: MappingHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void execute ( final IProgressMonitor monitor ) throws Exception
{
    monitor.setTaskName ( "Mapping elements" );

    this.parsedMappings = parse ();

    final TreeIterator<EObject> i = this.model.eAllContents ();
    while ( i.hasNext () )
    {
        final EObject o = i.next ();

        final String className = o.eClass ().getName ();

        final Set<String> features = this.parsedMappings.get ( className );
        if ( features == null )
        {
            continue;
        }
        for ( final String f : features )
        {
            final EStructuralFeature sf = o.eClass ().getEStructuralFeature ( f );
            if ( sf == null )
            {
                throw new RuntimeException ( String.format ( "Class %s does not have feature %s", className, f ) );
            }
            replaceName ( o, sf );
        }
    }
}
 
Example 13
Source File: N4JSCrossReferenceComputer.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Collects all Types, TVariables, TLiterals and IdentifiableElements that are directly referenced somewhere in the
 * given resource and aren't contained in this resource. References between AST element to its defined type and vice
 * versa as well as references to built-in and primitive types are ignored.
 *
 * @param resource
 *            the given fully resolved resource
 * @param acceptor
 *            the logic that collects the passed EObject found in a cross reference
 */
public void computeCrossRefs(Resource resource, IAcceptor<EObject> acceptor) {
	TreeIterator<EObject> allASTContentsIter;
	if (resource instanceof N4JSResource) {
		Script script = ((N4JSResource) resource).getScript();
		// We traverse the AST but not the TModule tree
		allASTContentsIter = script.eAllContents();
	} else {
		allASTContentsIter = resource.getAllContents();
	}
	while (allASTContentsIter.hasNext()) {
		EObject eObject = allASTContentsIter.next();
		computeCrossRefs(resource, eObject, acceptor);
	}
}
 
Example 14
Source File: AbstractTypeProviderPerformanceTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testLoadTypesAndResolveAllParameterNames() throws Exception {
	for (String name : getClassNamesToLoad()) {
		JvmDeclaredType type = loadAndResolve(name, true, true, true, true, true);
		TreeIterator<Object> iterator = EcoreUtil.getAllContents(type.eResource().getResourceSet(), true);
		while (iterator.hasNext()) {
			Object next = iterator.next();
			if (next instanceof JvmFormalParameter) {
				((JvmFormalParameter) next).getName();
			}
		}
	}
}
 
Example 15
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 16
Source File: DefaultCommentAssociater.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected EObject getEObjectForRemainingComments(ICompositeNode rootNode) {
	TreeIterator<INode> i = rootNode.getAsTreeIterable().iterator();
	while (i.hasNext()) {
		INode o = i.next();
		if (o.hasDirectSemanticElement())
			return o.getSemanticElement();
	}
	return null;
}
 
Example 17
Source File: N4JSValidationTestHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Asserts that root and the entire object tree below root does not contain any dangling references, i.e.
 * cross-references to target {@link EObject}s that are not contained in a {@link Resource}.
 */
public void assertNoDanglingReferences(EObject root) {
	final List<String> errMsgs = new ArrayList<>();
	final TreeIterator<EObject> iter = root.eAllContents();
	while (iter.hasNext()) {
		final EObject currObj = iter.next();
		if (currObj != null && !currObj.eIsProxy()) {
			for (EReference currRef : currObj.eClass().getEAllReferences()) {
				if (!currRef.isContainment() && !currRef.isContainer() && currRef.getEOpposite() == null) {
					if (currRef.isMany()) {
						@SuppressWarnings("unchecked")
						final EList<? extends EObject> targets = (EList<? extends EObject>) currObj.eGet(currRef,
								false);
						for (EObject currTarget : targets) {
							if (isDangling(currTarget)) {
								errMsgs.add(getErrorInfoForDanglingEObject(currObj, currRef));
								break;
							}
						}
					} else {
						final EObject target = (EObject) currObj.eGet(currRef, false);
						if (isDangling(target))
							errMsgs.add(getErrorInfoForDanglingEObject(currObj, currRef));
					}
				}
			}
		}
	}
	if (!errMsgs.isEmpty())
		fail("Expected no dangling references, but found the following: " + Joiner.on("; ").join(errMsgs) + ".");
}
 
Example 18
Source File: Linker.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void ensureModelLinked(EObject model, final IDiagnosticProducer producer) {
	boolean clearAllReferencesRequired = isClearAllReferencesRequired(model.eResource());
	TreeIterator<EObject> iterator = getAllLinkableContents(model);
	while(iterator.hasNext()) {
		EObject next = iterator.next();
		if (clearAllReferencesRequired) {
			clearReferences(next);
		}
		ensureLinked(next, producer);
	}
}
 
Example 19
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 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();
		}
	};

}