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

The following examples show how to use org.eclipse.emf.common.util.TreeIterator. 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: DefaultImportsConfiguration.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@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 #2
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 #3
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.6
 */
public static TreeIterator<EObject> getAllNonDerivedContents(EObject root, boolean includeRoot) {
	/*
	 * We cannot simply use root.eAllContents here since the iterator
	 * will probe for #hasNext on each invocation of #next. This is usually
	 * not a problem but with derived containment, it becomes an issue.
	 * For example, the accessor of XAbstractFeatureCall#getImplicitReceiver uses #getFeature
	 * to initialize itself. This will cause the potential proxy feature
	 * to be resolved which in turn tries to access the mapped proxy URI fragments
	 * in the resource. Now these fragments are currently in the process of being
	 * updated, e.g. there may not even be enough entries. Thus #getFeature
	 * shall not be called here. Long story short, this iterator filters
	 * derived containment features.
	 */
	return new AbstractTreeIterator<EObject>(root, includeRoot) {
		private static final long serialVersionUID = 1L;

		@Override
		public Iterator<EObject> getChildren(Object object) {
			EObject eObject = (EObject) object;
			return getNonDerivedContents(eObject);
		}

	};
}
 
Example #4
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public static final EPackage loadEPackage(String uriAsString, ClassLoader classLoader) {
	if (EPackage.Registry.INSTANCE.containsKey(uriAsString))
		return EPackage.Registry.INSTANCE.getEPackage(uriAsString);
	URI uri = URI.createURI(uriAsString);
	uri = new ClassloaderClasspathUriResolver().resolve(classLoader, uri);
	Resource resource = new ResourceSetImpl().getResource(uri, true);
	for (TreeIterator<EObject> allContents = resource.getAllContents(); allContents.hasNext();) {
		EObject next = allContents.next();
		if (next instanceof EPackage) {
			EPackage ePackage = (EPackage) next;
			// if (ePackage.getNsURI() != null &&
			// ePackage.getNsURI().equals(uriAsString)) {
			return ePackage;
			// }
		}
	}
	log.error("Could not load EPackage with nsURI" + uriAsString);
	return null;
}
 
Example #5
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isRangePartOfExceedingLookAhead(final CompositeNode node, final ReplaceRegion replaceRegion) {
  TreeIterator<AbstractNode> iterator = node.basicIterator();
  int lookAhead = node.getLookAhead();
  if (lookAhead == 0) {
    return false;
  }
  while (iterator.hasNext()) {
    AbstractNode child = iterator.next();
    if (child instanceof CompositeNode) {
      if (child.getTotalOffset() < replaceRegion.getEndOffset()) {
        lookAhead = Math.max(((CompositeNode) child).getLookAhead(), lookAhead);
      }
    } else if (!((ILeafNode) child).isHidden()) {
      lookAhead--;
      if (lookAhead == 0) {
        if (child.getTotalOffset() >= replaceRegion.getEndOffset()) {
          return false;
        }
      }
    }
  }
  return lookAhead > 0;
}
 
Example #6
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 #7
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 #8
Source File: LazyLinker.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void doLinkModel(final EObject model, IDiagnosticConsumer consumer) {
	final Multimap<EStructuralFeature.Setting, INode> settingsToLink = ArrayListMultimap.create();
	final LinkingDiagnosticProducer producer = new LinkingDiagnosticProducer(consumer);
	cache.execWithoutCacheClear(model.eResource(), new IUnitOfWork.Void<Resource>() {
		@Override
		public void process(Resource state) throws Exception {
			TreeIterator<EObject> iterator = getAllLinkableContents(model);
			boolean clearAllReferencesRequired = isClearAllReferencesRequired(state);
			while (iterator.hasNext()) {
				EObject eObject = iterator.next();
				if (clearAllReferencesRequired) {
					clearReferences(eObject);
				}
				installProxies(eObject, producer, settingsToLink);
			}
		}
	});
	installQueuedLinks(settingsToLink);
}
 
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: 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 #11
Source File: AbstractElementFinder.java    From xtext-core with 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 #12
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 #13
Source File: XbaseUsageCrossReferencer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@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 #14
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 #15
Source File: XbaseCompiler.java    From xtext-extras with 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 #16
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 #17
Source File: EMFGeneratorFragment.java    From xtext-extras with 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 #18
Source File: ProxyCompositeNode.java    From dsl-devkit with 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 #19
Source File: TypeComputationStateTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@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 #20
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 #21
Source File: TypeComputationStateTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@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 #22
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 #23
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 #24
Source File: EPackageChooser.java    From xtext-eclipse with 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 #25
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 #26
Source File: MyGenerator.java    From xtext-eclipse with 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 #27
Source File: DerivedMemberAwareEditorOpener.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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 #28
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 #29
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 #30
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;
}