Java Code Examples for org.eclipse.xtext.nodemodel.ICompositeNode

The following examples show how to use org.eclipse.xtext.nodemodel.ICompositeNode. These examples are extracted from open source projects. 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: xtext-core   Source File: NodeTreeIterator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean hasPrevious() {
	if (previousComputed)
		return previous != null;

	if (lastPreviousReturned == null) {
		previous = lastNextReturned != null ? lastNextReturned : root;
	} else if (!pruned && lastPreviousReturned instanceof ICompositeNode && ((ICompositeNode) lastPreviousReturned).hasChildren()) {
		previous = ((ICompositeNode) lastPreviousReturned).getLastChild();
	} else if (root.equals(lastPreviousReturned)) {
		previous = null;
	} else if ((previous = lastPreviousReturned.getPreviousSibling()) != null) {
		// previous found
	} else {
		for (INode parent = lastPreviousReturned.getParent(); previous == null && !root.equals(parent); parent = parent.getParent()) {
			previous = parent.getPreviousSibling();
		}
	}
	previousComputed = true;
	return previous != null;
}
 
Example 2
Source Project: xtext-core   Source File: PartialParserTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testPartialParseConcreteRuleFirstInnerToken_02() throws Exception {
	with(PartialParserTestLanguageStandaloneSetup.class);
	String model = "container c1 {\n" +
			"  children {\n" +
			"    -> C ( ch1 )\n" +
			"  }" +
			"}";
	XtextResource resource = getResourceFromString(model);
	assertTrue(resource.getErrors().isEmpty());
	ICompositeNode root = resource.getParseResult().getRootNode();
	ILeafNode childrenLeaf = findLeafNodeByText(root, model, "children");
	ILeafNode arrowLeaf = findLeafNodeByText(root, model, "->");
	// change the model and undo the change
	resource.update(model.indexOf("->"), 2, "-> ");
	resource.update(model.indexOf("->"), 3, "->");
	assertSame(root, resource.getParseResult().getRootNode());
	assertSame(childrenLeaf, findLeafNodeByText(root, model, "children"));
	assertNotSame(arrowLeaf, findLeafNodeByText(root, model, "->"));
}
 
Example 3
Source Project: dsl-devkit   Source File: AbstractLabelProvider.java    License: 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 Project: n4js   Source 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 5
Source Project: xtext-core   Source File: PartialParserTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testPartialParseConcreteRuleFirstInnerToken_01() throws Exception {
	with(PartialParserTestLanguageStandaloneSetup.class);
	String model = "container c1 {\n" +
			"  children {\n" +
			"    -> C ( ch1 )\n" +
			"  }" +
			"}";
	XtextResource resource = getResourceFromString(model);
	assertTrue(resource.getErrors().isEmpty());
	ICompositeNode root = resource.getParseResult().getRootNode();
	ILeafNode childrenLeaf = findLeafNodeByText(root, model, "children");
	ILeafNode arrowLeaf = findLeafNodeByText(root, model, "->");
	resource.update(model.indexOf("->"), 2, "->");
	resource.update(model.indexOf("->"), 2, "->");
	assertSame(root, resource.getParseResult().getRootNode());
	assertSame(childrenLeaf, findLeafNodeByText(root, model, "children"));
	assertSame(arrowLeaf, findLeafNodeByText(root, model, "->"));
}
 
Example 6
Source Project: xtext-core   Source File: NodeIterator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private INode findPrevious(INode node) {
	ICompositeNode parent = node.getParent();
	if (parent == null) {
		return null;
	}
	INode predecessor = node.getPreviousSibling();
	if (predecessor != null) {
		while (predecessor instanceof ICompositeNode && !prunedComposites.contains(predecessor)) {
			INode lastChild = ((ICompositeNode) predecessor).getLastChild();
			if (lastChild == null) {
				return predecessor;
			}
			predecessor = lastChild;
		}
		return predecessor;
	}
	return parent;
}
 
