Java Code Examples for org.eclipse.xtext.EcoreUtil2#getContainerOfType()

The following examples show how to use org.eclipse.xtext.EcoreUtil2#getContainerOfType() . 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: TargetURIKey.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void addFQNs(EObject object) {
	QualifiedName fullyQualifiedName = null;
	if (object instanceof TMember || object instanceof TEnumLiteral) {
		Type t = EcoreUtil2.getContainerOfType(object.eContainer(), Type.class);
		fullyQualifiedName = qualifiedNameProvider.getFullyQualifiedName(t);
	} else if (object instanceof Type) {
		fullyQualifiedName = qualifiedNameProvider.getFullyQualifiedName(object);
	} else if (object instanceof TModule) {
		fullyQualifiedName = qualifiedNameProvider.getFullyQualifiedName(object);
	} else if (object instanceof IdentifiableElement) {
		TModule containingModule = ((IdentifiableElement) object).getContainingModule();
		fullyQualifiedName = qualifiedNameProvider.getFullyQualifiedName(containingModule);
	}

	if (fullyQualifiedName != null) { // remove this when GH-733 is fixed
		typesOrModulesToFind.add(fullyQualifiedName);
	}
}
 
Example 2
Source File: ExtractMethodRefactoring.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public boolean initialize(XtextEditor editor, List<XExpression> selectedExpressions, boolean doSave) {
	if(selectedExpressions.isEmpty() || editor.getDocument() == null)
		return false;
	this.document = editor.getDocument();
	this.doSave = doSave;
	this.editor = editor;
	this.expressions = calculateExpressions(selectedExpressions);
	this.firstExpression = this.expressions.get(0);
	this.originalMethod = EcoreUtil2.getContainerOfType(firstExpression, XtendFunction.class);
	this.lastExpression = this.expressions.get(this.expressions.size()-1);
	this.resourceURI = EcoreUtil2.getPlatformResourceOrNormalizedURI(firstExpression).trimFragment();
	this.xtendClass = EcoreUtil2.getContainerOfType(firstExpression, XtendClass.class);
	if (xtendClass == null || originalMethod == null)
		return false;
	this.visibility = JvmVisibility.PROTECTED;
	this.isStatic = originalMethod.isStatic();
	this.isExplicitlyDeclareReturnType = true;
	XExpression successorExpression = expressionUtil
			.findSuccessorExpressionForVariableDeclaration(lastExpression);
	nameUtil.setFeatureScopeContext(successorExpression);
	rewriter = rewriterFactory.create(document, (XtextResource) firstExpression.eResource());
	return true;
}
 
