Java Code Examples for org.eclipse.xtext.nodemodel.util.NodeModelUtils#findNodesForFeature()

The following examples show how to use org.eclipse.xtext.nodemodel.util.NodeModelUtils#findNodesForFeature() . 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: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToProjectProperty(NameValuePair nvpDependency) {
	String projectName = nvpDependency.getName();
	SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));
	if (pdu != null) {
		List<INode> node = NodeModelUtils.findNodesForFeature(nvpDependency,
				JSONPackage.Literals.NAME_VALUE_PAIR__NAME);

		if (!node.isEmpty()) {
			INode nameNode = node.get(0);
			Region region = new Region(nameNode.getOffset() + 1, nameNode.getLength() - 2);

			return Tuples.pair(pdu, region);
		}
	}

	return null;
}
 
Example 2
Source File: LightweightTypeReferenceFactory.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
private LightweightTypeReference createUnknownTypeReference(JvmParameterizedTypeReference reference) {
	List<INode> nodes = NodeModelUtils.findNodesForFeature(reference, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
	if (nodes.isEmpty()) {
		Set<EObject> sourceElements = owner.getServices().getJvmModelAssociations().getSourceElements(reference);
		EObject firstSource = Iterables.getFirst(sourceElements, null);
		if (firstSource instanceof JvmParameterizedTypeReference) {
			nodes = NodeModelUtils.findNodesForFeature(firstSource, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE);
		}
	}
	if (nodes.size() == 1) {
		String name = nodes.get(0).getText().trim();
		if (name != null && name.length() != 0) {
			int lastDot = name.lastIndexOf('.');
			int lastDollar = name.lastIndexOf('$');
			int lastDotOrDollar = Math.max(lastDot, lastDollar);
			if (lastDotOrDollar != -1 && lastDotOrDollar != name.length() - 1) {
				String shortName = name.substring(lastDotOrDollar + 1);
				if (shortName.length() != 0) {
					name = shortName;
				}
			}
			return owner.newUnknownTypeReference(name);
		}
	}
	return owner.newUnknownTypeReference();
}
 
Example 3
Source File: AbstractXtextTestUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the offset and the error message for a given {@link Diagnostic}.
 *
 * @param diagnostic
 *          instance of {@link Diagnostic}
 * @return
 *         offset and error message
 */
private Pair<Integer, String> processDiagnostic(final Diagnostic diagnostic) {
  StringBuilder errorMessage = new StringBuilder();
  if (diagnostic instanceof AbstractValidationDiagnostic) {
    AbstractValidationDiagnostic avd = (AbstractValidationDiagnostic) diagnostic;
    errorMessage.append("Unexpected issue found. Code '");
    errorMessage.append(avd.getIssueCode()).append("'\n");
    errorMessage.append(avd.getMessage());
    if (avd instanceof FeatureBasedDiagnostic && ((FeatureBasedDiagnostic) avd).getFeature() != null) {
      List<INode> nodes = NodeModelUtils.findNodesForFeature(avd.getSourceEObject(), ((FeatureBasedDiagnostic) avd).getFeature());
      if (nodes != null && !nodes.isEmpty()) {
        return new Pair<Integer, String>(findFirstNonHiddenLeafNode(nodes.get(0)).getTotalOffset(), errorMessage.toString());
      }
    } else if (avd instanceof RangeBasedDiagnostic) {
      return new Pair<Integer, String>(((RangeBasedDiagnostic) avd).getOffset(), errorMessage.toString());
    } else {
      return new Pair<Integer, String>(NodeModelUtils.getNode(avd.getSourceEObject()).getTotalOffset(), errorMessage.toString());
    }
  }
  return null;
}
 
Example 4
Source File: XbaseProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean doNotProposeFeatureOfBinaryOperation(ContentAssistContext contentAssistContext,
		XBinaryOperation binaryOperation) {
	List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(binaryOperation, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
	if (!nodesForFeature.isEmpty()) {
		INode node = nodesForFeature.get(0);
		if (node.getOffset() < contentAssistContext.getOffset() - contentAssistContext.getPrefix().length()) {
			XExpression rightOperand = binaryOperation.getRightOperand();
			if (rightOperand == null)
				return true;
			ICompositeNode rightOperandNode = NodeModelUtils.findActualNodeFor(rightOperand);
			if (rightOperandNode != null) {
				if (rightOperandNode.getOffset() >= contentAssistContext.getOffset())
					return true;
				if (isParentOf(rightOperandNode, contentAssistContext.getLastCompleteNode()))
					return true;
			}
		}
	}
	return false;
}
 
Example 5
Source File: ElementIssueProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void synthesizeIssuesForFollowUpErrors(Resource resource, List<Issue> result) {
	List<EObject> contents = resource.getContents();
	if (!contents.isEmpty()) {
		IResolvedTypes resolvedTypes = typeResolver.resolveTypes(contents.get(0));
		for(ILinkingCandidate linkingCandidate: resolvedTypes.getFollowUpErrors()) {
			XExpression expression = linkingCandidate.getExpression();
			IssueImpl issue = new Issue.IssueImpl();
			issue.setUriToProblem(EcoreUtil.getURI(linkingCandidate.getExpression()));
			if (expression instanceof XAbstractFeatureCall)
				issue.setMessage(((XAbstractFeatureCall) expression).getConcreteSyntaxFeatureName() + " cannot be resolved");
			else {
				List<INode> nodes = NodeModelUtils.findNodesForFeature(expression, XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR);
				if (nodes.size() >= 1) {
					issue.setMessage(nodes.get(0).getText() + " cannot be resolved");
				}
			}
			result.add(issue);
		}
	}
}
 
Example 6
Source File: ArgumentSorter.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public static EList<Expression> getOrderedExpressions(List<Argument> arguments, Operation operation) {
	Expression[] result = new Expression[arguments.size()];
	for (int index = 0; index < arguments.size(); index++) {
		Argument argument = arguments.get(index);
		List<INode> nodes = NodeModelUtils.findNodesForFeature(argument,
				ExpressionsPackage.Literals.ARGUMENT__PARAMETER);
		if (nodes.isEmpty()) {
			result[index] = argument.getValue();
		} else {
			// operation.getParameters().indexOf(argument.getParameter() can
			// not be used here since it uses object.equals instead of
			// EcoreUtil.equals.)
			for (Parameter param : operation.getParameters()) {
				if (param.getName().equals(nodes.get(0).getText())) {
					int parameterIndex = operation.getParameters().indexOf(param);
					if (parameterIndex < result.length)
						result[parameterIndex] = argument.getValue();
					break;
				}
			}
		}
	}

	EList<Expression> resultAsList = new BasicEList<Expression>();
	for (int i = 0; i < result.length; i++) {
		Expression expression = result[i];
		if (expression != null)
			resultAsList.add(expression);
	}
	return resultAsList;
}
 
Example 7
Source File: ParameterContextInformationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected String getCalledFeatureName(XExpression call) {
	StringBuilder b = new StringBuilder();
	for (INode node : NodeModelUtils.findNodesForFeature(call, getCalledFeatureReference(call))) {
		for (ILeafNode leafNode : node.getLeafNodes()) {
			if (!leafNode.isHidden()) 
				b.append(leafNode.getText());
		}
	}
	return b.toString();
}
 
Example 8
Source File: SemanticHighlightingCalculator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the first node from the parse tree for given semantic object and structural feature.
 *
 * @param semanticElement
 *          the semantic element
 * @param feature
 *          the structural feature
 * @return the first parse tree node or {@code null} if none found
 */
private INode getFirstParseTreeNode(final EObject semanticElement, final EStructuralFeature feature) {
  if (feature == null) {
    return NodeModelUtils.findActualNodeFor(semanticElement);
  }
  List<INode> nodes = NodeModelUtils.findNodesForFeature(semanticElement, feature);
  if (!nodes.isEmpty()) {
    return nodes.get(0);
  }
  return null;
}
 
Example 9
Source File: DefaultSemanticHighlightingCalculator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Highlights an object at the position of the given {@link EStructuralFeature}
 */
protected void highlightFeature(IHighlightedPositionAcceptor acceptor, EObject object, EStructuralFeature feature,
		String... styleIds) {
	List<INode> children = NodeModelUtils.findNodesForFeature(object, feature);
	if (children.size() > 0)
		highlightNode(acceptor, children.get(0), styleIds);
}
 
Example 10
Source File: SARLQuickfixProvider.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the index where import declaration could be inserted into the given container.
 *
 * @param script the script to consider for the insertion
 * @return the insertion index.
 */
public int getImportInsertOffset(SarlScript script) {
	final ICompositeNode node = NodeModelUtils.findActualNodeFor(script.getImportSection());
	if (node == null) {
		final List<INode> children = NodeModelUtils.findNodesForFeature(script,
				XtendPackage.eINSTANCE.getXtendFile_Package());
		if (children.isEmpty()) {
			return 0;
		}
		return children.get(0).getEndOffset();
	}
	return node.getEndOffset();
}
 
Example 11
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void addTypeCastToExplicitReceiver(XAbstractFeatureCall featureCall, IModificationContext context,
		JvmType declaringType, EReference structuralFeature) throws BadLocationException {
	List<INode> nodes = NodeModelUtils.findNodesForFeature(featureCall, structuralFeature);
	if (nodes.isEmpty())
		return;
	INode firstNode = IterableExtensions.head(nodes);
	INode lastNode = IterableExtensions.last(nodes);
	int offset = firstNode.getOffset();
	int length = lastNode.getEndOffset() - offset;
	ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
			(XtextResource) featureCall.eResource(), offset, length);
	appendable.append("(");
	ListIterator<INode> nodeIter = nodes.listIterator();
	while (nodeIter.hasNext()) {
		String text = nodeIter.next().getText();
		if (nodeIter.previousIndex() == 0)
			appendable.append(Strings.removeLeadingWhitespace(text));
		else if (nodeIter.nextIndex() == nodes.size())
			appendable.append(Strings.trimTrailingLineBreak(text));
		else
			appendable.append(text);
	}
	appendable.append(" as ");
	appendable.append(declaringType);
	appendable.append(")");
	appendable.commitChanges();
}
 
Example 12
Source File: XbaseNodeModelTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testAssignment_rhs_03() throws Exception {
	String text = "a=b+=c";
	XBinaryOperation assignment = (XBinaryOperation) ((XAssignment) expression(text)).getValue();
	List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(assignment, XbasePackage.Literals.XBINARY_OPERATION__RIGHT_OPERAND);
	assertEquals(1, nodesForFeature.size());
	String nodeText = nodesForFeature.get(0).getText();
	assertEquals("c", nodeText);
}
 
Example 13
Source File: DefaultLocationInFileProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected List<INode> getLocationNodes(EObject obj) {
	final EStructuralFeature nameFeature = getIdentifierFeature(obj);
	if (nameFeature != null) {
		List<INode> result = NodeModelUtils.findNodesForFeature(obj, nameFeature);
		if (!result.isEmpty())
			return result;
	}

	List<INode> resultNodes = Lists.newArrayList();
	final ICompositeNode startNode = findNodeFor(obj);
	INode keywordNode = null;
	// use LeafNodes instead of children?
	for (INode child : startNode.getChildren()) {
		EObject grammarElement = child.getGrammarElement();
		if (grammarElement instanceof RuleCall) {
			RuleCall ruleCall = (RuleCall) grammarElement;
			String ruleName = ruleCall.getRule().getName();
			if (ruleName.equals("ID")) {
				resultNodes.add(child);
			}
		} else if (grammarElement instanceof Keyword) {
			// TODO use only keywords, that aren't symbols like '=' ?
			if (keywordNode == null && useKeyword((Keyword) grammarElement, obj)) {
				keywordNode = child;
			}
		}
	}
	if (resultNodes.isEmpty() && keywordNode != null)
		resultNodes.add(keywordNode);
	return resultNodes;
}
 
Example 14
Source File: XbaseNodeModelTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testBinaryOperation_03() throws Exception {
	String text = "a-b-c+d";
	XBinaryOperation operation = (XBinaryOperation) expression(text);
	List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(operation, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE);
	assertEquals(1, nodesForFeature.size());
	String nodeText = nodesForFeature.get(0).getText();
	assertEquals("+", nodeText);
}
 
Example 15
Source File: JdtVariableCompletions.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected String getTextUnderReference(EObject ctx, EReference refToTypeRef) {
	List<INode> nodes = NodeModelUtils.findNodesForFeature(ctx, refToTypeRef);
	StringBuilder sb = new StringBuilder();
	for (INode n : nodes) {
		sb.append(NodeModelUtils.getTokenText(n));
	}
	return sb.toString();
}
 
Example 16
Source File: DotArrowTypeValidator.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
private void reportRangeBasedWarning(String issueCode, String message,
		EObject object, EStructuralFeature feature) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(object, feature);

	if (nodes.size() != 1) {
		throw new IllegalStateException(
				"Exact 1 node is expected for the feature, but got "
						+ nodes.size() + " node(s).");
	}

	INode node = nodes.get(0);
	int offset = node.getTotalOffset();
	int length = node.getLength();

	String code = null;
	// the issueData will be evaluated by the quickfixes
	List<String> issueData = new ArrayList<>();
	issueData.add(issueCode);
	switch (issueCode) {
	case DEPRECATED_ARROW_SHAPE:
		DeprecatedArrowShape arrowShape = (DeprecatedArrowShape) object;
		issueData.add(arrowShape.getShape().toString());
		break;
	case INVALID_ARROW_SHAPE_MODIFIER:
		if (ArrowtypePackage.Literals.ARROW_SHAPE__OPEN == feature) {
			issueData.add("o");
		}
		if (ArrowtypePackage.Literals.ARROW_SHAPE__SIDE == feature) {
			issueData.add(((ArrowShape) object).getSide());
		}
		issueData.add(Integer.toString(offset));
	default:
		break;
	}

	getMessageAcceptor().acceptWarning(message, object, offset, length,
			code, issueData.toArray(new String[0]));
}
 