Example 7
Source Project: xtext-core   Source File: Bug419429Test.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected void compareWithFullParse(String model, int offset, int length, String newText) throws Exception {
	XtextResource resource = getResourceFromStringAndExpect(model, UNKNOWN_EXPECTATION);
	resource.update(offset, length, newText);
	String text = resource.getParseResult().getRootNode().getText();
	XtextResource newResource = getResourceFromStringAndExpect(text, UNKNOWN_EXPECTATION);
	assertEquals(text, resource.getContents().size(), newResource.getContents().size());
	EcoreUtil.resolveAll(resource);
	EcoreUtil.resolveAll(newResource);
	for(int i = 0; i < resource.getContents().size(); i++) {
		assertEquals(text, EmfFormatter.objToStr(newResource.getContents().get(i)), EmfFormatter.objToStr(resource.getContents().get(i)));
	}
	
	ICompositeNode rootNode = resource.getParseResult().getRootNode();
	ICompositeNode newRootNode = newResource.getParseResult().getRootNode();
	Iterator<INode> iterator = rootNode.getAsTreeIterable().iterator();
	Iterator<INode> newIterator = newRootNode.getAsTreeIterable().iterator();
	while(iterator.hasNext()) {
		assertTrue(newIterator.hasNext());
		assertEqualNodes(text, iterator.next(), newIterator.next());
	}
	assertFalse(iterator.hasNext());
	assertFalse(newIterator.hasNext());
}
 
Example 8
protected AbstractElement getEntryGrammarElement(ICompositeNode entryPoint) {
	EObject grammarElement = entryPoint.getGrammarElement();
	if (grammarElement instanceof RuleCall) {
		AbstractRule rule = ((RuleCall) grammarElement).getRule();
		if (rule instanceof ParserRule) {
			if (!GrammarUtil.isMultipleCardinality(rule.getAlternatives())) {
				grammarElement = rule.getAlternatives();
			}
		}
	} else if (grammarElement instanceof ParserRule) {
		grammarElement = ((ParserRule) grammarElement).getAlternatives();
	} else if (grammarElement instanceof CrossReference) {
		grammarElement = GrammarUtil.containingAssignment(grammarElement);
	}
	AbstractElement result = (AbstractElement) grammarElement;
	if (result instanceof Action) {
		return getEntryGrammarElement((ICompositeNode) entryPoint.getFirstChild());
	}
	return result;
}
 
Example 9
Source Project: xtext-xtend   Source 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 10
Source Project: xtext-core   Source File: LazyURIEncoder.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * ONLY public to be testable
 */
public INode getNode(final INode node, String path) {
	final List<String> split = Strings.split(path, '/');
	INode result = node;
	for (String string : split) {
		String trimmed = string.trim();
		if (trimmed.length() > 0) {
			if ("..".equals(trimmed)) {
				if (result.getParent() == null)
					throw new IllegalStateException("node has no parent");
				result = result.getParent();
			} else {
				int index = Integer.parseInt(string);
				if (index >= 0) {
					INode child = ((ICompositeNode) result).getFirstChild();
					while(index > 0) {
						child = child.getNextSibling();
						index--;
					}
					result = child;
				}
			}
		}
	}
	return result;
}
 
Example 11
Source Project: xtext-core   Source File: NodeModelUtils.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static ParserRule getEntryParserRule(INode node) {
	ICompositeNode root = node.getRootNode();
	EObject ge1 = root.getGrammarElement();
	if (ge1 instanceof ParserRule) {
		return (ParserRule) ge1;
	} else if (ge1 instanceof Action) {
		INode firstChild = root.getFirstChild();
		while (firstChild.getGrammarElement() instanceof Action && firstChild instanceof CompositeNode) {
			firstChild = ((CompositeNode)firstChild).getFirstChild();
		}
		EObject ge2 = firstChild.getGrammarElement();
		if (ge2 instanceof ParserRule) {
			return (ParserRule) ge2;
		}
	}
	throw new IllegalStateException("No Root Parser Rule found; The Node Model is broken.");
}
 
