org.eclipse.xtext.nodemodel.util.NodeModelUtils Java Examples

The following examples show how to use org.eclipse.xtext.nodemodel.util.NodeModelUtils. 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: XtextLabelProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private String getLiteralName(EnumLiteralDeclaration declaration) {
	if (declaration.getEnumLiteral() != null) {
		return declaration.getEnumLiteral().getName();
	}
	ICompositeNode node = NodeModelUtils.getNode(declaration);
	String literalName = UNKNOWN;
	if (node != null) {
		for (ILeafNode leaf : node.getLeafNodes()) {
			if (!leaf.isHidden()) {
				literalName = leaf.getText();
				break;
			}
		}
	}
	return literalName;
}
 
Example #2
Source File: DotHtmlLabelValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void reportRangeBasedError(String issueCode, String message,
		EObject object, EStructuralFeature feature, String[] issueData) {

	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();

	getMessageAcceptor().acceptError(message, object, offset, length,
			issueCode, issueData);
}
 
Example #3
Source File: QuickFixXpectMethod.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * CollectAll resolutions under the cursor at offset.
 *
 */
List<IssueResolution> collectAllResolutions(XtextResource resource, RegionWithCursor offset,
		Multimap<Integer, Issue> offset2issue) {

	EObject script = resource.getContents().get(0);
	ICompositeNode scriptNode = NodeModelUtils.getNode(script);
	ILeafNode offsetNode = NodeModelUtils.findLeafNodeAtOffset(scriptNode, offset.getGlobalCursorOffset());
	int offStartLine = offsetNode.getTotalStartLine();
	List<Issue> allIssues = QuickFixTestHelper.extractAllIssuesInLine(offStartLine, offset2issue);

	List<IssueResolution> resolutions = Lists.newArrayList();

	for (Issue issue : allIssues) {
		if (issue.getLineNumber() == offsetNode.getStartLine()
				&& issue.getLineNumber() <= offsetNode.getEndLine()) {

			IssueResolutionProvider quickfixProvider = resource.getResourceServiceProvider()
					.get(IssueResolutionProvider.class);
			Display.getDefault().syncExec(() -> resolutions.addAll(quickfixProvider.getResolutions(issue)));
		}
	}
	return resolutions;
}
 