Example 3
Source File: N4JSDReader.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The method {@link TModule#getTopLevelTypes()} returns also functions that are nested in functions. These are
 * filtered out in this method.
 *
 * @return real top level types
 */
private Collection<Type> getRealTopLevelTypes(Script script) {
	Collection<Type> realTLT = new LinkedList<>();
	for (Type tlt : script.getModule().getTopLevelTypes()) {
		if (tlt instanceof SyntaxRelatedTElement) {
			SyntaxRelatedTElement srte = (SyntaxRelatedTElement) tlt;
			EObject astElem = srte.getAstElement();
			astElem = astElem != null ? astElem.eContainer() : null;
			FunctionOrFieldAccessor fofa = EcoreUtil2.getContainerOfType(astElem, FunctionOrFieldAccessor.class);
			if (fofa != null) {
				continue;
			}
		}

		realTLT.add(tlt);
	}
	return realTLT;
}
 
Example 4
Source File: CheckCompiler.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
// CHECKSTYLE:OFF
@SuppressWarnings("restriction")
protected JvmType findEPackageInterfaceType(final ENamedElement element, final EObject context) {
  // CHECKSTYLE:ON
  EPackage ePackage = EcoreUtil2.getContainerOfType(element, EPackage.class);
  String qualifiedPackageInterfaceName = CheckGenModelUtil.getQualifiedPackageInterfaceName(ePackage);
  return getTypeComputationServices().getTypeReferences().findDeclaredType(qualifiedPackageInterfaceName, context);
}
 
Example 5
Source File: STextExtensions.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public Statechart getStatechart(EObject context) {
	final ContextElementAdapter provider = getContextElementAdapter(context.eResource());

	if (provider == null || provider.getElement() == null || provider.getElement().eResource() == null) {
		return EcoreUtil2.getContainerOfType(context, Statechart.class);
	} else {
		return (Statechart) EcoreUtil.getObjectByType(provider.getElement().eResource().getContents(),
				SGraphPackage.Literals.STATECHART);
	}
}
 
Example 6
Source File: JavaElementDelegate.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected JvmIdentifiableElement findAssociatedJvmElement(EObject element) {
	if (element == null)
		return null;
	Set<EObject> elements = associations.getJvmElements(element);
	if (elements.isEmpty()) {
		return findAssociatedJvmElement(element.eContainer());
	}
	EObject next = elements.iterator().next();
	if (next instanceof JvmIdentifiableElement)
		return (JvmIdentifiableElement) next;
	return EcoreUtil2.getContainerOfType(next, JvmIdentifiableElement.class);
}
 
Example 7
Source File: SARLValidator.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public void checkAnnotationTarget(XAnnotation annotation) {
	super.checkAnnotationTarget(annotation);
	if (isForbiddenActiveAnnotation(annotation)) {
		error(Messages.SARLValidator_89,
				annotation,
				null,
				ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
				FORBIDDEN_REFERENCE);
	} else if (isOOActiveAnnotation(annotation) || isAOActiveAnnotation(annotation)) {
		XtendTypeDeclaration container = EcoreUtil2.getContainerOfType(annotation.eContainer(), XtendTypeDeclaration.class);
		while (container != null && (container.isAnonymous() || container.getName() == null)) {
			container = EcoreUtil2.getContainerOfType(container.eContainer(), XtendTypeDeclaration.class);
		}
		if (container != null) {
			if (isOOType(container)) {
				if (!isOOActiveAnnotation(annotation)) {
					error(MessageFormat.format(Messages.SARLValidator_34, container.getName()),
							annotation,
							null,
							ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
							FORBIDDEN_REFERENCE);
				}
			} else {
				if (!isAOActiveAnnotation(annotation) || !isAOActiveAnnotationReceiver(container)) {
					error(MessageFormat.format(Messages.SARLValidator_90, container.getName()),
							annotation,
							null,
							ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
							FORBIDDEN_REFERENCE);
				}
			}
		}
	}
}
 
Example 8
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
/** Replies the outer-most type of the given member.
 * @return the container of {@code XtendTypeDeclaration} type if it exists, or the direct container.
 */
protected final EObject getOutermostType(XtendMember member) {
	XtendTypeDeclaration result = EcoreUtil2.getContainerOfType(member, XtendTypeDeclaration.class);
	if (result == null) {
		return member.eContainer();
	}
	while(!(result.eContainer() instanceof XtendFile)) {
		XtendTypeDeclaration next = EcoreUtil2.getContainerOfType(result.eContainer(), XtendTypeDeclaration.class);
		if (next == null) {
			return result;
		}
		result = next;
	}
	return result;
}
 
Example 9
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkActionInUnorderedGroup(final Action action) {
	if (EcoreUtil2.getContainerOfType(action, UnorderedGroup.class) != null)
		addIssue("Actions may not be used in unordered groups.", 
				action, 
				null,
				INVALID_ACTION_USAGE);
}
 
Example 10
Source File: DotOutlineTreeProvider.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected EObjectNode createEObjectNode(IOutlineNode parentNode,
		EObject modelElement, Image image, Object text, boolean isLeaf) {
	if (EcoreUtil2.getContainerOfType(modelElement,
			HtmlLabel.class) != null) {
		// in case of a html-like label addition offset should be calculated
		EObjectNode eObjectNode = new EObjectNode(modelElement, parentNode,
				image, text, isLeaf);
		ICompositeNode parserNode = NodeModelUtils.getNode(modelElement);
		if (parserNode != null) {
			ITextRegion parserNodeTextRegion = parserNode.getTextRegion();
			ITextRegion newTextRegion = new TextRegion(
					parserNodeTextRegion.getOffset()
							+ attributeValueStartOffset,
					parserNodeTextRegion.getLength());
			eObjectNode.setTextRegion(newTextRegion);
		}
		if (isLocalElement(parentNode, modelElement)) {
			ITextRegion significantTextRegion = locationInFileProvider
					.getSignificantTextRegion(modelElement);
			ITextRegion shortTextRegion = new TextRegion(
					significantTextRegion.getOffset()
							+ attributeValueStartOffset,
					significantTextRegion.getLength());
			eObjectNode.setShortTextRegion(shortTextRegion);
		}
		return eObjectNode;
	} else {
		return super.createEObjectNode(parentNode, modelElement, image,
				text, isLeaf);
	}

}
 
Example 11
Source File: InsertionOffsets.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public int getNewMethodInsertOffset(final EObject call, final XtendTypeDeclaration ownerType) {
  final XtendMember callingMember = EcoreUtil2.<XtendMember>getContainerOfType(call, XtendMember.class);
  if (((callingMember != null) && ownerType.getMembers().contains(callingMember))) {
    return this.after(callingMember);
  } else {
    boolean _isEmpty = ownerType.getMembers().isEmpty();
    if (_isEmpty) {
      return this.inEmpty(ownerType);
    } else {
      return this.after(IterableExtensions.<XtendMember>last(ownerType.getMembers()));
    }
  }
}
 
Example 12
Source File: UnresolvedAnnotationTypeAwareMessageProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isPropertyOfUnresolvedAnnotation(ILinkingDiagnosticContext context) {
	EObject object = context.getContext();
	if (object instanceof XAnnotationElementValuePair && context.getReference() == XAnnotationsPackage.Literals.XANNOTATION_ELEMENT_VALUE_PAIR__ELEMENT) {
		XAnnotation annotation = EcoreUtil2.getContainerOfType(object, XAnnotation.class);
		if (annotation != null) {
			JvmType annotationType = annotation.getAnnotationType();
			if (annotationType == null || annotationType.eIsProxy() || !(annotationType instanceof JvmAnnotationType)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 13
Source File: CodetemplatesProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected TemplateData(EObject model) {
	template = EcoreUtil2.getContainerOfType(model, Codetemplate.class);
	if (template != null) {
		templates = EcoreUtil2.getContainerOfType(template, Codetemplates.class);
		language = templates.getLanguage();
		rule = template.getContext();
	}
}
 
Example 14
Source File: Declarators.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public Declarators.DeclaratorsData getDeclaratorData(final TargetURIs targetURIs, final IReferenceFinder.IResourceAccess resourceAccess) {
  Declarators.DeclaratorsData result = targetURIs.<Declarators.DeclaratorsData>getUserData(Declarators.KEY);
  if ((result != null)) {
    return result;
  }
  final HashSet<QualifiedName> declaratorNames = CollectionLiterals.<QualifiedName>newHashSet();
  final Consumer<URI> _function = (URI uri) -> {
    final IUnitOfWork<Object, ResourceSet> _function_1 = (ResourceSet it) -> {
      Object _xblockexpression = null;
      {
        final Consumer<URI> _function_2 = (URI objectURI) -> {
          final EObject object = it.getEObject(objectURI, true);
          if ((object != null)) {
            final JvmType type = EcoreUtil2.<JvmType>getContainerOfType(object, JvmType.class);
            if ((type != null)) {
              QualifiedName _lowerCase = this.nameConverter.toQualifiedName(type.getIdentifier()).toLowerCase();
              declaratorNames.add(_lowerCase);
              QualifiedName _lowerCase_1 = this.nameConverter.toQualifiedName(type.getQualifiedName('.')).toLowerCase();
              declaratorNames.add(_lowerCase_1);
            }
          }
        };
        targetURIs.getEObjectURIs(uri).forEach(_function_2);
        _xblockexpression = null;
      }
      return _xblockexpression;
    };
    resourceAccess.<Object>readOnly(uri, _function_1);
  };
  targetURIs.getTargetResourceURIs().forEach(_function);
  Declarators.DeclaratorsData _declaratorsData = new Declarators.DeclaratorsData(declaratorNames);
  result = _declaratorsData;
  targetURIs.<Declarators.DeclaratorsData>putUserData(Declarators.KEY, result);
  return result;
}
 
Example 15
Source File: TypeUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Type references may be nested within other type references, e.g. the members of a union type. This method will
 * return the outermost type reference that contains the given type reference but is not itself contained in another
 * type reference, or the given type reference if it is not contained in another type reference.
 * <p>
 * Returns <code>null</code> if given <code>null</code>.
 */
public static TypeRef getRootTypeRef(TypeRef typeRef) {
	if (typeRef != null) {
		while (true) {
			final TypeRef nextOuter = EcoreUtil2.getContainerOfType(typeRef.eContainer(), TypeRef.class);
			if (nextOuter == null)
				break;
			typeRef = nextOuter;
		}
	}
	return typeRef;
}
 
Example 16
Source File: XtendHoverSignatureProvider.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected String _signature(XtendConstructor constructor, boolean typeAtEnd) {
	JvmConstructor inferredConstructor = associations.getInferredConstructor(constructor);
	XtendClass xtendClazz = EcoreUtil2.getContainerOfType(constructor, XtendClass.class);
	return xtendClazz.getName() + hoverUiStrings.parameters(inferredConstructor)
			+ getThrowsDeclaration(inferredConstructor);
}
 
Example 17
Source File: SuppressWarningsAddModification.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Create the quick fix if needed.
 *
 * @param provider the quick fix provider.
 * @param issue the issue to fix.
 * @param acceptor the quick fix acceptor.
 */
public static void accept(SARLQuickfixProvider provider, Issue issue, IssueResolutionAcceptor acceptor) {
	final IFile file = provider.getProjectUtil().findFileStorage(issue.getUriToProblem(), false);
	final ResourceSet resourceSet = provider.getResourceSetProvider().get(file.getProject());
	final EObject failingObject;
	try {
		failingObject = resourceSet.getEObject(issue.getUriToProblem(), true);
	} catch (Exception exception) {
		// Something is going really wrong. Must of the time the cause is a major syntax error.
		return;
	}
	XtendAnnotationTarget eObject = EcoreUtil2.getContainerOfType(failingObject, XtendAnnotationTarget.class);
	boolean first = true;
	int relevance = IProposalRelevance.ADD_SUPPRESSWARNINGS;
	while (eObject != null) {
		final URI uri = EcoreUtil2.getNormalizedURI(eObject);
		final SuppressWarningsAddModification modification = new SuppressWarningsAddModification(uri, issue.getCode());
		modification.setIssue(issue);
		modification.setTools(provider);
		final String elementName;
		final QualifiedName name = provider.getQualifiedNameProvider().getFullyQualifiedName(eObject);
		if (name != null) {
			elementName = name.getLastSegment();
		} else if (first) {
			elementName = Messages.AddSuppressWarnings_0;
		} else {
			elementName = null;
		}
		if (elementName != null) {
			acceptor.accept(issue,
					MessageFormat.format(Messages.AddSuppressWarnings_1, elementName),
					MessageFormat.format(Messages.AddSuppressWarnings_2, elementName),
					JavaPluginImages.IMG_OBJS_ANNOTATION_ALT,
					modification,
					relevance);
			--relevance;
		}
		first = false;
		eObject = EcoreUtil2.getContainerOfType(eObject.eContainer(), XtendAnnotationTarget.class);
	}
}
 
Example 18
Source File: CodetemplatesProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected VariableData(EObject model) {
	super(model);
	if (template != null)
		variable = EcoreUtil2.getContainerOfType(model, Variable.class);
}
 
Example 19
Source File: VariableImpl.java    From n4js with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public TModule getContainingModule() {
	return EcoreUtil2.<TModule>getContainerOfType(this, TModule.class);
}
 
Example 20
Source File: CheckCompiler.java    From dsl-devkit with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Gets the name of the implicit variable in a context.
 *
 * @param expr
 *          any expression
 * @return the parameter name, if the expression is within a context and set, or CheckConstants.IT otherwise.
 */
private String getContextImplicitVariableName(final XExpression expr) {
  Context ctx = EcoreUtil2.getContainerOfType(expr, Context.class);
  return ctx != null && ctx.getContextVariable().getName() != null ? ctx.getContextVariable().getName() : CheckConstants.IT;
}