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

The following examples show how to use org.eclipse.xtext.nodemodel.util.NodeModelUtils#getNode() . 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: DefaultTextEditComposer.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void beginRecording(Resource newResource) {
	reset();

	if (newResource != resource) {
		if (resource != null)
			resource.eAdapters().remove(this);
		newResource.eAdapters().add(this);
		resource = newResource;
	}
	if (resource.getContents().isEmpty()) {
		resourceSize = 0;
	} else {
		final EObject root = resource.getContents().get(0);
		ICompositeNode rootNode = NodeModelUtils.getNode(root);
		if (rootNode == null) {
			throw new IllegalStateException("Cannot find root node in resource " + resource.getURI());
		}
		resourceSize = rootNode.getTotalLength();
	}
	recording = true;
}
 
Example 2
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkNoJavaStyleTypeCasting(XBlockExpression blockExpression) {
	if(isIgnored(JAVA_STYLE_TYPE_CAST)) {
		return;
	}
	if (blockExpression.getExpressions().size() <= 1) {
		return;
	}
	ICompositeNode node = NodeModelUtils.getNode(blockExpression);
	if (node == null) {
		return;
	}
	INode expressionNode = null;
	for (INode child : node.getChildren()) {
		if (isSemicolon(child)) {
			expressionNode = null;
		} else if (isXExpressionInsideBlock(child)) {
			if (expressionNode != null) {
				checkNoJavaStyleTypeCasting(expressionNode);
			}
			expressionNode = child;
		}
	}
}
 
Example 3
Source File: AbstractLabelProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a default styled string for the given {@link EObject} model element.
 *
 * @param eObject
 *          the {@link EObject} model element
 * @return the styled string for the given {@link EObject} model element
 */
public Object getStyledLabel(final EObject eObject) {
  // first check if object is foreign to this grammar
  if (isForeignXtextObject(eObject)) {
    return getForeignObjectLabel(eObject);
  }
  // first check if object has a name
  String name = getNameOfObject(eObject);
  if (name != null) {
    return qualifiedStyledString(name, getTypeOfObject(eObject));
  }
  // secondly check first parsed element (keyword / feature)
  ICompositeNode node = NodeModelUtils.getNode(eObject);
  if (node != null) {
    Iterator<ILeafNode> leafNodesIterator = node.getLeafNodes().iterator();
    while (leafNodesIterator.hasNext()) {
      ILeafNode genericLeafNode = leafNodesIterator.next();
      if (!(genericLeafNode instanceof HiddenLeafNode)) {
        LeafNode leafNode = (LeafNode) genericLeafNode;
        return getLabelName(leafNode.getText(), eObject.eClass().getName(), true);
      }
    }
  }
  // fallback
  return super.doGetText(eObject);
}
 
Example 4
Source File: FormatResourceDescriptionStrategy.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether given EObject represents a Xbase local variable.
 *
 * @param eObject
 *          to be checked
 * @return true if the given object does not represent a xbase local variable
 */
public boolean isXbaseLocalVariableName(final EObject eObject) {
  INode semanticNode = NodeModelUtils.getNode(eObject);
  if (semanticNode != null) {
    INode leafNode = NodeModelUtils.findLeafNodeAtOffset(semanticNode, semanticNode.getTotalOffset());
    AbstractRule containingRule = GrammarUtil.containingRule(leafNode.getGrammarElement());
    if (leafNode != null && containingRule != null && "ValidID".equals(containingRule.getName())) {
      return true;
    }
  }
  return false;
}
 
Example 5
Source File: ExtractMethodHandler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void updateSelection(final XtextEditor editor, List<XExpression> expressions) {
	ICompositeNode firstNode = NodeModelUtils.getNode(expressions.get(0));
	ICompositeNode lastNode = NodeModelUtils.getNode(expressions.get(expressions.size() - 1));
	if (firstNode != null && lastNode != null) {
		int correctedSelectionOffset = firstNode.getOffset();
		int correctedSelectionLength = lastNode.getEndOffset() - correctedSelectionOffset;
		editor.selectAndReveal(correctedSelectionOffset, correctedSelectionLength);
	}
}
 