Example #4
Source File: SetEntryPointOnXtextResourceTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test1() throws Exception {
	with(ReferenceGrammarTestLanguageStandaloneSetup.class);
	String model = "kind (Hugo 13)";
	ParserRule kindRule = get(ReferenceGrammarTestLanguageGrammarAccess.class).getKindRule();
	XtextResource resource = createResource();
	// test 1: parse and assume there are no errors
	resource.setEntryPoint(kindRule);
	resource.load(new StringInputStream(model), Collections.emptyMap());
	Assert.assertTrue(resource.getErrors().isEmpty());
	Assert.assertEquals(kindRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
	// test 2: update and assume node model does not change
	String originalNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
	resource.update(0, model.length(), " " + model + " ");
	String reparsedNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
	Assert.assertEquals(originalNodeModel, reparsedNodeModel);
	// test 3: change parser rule
	ParserRule erwachsenerRule = get(ReferenceGrammarTestLanguageGrammarAccess.class).getErwachsenerRule();
	resource.setEntryPoint(erwachsenerRule);
	resource.update(0, model.length(), "erwachsener (Peter 30)");
	Assert.assertEquals(erwachsenerRule,
			NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
}
 
Example #5
Source File: AbstractSyntaxColoringTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the offset for given text by analyzing the parse tree and looking for leaf nodes having
 * a text attribute matching given value. Returns the first instance found and an error value if
 * no match found.
 *
 * @param model
 *          the model
 * @param text
 *          the text
 * @return the offset for text
 */
public static int getOffsetForText(final EObject model, final String text) {
  Iterable<ILeafNode> parseTreeNodes = NodeModelUtils.getNode(model).getLeafNodes();

  try {
    ILeafNode result = Iterables.find(parseTreeNodes, new Predicate<ILeafNode>() {
      @Override
      public boolean apply(final ILeafNode input) {
        return text.equals(input.getText());
      }
    });
    return result.getOffset();
  } catch (NoSuchElementException e) {
    return LEAF_NOT_FOUND_VALUE;
  }
}
 
Example #6
Source File: XtendHoverSerializer.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public String computeArguments(XAbstractFeatureCall featureCall) {
	StringBuilder stringBuilder = new StringBuilder("(");
	if (featureCall != null) {
		XExpression implicitFirstArgument = featureCall.getImplicitFirstArgument();
		List<XExpression> arguments = featureCall.getActualArguments();
		if (implicitFirstArgument != null) {
			XbaseSwitch<String> xbaseSwitch = new XtendHoverXbaseSwitch();
			String doSwitch = xbaseSwitch.doSwitch(implicitFirstArgument).trim();
			if (doSwitch != null)
				stringBuilder.append(doSwitch);
		}
		int start = implicitFirstArgument != null ? 1 : 0;
		for(int i = start; i < arguments.size(); i++) {
			if (i != 0) {
				stringBuilder.append(SEPARATOR);
			}
			XExpression expression = arguments.get(i);
			ICompositeNode node = NodeModelUtils.findActualNodeFor(expression);
			if (node != null)
				stringBuilder.append(node.getText().trim());
		}
	}
	stringBuilder.append(")");
	return stringBuilder.toString();
}
 
Example #7
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void internalDoAddAbstractKeyword(EObject element, IModificationContext context)
		throws BadLocationException {
	if (element instanceof XtendFunction) {
		element = element.eContainer();
	}
	if (element instanceof XtendClass) {
		XtendClass clazz = (XtendClass) element;
		IXtextDocument document = context.getXtextDocument();
		ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(clazz);
		if (clazzNode == null)
			throw new IllegalStateException("Cannot determine node for clazz " + clazz.getName());
		int offset = -1;
		for (ILeafNode leafNode : clazzNode.getLeafNodes()) {
			if (leafNode.getText().equals("class")) {
				offset = leafNode.getOffset();
				break;
			}
		}
		ReplacingAppendable appendable = appendableFactory.create(document, (XtextResource) clazz.eResource(),
				offset, 0);
		appendable.append("abstract ");
		appendable.commitChanges();
	}
}
 
Example #8
Source File: SingleLineCommentDocumentationProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds trailing comment for a given context object. I.e. the comment after / on the same line as the context object.
 *
 * @param context
 *          the object
 * @return the documentation string
 */
protected String findTrailingComment(final EObject context) {
  StringBuilder returnValue = new StringBuilder();
  ICompositeNode node = NodeModelUtils.getNode(context);
  if (node != null) {
    final int contextEndLine = node.getEndLine();
    // process all leaf nodes first
    for (ILeafNode leave : node.getLeafNodes()) {
      addComment(returnValue, leave, contextEndLine);
    }
    // we also need to process siblings (leave nodes only) due to the fact that the last comment after
    // a given element is not a leaf node of that element anymore.
    INode sibling = node.getNextSibling();
    while (sibling instanceof ILeafNode) {
      addComment(returnValue, (ILeafNode) sibling, contextEndLine);
      sibling = sibling.getNextSibling();
    }
  }
  return returnValue.toString();
}
 
Example #9
Source File: DotStyleValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void reportRangeBasedWarning(String issueCode, String message,
		StyleItem styleItem) {

	List<INode> nodes = NodeModelUtils.findNodesForFeature(styleItem,
			StylePackage.Literals.STYLE_ITEM__NAME);

	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();

	// the issueData will be evaluated by the quickfixes
	List<String> issueData = new ArrayList<>();
	issueData.add(issueCode);
	issueData.add(styleItem.getName());
	issueData.addAll(styleItem.getArgs());

	getMessageAcceptor().acceptWarning(message, styleItem, offset, length,
			issueCode, issueData.toArray(new String[0]));
}
 
Example #10
Source File: LabellingReferenceFinder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Acceptor toAcceptor(IAcceptor<IReferenceDescription> acceptor) {
	return new ReferenceAcceptor(acceptor, getResourceServiceProviderRegistry()) {

		@Override
		public void accept(EObject source, URI sourceURI, EReference eReference, int index, EObject targetOrProxy,
				URI targetURI) {
			// Check if we should ignore named import specifier
			if (N4JSReferenceQueryExecutor.ignoreNamedImportSpecifier && source instanceof NamedImportSpecifier)
				return;

			EObject displayObject = calculateDisplayEObject(source);
			String logicallyQualifiedDisplayName = N4JSHierarchicalNameComputerHelper
					.calculateHierarchicalDisplayName(displayObject, labelProvider, false);
			ICompositeNode srcNode = NodeModelUtils.getNode(source);
			int line = srcNode.getStartLine();
			LabelledReferenceDescription description = new LabelledReferenceDescription(source, displayObject,
					sourceURI,
					targetOrProxy,
					targetURI,
					eReference, index, logicallyQualifiedDisplayName, line);
			accept(description);
		}
	};
}
 
Example #11
Source File: FeatureCallCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected ILocationData getLocationWithoutTypeArguments(XAbstractFeatureCall call) {
	final ICompositeNode startNode = NodeModelUtils.getNode(call);
	if (startNode != null) {
		List<INode> resultNodes = Lists.newArrayList();
		if (call instanceof XFeatureCall || call instanceof XMemberFeatureCall) {
			boolean featureReferenceSeen = false;
			for (INode child : startNode.getChildren()) {
				if (featureReferenceSeen) {
					resultNodes.add(child);
				} else {
					EObject grammarElement = child.getGrammarElement();
					if (grammarElement instanceof CrossReference) {
						Assignment assignment = GrammarUtil.containingAssignment(grammarElement);
						if (assignment != null && "feature".equals(assignment.getFeature())) {
							featureReferenceSeen = true;
							resultNodes.add(child);
						}
					}
				}
			}
		}
		return toLocationData(resultNodes);
	}
	return null;
}
 
Example #12
Source File: EntryPointFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public ICompositeNode findEntryPoint(IParseResult parseResult, int offset) {
	ICompositeNode rootNode = parseResult.getRootNode();
	if (rootNode.getTotalLength() == offset) {
		return null;
	}
	ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset);
	ICompositeNode parent = leafNode.getParent();
	ICompositeNode result = findEntryPoint(parent, offset);
	if (result != null) {
		EObject grammarElement = result.getGrammarElement();
		if (grammarElement instanceof AbstractElement) {
			return result;
		}
	}
	return null;
}
 
Example #13
Source File: EObjectAtOffsetHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected EObject internalResolveElementAt(XtextResource resource, int offset, boolean containment) {
	if(!containment) {
		EObject crossRef = resolveCrossReferencedElementAt(resource, offset);
		if (crossRef != null)
			return crossRef;
	}
	IParseResult parseResult = resource.getParseResult();
	if (parseResult != null) {
		ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset);
		if (leaf != null && leaf.isHidden() && leaf.getOffset() == offset) {
			leaf = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), offset - 1);
		}
		if (leaf != null) {
			return NodeModelUtils.findActualSemanticObjectFor(leaf);
		}
	}
	return null;
}
 