Example 12
protected PartialParsingPointers calculatePartialParsingPointers(ICompositeNode oldRoot, ILeafNode left, ILeafNode right) {
	ICompositeNode result = right.getParent();
	while(result.getTotalOffset() > left.getTotalOffset()) {
		result = result.getParent();
	}
	List<ICompositeNode> nodesEnclosingRegion = getAllParents(result);
	Range range = new Range(left.getTotalOffset(), right.getTotalEndOffset());
	List<ICompositeNode> validReplaceRootNodes = internalFindValidReplaceRootNodeForChangeRegion(nodesEnclosingRegion);

	filterInvalidRootNodes(validReplaceRootNodes);

	if (validReplaceRootNodes.isEmpty()) {
		validReplaceRootNodes = Collections.singletonList(oldRoot);
	}
	return new PartialParsingPointers(oldRoot, range.getOffset(), range.getLength(), validReplaceRootNodes, nodesEnclosingRegion);
}
 
Example 13
Source Project: sarl   Source File: SARLQuickfixProvider.java    License: Apache License 2.0 6 votes vote down vote up
private void addAbstractKeyword(XtendTypeDeclaration typeDeclaration, IXtextDocument document,
		String declarationKeyword) throws BadLocationException {
	final ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(typeDeclaration);
	if (clazzNode == null) {
		throw new IllegalStateException("Cannot determine node for the type declaration" //$NON-NLS-1$
				+ typeDeclaration.getName());
	}
	int offset = -1;
	final Iterator<ILeafNode> nodes = clazzNode.getLeafNodes().iterator();
	while (offset == -1 && nodes.hasNext()) {
		final ILeafNode leafNode  = nodes.next();
		if (leafNode.getText().equals(declarationKeyword)) {
			offset = leafNode.getOffset();
		}
	}
	final ReplacingAppendable appendable = this.appendableFactory.create(document,
			(XtextResource) typeDeclaration.eResource(),
			offset, 0);
	appendable.append(getGrammarAccess()
			.getAbstractKeyword())
			.append(" "); //$NON-NLS-1$
	appendable.commitChanges();
}
 
Example 14
@Override
protected IssueLocation getLocationData(EObject obj, EStructuralFeature structuralFeature, int index) {
	if (NodeModelUtils.getNode(obj) == null) {
		ITextRegion location = locationInFileProvider.getSignificantTextRegion(obj);
		if (location != null) {
			ICompositeNode rootNode = NodeModelUtils.getNode(EcoreUtil.getRootContainer(obj));
			if (rootNode != null) {
				ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(rootNode, location.getOffset());
				return getLocationForNode(leafNode);
			}
		} else {
			return super.getLocationData(obj.eContainer(), null, index);
		}
	}
	return super.getLocationData(obj, structuralFeature, index);
}
 
Example 15
/**
 * Returns predecessor of the given node in the parse tree.
 * Copied method from: org.eclipse.xtext.parsetree.reconstr.impl.NodeIterator
 *
 * @param node
 *          for which predecessor should be found
 * @return predecessor
 */
private INode findPrevious(final INode node) {
  ICompositeNode parent = node.getParent();
  if (parent == null) {
    return null;
  }
  INode predecessor = node.getPreviousSibling();
  if (predecessor != null) {
    while (predecessor instanceof ICompositeNode) {
      INode lastChild = ((ICompositeNode) predecessor).getLastChild();
      if (lastChild == null) {
        return predecessor;
      }
      predecessor = lastChild;
    }
    return predecessor;
  }
  return parent;
}
 
