Java Code Examples for org.eclipse.emf.common.util.TreeIterator

The following examples show how to use org.eclipse.emf.common.util.TreeIterator. These examples are extracted from open source projects. 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 Project: n4js   Source File: TranspilerUtils.java    License: 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 Project: n4js   Source File: TranspilerUtils.java    License: 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 Project: n4js   Source File: N4JSPostProcessor.java    License: 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 4
Source Project: n4js   Source File: GlobalObjectScope.java    License: 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
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 6
Source Project: xtext-extras   Source File: XbaseValidator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected boolean hasConstructorCallWithThis(JvmConstructor constr) {
	XExpression associatedExpression = logicalContainerProvider.getAssociatedExpression(constr);
	if (associatedExpression == null) {
		return false;
	}
	TreeIterator<EObject> contents = associatedExpression.eAllContents();
	while (contents.hasNext()) {
		EObject next = contents.next();
		if (next instanceof XFeatureCall) {
			XFeatureCall featureCall = (XFeatureCall) next;
			if (featureCall.getFeature() instanceof JvmConstructor && featureCall.getConcreteSyntaxFeatureName().equals(IFeatureNames.THIS.toString())) {
				return true;
			}
		}
	}
	return false;
}
 
Example 7
Source Project: xtext-extras   Source File: XbaseValidator.java    License: 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 8
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 9
Source Project: dsl-devkit   Source File: ResourceDescription2.java    License: 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 10
@Override
protected TreeIterator<Notifier> newContentsIterator() {
	return new ContentTreeIterator<Notifier>(emfObjects) {
		private static final long serialVersionUID = 1L;

		@Override
		protected Iterator<? extends EObject> getEObjectChildren(EObject eObject) {
			if(eObject instanceof XAbstractFeatureCall){
				Iterable<EObject> result = eObject.eContents();
				XAbstractFeatureCall featureCall = (XAbstractFeatureCall) eObject;
				XExpression implicitReceiver = featureCall.getImplicitReceiver();
				if(implicitReceiver != null) 
					result = Iterables.concat(result, Collections.singleton(implicitReceiver));
				XExpression implicitFirstArgument = featureCall.getImplicitFirstArgument();
				if(implicitFirstArgument != null)
					result = Iterables.concat(result, Collections.singleton(implicitFirstArgument));
				return result.iterator();
			} else 
				return super.getEObjectChildren(eObject);
		}
	};
}
 
Example 11
Source Project: xtext-extras   Source File: XbaseCompiler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected boolean canCompileToJavaLambda(XClosure closure, LightweightTypeReference typeRef, JvmOperation operation) {
	if (!typeRef.isInterfaceType())
		return false;
	
	if (!operation.getTypeParameters().isEmpty())
		return false;
	
	TreeIterator<EObject> iterator = closure.eAllContents();
	JvmType jvmType = typeRef.getType();
	while (iterator.hasNext()) {
		EObject obj = iterator.next();
		if (obj instanceof XClosure) {
			iterator.prune();
		} else if (obj instanceof XFeatureCall && isReferenceToSelf((XFeatureCall) obj, jvmType)) {
			return false;
		}
	}
	return true;
}
 
Example 12
@Override
public Iterable<JvmDeclaredType> getLocallyDefinedTypes(XtextResource resource) {
	final List<JvmDeclaredType> locallyDefinedTypes = newArrayList();
	for (TreeIterator<EObject> i = resource.getAllContents(); i.hasNext();) {
		EObject next = i.next();
		if (next instanceof JvmDeclaredType) {
			JvmDeclaredType declaredType = (JvmDeclaredType) next;
			locallyDefinedTypes.add(declaredType);
			addInnerTypes(declaredType, new IAcceptor<JvmDeclaredType>() {
				@Override
				public void accept(JvmDeclaredType t) {
					locallyDefinedTypes.add(t);
				}
			});
			i.prune();
		}
		if(next instanceof XExpression) {
			i.prune();
		}
	}
	return locallyDefinedTypes;
}
 
Example 13
Source Project: xtext-extras   Source File: EMFGeneratorFragment.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, EPackage> findAllUsedEPackages(List<EPackage> generatedPackages) {
	Map<String, EPackage> result = Maps.newHashMap();
	TreeIterator<EObject> packageContentIterator = EcoreUtil.<EObject>getAllContents(generatedPackages);
	while(packageContentIterator.hasNext()) {
		EObject current = packageContentIterator.next();
		for(EObject referenced: current.eCrossReferences()) {
			if (referenced.eIsProxy())
				throw new RuntimeException("Unresolved proxy: " + referenced + " in " + current);
			if (referenced instanceof EClassifier) {
				EPackage referencedPackage = ((EClassifier) referenced).getEPackage();
				if (!generatedPackages.contains(referencedPackage)) {
					result.put(referencedPackage.getNsURI(), referencedPackage);
				}
			}
		}
	}
	return result;
}
 
Example 14
@Test
public void testTypeOnlyRegisteredOnce_02() throws Exception {
	XMemberFeatureCall expression = ((XMemberFeatureCall) expression("1.toString"));
	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> types = expressionTypes.get(o);
		assertEquals(types.toString(), 1, size(filter(types, it -> !it.isReturnType())));
	}
}
 