Example #14
Source File: BrokenConstructorCallAwareEObjectAtOffsetHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected EObject resolveCrossReferencedElement(INode node) {
	EObject referenceOwner = NodeModelUtils.findActualSemanticObjectFor(node);
	if (referenceOwner != null) {
		EReference crossReference = GrammarUtil.getReference((CrossReference) node.getGrammarElement(),
				referenceOwner.eClass());
		if (!crossReference.isMany()) {
			EObject resultOrProxy = (EObject) referenceOwner.eGet(crossReference);
			if (resultOrProxy != null && resultOrProxy.eIsProxy() && crossReference == XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR) {
				if (referenceOwner instanceof XConstructorCall) {
					JvmIdentifiableElement linkedType = batchTypeResolver.resolveTypes(referenceOwner).getLinkedFeature((XConstructorCall)referenceOwner);
					if (linkedType != null)
						return linkedType;
				}
			} 
			return resultOrProxy;
		} else {
			return super.resolveCrossReferencedElement(node);
		}
	}
	return null;
}
 
Example #15
Source File: TaxonomyCheckboxListView.java    From slr-toolkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
	if (part instanceof XtextEditor && !selection.isEmpty()) {
		final XtextEditor editor = (XtextEditor) part;
		final IXtextDocument document = editor.getDocument();

		document.readOnly(new IUnitOfWork.Void<XtextResource>() {
			@Override
			public void process(XtextResource resource) throws Exception {
				IParseResult parseResult = resource.getParseResult();
				if (parseResult != null) {
					ICompositeNode root = parseResult.getRootNode();
					EObject taxonomy = NodeModelUtils.findActualSemanticObjectFor(root);
					if (taxonomy instanceof Model) {
						ModelRegistryPlugin.getModelRegistry().setActiveTaxonomy((Model) taxonomy);
					}
				}
			}
		});
	}
}
 