Example 16
protected void assertSameStructure(ICompositeNode first, ICompositeNode second) {
	BidiTreeIterator<INode> firstIter = first.getAsTreeIterable().iterator();
	BidiTreeIterator<INode> secondIter = second.getAsTreeIterable().iterator();
	while(firstIter.hasNext()) {
		assertTrue(secondIter.hasNext());
		INode firstNext = firstIter.next();
		INode secondNext = secondIter.next();
		assertEquals(firstNext.getGrammarElement(), secondNext.getGrammarElement());
		assertEquals(firstNext.getClass(), secondNext.getClass());
		assertEquals(firstNext.getTotalOffset(), secondNext.getTotalOffset());
		assertEquals(firstNext.getTotalLength(), secondNext.getTotalLength());
		assertEquals(firstNext.getText(), secondNext.getText());
		
	}
	assertEquals(firstIter.hasNext(), secondIter.hasNext());
}
 
Example 17
Source Project: xtext-core   Source File: DocumentExtensions.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public Position newPosition(Resource resource, int offset) {
	if (resource instanceof XtextResource) {
		ICompositeNode rootNode = ((XtextResource) resource).getParseResult().getRootNode();
		LineAndColumn lineAndColumn = getLineAndColumn(rootNode, offset);
		return new Position(lineAndColumn.getLine() - 1, lineAndColumn.getColumn() - 1);
	}
	return null;
}
 
Example 18
Source Project: xtext-core   Source File: Bug305397Test.java    License: 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 19
Source Project: xtext-xtend   Source File: CodeBuilderQuickfix.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected int getTypeIndentation(final XtextResource resource, final IXtextDocument document, final XtendTypeDeclaration xtendClass) {
  final EObject object = resource.getEObject(EcoreUtil.getURI(xtendClass).fragment());
  if ((object != null)) {
    final ICompositeNode node = NodeModelUtils.findActualNodeFor(object);
    if ((node != null)) {
      return this.appendableFactory.getIndentationLevelAtOffset(node.getOffset(), document, resource);
    }
  }
  return 0;
}
 
Example 20
Source Project: dsl-devkit   Source File: AbstractXtextTestUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Given an AST node, find the first non-hidden leaf node among child nodes using deep search.
 * For the sake of compatibility the method can handle LeafNodes and CompositeNodes.
 * In case of a LeafNode the result is the input node itself.
 *
 * @param node
 *          entry point
 * @return
 *         first node for which isHidden() is false or the original node
 */
public INode findFirstNonHiddenLeafNode(final INode node) {
  if (node instanceof ICompositeNode) {
    for (ILeafNode leaf : node.getLeafNodes()) {
      if (!leaf.isHidden()) {
        return leaf;
      }
    }
  }
  return node;
}
 
Example 21
Source Project: n4js   Source File: PreparationStep.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Here we use the target of the original cross reference "id", "property", or "declaredType" to set the rewired
 * target (i.e. symbol table entry) of the corresponding IM-model reference "id_IM", "property_IM", or
 * "declaredType_IM".
 */
