Java Code Examples for org.eclipse.emf.ecore.EObject#eContainer()

The following examples show how to use org.eclipse.emf.ecore.EObject#eContainer() . 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: XtendEObjectAtOffsetHelper.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected EObject resolveCrossReferencedElement(INode node) {
	EObject referencedElement = super.resolveCrossReferencedElement(node);
	EObject referenceOwner = NodeModelUtils.findActualSemanticObjectFor(node);
	if(referenceOwner instanceof XConstructorCall) {
		if (referenceOwner.eContainer() instanceof AnonymousClass) {
			AnonymousClass anon = (AnonymousClass) referenceOwner.eContainer();
			JvmGenericType superType = anonymousClassUtil.getSuperType(anon);
			if(superType != null) {
				if (referencedElement instanceof JvmGenericType)  
					return superType;
				else if(referencedElement instanceof JvmConstructor) {
					if(superType.isInterface())
						return superType;
					JvmConstructor superConstructor = anonymousClassUtil.getSuperTypeConstructor(anon);
					if(superConstructor != null)
						return superConstructor;
				}
			}
		}
	}
	return referencedElement;
}
 
Example 2
Source File: EmfFormatter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private static void objPath(StringBuffer b, EObject obj) {
	if (obj.eContainer() != null) {
		objPath(b, obj.eContainer());
		b.append(".");
		b.append(obj.eContainingFeature().getName());
		if (obj.eContainingFeature().isMany()) {
			b.append("[");
			b.append(((List<?>) obj.eContainer().eGet(obj.eContainingFeature())).indexOf(obj));
			b.append("]");
		}
		b.append("->");
	}
	b.append(obj.eClass().getName());
	EStructuralFeature nameF = obj.eClass().getEStructuralFeature("name");
	Object name = nameF != null ? obj.eGet(nameF) : null;
	if (name != null) {
		b.append("'");
		b.append(name);
		b.append("'");
	}
}
 
Example 3
Source File: FormatResourceDescriptionStrategy.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean createEObjectDescriptions(final EObject eObject, final IAcceptor<IEObjectDescription> acceptor) {

  if (eObject instanceof XBlockExpression || isXbaseLocalVariableName(eObject)) {
    return false;
  }

  boolean indexObject = false;
  boolean indexDefault = false;
  String objectFingerprint = null;
  if (fingerprintComputer != null && eObject.eContainer() instanceof FormatConfiguration && NodeModelUtils.getNode(eObject) != null) {
    objectFingerprint = fingerprintComputer.computeFingerprint(eObject);
  }

  if (objectFingerprint != null && !"".equals(objectFingerprint) && eObject.eContainer() instanceof FormatConfiguration) {
    acceptor.accept(EObjectDescription.create(objectFingerprint, eObject));
    indexObject = true;
  }

  indexDefault = createDescriptionsForNonXbaseFormalParameters(eObject, acceptor);

  return indexDefault || indexObject;
}
 