Example #16
Source File: XbaseProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isKeywordWorthyToPropose(Keyword keyword, ContentAssistContext context) {
	if (isKeywordWorthyToPropose(keyword)) {
		if ("as".equals(keyword.getValue()) || "instanceof".equals(keyword.getValue())) {
			EObject previousModel = context.getPreviousModel();
			if (previousModel instanceof XExpression) {
				if (context.getPrefix().length() == 0) {
					if (NodeModelUtils.getNode(previousModel).getEndOffset() > context.getOffset()) {
						return false;
					}
				}
				LightweightTypeReference type = typeResolver.resolveTypes(previousModel).getActualType((XExpression) previousModel);
				if (type == null || type.isPrimitiveVoid()) {
					return false;
				}
			}
		}
		return true;
	}
	return false;
}
 
Example #17
Source File: JSDoc2SpecAcceptor.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private String toPos(EObject eobj) {
	if (eobj == null)
		return "";
	StringBuilder strb = new StringBuilder();
	String res = null;
	if (eobj.eResource() != null) {
		res = eobj.eResource().getURI().toString();
		if (res.startsWith("platform:/resource/")) {
			res = res.substring("platform:/resource/".length());
		}
	}
	if (res != null)
		strb.append(res);
	EObject astNode = eobj instanceof SyntaxRelatedTElement ? ((SyntaxRelatedTElement) eobj).getAstElement() : eobj;
	ICompositeNode node = NodeModelUtils.findActualNodeFor(astNode);
	if (node != null) {
		strb.append(":").append(node.getStartLine());
	}
	return strb.toString();
}
 