Example 17
Source File: AbstractLabelProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Searches for a keyword before the {@link EStructuralFeature} of the given {@link EObject} model element.
 *
 * @param modelElement
 *          the {@link EObject} model element
 * @param feature
 *          the {@link EStructuralFeature}
 * @return the keyword before the {@link EStructuralFeature} of the given {@link EObject} model element, or {@code null} if no keyword was found
 */
protected String findKeywordBeforeFeature(final EObject modelElement, final EStructuralFeature feature) {
  List<INode> nodes = NodeModelUtils.findNodesForFeature(modelElement, feature);
  if (!nodes.isEmpty()) {
    INode node = nodes.get(0);
    while (!(node.getGrammarElement() instanceof Keyword) && node.hasPreviousSibling()) {
      node = node.getPreviousSibling();
    }
    if (node.getGrammarElement() instanceof Keyword) {
      return node.getText();
    }
  }
  return null;
}
 
Example 18
Source File: ImportsCollector.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected void _visit(final XTypeLiteral semanticElement, final INode originNode, final ImportsAcceptor acceptor) {
  final List<INode> elementNode = NodeModelUtils.findNodesForFeature(semanticElement, XbasePackage.Literals.XTYPE_LITERAL__TYPE);
  this.visit(semanticElement.getType(), IterableExtensions.<INode>head(elementNode), acceptor);
}
 
