org.eclipse.xtext.EcoreUtil2 Java Examples

The following examples show how to use org.eclipse.xtext.EcoreUtil2. 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: TokenTypeRewriter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private static void rewriteIdentifiers(N4JSGrammarAccess ga,
		ImmutableMap.Builder<AbstractElement, Integer> builder) {
	ImmutableSet<AbstractRule> identifierRules = ImmutableSet.of(
			ga.getBindingIdentifierRule(),
			ga.getIdentifierNameRule(),
			ga.getIDENTIFIERRule());
	for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) {
		for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) {
			if (obj instanceof Assignment) {
				Assignment assignment = (Assignment) obj;
				AbstractElement terminal = assignment.getTerminal();
				int type = InternalN4JSParser.RULE_IDENTIFIER;
				if (terminal instanceof CrossReference) {
					terminal = ((CrossReference) terminal).getTerminal();
					type = IDENTIFIER_REF_TOKEN;
				}
				if (terminal instanceof RuleCall) {
					AbstractRule calledRule = ((RuleCall) terminal).getRule();
					if (identifierRules.contains(calledRule)) {
						builder.put(assignment, type);
					}
				}
			}
		}
	}
}
 
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: TypeReferenceProviderImpl.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public JvmParameterizedTypeReference createTypeRef(final JvmType type, final JvmTypeReference... typeArgs) {
  if ((type == null)) {
    throw new NullPointerException("type");
  }
  final JvmParameterizedTypeReference reference = TypesFactory.eINSTANCE.createJvmParameterizedTypeReference();
  reference.setType(type);
  for (final JvmTypeReference typeArg : typeArgs) {
    reference.getArguments().add(EcoreUtil2.<JvmTypeReference>cloneIfContained(typeArg));
  }
  if ((type instanceof JvmGenericType)) {
    final EList<JvmTypeParameter> list = ((JvmGenericType)type).getTypeParameters();
    if (((!reference.getArguments().isEmpty()) && (list.size() != reference.getArguments().size()))) {
      String _identifier = ((JvmGenericType)type).getIdentifier();
      String _plus = ("The type " + _identifier);
      String _plus_1 = (_plus + " expects ");
      int _size = list.size();
      String _plus_2 = (_plus_1 + Integer.valueOf(_size));
      String _plus_3 = (_plus_2 + " type arguments, but was ");
      int _size_1 = reference.getArguments().size();
      String _plus_4 = (_plus_3 + Integer.valueOf(_size_1));
      String _plus_5 = (_plus_4 + ". Either pass zero arguments (raw type) or the correct number.");
      throw new IllegalArgumentException(_plus_5);
    }
  }
  return reference;
}
 
Example #4
Source File: SCTDiagnosticConverterImpl.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void convertValidatorDiagnostic(final Diagnostic diagnostic, final IAcceptor<Issue> acceptor) {
	super.convertValidatorDiagnostic(diagnostic, new IAcceptor<Issue>() {
		@Override
		public void accept(Issue t) {
			boolean notAccepted = true;
			if (diagnostic.getData().get(0) instanceof EObject) {
				EObject eObject = (EObject) diagnostic.getData().get(0);
				if (eObject != null && eObject.eResource() != null) {
					if (NodeModelUtils.getNode(eObject) != null) {
						eObject = EcoreUtil2.getContainerOfType(eObject, SpecificationElement.class);
					}
					if (eObject != null && eObject.eResource() != null) {
						acceptor.accept(issueCreator.create(t, eObject.eResource().getURIFragment(eObject)));
						notAccepted = false;
					}
				}
			}
			if (notAccepted) {
				acceptor.accept(t);
			}
		}
	});
}
 
Example #5
Source File: ExtractMethodRefactoring.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected List<XExpression> calculateExpressions(final List<XExpression> expressions) {
	final XExpression firstExpression = expressions.get(0);
	// If there is a XVariableDeclaration selected and there is a usage of that variable outside of the selected expressions, we need to take the right side
	// instead of the complete XVariableDeclaration
	if(expressions.size() == 1 && firstExpression instanceof XVariableDeclaration){
		final XtendFunction originalMethod = EcoreUtil2.getContainerOfType(firstExpression, XtendFunction.class);
		for (final EObject element : Iterables.filter(EcoreUtil2.eAllContents(originalMethod.getExpression()), new Predicate<EObject>() {
			@Override
			public boolean apply(EObject input) {
				return !EcoreUtil.isAncestor(expressions, input);
			}
		}
		)){
			if (element instanceof XFeatureCall) {
				XFeatureCall featureCall = (XFeatureCall) element;
				JvmIdentifiableElement feature = featureCall.getFeature();
				if(EcoreUtil.isAncestor(expressions, feature)){
					return singletonList(((XVariableDeclaration) firstExpression).getRight());
				}
			}
		}
	}
	return expressions;
}
 