Example #18
Source File: AbstractCompletePrefixProviderTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private void assertLastCompleteNode(final String model, final String expectation) {
  try {
    int offset = model.indexOf("<|>");
    if ((offset == (-1))) {
      offset = model.length();
    }
    int completionOffset = model.indexOf("<|>", offset);
    if ((completionOffset == (-1))) {
      completionOffset = offset;
    }
    final Tree tree = this.parseHelper.parse(model.replace("<|>", ""));
    final ICompositeNode nodeModel = NodeModelUtils.findActualNodeFor(tree);
    final INode completeNode = this.getTestee().getLastCompleteNodeByOffset(nodeModel, offset, completionOffset);
    this.assertNodeModel(expectation, completeNode);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #19
Source File: XtextElementSelectionListener.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the URI of the semantic element currently selected.
 *
 * @return URI or null
 */
public URI getSelectedElementUri() {
  if (selection instanceof IStructuredSelection) {
    if (((IStructuredSelection) selection).getFirstElement() instanceof InternalEObject) {
      // structured selection, e.g. GMFEditor
      return EcoreUtil.getURI((EObject) ((IStructuredSelection) selection).getFirstElement());
    } else if (((IStructuredSelection) selection).getFirstElement() instanceof EObjectNode) {
      // selection in outline
      return ((EObjectNode) ((IStructuredSelection) selection).getFirstElement()).getEObjectURI();
    }
  } else {
    ILeafNode node = nodeAtTextSelection();
    EObject semanticObject = NodeModelUtils.findActualSemanticObjectFor(node);
    if (semanticObject != null) {
      return EcoreUtil.getURI(semanticObject);
    }
  }
  return null;
}
 
Example #20
Source File: XtextResource.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public void update(int offset, int replacedTextLength, String newText) {
	if (!isLoaded()) {
		throw new IllegalStateException("You can't update an unloaded resource.");
	}
	try {
		isUpdating = true;
		IParseResult oldParseResult = parseResult;
		ReplaceRegion replaceRegion = new ReplaceRegion(new TextRegion(offset, replacedTextLength), newText);
		IParseResult newParseResult;
		ParserRule oldEntryPoint = NodeModelUtils.getEntryParserRule(oldParseResult.getRootNode());
		if (entryPoint == null || entryPoint == oldEntryPoint) {
			newParseResult = getParser().reparse(oldParseResult, replaceRegion);
		} else {
			StringBuilder builder = new StringBuilder(oldParseResult.getRootNode().getText());
			replaceRegion.applyTo(builder);
			newParseResult = getParser().parse(entryPoint, new StringReader(builder.toString()));
		}
		updateInternalState(oldParseResult, newParseResult);
	} finally {
		isUpdating = false;
	}
}
 
Example #21
Source File: XbaseLocationInFileProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ITextRegion getSignificantTextRegion(EObject element) {
	if (element instanceof XAbstractFeatureCall) {
		XAbstractFeatureCall typeLiteral = typeLiteralHelper.getRootTypeLiteral((XAbstractFeatureCall) element);
		if (typeLiteral != null) {
			if (typeLiteral instanceof XMemberFeatureCall) {
				XAbstractFeatureCall target = (XAbstractFeatureCall) ((XMemberFeatureCall) typeLiteral).getMemberCallTarget();
				if (target.isTypeLiteral()) {
					return super.getSignificantTextRegion(typeLiteral);
				}
			}
			INode node = NodeModelUtils.findActualNodeFor(typeLiteral);
			if (node != null) {
				return toZeroBasedRegion(node.getTextRegionWithLineInformation());
			}
		}
	}
	return super.getSignificantTextRegion(element);
}
 
Example #22
Source File: AbstractValidationTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Persist list diagnostics into string to display the list of issue codes.
 *
 * @param diagnostics
 *          list of diagnostics
 * @param displayPathToTargetObject
 *          if true, the path through the object hierarchy is printed out up to the root node
 * @return
 *         string with list of issue codes, separated with a line break
 */
// TODO (ACF-4153) generalize for all kinds of errors and move to AbstractXtextTest
private String diagnosticsToString(final Diagnostic diagnostics, final boolean displayPathToTargetObject) {
  StringBuilder sb = new StringBuilder();
  for (Diagnostic diagnostic : diagnostics.getChildren()) {
    if (diagnostic instanceof AbstractValidationDiagnostic) {
      AbstractValidationDiagnostic avd = (AbstractValidationDiagnostic) diagnostic;
      sb.append("    ");
      sb.append(avd.getIssueCode());
      if (displayPathToTargetObject) {
        sb.append(" at line: ");
        sb.append(NodeModelUtils.findActualNodeFor(avd.getSourceEObject()).getStartLine());
        sb.append(" on \n");
        sb.append(pathFromRootAsString(avd.getSourceEObject(), "      "));
      }
      sb.append(LINE_BREAK);
    }
  }
  return sb.toString();
}
 
Example #23
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Fix(IssueCodes.MISSING_OVERRIDE)
public void fixMissingOverride(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Change 'def' to 'override'", "Marks this function as 'override'", "fix_indent.gif",
			new ISemanticModification() {
				@Override
				public void apply(EObject element, IModificationContext context) throws Exception {
					replaceKeyword(grammarAccess.getMethodModifierAccess().findKeywords("def").get(0), "override", element,
							context.getXtextDocument());
					if (element instanceof XtendFunction) {
						XtendFunction function = (XtendFunction) element;
						for (XAnnotation anno : Lists.reverse(function.getAnnotations())) {
							if (anno != null && anno.getAnnotationType() != null && Override.class.getName().equals(anno.getAnnotationType().getIdentifier())) {
								ICompositeNode node = NodeModelUtils.findActualNodeFor(anno);
								context.getXtextDocument().replace(node.getOffset(), node.getLength(), "");
							}
						}
					}
				}
			});
}
 
Example #24
Source File: TestLanguageRenameService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected EObject getElementWithIdentifierAt(XtextResource xtextResource, int offset) {
	if (offset >= 0) {
		if (xtextResource != null) {
			IParseResult parseResult = xtextResource.getParseResult();
			if (parseResult != null) {
				ICompositeNode rootNode = parseResult.getRootNode();
				if (rootNode != null) {
					ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset);
					if (leaf != null && isIdentifier(leaf)) {
						EObject element = eObjectAtOffsetHelper.resolveElementAt(xtextResource, offset);
						if (element != null) {
							IQualifiedNameProvider nameProvider = xtextResource.getResourceServiceProvider()
									.get(IQualifiedNameProvider.class);
							QualifiedName fqn = nameProvider.getFullyQualifiedName(element);
							if (fqn != null) {
								String leafText = NodeModelUtils.getTokenText(leaf);
								if (fqn.getSegmentCount() == 1 && Objects.equal(fqn.toString(), leafText)
										|| Objects.equal(fqn.getLastSegment(), leafText)) {
									return element;
								}
							}
						}
					}
				}
			}
		}
	}
	return null;
}
 