private void rewire(EObject eObject, ReferencingElement_IM copyEObject) {
	final IdentifiableElement originalTarget = getOriginalTargetOfNodeToRewire(eObject);
	final SymbolTableEntry rewiredTarget;
	if (!originalTarget.eIsProxy()) {
		// standard case: original target is a valid IdentifiableElement
		rewiredTarget = getSymbolTableEntry(originalTarget, true);
		copyEObject.setRewiredTarget(rewiredTarget);
	} else {
		// special case: unresolved proxy
		// -> this is usually an error, except in the following special cases:
		if (eObject instanceof ParameterizedPropertyAccessExpression) {
			// property access to an any+ type
			// -> because we know the transpiler is never invoked for resources that contain errors, we can
			// simply assume that we have the any+ case without actually checking the type of the receiver
			final String propName = getPropertyAsString((ParameterizedPropertyAccessExpression) eObject);
			((ParameterizedPropertyAccessExpression_IM) copyEObject).setAnyPlusAccess(true);
			((ParameterizedPropertyAccessExpression_IM) copyEObject).setNameOfAnyPlusProperty(propName);
		} else if (isDynamicNamespaceReference(eObject)) {
			// type references via dynamic namespace imports can still be transpiled
			// (no additional properties to set in ParameterizedTypeRef_IM)
		} else if (eObject instanceof IdentifierRef && eObject.eContainer() instanceof JSXElementName) {
			// name of a JSX element, e.g. the "div" in something like: <div prop='value'></div>
			String tagName = ((IdentifierRef) eObject).getIdAsText();
			((IdentifierRef_IM) copyEObject).setIdAsText(tagName);
		} else if (MigrationUtils.isMigrateCall(eObject.eContainer())) {
			// unresolved migrate-calls can still be transpiled
		} else {
			final ICompositeNode node = NodeModelUtils.findActualNodeFor(eObject);
			final LineAndColumn pos = NodeModelUtils.getLineAndColumn(node, node.getOffset());
			throw new UnresolvedProxyInSubGeneratorException(
					eObject.eResource(), pos.getLine(), pos.getColumn());
		}
	}
}
 
Example 22
Source Project: dsl-devkit   Source File: EObjectUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a location string for an EObject suitable to include in debugging error messages.
 *
 * @param obj
 *          object
 * @return location string including URI of object
 */
public static String getLocationString(final EObject obj) {
  if (obj == null) {
    return null;
  }
  ICompositeNode node = NodeModelUtils.findActualNodeFor(obj);
  URI uri = EcoreUtil.getURI(obj);
  if (node != null) {
    return uri.trimFragment() + ":" + node.getStartLine() + " (" + obj + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  }
  return uri.toString() + " (" + obj + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
 
Example 23
public ITextRegion selectEnclosing(XtextResource resource, ITextRegion currentEditorSelection) {
	Pair<EObject, EObject> currentlySelected = getSelectedAstElements(resource, currentEditorSelection);
	if (currentlySelected == null) {
		IParseResult parseResult = resource.getParseResult();
		if (parseResult != null) {
			ICompositeNode rootNode = parseResult.getRootNode();
			int offset = getSelectionOffset(rootNode, currentEditorSelection);
			INode node = findLeafNodeAtOffset(rootNode, offset);
			if (node != null) {
				ITextRegion fineGrainedRegion = computeInitialFineGrainedSelection(node, currentEditorSelection);
				if (fineGrainedRegion != null) {
					selectionHistory.clear();
					register(currentEditorSelection);
					return register(fineGrainedRegion);
				}
				EObject eObject = findSemanticObjectFor(node);
				return register(getTextRegion(eObject));
			}
		}
	} else {
		EObject first = currentlySelected.getFirst();
		if (first.eContainer() != null) {
			return register(getTextRegion(first.eContainer()));
		}
	}
	return ITextRegion.EMPTY_REGION;
}
 
Example 24
protected Multimap<EObject, AbstractElement> computeCurrentModel(EObject currentModel, INode lastCompleteNode,
		Collection<AbstractElement> followElements) {
	Multimap<EObject, AbstractElement> result = LinkedHashMultimap.create();
	ICompositeNode currentParserNode = NodeModelUtils.getNode(currentModel);
	if (currentParserNode == null) {
		result.putAll(currentModel, followElements);
		return result;
	}
	EObject currentGrammarElement = currentParserNode.getGrammarElement();
	AbstractRule currentRule = getRule(currentGrammarElement);
	for (AbstractElement grammarElement : followElements) {
		AbstractRule rule = currentRule;
		ICompositeNode loopParserNode = currentParserNode;
		EObject loopLastGrammarElement = lastCompleteNode.getGrammarElement();
		while (!canBeCalledAfter(rule, loopLastGrammarElement, lastCompleteNode.getText(), grammarElement) && loopParserNode.getParent() != null) {
			loopLastGrammarElement = loopParserNode.getGrammarElement();
			loopParserNode = loopParserNode.getParent();
			while (loopParserNode.getGrammarElement() == null && loopParserNode.getParent() != null)
				loopParserNode = loopParserNode.getParent();
			EObject loopGrammarElement = loopParserNode.getGrammarElement();
			rule = getRule(loopGrammarElement);
		}
		EObject context = loopParserNode.getSemanticElement();
		result.put(context, grammarElement);
	}
	return result;
}
 
Example 25
Source Project: xtext-xtend   Source File: InsertionOffsets.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected int after(final EObject element) {
  int _xblockexpression = (int) 0;
  {
    final ICompositeNode node = NodeModelUtils.findActualNodeFor(element);
    _xblockexpression = node.getEndOffset();
  }
  return _xblockexpression;
}
 
Example 26
Source Project: xtext-core   Source File: NodeModelBuilder.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public ICompositeNode newCompositeNode(EObject grammarElement, int lookahead, ICompositeNode parent) {
	CompositeNodeWithSemanticElement result = new CompositeNodeWithSemanticElement();
	if (forcedGrammarElement != null) {
		result.basicSetGrammarElement(forcedGrammarElement);
		forcedGrammarElement = null;
	} else {
		result.basicSetGrammarElement(grammarElement);
	}
	result.basicSetLookAhead(lookahead);
	addChild(parent, result);
	return result;
}
 
Example 27
Source Project: xtext-core   Source File: Serializer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options) {
	ICompositeNode node = NodeModelUtils.findActualNodeFor(obj);
	if (node == null) {
		throw new IllegalStateException("Cannot replace an obj that has no associated node");
	}
	String text = serialize(obj, options);
	int replaceRegionLength = calculateReplaceRegionLength(node, text);
	return new ReplaceRegion(node.getTotalOffset(), replaceRegionLength, text);
}
 
