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 Project: gef   Author: eclipse   File: DotHtmlLabelValidator.java    License: 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 #2
Source Project: n4js   Author: eclipse   File: QuickFixXpectMethod.java    License: 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 #3
Source Project: n4js   Author: eclipse   File: LabellingReferenceFinder.java    License: 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 #4
Source Project: xtext-core   Author: eclipse   File: EObjectAtOffsetHelper.java    License: 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 #5
Source Project: dsl-devkit   Author: dsldevkit   File: XtextElementSelectionListener.java    License: 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 #6
Source Project: n4js   Author: eclipse   File: JSDoc2SpecAcceptor.java    License: 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 #7
Source Project: xtext-eclipse   Author: eclipse   File: XtextLabelProvider.java    License: 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 #8
Source Project: xtext-core   Author: eclipse   File: EntryPointFinder.java    License: 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 #9
Source Project: xtext-core   Author: eclipse   File: SetEntryPointOnXtextResourceTest.java    License: 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 #10
Source Project: dsl-devkit   Author: dsldevkit   File: AbstractSyntaxColoringTest.java    License: 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 #11
Source Project: xtext-xtend   Author: eclipse   File: XtendQuickfixProvider.java    License: 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 #12
Source Project: dsl-devkit   Author: dsldevkit   File: AbstractValidationTest.java    License: 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 #13
Source Project: xtext-eclipse   Author: eclipse   File: XbaseProposalProvider.java    License: 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 #14
Source Project: slr-toolkit   Author: sebastiangoetz   File: TaxonomyCheckboxListView.java    License: 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 #15
Source Project: xtext-core   Author: eclipse   File: AbstractCompletePrefixProviderTest.java    License: 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 #16
Source Project: xtext-core   Author: eclipse   File: XtextResource.java    License: 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 #17
Source Project: xtext-extras   Author: eclipse   File: XbaseLocationInFileProvider.java    License: 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 #18
@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 #19
Source Project: xtext-extras   Author: eclipse   File: FeatureCallCompiler.java    License: 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 #20
Source Project: gef   Author: eclipse   File: DotStyleValidator.java    License: 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 #21
Source Project: dsl-devkit   Author: dsldevkit   File: SingleLineCommentDocumentationProvider.java    License: 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 #22
Source Project: xtext-xtend   Author: eclipse   File: XtendHoverSerializer.java    License: 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 #23
Source Project: xtext-xtend   Author: eclipse   File: XtendQuickfixProvider.java    License: 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 #24
Source Project: xtext-core   Author: eclipse   File: SemanticNodeIterator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public SemanticNodeIterator(EObject obj) {
	INode start = NodeModelUtils.findActualNodeFor(obj);
	if (start != null) {
		this.next = findNext(start, false);
		while (this.next != null && this.next.getThird() == obj)
			this.next = findNext(this.next.getFirst(), false);
	} else
		this.next = null;
}
 
Example #25
Source Project: xtext-core   Author: eclipse   File: UnassignedRuleCallTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testNodeModel_01() throws Exception {
	String modelAsText = "model 7 feature Zonk 1 keyword 1;";
	Model model = (Model) getModel(modelAsText);
	ICompositeNode node = NodeModelUtils.getNode(model);
	assertEquals(4, Iterables.size(node.getChildren()));
	ModelFeatures modelFeatures = model.getModelFeatures();
	ICompositeNode featuresNode = NodeModelUtils.getNode(modelFeatures);
	assertSame(featuresNode, Iterables.get(node.getChildren(), 3));
	assertEquals(6, Iterables.size(featuresNode.getChildren()));
	ICompositeNode dataTypeNode = (ICompositeNode) Iterables.get(featuresNode.getChildren(), 4);
	assertEquals(6, Iterables.size(dataTypeNode.getChildren()));
}
 
Example #26
Source Project: xtext-core   Author: eclipse   File: DefaultCallHierarchyBuilder.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected String getText(EObject obj, ITextRegionWithLineInformation textRegion) {
	if (obj == null || textRegion == ITextRegionWithLineInformation.EMPTY_REGION) {
		return "";
	}
	ICompositeNode node = NodeModelUtils.getNode(EcoreUtil.getRootContainer(obj));
	if (node == null) {
		return "";
	}
	int endOffset = textRegion.getOffset() + textRegion.getLength();
	return node.getRootNode().getText().substring(textRegion.getOffset(), endOffset);
}
 
Example #27
Source Project: dsl-devkit   Author: dsldevkit   File: ReorderingHiddenTokenSequencer.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void init(final ISerializationContext context, final EObject semanticObject, final ISequenceAcceptor sequenceAcceptor, final Acceptor errorAcceptor) {
  this.delegate = sequenceAcceptor;
  this.lastNode = NodeModelUtils.findActualNodeFor(semanticObject);
  this.rootNode = lastNode;
  if (rootNode != null) {
    this.rootOffset = rootNode.getTotalOffset();
    this.rootEndOffset = rootNode.getTotalEndOffset();
  }
}
 
Example #28
Source Project: sarl   Author: sarl   File: SARLOutlineTreeProvider.java    License: Apache License 2.0 5 votes vote down vote up
private void configureNode(IOutlineNode parentNode, EObject modelElement, SARLEObjectNode objectNode) {
	final EObject primarySourceElement = this.associations.getPrimarySourceElement(modelElement);
	final ICompositeNode parserNode = NodeModelUtils.getNode(
			(primarySourceElement == null) ? modelElement : primarySourceElement);

	if (parserNode != null) {
		objectNode.setTextRegion(parserNode.getTextRegion());
	}

	if (isLocalElement(parentNode, modelElement)) {
		objectNode.setShortTextRegion(this.locationInFileProvider.getSignificantTextRegion(modelElement));
	}

	objectNode.setStatic(isStatic(modelElement));
}
 
Example #29
Source Project: xtext-eclipse   Author: eclipse   File: OutlineNodeFactory.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public EObjectNode createEObjectNode(IOutlineNode parentNode, EObject modelElement, ImageDescriptor imageDescriptor, Object text,
		boolean isLeaf) {
	EObjectNode eObjectNode = new EObjectNode(modelElement, parentNode, imageDescriptor, text, isLeaf);
	ICompositeNode parserNode = NodeModelUtils.getNode(modelElement);
	if (parserNode != null)
		eObjectNode.setTextRegion(parserNode.getTextRegion());
	if(isLocalElement(parentNode, modelElement))
		eObjectNode.setShortTextRegion(locationInFileProvider.getSignificantTextRegion(modelElement));
	return eObjectNode;
}
 
Example #30
Source Project: xtext-eclipse   Author: eclipse   File: InsertionOffsets.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public int inEmpty(EObject element) {
	ICompositeNode compositeNode = NodeModelUtils.findActualNodeFor(element);
	for (ILeafNode leafNode : compositeNode.getLeafNodes()) {
		if ("{".equals(leafNode.getText())) {
			return leafNode.getOffset() + 1;
		}
	}
	return compositeNode.getEndOffset();
}