Example #25
Source File: OverrideIndicatorModelListener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected Map<Annotation, Position> createOverrideIndicatorAnnotationMap(XtextResource xtextResource, CancelIndicator cancelIndicator) {
	List<EObject> contents = xtextResource.getContents();
	if (contents.isEmpty())
		return Maps.newHashMap();
	EObject eObject = contents.get(0);
	if (!(eObject instanceof XtendFile)) {
		return Maps.newHashMap();
	}
	XtendFile xtendFile = (XtendFile) eObject;
	Map<Annotation, Position> annotationToPosition = Maps.newHashMap();
	for (XtendFunction xtendFunction : getXtendFunctions(xtendFile)) {
		if(cancelIndicator.isCanceled())
			throw new OperationCanceledException();
		if (xtendFunction.isOverride()) {
			typeResolver.resolveTypes(xtendFunction);
			INode node = NodeModelUtils.getNode(xtendFunction);
			JvmOperation inferredOperation = associations.getDirectlyInferredOperation(xtendFunction);
			if (inferredOperation != null) {
				JvmOperation jvmOperation = overrideHelper.findOverriddenOperation(inferredOperation);
				if (node != null && jvmOperation != null) {
					boolean overwriteIndicator = isOverwriteIndicator(jvmOperation);
					String text = (overwriteIndicator ? "overrides " : "implements ") + jvmOperation.getQualifiedName(); //$NON-NLS-1$ //$NON-NLS-2$
					node = getFirst(findNodesForFeature(xtendFunction, XtendPackage.eINSTANCE.getXtendFunction_Name()),
							node);
					annotationToPosition.put(
							new OverrideIndicatorAnnotation(overwriteIndicator, text, xtextResource
									.getURIFragment(xtendFunction)), new Position(node.getOffset()));
				}
			}
		}
	}
	return annotationToPosition;
}
 
Example #26
Source File: CompileTimeEvaluationError.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns this error's message with a suffix explaining where the error occurred if {@link #astNode} is given. This
 * method ignores field {@link #feature}.
 */
public String getMessageWithLocation() {
	if (astNode == null) {
		return message;
	}
	final INode node = NodeModelUtils.findActualNodeFor(astNode);
	final String tokenText = node != null ? NodeModelUtils.getTokenText(node) : null;
	if (tokenText == null) {
		return message;
	}
	return message + " at \"" + tokenText + "\"";
}
 
Example #27
Source File: AbstractFragmentsTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testFragmentRecursive_03() throws Exception {
	ParserRuleFragments fragments = parseAndValidate("#11 myName myPrev");
	Assert.assertNotNull(fragments);
	Assert.assertEquals("myName", fragments.getElement().getName());
	PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev();
	Assert.assertEquals("myPrev", prev.getName());
	ICompositeNode node = NodeModelUtils.findActualNodeFor(prev);
	Assert.assertEquals(" myPrev", node.getText());
	EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node);
	Assert.assertSame(prev, lookup);
}
 
Example #28
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 #29
Source File: ParseErrorHandlingTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=236425
 * @throws Exception
 */
@Test public void testBug236425() throws Exception {
	with(ReferenceGrammarTestLanguageStandaloneSetup.class);
	String model = "spielplatz 100 }";
	EObject object = getModelAndExpect(model, 1);
	ICompositeNode node = NodeModelUtils.getNode(object).getRootNode();
	assertEquals(1, Iterables.size(allSyntaxErrors(node)));
}
 
Example #30
Source File: FastLazyURIEncoder.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Triple<EObject, EReference, INode> decode(final Resource res, final String uriFragment) {
  if (isUseIndexFragment(res)) {
    return getLazyProxyInformation(res, uriFragment);
  }
  try {
    int idx = DECODE_START_IDX;
    int idx2 = uriFragment.indexOf(SEP, idx);
    EObject source = resolveShortFragment(res, uriFragment.substring(idx, idx2));

    idx = idx2 + 2;
    idx2 = uriFragment.indexOf(SEP, idx);
    INode node = NodeModelUtils.getNode(source);
    if (node == null) {
      throw new IllegalStateException("Couldn't resolve lazy link, because no node model is attached."); //$NON-NLS-1$
    }

    EReference ref = fromShortExternalForm(source.eClass(), uriFragment.substring(idx, idx2));
    idx = idx2 + 2;
    INode text = getNode(node, uriFragment.substring(idx));
    return Tuples.create(source, ref, text);
    // CHECKSTYLE:OFF Yes, we *do* want to catch RuntimeExceptions here
  } catch (RuntimeException ex) {
    // CHECKSTYLE:ON
    throw new DecodingError(ex);
  }
}