Example 19
Source File: AbstractOutlineTreeProvider.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates children for all {@link EStructuralFeatures} (that are set) of the given {@link EObject} model element. {@inheritDoc}
 *
 * @param parentNode
 *          the parent {@link IOutlineNode}
 * @param modelElement
 *          a valid {@link EObject}
 */
@SuppressWarnings({"unchecked", "PMD.NPathComplexity"})
@Override
protected void internalCreateChildren(final IOutlineNode parentNode, final EObject modelElement) {
  // from all structural features, select only those which are set and retrieve the text location
  // TODO : sorting for feature lists needs to be based on the objects in the list, not the feature.
  List<Pair<Integer, EStructuralFeature>> pairsLocationFeature = Lists.newArrayList();
  for (EStructuralFeature structuralFeature : modelElement.eClass().getEAllStructuralFeatures()) {
    if (modelElement.eIsSet(structuralFeature)) {
      int offset = 0;
      List<INode> nodes = NodeModelUtils.findNodesForFeature(modelElement, structuralFeature);
      if (!nodes.isEmpty()) {
        offset = nodes.get(0).getTotalOffset();
      }
      pairsLocationFeature.add(Tuples.create(offset, structuralFeature));
    }
  }
  // sort the features according to their appearance in the source text
  Collections.sort(pairsLocationFeature, new Comparator<Pair<Integer, EStructuralFeature>>() {
    @Override
    public int compare(final Pair<Integer, EStructuralFeature> o1, final Pair<Integer, EStructuralFeature> o2) {
      return o1.getFirst() - o2.getFirst();
    }
  });
  // go through the sorted list of children and create nodes
  for (Pair<Integer, EStructuralFeature> pairLocationFeature : pairsLocationFeature) {
    EStructuralFeature feature = pairLocationFeature.getSecond();
    if (feature instanceof EAttribute) {
      if (getRelevantElements().contains(feature)) {
        createNodeDispatcher.invoke(parentNode, modelElement, feature);
      }
    } else if (feature instanceof EReference && ((EReference) feature).isContainment()) { // only consider containment references
      IOutlineNode listNode = null;
      EList<EObject> featureElements;
      Object value = modelElement.eGet(feature);
      if (feature.isMany()) {
        featureElements = (EList<EObject>) value;
        if (getRelevantElements().contains(feature)) {
          listNode = createEStructuralFeatureNode(parentNode, modelElement, feature, getImageDescriptor(feature), feature.getName(), false);
        }
      } else {
        featureElements = new BasicEList<EObject>();
        featureElements.add((EObject) value);
      }
      for (EObject childElement : featureElements) {
        if (childElement == null) {
          continue;
        }
        if (isRelevantElement(childElement)) {
          createNodeDispatcher.invoke(listNode != null ? listNode : parentNode, childElement);
        } else {
          createChildrenDispatcher.invoke(listNode != null ? listNode : parentNode, childElement);
        }
      }
    }
  }
}
 
Example 20
Source File: FeatureCallAsTypeLiteralHelper.java    From xtext-extras with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Returns the segments that are preceding the feature call, e.g. it returns 
 * <code>'java', 'lang'</code> for a feature call <code>java.lang.String</code>.
 * <code>java::lang::String</code>.
 * Returns <code>null</code> if no such segments exist, e.g. because the member call target
 * does not indicate a type reference syntactically, e.g. <code>(java.lang).String</code>.
 */
/* @Nullable */
public List<String> getTypeNameSegmentsFromConcreteSyntax(XMemberFeatureCall featureCall) {
	List<INode> nodes = NodeModelUtils.findNodesForFeature(featureCall, XbasePackage.Literals.XMEMBER_FEATURE_CALL__MEMBER_CALL_TARGET);
	List<String> prefix = getTypeNameSegmentsFromConcreteSyntax(nodes, featureCall.isExplicitStatic());
	return prefix;
}