Java Code Examples for org.eclipse.xtext.EcoreUtil2

The following examples show how to use org.eclipse.xtext.EcoreUtil2. 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
@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 2
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 3
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 4
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 5
@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 6
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 7
@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 8
/**
 * 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 9
@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 10
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 11
Source Project: statecharts   Source File: SGenJavaValidator.java    License: 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 12
Source Project: n4js   Source File: TokenTypeRewriter.java    License: 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 13
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 14
/**
 * @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
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 16
Source Project: xsemantics   Source File: FjTypeSystem.java    License: 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 17
@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 18
Source Project: xtext-xtend   Source File: InsertionOffsets.java    License: 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 19
@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 20
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 21
@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 22
Source Project: xtext-web   Source File: OccurrencesService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Find occurrences of the element at the given offset.
 */
public OccurrencesResult findOccurrences(XtextWebDocumentAccess document, int offset) {
	return document.readOnly(new CancelableUnitOfWork<OccurrencesResult, IXtextWebDocument>() {
		@Override
		public OccurrencesResult exec(IXtextWebDocument doc, CancelIndicator cancelIndicator) throws Exception {
			EObject element = elementAtOffsetUtil.getElementAt(doc.getResource(), offset);
			OccurrencesResult occurrencesResult = new OccurrencesResult(doc.getStateId());
			if (element != null && filter(element)) {
				URI elementURI = EcoreUtil2.getPlatformResourceOrNormalizedURI(element);
				TargetURIs targetURIs = targetURIsProvider.get();
				targetURIs.addURI(elementURI);
				IReferenceFinder.Acceptor acceptor = new IReferenceFinder.Acceptor() {
					@Override
					public void accept(EObject source, URI sourceURI, EReference eReference, int index,
							EObject targetOrProxy, URI targetURI) {
						ITextRegion region = locationInFileProvider.getSignificantTextRegion(source, eReference,
								index);
						occurrencesResult.getReadRegions()
								.add(new TextRegion(region.getOffset(), region.getLength()));
					}

					@Override
					public void accept(IReferenceDescription description) {
					}
				};
				referenceFinder.findReferences(targetURIs, doc.getResource(), acceptor,
						new CancelIndicatorProgressMonitor(cancelIndicator));
				if (Objects.equal(element.eResource(), doc.getResource())) {
					ITextRegion definitionRegion = locationInFileProvider.getSignificantTextRegion(element);
					if (definitionRegion != null
							&& definitionRegion != ITextRegionWithLineInformation.EMPTY_REGION) {
						occurrencesResult.getWriteRegions()
								.add(new TextRegion(definitionRegion.getOffset(), definitionRegion.getLength()));
					}
				}
			}
			return occurrencesResult;
		}
	});
}
 
Example 23
public Operation_Compare resolveProxies(final Resource resource, final ResourceSet resourceSet) {
    EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl);
    final Operation_Compare compareOp = (Operation_Compare) resource.getContents().get(0);
    final List<Expression_ProcessRef> allRefs = modelSearch.getAllItemsOfType(compareOp, Expression_ProcessRef.class);
    for (final Expression_ProcessRef ref : allRefs) {
        final EObject proxy = ref.getValue();
        if (proxy.eIsProxy()) {
            ref.eSet(ConditionModelPackage.Literals.EXPRESSION_PROCESS_REF__VALUE, EcoreUtil.resolve(proxy, resourceSet));
        }
    }
    return compareOp;
}
 