Example #6
Source File: XFunctionTypeRefImplCustom.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected JvmTypeReference getJavaLangObjectTypeRef(JvmType rawType, TypesFactory typesFactory) {
	ResourceSet rs = EcoreUtil2.getResourceSet(rawType);
	JvmParameterizedTypeReference refToObject = typesFactory.createJvmParameterizedTypeReference();
	if (rs != null) {
		EObject javaLangObject = rs.getEObject(javaLangObjectURI, true);
		if (javaLangObject instanceof JvmType) {
			JvmType objectDeclaration = (JvmType) javaLangObject;
			refToObject.setType(objectDeclaration);
			return refToObject;
		}
	}
	JvmGenericType proxy = typesFactory.createJvmGenericType();
	((InternalEObject)proxy).eSetProxyURI(javaLangObjectURI);
	refToObject.setType(proxy);
	return refToObject;
}
 
Example #7
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected int[] getOffsetAndLength(XIfExpression ifExpression, ICompositeNode node) {
	int offset = node.getOffset();
	int length = node.getLength();
	if (ifExpression.getElse() != null) {
		ICompositeNode elseNode = NodeModelUtils.findActualNodeFor(ifExpression.getElse());
		if (elseNode != null) {
			length = elseNode.getOffset() - offset;
		}
	} else {
		XIfExpression parentIfExpression = EcoreUtil2.getContainerOfType(ifExpression.eContainer(),
				XIfExpression.class);
		if (parentIfExpression != null && parentIfExpression.getElse() == ifExpression) {
			ICompositeNode thenNode = NodeModelUtils.findActualNodeFor(parentIfExpression.getThen());
			if (thenNode != null) {
				int endOffset = thenNode.getEndOffset();
				length = length + (offset - endOffset);
				offset = endOffset;
			}
		}
	}
	return new int[] { offset, length };
}
 
Example #8
Source File: EventDrivenSimulationEngine.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void notifyChanged(Notification notification) {
	// Only run cycle if responsible for this kind of notification
	if (EcoreUtil2.getContainerOfType((EObject) notification.getNotifier(),
			ExecutionContext.class) != interpreter.getExecutionContext()) {
		return;
	}
	super.notifyChanged(notification);
	if (notification.getNotifier() instanceof ExecutionEvent
			&& notification.getFeature() == SRuntimePackage.Literals.EXECUTION_EVENT__RAISED) {
		ExecutionEvent event = (ExecutionEvent) notification.getNotifier();
		if (notification.getNewBooleanValue() != notification.getOldBooleanValue()) {
			if (notification.getNewBooleanValue() && event.getDirection() != Direction.OUT) {
				if (!suspended)
					interpreter.runCycle();
				else {
					cycleAfterResume = true;
				}
			}
		}
	}

}
 
Example #9
Source File: InsertionOffsets.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public int getNewFieldInsertOffset(final EObject call, final XtendTypeDeclaration ownerType) {
  boolean _isEmpty = ownerType.getMembers().isEmpty();
  if (_isEmpty) {
    return this.inEmpty(ownerType);
  }
  final XtendField callingMember = EcoreUtil2.<XtendField>getContainerOfType(call, XtendField.class);
  if (((callingMember != null) && ownerType.getMembers().contains(callingMember))) {
    return this.before(callingMember);
  }
  final XtendField lastDefinedField = IterableExtensions.<XtendField>last(Iterables.<XtendField>filter(ownerType.getMembers(), XtendField.class));
  if ((lastDefinedField == null)) {
    return this.before(IterableExtensions.<XtendMember>head(ownerType.getMembers()));
  } else {
    return this.after(lastDefinedField);
  }
}
 