Example 28
Source Project: xtext-extras   Source File: Bug480686Test.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void assertEqualNodes(INode node, INode other) {
	Assert.assertEquals(node.getClass(), other.getClass());
	if (node instanceof ILeafNode) {
		ILeafNode leafNode = (ILeafNode) node;
		Assert.assertEquals(leafNode.getTotalOffset(), other.getTotalOffset());
		Assert.assertEquals(leafNode.getTotalLength(), other.getTotalLength());
	}
	Assert.assertEquals(node.getGrammarElement(), other.getGrammarElement());
	Assert.assertEquals(Boolean.valueOf(node.hasDirectSemanticElement()), other.hasDirectSemanticElement());
	Assert.assertEquals(node.getSyntaxErrorMessage(), other.getSyntaxErrorMessage());
	if (node instanceof ICompositeNode) {
		ICompositeNode compositeNode = (ICompositeNode) node;
		Assert.assertEquals(compositeNode.getText(), compositeNode.getLookAhead(), ((ICompositeNode) other).getLookAhead());
	}
}
 
Example 29
Source Project: xtext-xtend   Source File: XtendProposalProvider.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void completeWithinBlock(EObject model, ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
	if (model instanceof AnonymousClass) {
		ICompositeNode node = NodeModelUtils.getNode(model);
		if (node.getOffset() >= context.getOffset()) {
			super.completeWithinBlock(model, context, acceptor);
		} else {
			return;
		}
	}
	if (model instanceof XtendMember && model.eContainer() instanceof AnonymousClass) {
		return;
	}
	super.completeWithinBlock(model, context, acceptor);
}
 
Example 30
private INode getLastChild(final ICompositeNode parent) {
  BidiTreeIterator<? extends INode> iterator = parent.getAsTreeIterable().iterator();
  while (iterator.hasPrevious()) {
    INode previous = iterator.previous();
    if (previous instanceof ILeafNode) {
      return previous;
    } else if (previous instanceof ICompositeNode) {
      if (!((ICompositeNode) previous).hasChildren()) {
        return previous;
      }
    }
  }
  return parent;
}