Example 24
protected List<XAbstractFeatureCall> findFeatureCalls(final CharSequence expression) {
  try {
    final XExpression xExpression = this.expression(expression, false);
    final List<XAbstractFeatureCall> featureCalls = IteratorExtensions.<XAbstractFeatureCall>toList(Iterators.<XAbstractFeatureCall>filter(EcoreUtil2.eAll(xExpression), XAbstractFeatureCall.class));
    final Function1<XAbstractFeatureCall, Integer> _function = (XAbstractFeatureCall it) -> {
      return Integer.valueOf(IterableExtensions.<INode>head(NodeModelUtils.findNodesForFeature(it, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE)).getOffset());
    };
    return IterableExtensions.<XAbstractFeatureCall, Integer>sortBy(featureCalls, _function);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 25
Source Project: xtext-extras   Source File: Generator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void checkConfigurationInternal(Issues issues) {
	naming.setProjectNameRt(getProjectNameRt());
	naming.setProjectNameIde(getProjectNameIde());
	naming.setIdeBasePackage(!isIde() && isUi() ? getProjectNameUi() : getProjectNameIde());
	naming.setProjectNameUi(getProjectNameUi());
	naming.setUiBasePackage(getProjectNameUi());
	naming.setActivatorName(getActivator());
	naming.setPathTestProject(getPathTestProject());
	naming.setFileHeader(getFileHeader());
	naming.setClassAnnotations(getClassAnnotationsAsString());
	naming.setAnnotationImports(getAnnotationImportsAsString());
	naming.setHasUI(isUi());
	naming.setHasIde(isIde());
	Map<String, Grammar> uris = new HashMap<String, Grammar>();
	for (LanguageConfig config : languageConfigs) {
		config.registerNaming(naming);
		config.checkConfiguration(issues);
		Grammar grammar = config.getGrammar();
		List<GeneratedMetamodel> select = EcoreUtil2.typeSelect(grammar.getMetamodelDeclarations(),
				GeneratedMetamodel.class);
		for (GeneratedMetamodel generatedMetamodel : select) {
			String nsURI = generatedMetamodel.getEPackage().getNsURI();
			if (uris.containsKey(nsURI)) {
				issues.addError("Duplicate generated grammar with nsURI '" + nsURI + "' in "
						+ uris.get(nsURI).getName() + " and " + grammar.getName());
			} else {
				uris.put(nsURI, grammar);
			}
		}
	}
	if (getProjectNameRt() == null)
		issues.addError("The property 'projectNameRt' is mandatory");
	if (isUiMergedIntoRt() && getPathIdeProject() != null && ! isIdeMergedIntoRt()) {
		issues.addError("Cannot have a dedicated ide project when ui project is merged into runtime project");
	}
}
 
Example 26
@Override
protected void createCodeMinings(IDocument document, XtextResource resource, CancelIndicator indicator,
	IAcceptor<? super ICodeMining> acceptor) throws BadLocationException {

	EList<EObject> contents = resource.getContents();
	if (contents.isEmpty()) {
		return;
	}

	// get all evaluations contained by the open document
	List<Evaluation> allEvaluations = EcoreUtil2.eAllOfType(contents.get(0), Evaluation.class);

	// get keyword for ';'
	Keyword semicolon = grammar.getEvaluationAccess().getSemicolonKeyword_1();

	for (Evaluation evaluation : allEvaluations) {
		ICompositeNode node = NodeModelUtils.findActualNodeFor(evaluation);
		for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
			INode child = it.next();
			if (semicolon.equals(child.getGrammarElement())) {
				int annotationOffset = child.getTotalOffset();
				String annotationText = getAnnotationText(evaluation);
				acceptor.accept(createNewLineContentCodeMining(annotationOffset, annotationText));
			}
		}
	}
}
 
Example 27
Source Project: sarl   Source File: ExpressionBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
/** Create a reference to "this" object or to the current type.
 *
 * @return the reference.
 */
public XFeatureCall createReferenceToThis() {
	final XExpression expr = getXExpression();
	XtendTypeDeclaration type = EcoreUtil2.getContainerOfType(expr, XtendTypeDeclaration.class);
	JvmType jvmObject = getAssociatedElement(JvmType.class, type, expr.eResource());
	final XFeatureCall thisFeature = XbaseFactory.eINSTANCE.createXFeatureCall();
	thisFeature.setFeature(jvmObject);
	return thisFeature;
}
 
Example 28
Source Project: n4js   Source File: DeadCodeAnalyser.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** Finds the nearest reachable {@link Block} of the given {@link ControlFlowElement} */
private EObject getReachableContainer(Set<ControlFlowElement> unreachableElems, ControlFlowElement unreachableElem,
		Set<ControlFlowElement> moreUnreachableElems) {

	EObject elemContainer = unreachableElem.eContainer();
	if (elemContainer instanceof ExpressionStatement) {
		moreUnreachableElems.add((ExpressionStatement) elemContainer);
	}

	EObject block = EcoreUtil2.getContainerOfType(unreachableElem, Block.class);
	if (block == null) {
		block = EcoreUtil2.getContainerOfType(unreachableElem, Script.class);
	}

	EObject blockContainer = block.eContainer();
	boolean isDeadContainer = blockContainer instanceof ControlFlowElement;
	isDeadContainer &= isDeadContainer && FGUtils.isControlStatement((ControlFlowElement) blockContainer);
	isDeadContainer &= isDeadContainer && isDeadCode((ControlFlowElement) blockContainer);

	if (isDeadContainer) {
		ControlFlowElement cfe = (ControlFlowElement) blockContainer;
		moreUnreachableElems.add(cfe);
		return getReachableContainer(unreachableElems, cfe, moreUnreachableElems);
	}

	return block;
}
 
Example 29
private String _getLabel(final Operation it) {
  StringConcatenation _builder = new StringConcatenation();
  String _name = EcoreUtil2.<TypeDeclaration>getContainerOfType(it, TypeDeclaration.class).getName();
  _builder.append(_name);
  _builder.append(".");
  String _name_1 = it.getName();
  _builder.append(_name_1);
  _builder.append("(");
  {
    EList<Parameter> _params = it.getParams();
    boolean _hasElements = false;
    for(final Parameter p : _params) {
      if (!_hasElements) {
        _hasElements = true;
      } else {
        _builder.appendImmediate(", ", "");
      }
      String _name_2 = p.getName();
      _builder.append(_name_2);
      _builder.append(": ");
      String _label = this.getLabel(p.getType());
      _builder.append(_label);
    }
  }
  _builder.append("): ");
  {
    Type _returnType = it.getReturnType();
    boolean _tripleEquals = (_returnType == null);
    if (_tripleEquals) {
      _builder.append("void");
    } else {
      String _label_1 = this.getLabel(it.getReturnType());
      _builder.append(_label_1);
    }
  }
  return _builder.toString();
}
 
Example 30
/**
 * Returns fully qualified name of the model type which formatting is described by the given rule.
 *
 * @param rule
 *          a grammar rule
 * @return fully qualified name of the model type
 */
public String getModelTypeName(final GrammarRule rule) {
  String ruleName = rule.getTargetRule().getName();
  String ruleContainingGrammarName = rule.getTargetRule().getType().getMetamodel().getAlias();
  String grammarElementName = "com.avaloq.tools.dsl." + ruleContainingGrammarName + "." + ruleContainingGrammarName + "." + ruleName;
  if (ruleContainingGrammarName == null) {
    grammarElementName = EcoreUtil2.getContainerOfType(rule.getTargetRule().getType().getMetamodel(), Grammar.class).getName().toLowerCase() + "." + ruleName;
  }
  return grammarElementName;
}