Example #10
Source File: JvmAnnotationTargetImpl.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public AnnotationReference addAnnotation(final AnnotationReference annotationReference) {
  AnnotationReference _xblockexpression = null;
  {
    this.checkMutable();
    Preconditions.checkArgument((annotationReference != null), "annotationReference cannot be null");
    AnnotationReference _xifexpression = null;
    if ((annotationReference instanceof JvmAnnotationReferenceImpl)) {
      AnnotationReference _xblockexpression_1 = null;
      {
        final JvmAnnotationReference jvmAnnotationReference = EcoreUtil2.<JvmAnnotationReference>cloneWithProxies(((JvmAnnotationReferenceImpl)annotationReference).getDelegate());
        EList<JvmAnnotationReference> _annotations = this.getDelegate().getAnnotations();
        _annotations.add(jvmAnnotationReference);
        _xblockexpression_1 = this.getCompilationUnit().toAnnotationReference(jvmAnnotationReference);
      }
      _xifexpression = _xblockexpression_1;
    } else {
      StringConcatenation _builder = new StringConcatenation();
      _builder.append(annotationReference);
      _builder.append(" is not annotation reference");
      throw new IllegalArgumentException(_builder.toString());
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #11
Source File: ConcreteSyntaxAwareReferenceFinder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void checkValue(EObject value, Resource localResource, Predicate<URI> targetURIs, EObject sourceCandidate,
		URI sourceURI, EReference ref, Acceptor acceptor) {
	EObject instanceOrProxy = toValidInstanceOrNull(localResource, targetURIs,
			value);

	if (instanceOrProxy != null) {
		URI refURI = EcoreUtil2.getPlatformResourceOrNormalizedURI(instanceOrProxy);
		// CUSTOM BEHAVIOR: handle composed members
		if (referenceHasBeenFound(targetURIs, refURI, instanceOrProxy)) {
			sourceURI = (sourceURI == null) ? EcoreUtil2
					.getPlatformResourceOrNormalizedURI(sourceCandidate) : sourceURI;
			acceptor.accept(sourceCandidate, sourceURI, ref, -1, instanceOrProxy, refURI);
		}
	}

}
 
Example #12
Source File: CachingDeclaredTypeFactory.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public JvmDeclaredType createType(BinaryClass clazz) {
	try {
		JvmDeclaredType cachedResult = get(clazz);
		// the cached result contains proxies and is not 
		// contained in a resource set. clone it since the
		// client of #createClass will usually put the result
		// into a resource and perform proxy resolution afterwards
		// in the context of a single resource set.
		return EcoreUtil2.cloneWithProxies(cachedResult);
	} catch (Exception e) {
		if (log.isDebugEnabled()) {
			log.debug(e.getMessage(), e);
		}
		return delegate.createType(clazz);
	}
}
 
Example #13
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Not a full featured solution for the computation of available structural features, but it is sufficient for some
 * interesting 85%.
 */
@Override
public void completeAssignment_Feature(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	AbstractRule rule = EcoreUtil2.getContainerOfType(model, AbstractRule.class);
	TypeRef typeRef = rule.getType();
	if (typeRef != null && typeRef.getClassifier() instanceof EClass) {
		Iterable<EStructuralFeature> features = ((EClass) typeRef.getClassifier()).getEAllStructuralFeatures();
		Function<IEObjectDescription, ICompletionProposal> factory = getProposalFactory(grammarAccess.getValidIDRule().getName(), context);
		Iterable<String> processedFeatures = completeStructuralFeatures(context, factory, acceptor, features);
		if(rule.getType().getMetamodel() instanceof GeneratedMetamodel) {
			if(notNull(rule.getName()).toLowerCase().startsWith("import")) {
				completeSpecialAttributeAssignment("importedNamespace", 2, processedFeatures, factory, context, acceptor); 
				completeSpecialAttributeAssignment("importURI", 1, processedFeatures, factory, context, acceptor); 
			} else {
				completeSpecialAttributeAssignment("name", 3, processedFeatures, factory, context, acceptor); 
			}
		}
	}
	super.completeAssignment_Feature(model, assignment, context, acceptor);
}
 
Example #14
Source File: UnresolvedFeatureCallTypeAwareMessageProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @Nullable
 */
protected String getTypeName(final EClass c, final EStructuralFeature referingFeature) {
  if ((referingFeature == XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE)) {
    return " to an annotation type";
  }
  if ((c == TypesPackage.Literals.JVM_ENUMERATION_TYPE)) {
    return " to an enum type";
  }
  boolean _isAssignableFrom = EcoreUtil2.isAssignableFrom(TypesPackage.Literals.JVM_TYPE, c);
  if (_isAssignableFrom) {
    return " to a type";
  }
  if ((c == TypesPackage.Literals.JVM_OPERATION)) {
    return " to an operation";
  }
  return "";
}
 
Example #15
Source File: LayeredTypeResourceDescription.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Iterable<IEObjectDescription> getExportedObjectsByObject(final EObject object) {
	final URI uri = EcoreUtil2.getPlatformResourceOrNormalizedURI(object);
	Iterable<IEObjectDescription> additionallyFiltered = Iterables.filter(getExportedObjects(), new Predicate<IEObjectDescription>() {
		@Override
		public boolean apply(IEObjectDescription input) {
			if (input.getEObjectOrProxy() == object)
				return true;
			if (uri.equals(input.getEObjectURI())) {
				return true;
			}
			return false;
		}
	});
	return Iterables.concat(delegate.getExportedObjectsByObject(object), additionallyFiltered);
}
 
Example #16
Source File: XbaseHighlightingCalculator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void computeReferencedJvmTypeHighlighting(IHighlightedPositionAcceptor acceptor, EObject referencer,
		CancelIndicator cancelIndicator) {
	for (EReference reference : referencer.eClass().getEAllReferences()) {
		EClass referencedType = reference.getEReferenceType();
		if (EcoreUtil2.isAssignableFrom(TypesPackage.Literals.JVM_TYPE, referencedType)) {
			List<EObject> referencedObjects = EcoreUtil2.getAllReferencedObjects(referencer, reference);
			if (referencedObjects.size() > 0)
				operationCanceledManager.checkCanceled(cancelIndicator);
			for (EObject referencedObject : referencedObjects) {
				EObject resolvedReferencedObject = EcoreUtil.resolve(referencedObject, referencer);
				if (resolvedReferencedObject != null && !resolvedReferencedObject.eIsProxy()) {
					highlightReferenceJvmType(acceptor, referencer, reference, resolvedReferencedObject);
				}
			}
		}
	}
}
 
Example #17
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 #18
Source File: SGenJavaValidator.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
@Check
public void checkRequiredFeatures(GeneratorEntry entry) {
	GeneratorModel model = (GeneratorModel) EcoreUtil2.getRootContainer(entry);

	Optional<IGeneratorDescriptor> generatorDescriptor = GeneratorExtensions
			.getGeneratorDescriptor(model.getGeneratorId());
	if (!generatorDescriptor.isPresent()) {
		return;
	}
	Iterable<ILibraryDescriptor> libraryDescriptors = LibraryExtensions
			.getLibraryDescriptors(generatorDescriptor.get().getLibraryIDs());

	Iterable<FeatureType> requiredFeatures = filter(
			concat(transform(transform(libraryDescriptors, getFeatureTypeLibrary()), getFeatureTypes())),
			isRequired());
	List<String> configuredTypes = Lists.newArrayList();
	for (FeatureConfiguration featureConfiguration : entry.getFeatures()) {
		configuredTypes.add(featureConfiguration.getType().getName());
	}
	for (FeatureType featureType : requiredFeatures) {
		if (!configuredTypes.contains(featureType.getName()))
			error(String.format(MISSING_REQUIRED_FEATURE + " %s", featureType.getName()),
					SGenPackage.Literals.GENERATOR_ENTRY__ELEMENT_REF, CODE_REQUIRED_FEATURE,
					featureType.getName());
	}
}
 
Example #19
Source File: LoadOnDemandResourceDescriptions.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public IResourceDescription getResourceDescription(URI uri) {
	IResourceDescription result = delegate.getResourceDescription(uri);
	if (result == null) {
		Resource resource = EcoreUtil2.getResource(context, uri.toString());
		if (resource != null) {
			IResourceServiceProvider serviceProvider = serviceProviderRegistry.getResourceServiceProvider(uri);
			if (serviceProvider==null)
				throw new IllegalStateException("No "+IResourceServiceProvider.class.getSimpleName()+" found in registry for uri "+uri);
			final Manager resourceDescriptionManager = serviceProvider.getResourceDescriptionManager();
			if (resourceDescriptionManager == null)
				throw new IllegalStateException("No "+IResourceDescription.Manager.class.getName()+" provided by service provider for URI "+uri);
			result = resourceDescriptionManager.getResourceDescription(resource);
		}
	}
	return result;
}
 
Example #20
Source File: FjTypeSystem.java    From xsemantics with Eclipse Public License 1.0 6 votes vote down vote up
protected List<Field> applyAuxFunFields(final RuleApplicationTrace _trace_, final org.eclipse.xsemantics.example.fj.fj.Class clazz) throws RuleFailedException {
  ArrayList<Field> _xblockexpression = null;
  {
    Iterable<Field> fields = new ArrayList<Field>();
    List<org.eclipse.xsemantics.example.fj.fj.Class> _superclasses = this.superclassesInternal(_trace_, clazz);
    for (final org.eclipse.xsemantics.example.fj.fj.Class superclass : _superclasses) {
      List<Field> _typeSelect = EcoreUtil2.<Field>typeSelect(superclass.getMembers(), Field.class);
      Iterable<Field> _plus = Iterables.<Field>concat(_typeSelect, fields);
      fields = _plus;
    }
    List<Field> _typeSelect_1 = EcoreUtil2.<Field>typeSelect(clazz.getMembers(), Field.class);
    Iterable<Field> _plus_1 = Iterables.<Field>concat(fields, _typeSelect_1);
    fields = _plus_1;
    _xblockexpression = (Lists.<Field>newArrayList(fields));
  }
  return _xblockexpression;
}
 
Example #21
Source File: ImportUriProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected boolean isValidUri(Resource context, URI uri) {
	boolean validURI = EcoreUtil2.isValidUri(context, uri);
	if (!validURI) {
		return getConverter().exists(uri, null);
	}
	return true;
}
 
Example #22
Source File: DomainSpecificTaskFinder.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<Task> findTasks(Resource resource) {
	if (resource instanceof AbstractSCTResource) {
		IDomain domain = DomainRegistry.getDomain(
				(EObject) EcoreUtil2.getObjectByType(resource.getContents(), SGraphPackage.Literals.STATECHART));
		ITaskFinder taskFinder = domain.getInjector(IDomain.FEATURE_RESOURCE).getInstance(ITaskFinder.class);
		if (taskFinder != null)
			return taskFinder.findTasks(resource);
	}
	return Collections.emptyList();
}
 
Example #23
Source File: DefaultReferenceFinder.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Deprecated
protected Map<EObject, URI> createExportedElementsMap(final Resource resource) {
	return new ForwardingMap<EObject, URI>() {

		private Map<EObject, URI> delegate;
		
		@Override
		protected Map<EObject, URI> delegate() {
			if (delegate != null) {
				return delegate;
			}
			URI uri = EcoreUtil2.getPlatformResourceOrNormalizedURI(resource);
			IResourceServiceProvider resourceServiceProvider = getServiceProviderRegistry().getResourceServiceProvider(uri);
			if (resourceServiceProvider == null) {
				return delegate = Collections.emptyMap();
			}
			IResourceDescription.Manager resourceDescriptionManager = resourceServiceProvider.getResourceDescriptionManager();
			if (resourceDescriptionManager == null) {
				return delegate = Collections.emptyMap();
			}
			IResourceDescription resourceDescription = resourceDescriptionManager.getResourceDescription(resource);
			Map<EObject, URI> exportedElementMap = newIdentityHashMap();
			if (resourceDescription != null) {
				for (IEObjectDescription exportedEObjectDescription : resourceDescription.getExportedObjects()) {
					EObject eObject = resource.getEObject(exportedEObjectDescription.getEObjectURI().fragment());
					if (eObject != null)
						exportedElementMap.put(eObject, exportedEObjectDescription.getEObjectURI());
				}
			}
			return delegate = exportedElementMap;
		}

		
	};
}
 
Example #24
Source File: SARLValidator.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isInitialized(JvmField input) {
	if (super.isInitialized(input)) {
		return true;
	}
	// Check initialization into a static constructor.
	final XtendField sarlField = (XtendField) this.associations.getPrimarySourceElement(input);
	if (sarlField == null) {
		return false;
	}
	final XtendTypeDeclaration declaringType = sarlField.getDeclaringType();
	if (declaringType == null) {
		return false;
	}
	for (final XtendConstructor staticConstructor : Iterables.filter(Iterables.filter(
			declaringType.getMembers(), XtendConstructor.class), it -> it.isStatic())) {
		if (staticConstructor.getExpression() != null) {
			for (final XAssignment assign : EcoreUtil2.getAllContentsOfType(staticConstructor.getExpression(), XAssignment.class)) {
				if (assign.isStatic() && Strings.equal(input.getIdentifier(), assign.getFeature().getIdentifier())) {
					// Mark the field as initialized in order to be faster during the next initialization test.
					this.readAndWriteTracking.markInitialized(input, null);
					return true;
				}
			}
		}
	}
	return false;
}
 
Example #25
Source File: CharSequenceTraceWrapper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public CharSequence wrapWithTraceData(CharSequence sequence, EObject origin) {
	ITextRegionWithLineInformation location = (ITextRegionWithLineInformation) locationInFileProvider.getSignificantTextRegion(origin);
	AbsoluteURI absoluteURI = new AbsoluteURI(origin.eResource().getURI());
	IProjectConfig projectConfig = projectConfigProvider.getProjectConfig(EcoreUtil2.getResourceSet(origin));
	SourceRelativeURI sourceRelativeURI = absoluteURI.deresolve(projectConfig);
	return wrapWithTraceData(sequence, sourceRelativeURI, location.getOffset(), location.getLength(), location.getLineNumber(), location.getEndLineNumber());
}
 
Example #26
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void completeAction_Feature(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	Action action = EcoreUtil2.getContainerOfType(model, Action.class);
	if (action != null && action.getType() != null) {
		EClassifier classifier = action.getType().getClassifier();
		if (classifier instanceof EClass) {
			List<EReference> containments = ((EClass) classifier).getEAllContainments();
			Function<IEObjectDescription, ICompletionProposal> factory = getProposalFactory(grammarAccess.getValidIDRule().getName(), context);
			completeStructuralFeatures(context, factory, acceptor, containments);
		}
	}
	super.completeAction_Feature(model, assignment, context, acceptor);
}
 
Example #27
Source File: XtextGrammarRefactoringIntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private EReference getReferenceoGreeting(Resource ecoreResource, final EClassifier classifier) {
	final EReference greetingRef = Iterables
			.filter(EcoreUtil2.getAllContentsOfType(ecoreResource.getContents().get(0), EReference.class),
					new Predicate<EReference>() {
						@Override
						public boolean apply(EReference input) {
							return input.getEType() == classifier;
						}
					}).iterator().next();
	return greetingRef;
}
 
Example #28
Source File: OpenFileContext.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
public void resolveOpenFile(CancelIndicator cancelIndicator) {
	// resolve
	EcoreUtil2.resolveLazyCrossReferences(mainResource, cancelIndicator);
	// update dirty state
	updateSharedDirtyState();
	// notify open file listeners
	parent.onDidRefreshOpenFile(this, cancelIndicator);
}
 
Example #29
Source File: EventDrivenSimulationEngine.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void notifyChanged(Notification notification) {
	// Only run cycle if responsible for this kind of notification
	if (EcoreUtil2.getContainerOfType((EObject) notification.getNotifier(),
			ExecutionContext.class) != interpreter.getExecutionContext()) {
		return;
	}
	super.notifyChanged(notification);
	if (notification.getNotifier() instanceof ExecutionEvent
			&& notification.getFeature() == SRuntimePackage.Literals.EXECUTION_EVENT__RAISED) {
		ExecutionEvent event = (ExecutionEvent) notification.getNotifier();
		if (notification.getNewBooleanValue() != notification.getOldBooleanValue()) {
			if (notification.getNewBooleanValue() && event.getDirection() == Direction.OUT) {
				// an out event was raised => check if there is a parent execution context that
				// contains a corresponding shadow event
				ExecutionContext thisContext = interpreter.getExecutionContext();
				if (thisContext.getName() == null || thisContext.getName().isEmpty()) {
					return;
				}
				ExecutionContext parentContext = EcoreUtil2.getContainerOfType(thisContext.eContainer(),
						ExecutionContext.class);
				if (parentContext == null) {
					return;
				}
				ExecutionEvent shadowEvent = findShadowEvent(event, parentContext);
				if (shadowEvent == null) {
					return;
				}
				// raise shadow event
				Optional<IExecutionFlowInterpreter> parentInterpreter = interpreterProvider
						.findInterpreter(parentContext);
				if (parentInterpreter.isPresent() && parentInterpreter.get() instanceof IEventRaiser) {
					((IEventRaiser) parentInterpreter.get()).raise(shadowEvent, event.getValue());
				}
			}
		}
	}
}
 
Example #30
Source File: CompilerPhases.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public boolean isIndexing(Notifier ctx) {
	ResourceSet set = EcoreUtil2.getResourceSet(ctx);
	if (set != null) {
		return EcoreUtil.getAdapter(set.eAdapters(), IndexingAdapter.INSTANCE) != null;
	}
	return false;
}