Example 4
Source File: Utils.java    From sarl with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the closest {@link EObject#eContainer() container object} that is not of the requested type.
 *
 * @param element the element to start from.
 * @param type the unexpected type.
 * @param container the container.
 * @param directContainerChild the child of the container that is or contains the given element.
 * @return {@code true} if the container was found.
 * @since 0.5
 * @see EcoreUtil2#getContainerOfType(EObject, Class)
 */
public static boolean getContainerNotOfType(EObject element, Class<? extends EObject> type,
		OutParameter<EObject> container, OutParameter<EObject> directContainerChild) {
	EObject previous = element;
	EObject elt = element.eContainer();
	while (elt != null) {
		if (!type.isInstance(elt)) {
			if (directContainerChild != null) {
				directContainerChild.set(previous);
			}
			if (container != null) {
				container.set(elt);
			}
			return true;
		}
		previous = elt;
		elt = elt.eContainer();
	}
	return false;
}
 
Example 5
Source File: JvmTypeReferencesValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void error(String message, String issueCode, JvmParameterizedTypeReference typeReference) {
	EObject rootContainer = EcoreUtil.getRootContainer(typeReference);
	Resource resource = rootContainer.eResource();
	if (resource.getContents().get(0) == rootContainer) {
		super.error(message, typeReference, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE, -1, issueCode);
	} else {
		EObject container = typeReference;
		EObject sourceElement = jvmModelAssociations.getPrimarySourceElement(container);
		container = container.eContainer();
		while(sourceElement == null && container != null) {
			sourceElement = jvmModelAssociations.getPrimarySourceElement(container);
			container = container.eContainer();
		}
		if (sourceElement != null) {
			error(message, sourceElement, sourceElement.eClass().getEStructuralFeature("name"), -1, issueCode);
		} else {
			super.error(message, typeReference, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE, -1, issueCode);
		}
	}
}
 
Example 6
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public ITextRegion selectNext(XtextResource resource, ITextRegion currentEditorSelection) {
	Pair<EObject, EObject> currentlySelected = getSelectedAstElements(resource, currentEditorSelection);
	if (currentlySelected == null) {
		return selectEnclosing(resource, currentEditorSelection);
	}
	EObject second = currentlySelected.getSecond();
	EObject nextSibling = EcoreUtil2.getNextSibling(second);
	if (nextSibling != null) {
		return register(getRegion(Tuples.create(currentlySelected.getFirst(), nextSibling)));
	} else {
		if (second.eContainer() == null)
			return ITextRegion.EMPTY_REGION;
		return register(getRegion(Tuples.create(second.eContainer(), second.eContainer())));
	}
}
 
Example 7
Source File: AbstractValidationTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Display the path from root object to the target EObject.
 *
 * @param eObject
 *          object to display the object path for
 * @param offset
 *          string offset that is added in the beginning of each line
 * @return
 *         object hierarchy as string (each object on a single line)
 */
private String pathFromRootAsString(final EObject eObject, final String offset) {
  List<String> hierarchy = Lists.newLinkedList();

  EObject currentObject = eObject;
  while (currentObject != null) {
    hierarchy.add(0, offset + currentObject.toString());
    currentObject = currentObject.eContainer();
  }

  return String.join("\n", hierarchy);
}
 
Example 8
Source File: DeprecationUtil.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns {@code true} if the given member is contained in a deprecated member.
 * @param member the member to be checked
 */
public static boolean isTransitivelyDeprecatedMember(JvmMember member) {
	EObject container = member;
	while(container instanceof JvmMember) {
		if (isDeprecatedMember((JvmMember) container)) {
			return true;
		}
		container = container.eContainer();
	}
	return false;
}
 
Example 9
Source File: CreateNewFormProposalListener.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private Contract contractFor(final EObject context) {
    EObject contractContainer = context;
    while (contractContainer != null && !(contractContainer instanceof ContractContainer)) {
        contractContainer = contractContainer.eContainer();
    }
    if (contractContainer instanceof ContractContainer) {
        return ((ContractContainer) contractContainer).getContract();
    }
    throw new IllegalStateException("No contract found for context " + context);
}
 
Example 10
Source File: ReferenceUpdater.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public Delta findContainingDelta(Deltas deltas, EObject obj) {
	EObject current = obj;
	while (current != null) {
		Delta delta = deltas.getDelta(current);
		if (delta != null && delta.hasSimpleNameOrUserdataChanged()) {
			return delta;
		}
		current = current.eContainer();
	}
	return null;
}
 
Example 11
Source File: CustomClipboardSupportGlobalActionHandler.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param semantic
 * @return
 */
private Container getContainer(EObject semantic) {
	while (semantic != null && ! (semantic instanceof Container)) {
		semantic = semantic.eContainer();
	}
	return (Container)semantic;
}
 
Example 12
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.1
 */
public static <T extends EObject> List<T> getSiblingsOfType(EObject ele, Class<T> type) {
	if (ele.eContainer() != null) {
		List<T> siblings = typeSelect(ele.eContainer().eContents(), type);
		siblings.remove(ele);
		return siblings;
	}
	return emptyList();
}
 
Example 13
Source File: FGUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** @return the AST depth of the given {@link EObject}. */
public static int getASTDepth(EObject eObj) {
	int i;
	for (i = 0; eObj != null; i++) {
		eObj = eObj.eContainer();
	}
	return i;
}
 
Example 14
Source File: XbaseImportedNamespaceScopeProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected IScope internalGetScope(IScope parent, IScope globalScope, EObject context, EReference reference) {
	IScope result = parent;
	if (context.eContainer() == null) {
		if (parent != globalScope)
			throw new IllegalStateException("the parent should be the global scope");
		result = getResourceScope(globalScope, context.eResource(), reference);
	} else {
		result = internalGetScope(parent, globalScope, context.eContainer(), reference);
	}
	return getLocalElementsScope(result, globalScope, context, reference);
}
 
Example 15
Source File: XtendRenameContextFactory.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected EObject getDeclarationTarget(EObject targetElement) {
	EObject declarationTarget = super.getDeclarationTarget(targetElement);
	if (declarationTarget instanceof XtendConstructor)
		return declarationTarget.eContainer();
	else
		return declarationTarget;
}
 
Example 16
Source File: LinkingXpectMethod.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Similar to {@link #linkedName(IStringExpectation, ICrossEReferenceAndEObject)} but concatenating the fully
 * qualified name again instead of using the qualified name provider, as the latter may not create a valid name for
 * non-globally available elements.
 * <p>
 * The qualified name created by retrieving all "name" properties of the target and its containers, using '/' as
 * separator.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void linkedPathname(@StringExpectation IStringExpectation expectation,
		ICrossEReferenceAndEObject arg1) {
	EObject targetObject = (EObject) arg1.getEObject().eGet(arg1.getCrossEReference());
	if (targetObject == null) {
		Assert.fail("Reference is null");
		return; // to avoid warnings in the following
	}
	if (targetObject.eIsProxy())
		Assert.fail("Reference is a Proxy: " + ((InternalEObject) targetObject).eProxyURI());
	Resource targetResource = targetObject.eResource();
	if (targetResource instanceof TypeResource)
		targetResource = arg1.getEObject().eResource();
	if (!(targetResource instanceof XtextResource))
		Assert.fail("Referenced EObject is not in an XtextResource.");

	Deque<String> segments = new ArrayDeque<>();
	do {
		EStructuralFeature nameFeature = targetObject.eClass().getEStructuralFeature("name");
		if (nameFeature != null) {
			Object obj = targetObject.eGet(nameFeature);
			if (obj instanceof String) {
				segments.push((String) obj);
			}
		} else {
			if (targetObject instanceof NamedElement) {
				segments.push(((NamedElement) targetObject).getName());
			}
		}
		targetObject = targetObject.eContainer();
	} while (targetObject != null);
	String pathname = Joiner.on('/').join(segments);
	expectation.assertEquals(pathname);
}
 
Example 17
Source File: ASTGraphProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private String getDocumentation(/* @NonNull */EObject object) {
	if (object.eContainer() == null) {
		// if a comment is at the beginning of the file it will be returned for
		// the root element (e.g. Script in N4JS) as well -> avoid this!
		return null;
	}

	ICompositeNode node = NodeModelUtils.getNode(object);
	if (node != null) {
		// get the last multi line comment before a non hidden leaf node
		for (ILeafNode leafNode : node.getLeafNodes()) {
			if (!leafNode.isHidden())
				break;

			EObject grammarElem = leafNode.getGrammarElement();
			if (grammarElem instanceof TerminalRule
					&& "ML_COMMENT".equalsIgnoreCase(((TerminalRule) grammarElem).getName())) {

				String comment = leafNode.getText();
				if (commentStartTagRegex.matcher(comment).matches()) {
					return leafNode.getText();
				}
			}
		}
	}
	return null;
}
 
Example 18
Source File: ExtendedFormattingConfigBasedStream.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds the semanticNode {@link EObject} that is associated to the container node of the given {@link INode}.
 *
 * @param givenNode
 *          the {@link INode} to find the semantic node for
 * @param expectedType
 *          The type of the semantic node to find
 * @return the semantic node found, {@code null} if none was found.
 */
private EObject findSemanticNode(final INode givenNode, final Type expectedType) {
  INode node = givenNode;
  // Node type
  EObject semanticNode = NodeModelUtils.findActualSemanticObjectFor(node);
  if (semanticNode == null) {
    return null;
  }
  Class<?> semanticNodeType = getSemanticNodeType(semanticNode);

  // Find correct node
  while (!expectedType.equals(semanticNodeType)) {
    if (semanticNode == null) {
      break;
    }
    if (semanticNode.eContainer() == null) {
      while (semanticNode != null && semanticNode.eContainer() == null) {
        node = findPrevious(node);
        semanticNode = NodeModelUtils.findActualSemanticObjectFor(node);
        semanticNodeType = getSemanticNodeType(semanticNode);
      }

    } else {
      semanticNode = semanticNode.eContainer();
      semanticNodeType = getSemanticNodeType(semanticNode);
    }
  }
  return semanticNode;
}
 
Example 19
Source File: ModelHelper.java    From bonita-studio with GNU General Public License v2.0 3 votes vote down vote up
/**
 * To be used when dealing with scopes (for groups or datatypes)
 *
 * @param a
 *        model object
 * @return the list of parent processes for this object. Includes object if
 *         object is a process. This basically contains: * Only the Main
 *         process in case of a top level node which is contained in main
 *         process * Main process and pool for pools and items that are
 *         contained inside a pool
 */
public static List<AbstractProcess> getAllParentProcesses(EObject eObject) {
    final List<AbstractProcess> res = new ArrayList<AbstractProcess>();
    while (eObject != null) {
        if (eObject instanceof AbstractProcess) {
            res.add((AbstractProcess) eObject);
        }
        eObject = eObject.eContainer();
    }
    return res;
}
 
Example 20
Source File: AnnotationDefinition.java    From n4js with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * take care for {@link ExportDeclaration}s to be included. Note that {@link TAnnotatableWrapper} does nto have
 * to do this as types builder is taking care of that.
 *
 * @param element
 *            from which we want to obtain annotations
 * @return iterable with annotations attached to the provided element
 */
private static final Iterable<Annotation> getASTAnnotations(EObject element) {
	Iterable<Annotation> anns = ((AnnotableElement) element).getAnnotations();
	if (element.eContainer() != null && element.eContainer() instanceof ExportDeclaration) {
		return concat(anns, ((AnnotableElement) element.eContainer()).getAnnotations());
	}
	return anns;
}