Example 15
@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 16
@Test
public void testTypeOnlyRegisteredOnce_04() throws Exception {
	XNumberLiteral expression = ((XNumberLiteral) expression("1"));
	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> types = expressionTypes.get((o));
		assertEquals(types.toString(), 1, size(filter(types, it -> !it.isReturnType())));
	}
}
 
Example 17
Source Project: xtext-eclipse   Source File: EPackageChooser.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected List<EPackageInfo> createEPackageInfosFromGenModel(URI genModelURI) {
	ResourceSet resourceSet = createResourceSet(genModelURI);
	Resource resource = resourceSet.getResource(genModelURI, true);
	List<EPackageInfo> ePackageInfos = Lists.newArrayList();
	for (TreeIterator<EObject> i = resource.getAllContents(); i.hasNext();) {
		EObject next = i.next();
		if (next instanceof GenPackage) {
			GenPackage genPackage = (GenPackage) next;
			EPackage ePackage = genPackage.getEcorePackage();
			URI importURI;
			if(ePackage.eResource() == null) {
				importURI = URI.createURI(ePackage.getNsURI());
			} else {
				importURI = ePackage.eResource().getURI();
			}
			EPackageInfo ePackageInfo = new EPackageInfo(ePackage, importURI, genModelURI, genPackage
					.getQualifiedPackageInterfaceName(), genPackage.getGenModel().getModelPluginID());
			ePackageInfos.add(ePackageInfo);
		} else if (!(next instanceof GenModel)) {
			i.prune();
		}
	}
	return ePackageInfos;
}
 
Example 18
@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 19
Source Project: xtext-eclipse   Source File: MyGenerator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doGenerate(Resource input, IFileSystemAccess fsa) {
	TreeIterator<EObject> allContents = input.getAllContents();
	while (allContents.hasNext()) {
		EObject next = allContents.next();
		if (next instanceof Element) {
			Element ele = (Element) next;
			String fileName = ele.getName() + ".txt";
			if (fsa instanceof IFileSystemAccess2) {
				IFileSystemAccess2 fileSystemAccess2 = (IFileSystemAccess2) fsa;
				if (fileSystemAccess2.isFile(fileName)) {
					fileSystemAccess2.readTextFile(fileName);
				}
			}
			fsa.generateFile(fileName, "object " + ele.getName());
		}
	}
}
 
Example 20
@Override
protected EObject findEObjectByURI(URI uri, XtextResource resource) {
	if (uri.query() != null) {
		String identifier = uri.query();
		TreeIterator<EObject> contents = EcoreUtil.<EObject>getAllContents(resource, true);
		while(contents.hasNext()) {
			EObject content = contents.next();
			if (content instanceof JvmMember) {
				String identifierFromResource = ((JvmIdentifiableElement) content).getIdentifier();
				if (identifier.equals(identifierFromResource)) {
					EObject sourceElement = associations.getPrimarySourceElement(content);
					return sourceElement;
				}
			}
		}
	}
	return super.findEObjectByURI(uri, resource);
}
 
Example 21
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 22
Source Project: xtext-xtend   Source File: XtendCompiler.java    License: 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 23
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 24
@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 25
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 26
Source Project: dsl-devkit   Source File: ProxyCompositeNode.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Uninstalls the proxy node model in the given resource (if present).
 *
 * @param resource
 *          resource, must not be {@code null}
 * @return original EObject ID map or {@code null} if no proxied node model was present
 */
static List<EObject> uninstallProxyNodeModel(final Resource resource) {
  List<EObject> result = null;
  if (!resource.getContents().isEmpty()) {
    EObject root = resource.getContents().get(0);
    ProxyCompositeNode proxyNode = uninstallProxyNode(root);
    if (proxyNode != null) {
      result = proxyNode.idToEObjectMap;
      for (TreeIterator<EObject> it = root.eAllContents(); it.hasNext();) {
        uninstallProxyNode(it.next());
      }
    }
  }

  if (resource instanceof XtextResource) {
    ((XtextResource) resource).setParseResult(null);
  }
  return result;
}
 
Example 27
@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 28
Source Project: xtext-core   Source File: AbstractElementFinder.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public List<CrossReference> findCrossReferences(EClassifier... targetEClassifiers) {
	Set<EClassifier> classifiers = new HashSet<EClassifier>(Arrays.asList(targetEClassifiers));
	Collection<EClass> classes = Lists.newArrayList(Iterables.filter(classifiers, EClass.class));
	ArrayList<CrossReference> r = new ArrayList<CrossReference>();
	for (AbstractRule ar : getRules()) {
		TreeIterator<EObject> i = ar.eAllContents();
		while (i.hasNext()) {
			EObject o = i.next();
			if (o instanceof CrossReference) {
				CrossReference c = (CrossReference) o;
				if (classifiers.contains(c.getType().getClassifier()))
					r.add(c);
				else if (c.getType().getClassifier() instanceof EClass)
					for (EClass cls : classes)
						if (EcoreUtil2.isAssignableFrom(cls,(EClass) c.getType().getClassifier())) {
							r.add(c);
							break;
						}
				i.prune();
			}
		}
	}
	return r;

}
 
Example 29
Source Project: xtext-core   Source File: AbstractElementFinder.java    License: 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 30
Source Project: xtext-core   Source File: AbstractElementFinder.java    License: 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;
}