Example 6
Source File: XtendOutlineNodeFactory.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
private void configureNode(IOutlineNode parentNode, EObject modelElement, int inheritanceDepth,
		XtendEObjectNode featureNode) {
	EObject primarySourceElement = associations.getPrimarySourceElement(modelElement);
	ICompositeNode parserNode = NodeModelUtils.getNode(primarySourceElement==null?modelElement:primarySourceElement);
	if (parserNode != null)
		featureNode.setTextRegion(parserNode.getTextRegion());
	if (isLocalElement(parentNode, modelElement))
		featureNode.setShortTextRegion(getLocationInFileProvider().getSignificantTextRegion(primarySourceElement==null?modelElement:primarySourceElement));
	featureNode.setStatic(isStatic(modelElement));
	featureNode.setInheritanceDepth(inheritanceDepth);
}
 
Example 7
Source File: N4JSDocumentationProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns documentation nodes for N4JS AST and type elements (in which case the method returns the nodes of the
 * corresponding AST element). If the AST element has no documentation nodes itself, but is an exportable element,
 * then the documentation of the export statement is returned if present.
 */
@Override
public List<INode> getDocumentationNodes(EObject object) {
	final EObject astNode = N4JSASTUtils.getCorrespondingASTNode(object);
	if (astNode != null) {
		List<INode> nodes = super.getDocumentationNodes(astNode);
		if (nodes.isEmpty() && astNode instanceof VariableDeclaration) {
			TypeRef typeRef = ((VariableDeclaration) astNode).getDeclaredTypeRef();
			if (typeRef != null) {
				nodes = getDocumentationNodes(typeRef);
			}
		}
		if (nodes.isEmpty()) {
			if (astNode instanceof ExportedVariableDeclaration
					&& astNode.eContainer() instanceof ExportedVariableStatement) {
				EList<VariableDeclaration> decls = ((ExportedVariableStatement) astNode.eContainer()).getVarDecl();
				if (decls.size() == 1) {
					return getDocumentationNodes(astNode.eContainer());
				}
			}
			if (astNode instanceof ExportableElement && astNode.eContainer() instanceof ExportDeclaration) {
				nodes = super.getDocumentationNodes(astNode.eContainer());
			}
		}
		if (nodes.isEmpty()) {
			// failure case, was ASI grabbing the doc?
			// backward search for first non-hidden element, over-stepping if it is a LeafNodeWithSyntaxError from
			// ASI.
			ICompositeNode ptNodeOfASTNode = NodeModelUtils.getNode(astNode);
			LeafNode lNode = searchLeafNodeDocumentation(ptNodeOfASTNode);
			if (lNode != null) {
				return Collections.<INode> singletonList(lNode);
			}
		}
		return nodes;
	}
	return super.getDocumentationNodes(object);
}
 
Example 8
Source File: EvaluatedTemplate.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public EvaluatedTemplate(Codetemplate template) {
	TemplateBody body = template.getBody();
	StringBuilder buffer = new StringBuilder();
	StringBuilder original = new StringBuilder();
	mappedOffsetHints = Lists.newArrayList();
	int lastOffset = 0;
	for(TemplatePart part: body.getParts()) {
		ICompositeNode node = NodeModelUtils.getNode(part);
		if (node != null) {
			mappedOffsetHints.add(Tuples.create(buffer.length(), node.getTotalOffset()));
			lastOffset = node.getTotalOffset() + node.getTotalLength();
			original.append(node.getText());
			if (part instanceof Literal) {
				buffer.append(((Literal) part).getValue());
			} else if (part instanceof Dollar) {
				buffer.append("$");
			} else if (part instanceof Variable) {
				if (((Variable) part).getName() != null) {
					buffer.append(((Variable) part).getName());
				}
			}
		}
	}
	mappedOffsetHints.add(Tuples.create(buffer.length(), lastOffset));
	evaluatedResult = buffer.toString();
	originalTemplate = original.toString();
}
 
