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

The following examples show how to use org.eclipse.emf.common.util.TreeIterator#next() . 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: ArithmeticsValidator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkNormalizable(Expression expr) {
	if (expr instanceof NumberLiteral || expr instanceof FunctionCall) {
		return;
	}
	Evaluation eval = EcoreUtil2.getContainerOfType(expr, Evaluation.class);
	if (eval != null) {
		return;
	}
	TreeIterator<EObject> contents = expr.eAllContents();
	while (contents.hasNext()) {
		EObject next = contents.next();
		if ((next instanceof FunctionCall)) {
			return;
		}
	}
	BigDecimal decimal = calculator.evaluate(expr);
	if (decimal.toString().length() <= 8) {
		warning("Expression could be normalized to constant \'" + decimal + "\'", null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
				ArithmeticsValidator.NORMALIZABLE, decimal.toString());
	}
}
 
Example 3
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 4
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 5
Source File: TypeComputationStateTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Ignore("TODO FixMe")
@Test
public void testTypeOnlyRegisteredOnce_03() throws Exception {
	XMemberFeatureCall expression = ((XMemberFeatureCall) expression("<String>newArrayList.map[toUpperCase]"));
	resolver.initializeFrom(expression);
	PublicResolvedTypes resolution = new PublicResolvedTypes(resolver);
	AnyTypeReference any = resolution.getReferenceOwner().newAnyTypeReference();
	new ExpressionBasedRootTypeComputationState(resolution, resolver.getBatchScopeProvider().newSession(expression.eResource()),
			expression, any).computeTypes();
	Map<XExpression, List<TypeData>> expressionTypes = resolution.basicGetExpressionTypes();
	TreeIterator<EObject> allContents = expression.eAllContents();
	while (allContents.hasNext()) {
		EObject o = allContents.next();
		List<TypeData> typesForMemberFeatureCall = expressionTypes.get((o));
		assertEquals(o + " " + typesForMemberFeatureCall.toString(), 1,
				IterableExtensions.size(filter(typesForMemberFeatureCall, it -> it.isReturnType())));
		assertEquals(typesForMemberFeatureCall.toString(), 1,
				IterableExtensions.size(filter(typesForMemberFeatureCall, it -> !it.isReturnType())));
	}
}
 
Example 6
Source File: ConcreteSyntaxConstraintProvider.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean ruleContainsAssignedAction(AbstractRule rule, Set<AbstractRule> visited) {
	if (!visited.add(rule))
		return false;
	TreeIterator<EObject> i = rule.eAllContents();
	while (i.hasNext()) {
		EObject o = i.next();
		if (o instanceof Action && ((Action) o).getFeature() != null)
			return true;
		else if (o instanceof Assignment)
			i.prune();
		else if (o instanceof RuleCall && isParserRule(((RuleCall) o).getRule())) {
			if (ruleContainsAssignedAction(((RuleCall) o).getRule(), visited))
				return true;
		}
	}
	return false;
}
 
Example 7
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 8
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 9
Source File: StratumBreakpointAdapterFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected String getClassNamePattern(XtextResource state) {
	TreeIterator<Object> contents = EcoreUtil.getAllContents(state, false);
	StringBuilder sb = new StringBuilder();
	while (contents.hasNext()) {
		Object next = contents.next();
		if (next instanceof JvmDeclaredType) {
			JvmDeclaredType type = (JvmDeclaredType) next;
			sb.append(type.getQualifiedName()).append("*");
			sb.append(",");
		}
	}
	if (sb.length() == 0)
		return null;
	else
		return sb.substring(0, sb.length() - 1);
}
 
Example 10
Source File: SoliditySemanticHighlighter.java    From solidity-ide with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void provideHighlightingFor(XtextResource resource, IHighlightedPositionAcceptor acceptor,
		CancelIndicator cancelIndicator) {
	TreeIterator<EObject> allContents = resource.getAllContents();
	while (allContents.hasNext()) {
		EObject next = allContents.next();
		if (next.eIsProxy()) {
			continue;
		}
		if (next instanceof ContractDefinition) {
			ContractDefinition definition = (ContractDefinition) next;
			provideHighligtingFor(definition, acceptor);
		}
		if (next instanceof Operation) {
			Operation operation = (Operation) next;
			provideHighligtingFor(operation, acceptor);
		}
		if (next instanceof Block) {
			Block block = (Block) next;
			provideHighligtingFor(block, acceptor);
		}
		if (next instanceof ElementReferenceExpression) {
			ElementReferenceExpression expression = (ElementReferenceExpression) next;
			provideHighligtingFor(expression, acceptor);
		}
	}
}
 