Example 9
Source File: SARLOutlineTreeProvider.java    From sarl with 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 10
Source File: RepoRelativePath.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a (maybe new) RepoRelativePath with line number of the given test member.
 */
public RepoRelativePath withLine(SyntaxRelatedTElement testMember) {
	ICompositeNode node = NodeModelUtils.getNode(testMember.getAstElement());
	if (node != null) {
		final int line = node.getStartLine();
		final RepoRelativePath rrp = new RepoRelativePath(repositoryName, pathOfProjectInRepo, projectName,
				pathInProject, line);
		return rrp;
	}
	return this;
}
 
Example 11
Source File: InterpreterAutoEdit.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected Evaluation findEvaluation(DocumentCommand command, XtextResource state) {
	if (!state.getContents().isEmpty()) {
		org.eclipse.xtext.example.arithmetics.arithmetics.Module m = 
				(org.eclipse.xtext.example.arithmetics.arithmetics.Module) state.getContents().get(0);
		for (Evaluation evaluation : Iterables.filter(m.getStatements(), Evaluation.class)) {
			ICompositeNode node = NodeModelUtils.getNode(evaluation);
			if (node.getOffset() <= command.offset && node.getOffset() + node.getLength() >= command.offset) {
				return evaluation;
			}
		}
	}
	return null;
}
 
Example 12
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void completeTypeRef_Classifier(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	Grammar grammar = GrammarUtil.getGrammar(model);
	ContentAssistContext.Builder myContextBuilder = context.copy();
	myContextBuilder.setMatcher(new ClassifierPrefixMatcher(context.getMatcher(), classifierQualifiedNameConverter));
	if (model instanceof TypeRef) {
		ICompositeNode node = NodeModelUtils.getNode(model);
		if (node != null) {
			int offset = node.getOffset();
			Region replaceRegion = new Region(offset, context.getReplaceRegion().getLength()
					+ context.getReplaceRegion().getOffset() - offset);
			myContextBuilder.setReplaceRegion(replaceRegion);
			myContextBuilder.setLastCompleteNode(node);
			StringBuilder availablePrefix = new StringBuilder(4);
			for (ILeafNode leaf : node.getLeafNodes()) {
				if (leaf.getGrammarElement() != null && !leaf.isHidden()) {
					if ((leaf.getTotalLength() + leaf.getTotalOffset()) < context.getOffset())
						availablePrefix.append(leaf.getText());
					else
						availablePrefix.append(leaf.getText().substring(0,
								context.getOffset() - leaf.getTotalOffset()));
				}
				if (leaf.getTotalOffset() >= context.getOffset())
					break;
			}
			myContextBuilder.setPrefix(availablePrefix.toString());
		}
	}
	ContentAssistContext myContext = myContextBuilder.toContext();
	for (AbstractMetamodelDeclaration declaration : grammar.getMetamodelDeclarations()) {
		if (declaration.getEPackage() != null) {
			createClassifierProposals(declaration, model, myContext, acceptor);
		}
	}
}
 
Example 13
Source File: DefaultCallHierarchyBuilder.java    From xtext-core with 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 14
Source File: SerializerTester.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected String getTextFromNodeModel(EObject semanticObject) {
	Resource res = semanticObject.eResource();
	if (res instanceof XtextResource && res.getContents().contains(semanticObject))
		return ((XtextResource) res).getParseResult().getRootNode().getText();
	INode node = NodeModelUtils.getNode(semanticObject);
	Assert.assertNotNull(node);
	return node.getText();
}
 
Example 15
Source File: N4JSOutlineNodeFactory.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns N4JSEObjectNode instead of simple EObjectNode to allow for attaching additional information such as
 * inheritance state of members.
 */
@Override
public N4JSEObjectNode createEObjectNode(IOutlineNode parentNode, EObject modelElement,
		ImageDescriptor imageDescriptor,
		Object text,
		boolean isLeaf) {
	N4JSEObjectNode eObjectNode = new N4JSEObjectNode(modelElement, parentNode, imageDescriptor, text, isLeaf);
	ICompositeNode parserNode = NodeModelUtils.getNode(modelElement);
	if (parserNode != null)
		eObjectNode.setTextRegion(parserNode.getTextRegion());
	if (isLocalElement(parentNode, modelElement))
		eObjectNode.setShortTextRegion(getLocationInFileProvider().getSignificantTextRegion(modelElement));
	return eObjectNode;
}
 
Example 16
Source File: Bug305397Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testBug() throws Exception {
	with(new Bug305397StandaloneSetup());
	Model model = (Model) getModel("   a element \n   element X end\n element Y end \nend");
	Element outer = model.getElements().get(0);
	Element firstInner = outer.getElements().get(0);
	
	ICompositeNode outerNode = NodeModelUtils.getNode(outer);
	assertEquals(3,outerNode.getOffset());
	ICompositeNode firstInnerNode = NodeModelUtils.getNode(firstInner);
	assertEquals(17,firstInnerNode.getOffset());
}
 
Example 17
Source File: Bug317840Test.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testNodeModel_11() throws Exception {
	Model model = getModel("element a.a ");
	INode node = NodeModelUtils.getNode(model);
	assertEquals("element a.a ", node.getText());
	assertEquals("[[(element)[[( )(a)(.)(a)]]]( )]", toDebugString(node));
}
 
Example 18
Source File: Bug317840Test.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testNodeModel_08() throws Exception {
	Element element = getFirstElement("element a.a b.b c.c");
	INode node = NodeModelUtils.getNode(element);
	assertEquals("element a.a b.b c.c", node.getText());
	assertEquals("[(element)[[( )(a)(.)(a)]][[( )(b)(.)(b)]][[( )(c)(.)(c)]]]", toDebugString(node));
}
 
Example 19
Source File: Bug317840Test.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testNodeModel_03() throws Exception {
	Element element = getFirstElement("element a b c");
	INode node = NodeModelUtils.getNode(element);
	assertEquals("element a b c", node.getText());
	assertEquals("[(element)[[( )(a)]][[( )(b)]][[( )(c)]]]", toDebugString(node));
}
 
Example 20
Source File: ReplAutoEdit.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected String computeResultText(final IDocument document, final DocumentCommand command, XtextResource resource)
		throws BadLocationException {
	if (resource.getContents().isEmpty())
		return null;
	if (!(resource.getContents().get(0) instanceof Model))
		return null;
	Model model = (Model) resource.getContents().get(0);
	if (model.getBlock() == null)
		return null;
	EList<XExpression> expressions = model.getBlock().getExpressions();
	if (expressions.isEmpty())
		return null;
	XExpression expression = expressions.get(expressions.size() - 1);
	if (expression == null) {
		return null;
	}
	ICompositeNode node = NodeModelUtils.getNode(expression);
	if (node == null || document.getLineOfOffset(command.offset) + 1 != node.getEndLine())
		return null;
	List<Issue> issues = validator.validate(resource, CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl);
	if (issues.stream().anyMatch(i -> i.getSeverity() == Severity.ERROR)) {
		return null;
	}
	XbaseInterpreter xbaseInterpreter = getConfiguredInterpreter(resource);
	IEvaluationResult result = xbaseInterpreter.evaluate(model.getBlock(), new DefaultEvaluationContext(),
			new CancelIndicator() {
				private long stopAt = System.currentTimeMillis() + 2000;

				@Override
				public boolean isCanceled() {
					return System.currentTimeMillis() > stopAt;
				}
			});
	if (result == null)
		return null;

	String value = "" + result.getResult();
	if (result.getException() != null)
		value = "threw " + result.getException().getClass().getSimpleName();

	LightweightTypeReference expressionType = typeResolver.resolveTypes(expression).getActualType(expression);
	if (expressionType != null) {
		String newText = command.text + "// " + value + " ("
				+ expressionType.getSimpleName() + ")" + command.text;
		return newText;
	}
	return command.text + "// " + value;
}