Example 11
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void replaceReferencesInGeneratedPackages(final List<EPackage> generatedPackages, final Map<EObject, EObject> eNamedElementMapping) {
  final TreeIterator<EObject> packageContentIterator = EcoreUtil.<EObject>getAllContents(generatedPackages);
  while (packageContentIterator.hasNext()) {
    {
      final EObject current = packageContentIterator.next();
      EList<EStructuralFeature> _eAllStructuralFeatures = current.eClass().getEAllStructuralFeatures();
      final EStructuralFeature[] crossReferenceFeatures = ((EClassImpl.FeatureSubsetSupplier) _eAllStructuralFeatures).crossReferences();
      if ((crossReferenceFeatures != null)) {
        for (final EStructuralFeature crossReferenceFeature : crossReferenceFeatures) {
          boolean _isChangeable = crossReferenceFeature.isChangeable();
          if (_isChangeable) {
            final EReference reference = ((EReference) crossReferenceFeature);
            boolean _isMany = reference.isMany();
            if (_isMany) {
              Object _eGet = current.eGet(reference);
              final List<EObject> values = ((List<EObject>) _eGet);
              for (final EObject value : values) {
                boolean _containsKey = eNamedElementMapping.containsKey(value);
                if (_containsKey) {
                  EcoreUtil.replace(current, reference, value, eNamedElementMapping.get(value));
                }
              }
            } else {
              Object _eGet_1 = current.eGet(reference);
              final EObject value_1 = ((EObject) _eGet_1);
              boolean _containsKey_1 = eNamedElementMapping.containsKey(value_1);
              if (_containsKey_1) {
                EcoreUtil.replace(current, reference, value_1, eNamedElementMapping.get(value_1));
              }
            }
          }
        }
      }
    }
  }
}
 
Example 12
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 13
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void validateInferredType(JvmTypeReference inferredType, XtendMember member, String messagePrefix,
		EAttribute location) {
	if (inferredType != null) {
		TreeIterator<EObject> iterator = EcoreUtil2.eAll(inferredType);
		while(iterator.hasNext()) {
			EObject next = iterator.next();
			if (next instanceof JvmParameterizedTypeReference) {
				JvmParameterizedTypeReference candidate = (JvmParameterizedTypeReference) next;
				JvmType type = candidate.getType();
				if (type instanceof JvmGenericType && !((JvmGenericType) type).getTypeParameters().isEmpty()) {
					if (candidate.getArguments().isEmpty()) {
						StringBuilder message = new StringBuilder(messagePrefix);
						message = proxyAwareUIStrings.visit(inferredType, message);
						if (message != null) {
							message.append(" uses the raw type ");
							message.append(type.getSimpleName());
							message.append(". References to generic type ");
							message = proxyAwareUIStrings.appendTypeSignature(type, message);
							message.append(" should be parameterized");
							warning(message.toString(), member, location, org.eclipse.xtext.xbase.validation.IssueCodes.RAW_TYPE);
						}
						return;
					}
				}
			} else if (next instanceof XComputedTypeReference) {
				validateInferredType(((XComputedTypeReference) next).getEquivalent(), member, messagePrefix, location);
				iterator.prune();
			}
		}
	}
}
 
Example 14
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 15
Source File: UserContentManager.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Launch Parsing.
 */
private void launchParsing() {
    IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query
            .newEnvironmentWithDefaultServices(null);
    mapIdUserContent = new HashMap<>();
    if (memoryCopy != null) {
        try {
            userDocDocument = M2DocUtils.parseUserContent(uriConverter, memoryCopy, queryEnvironment);
            final TreeIterator<EObject> iter = userDocDocument.eAllContents();
            while (iter.hasNext()) {
                EObject eObject = iter.next();
                if (eObject instanceof UserContent) {
                    UserContent userContent = (UserContent) eObject;
                    storeUserContent(mapIdUserContent, userContent);
                }
            }
            // CHECKSTYLE:OFF
        } catch (Exception e) {
            // CHECKSTYLE:ON
            // In this case, we do nothing.
            // The old output doc is not a docx document and it will be overwrite at current generation.
            // And we have nothing to extract from a no docx file.
        } finally {
            uriConverter.getURIHandlers().remove(uriHandler);
            uriHandler.clear();
        }
    }
}
 
Example 16
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 17
Source File: TypeWalker.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected void walk ( final TreeIterator<?> iterator, final TypeVisitor<? super T> visitor ) throws Exception
{
    while ( iterator.hasNext () )
    {
        final Object o = iterator.next ();
        if ( this.clazz.isAssignableFrom ( o.getClass () ) )
        {
            visitor.visit ( this.clazz.cast ( o ) );
        }
    }
}
 
Example 18
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 19
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 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();
		}
	};

}