org.eclipse.xtext.nodemodel.BidiTreeIterator Java Examples

The following examples show how to use org.eclipse.xtext.nodemodel.BidiTreeIterator. 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: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void checkNoJavaStyleTypeCasting(INode node) {
	BidiTreeIterator<INode> iterator = node.getAsTreeIterable().reverse().iterator();
	ILeafNode child = getFirstLeafNode(iterator);
	if (child != null && child.getGrammarElement() == grammarAccess.getXParenthesizedExpressionAccess().getRightParenthesisKeyword_2()) {
		INode expressionNode = getNode(iterator, grammarAccess.getXParenthesizedExpressionAccess().getXExpressionParserRuleCall_1());
		EObject semanticObject = NodeModelUtils.findActualSemanticObjectFor(expressionNode);
		if (semanticObject instanceof XFeatureCall || semanticObject instanceof XMemberFeatureCall) {
			XAbstractFeatureCall featureCall = (XAbstractFeatureCall) semanticObject;
			if (featureCall.isTypeLiteral()) {
				ICompositeNode parenthesizedNode = child.getParent();
				ITextRegion parenthesizedRegion = parenthesizedNode.getTextRegion();
				addIssue("Use 'as' keyword for type casting.", featureCall, parenthesizedRegion.getOffset(), parenthesizedRegion.getLength(), JAVA_STYLE_TYPE_CAST);
			}
		}
	}
}
 
Example #2
Source File: NodeModelBuilder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public void replaceAndTransferLookAhead(INode oldNode, INode newRootNode) {
	AbstractNode newNode = ((CompositeNode) newRootNode).basicGetFirstChild();
	replaceWithoutChildren((AbstractNode) oldNode, newNode);
	if (oldNode instanceof ICompositeNode && newNode instanceof CompositeNode) {
		CompositeNode newCompositeNode = (CompositeNode) newNode;
		newCompositeNode.basicSetLookAhead(((ICompositeNode) oldNode).getLookAhead());
	}
	ICompositeNode root = newNode.getRootNode();
	BidiTreeIterator<AbstractNode> iterator = ((AbstractNode) root).basicIterator();
	int offset = 0;
	while(iterator.hasNext()) {
		AbstractNode node = iterator.next();
		if (node instanceof LeafNode) {
			((LeafNode) node).basicSetTotalOffset(offset);
			offset += node.getTotalLength();
		}
	}
}
 
Example #3
Source File: TokenSequencePreservingPartialParsingHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns true if the previous document state was completely broken, e.g. the parser did not recover at all.
 * This may happen e.g. in Xtend for documents like
 * <pre>import static class C {}</pre>
 * where the class keyword is consumed as an invalid token in the import declaration and everything thereafter
 * is unrecoverable.
 */
protected boolean isBrokenPreviousState(IParseResult previousParseResult, int offset) {
	if (previousParseResult.hasSyntaxErrors()) {
		BidiTreeIterator<AbstractNode> iterator = ((AbstractNode) previousParseResult.getRootNode()).basicIterator();
		while(iterator.hasPrevious()) {
			AbstractNode previous = iterator.previous();
			if (previous.getGrammarElement() == null) {
				return true;
			}
			if (previous instanceof ILeafNode && previous.getOffset() <= offset) {
				break;
			}
		}
	}
	return false;
}
 
Example #4
Source File: ImportRegionHelper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Goes from the beginning of the RootNode up to the passed in node. Looks only at hidden leafs and at
 * ASI-LeafNodes.
 *
 * @return {@code false} if any comment is encountered on the way.
 */
private boolean hasNoCommentUpTo(ILeafNode node) {
	if (node == null)
		return true;

	BidiTreeIterator<INode> iter = node.getRootNode().getAsTreeIterable().iterator();
	while (iter.hasNext()) {
		INode curr = iter.next();
		// exit case:
		if (curr == node)
			return true;

		if (curr instanceof LeafNode) {
			if (((LeafNode) curr).isHidden() ||
					UtilN4.isIgnoredSyntaxErrorNode(curr, InternalSemicolonInjectingParser.SEMICOLON_INSERTED)) {
				// hidden OR ASI
				if (!curr.getText().trim().isEmpty()) {
					// token-text contains not only whitespace --> there must be a comment.
					return false;
				}
			}
		}
	}
	// should never be reached.
	throw new IllegalStateException("Iteration over-stepped the passed in node.");
}
 
Example #5
Source File: AbstractPartialParserTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
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 #6
Source File: RichStringFormatter.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean _hasSyntaxError(final NodeEObjectRegion region) {
  final BidiTreeIterator<INode> i = region.getNode().getAsTreeIterable().iterator();
  while (i.hasNext()) {
    SyntaxErrorMessage _syntaxErrorMessage = i.next().getSyntaxErrorMessage();
    boolean _tripleNotEquals = (_syntaxErrorMessage != null);
    if (_tripleNotEquals) {
      return true;
    }
  }
  return false;
}
 
Example #7
Source File: AbstractInternalAntlrParser.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected INode getLastLeafNode() {
	BidiTreeIterator<INode> iter = currentNode.getAsTreeIterable().iterator();
	while(iter.hasPrevious()) {
		INode previous = iter.previous();
		if (previous instanceof ILeafNode)
			return previous;
	}
	return currentNode;
}
 
Example #8
Source File: PartialParsingHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private INode getLastChild(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;
}
 
Example #9
Source File: PartialParsingHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private INode getLastLeaf(ICompositeNode parent) {
	BidiTreeIterator<? extends INode> iterator = parent.getAsTreeIterable().iterator();
	while(iterator.hasPrevious()) {
		INode previous = iterator.previous();
		if (previous instanceof ILeafNode) {
			return previous;
		} 
	}
	return null;
}
 
Example #10
Source File: SemanticNodeProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected EObject getSemanticChild(INode node) {
	EObject root = node.getSemanticElement();
	if (root != null && root != this.semanticObject)
		return root;
	BidiTreeIterator<INode> iterator = node.getAsTreeIterable().iterator();
	while (iterator.hasNext()) {
		EObject candidate = iterator.next().getSemanticElement();
		if (candidate != null && candidate != this.semanticObject)
			return candidate;
	}
	return null;
}
 
Example #11
Source File: PartialParserTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void checkGrammarAssigned(ICompositeNode rootNode) {
	BidiTreeIterator<INode> iterator = rootNode.getAsTreeIterable().iterator();
	while(iterator.hasNext()) {
		INode next = iterator.next();
		if (next != rootNode) {
			assertNotNull(next.getGrammarElement());
		}
	}
}
 
Example #12
Source File: IndentationAwareCompletionPrefixProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected INode getLastCompleteNodeByOffset(INode node, int offset) {
	BidiTreeIterator<INode> iterator = node.getRootNode().getAsTreeIterable().iterator();
	INode result = node;
	ITextRegion candidateTextRegion = node.getTextRegion();
	while (iterator.hasNext()) {
		INode candidate = iterator.next();
		ITextRegion textRegion = candidate.getTextRegion();
		if (textRegion.getOffset() >= offset && !(textRegion.getOffset() == offset && textRegion.getLength() == 0)) {
			if (!candidateTextRegion.equals(textRegion) && candidate instanceof ILeafNode && textRegion.getLength() + textRegion.getOffset() >= offset) {
				break;
			}
		} 
		if ((candidate instanceof ILeafNode) &&
				   (candidate.getGrammarElement() == null ||
						   candidate.getGrammarElement() instanceof AbstractElement ||
						   candidate.getGrammarElement() instanceof ParserRule)) {
			if (textRegion.getLength() == 0) {
				if (candidateTextRegion.getOffset() + candidateTextRegion.getLength() < offset || candidateTextRegion.getLength() == 0 && candidateTextRegion.getOffset() <= offset) {
					result = candidate;
					candidateTextRegion = candidate.getTextRegion();
				}
			} else {
				result = candidate;
				candidateTextRegion = candidate.getTextRegion();
			}
		}
	}
	return result;
}
 
Example #13
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: FixedPartialParsingHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private INode getLastLeaf(final ICompositeNode parent) {
  BidiTreeIterator<? extends INode> iterator = parent.getAsTreeIterable().iterator();
  while (iterator.hasPrevious()) {
    INode previous = iterator.previous();
    if (previous instanceof ILeafNode) {
      return previous;
    }
  }
  return null;
}
 
Example #15
Source File: Bug480686Test.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private void assertEqual(ICompositeNode fromScratch, ICompositeNode reparsed) {
	BidiTreeIterator<INode> scratchIterator = fromScratch.getAsTreeIterable().iterator();
	BidiTreeIterator<INode> reparsedIterator = reparsed.getAsTreeIterable().iterator();
	while (scratchIterator.hasNext()) {
		Assert.assertTrue(reparsedIterator.hasNext());
		assertEqualNodes(scratchIterator.next(), reparsedIterator.next());
	}
	Assert.assertFalse(scratchIterator.hasNext());
	Assert.assertFalse(reparsedIterator.hasNext());
}
 
Example #16
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected ILeafNode getFirstLeafNode(BidiTreeIterator<INode> iterator) {
	while(iterator.hasNext()) {
		INode child = iterator.next();
		if (isHidden(child)) {
			continue;
		}
		if (child instanceof ILeafNode) {
			return (ILeafNode) child;
		}
	}
	return null;
}
 
Example #17
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected INode getNode(BidiTreeIterator<INode> iterator, EObject... grammarElements) {
	while (iterator.hasNext()) {
		INode node = iterator.next();
		EObject grammarElement = node.getGrammarElement();
		for (EObject expectedGrammarElement : grammarElements) {
			if (grammarElement == expectedGrammarElement) {
				return node;
			}
		}
	}
	return null;
}
 
Example #18
Source File: SoliditySemanticHighlighter.java    From solidity-ide with Eclipse Public License 1.0 5 votes vote down vote up
private void provideHighLightForNamedElement(NamedElement namedElement, String textStyle,
		IHighlightedPositionAcceptor acceptor) {
	ICompositeNode node = NodeModelUtils.findActualNodeFor(namedElement);
	if (node != null && namedElement.getName() != null) {
		BidiTreeIterator<INode> iterator = node.getAsTreeIterable().iterator();
		while (iterator.hasNext()) {
			INode nextNode = iterator.next();
			if (namedElement.getName().equals(nextNode.getText())) {
				provideHighLightForNamedElement(namedElement, nextNode, textStyle, acceptor);
			}
		}
	}
}
 
Example #19
Source File: NodeModelUtils.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Find the leaf node at the given offset. May return <code>null</code> if the given offset is not valid for the
 * node (sub-)tree.
 * 
 * A node matches the <code>leafNodeOffset</code> if it fulfills the following condition:
 * <pre>
 *  node.totalOffset &lt;= leafNodeOffset &amp;&amp;
 *  node.totalEndOffset &gt; leafNodeOffset 
 * </pre>
 * 
 * @param node the container node. May not be <code>null</code>.
 * @param leafNodeOffset the offset that is covered by the searched node.
 * @return the leaf node at the given offset or <code>null</code>.
 */
/* @Nullable */
public static ILeafNode findLeafNodeAtOffset(/* @NonNull */ INode node, int leafNodeOffset) {
	INode localNode = node;
	while(!(localNode instanceof AbstractNode)) {
		localNode = localNode.getParent();
	}
	int offset = localNode.getTotalOffset();
	int length = localNode.getTotalLength();
	BidiTreeIterator<AbstractNode> iterator = ((AbstractNode) localNode).basicIterator();
	if (leafNodeOffset > (offset + length) / 2) {
		while (iterator.hasPrevious()) {
			AbstractNode previous = iterator.previous();
			int previousOffset = previous.getTotalOffset();
			int previousLength = previous.getTotalLength();
			if (!intersects(previousOffset, previousLength, leafNodeOffset)) {
				if (previousOffset + previousLength <= leafNodeOffset) {
					return null;
				}
				iterator.prune();
			} else {
				if (previous instanceof ILeafNode)
					return (ILeafNode) previous;
			}
		}
	} else {
		while (iterator.hasNext()) {
			AbstractNode next = iterator.next();
			int nextOffset = next.getTotalOffset();
			int nextLength = next.getTotalLength();
			if (!intersects(nextOffset, nextLength, leafNodeOffset)) {
				if (nextOffset > leafNodeOffset) {
					return null;
				}
				iterator.prune();
			} else {
				if (next instanceof ILeafNode)
					return (ILeafNode) next;
			}
		}
	}
	return null;
}
 
Example #20
Source File: ProxyCompositeNode.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public BidiTreeIterator<INode> iterator() {
  // it is important to not delegate this method, because the iterator must return this instance for some clients such as NodeModelUtils to work correctly
  return new NodeTreeIterator(this);
}
 
Example #21
Source File: SyntheticCompositeNode.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public BidiTreeIterator<INode> iterator() {
	return new NodeTreeIterator(this);
}
 
Example #22
Source File: AbstractNode.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public BidiTreeIterator<AbstractNode> basicIterator() {
	return new BasicNodeTreeIterator(this);
}
 
Example #23
Source File: AbstractNode.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public BidiTreeIterator<INode> iterator() {
	return new NodeTreeIterator(this);
}
 
Example #24
Source File: ReversedBidiTreeIterator.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected BidiTreeIterator<T> getDelegate() {
	return (BidiTreeIterator<T>) super.getDelegate();
}
 
Example #25
Source File: ReversedBidiTreeIterator.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public ReversedBidiTreeIterator(BidiTreeIterator<T> delegate) {
	super(delegate);
}
 
Example #26
Source File: ReversedBidiTreeIterable.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public BidiTreeIterator<T> iterator() {
	BidiTreeIterator<T> delegate = getDelegate().iterator(); 
	return new ReversedBidiTreeIterator<T>(delegate);
}
 
Example #27
Source File: ResourceStorageTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testWriteAndLoad() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo");
    _builder.newLine();
    _builder.newLine();
    _builder.append("class Bar {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def dispatch myMethod(String s) {}");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("/**");
    _builder.newLine();
    _builder.append("\t ");
    _builder.append("* Hello myMethod ");
    _builder.newLine();
    _builder.append("\t ");
    _builder.append("*/");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def dispatch myMethod(CharSequence cs) {}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    _builder.append("class Foo {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def dispatch other(String it) {");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("var x = \"\"");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("x = length.toString");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("println(x)");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final String contents = _builder.toString();
    final XtendFile file = this.file(contents);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ((ResourceStorageFacade) this.resourceStorageFacade).setStoreNodeModel(true);
    Resource _eResource = file.eResource();
    this.resourceStorageFacade.createResourceStorageWritable(bout).writeResource(((StorageAwareResource) _eResource));
    byte[] _byteArray = bout.toByteArray();
    ByteArrayInputStream _byteArrayInputStream = new ByteArrayInputStream(_byteArray);
    final ResourceStorageLoadable in = this.resourceStorageFacade.createResourceStorageLoadable(_byteArrayInputStream);
    Resource _createResource = file.eResource().getResourceSet().createResource(URI.createURI("synthetic:/test/MyClass.xtend"));
    final StorageAwareResource resource = ((StorageAwareResource) _createResource);
    final InMemoryURIConverter converter = new InMemoryURIConverter();
    converter.addModel(resource.getURI().toString(), contents);
    ResourceSet _resourceSet = resource.getResourceSet();
    _resourceSet.setURIConverter(converter);
    EList<Resource> _resources = file.eResource().getResourceSet().getResources();
    _resources.add(resource);
    resource.loadFromStorage(in);
    EObject _get = resource.getContents().get(1);
    final JvmGenericType jvmClass = ((JvmGenericType) _get);
    Assert.assertEquals("java.lang.CharSequence", IterableExtensions.<JvmFormalParameter>head((((JvmOperation[])Conversions.unwrapArray(jvmClass.getDeclaredOperations(), JvmOperation.class))[2]).getParameters()).getParameterType().getQualifiedName());
    Assert.assertEquals("java.lang.Object", (((JvmOperation[])Conversions.unwrapArray(jvmClass.getDeclaredOperations(), JvmOperation.class))[2]).getReturnType().getQualifiedName());
    Assert.assertEquals("Hello myMethod", IterableExtensions.<DocumentationAdapter>head(Iterables.<DocumentationAdapter>filter((((JvmOperation[])Conversions.unwrapArray(jvmClass.getDeclaredOperations(), JvmOperation.class))[1]).eAdapters(), DocumentationAdapter.class)).getDocumentation());
    Assert.assertEquals(resource.getURI(), resource.getResourceDescription().getURI());
    Assert.assertEquals(2, IterableExtensions.size(resource.getResourceDescription().getExportedObjects()));
    Assert.assertEquals("foo.Bar", IterableExtensions.<IEObjectDescription>head(resource.getResourceDescription().getExportedObjects()).getQualifiedName().toString());
    final BidiTreeIterator<INode> restoredNodes = NodeModelUtils.findActualNodeFor(IterableExtensions.<EObject>head(resource.getContents())).getAsTreeIterable().iterator();
    final BidiTreeIterator<INode> originalNodes = NodeModelUtils.findActualNodeFor(file).getAsTreeIterable().iterator();
    while (restoredNodes.hasNext()) {
      {
        final INode rest = restoredNodes.next();
        final INode orig = originalNodes.next();
        Assert.assertEquals(orig.getStartLine(), rest.getStartLine());
        Assert.assertEquals(orig.getEndLine(), rest.getEndLine());
        Assert.assertEquals(orig.getOffset(), rest.getOffset());
        Assert.assertEquals(orig.getEndOffset(), rest.getEndOffset());
        Assert.assertEquals(orig.getLength(), rest.getLength());
        Assert.assertEquals(orig.getTotalStartLine(), rest.getTotalStartLine());
        Assert.assertEquals(orig.getTotalEndLine(), rest.getTotalEndLine());
        Assert.assertEquals(orig.getTotalOffset(), rest.getTotalOffset());
        Assert.assertEquals(orig.getTotalEndOffset(), rest.getTotalEndOffset());
        Assert.assertEquals(orig.getTotalLength(), rest.getTotalLength());
        Assert.assertSame(orig.getGrammarElement(), rest.getGrammarElement());
        Assert.assertEquals(file.eResource().getURIFragment(orig.getSemanticElement()), resource.getURIFragment(rest.getSemanticElement()));
        Assert.assertEquals(orig.getText(), rest.getText());
      }
    }
    Assert.assertFalse(originalNodes.hasNext());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #28
Source File: ResourceStorageTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testWriteAndLoad() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("{");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("var x = \"Hello\"");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("var y = \"\"");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("val it = x");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("y = length.toString");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("println(x)");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("y = length.toString");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("println(x)");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("y = length.toString");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("println(x)");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final String contents = _builder.toString();
    final XExpression file = this.expression(contents);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ((ResourceStorageFacade) this.resourceStorageFacade).setStoreNodeModel(true);
    Resource _eResource = file.eResource();
    this.resourceStorageFacade.createResourceStorageWritable(bout).writeResource(((StorageAwareResource) _eResource));
    byte[] _byteArray = bout.toByteArray();
    ByteArrayInputStream _byteArrayInputStream = new ByteArrayInputStream(_byteArray);
    final ResourceStorageLoadable in = this.resourceStorageFacade.createResourceStorageLoadable(_byteArrayInputStream);
    Resource _createResource = file.eResource().getResourceSet().createResource(URI.createURI("synthetic:/Test.___xbase"));
    final StorageAwareResource resource = ((StorageAwareResource) _createResource);
    final ResourceStorageTest.InMemoryURIConverter converter = new ResourceStorageTest.InMemoryURIConverter();
    converter.addModel(resource.getURI().toString(), contents);
    ResourceSet _resourceSet = resource.getResourceSet();
    _resourceSet.setURIConverter(converter);
    EList<Resource> _resources = file.eResource().getResourceSet().getResources();
    _resources.add(resource);
    resource.loadFromStorage(in);
    EObject _get = resource.getContents().get(0);
    final XExpression root = ((XExpression) _get);
    Assert.assertTrue((root instanceof XBlockExpression));
    final BidiTreeIterator<INode> restoredNodes = NodeModelUtils.findActualNodeFor(IterableExtensions.<EObject>head(resource.getContents())).getAsTreeIterable().iterator();
    final BidiTreeIterator<INode> originalNodes = NodeModelUtils.findActualNodeFor(file).getAsTreeIterable().iterator();
    while (restoredNodes.hasNext()) {
      {
        final INode rest = restoredNodes.next();
        final INode orig = originalNodes.next();
        Assert.assertEquals(orig.getStartLine(), rest.getStartLine());
        Assert.assertEquals(orig.getEndLine(), rest.getEndLine());
        Assert.assertEquals(orig.getOffset(), rest.getOffset());
        Assert.assertEquals(orig.getEndOffset(), rest.getEndOffset());
        Assert.assertEquals(orig.getLength(), rest.getLength());
        Assert.assertEquals(orig.getTotalStartLine(), rest.getTotalStartLine());
        Assert.assertEquals(orig.getTotalEndLine(), rest.getTotalEndLine());
        Assert.assertEquals(orig.getTotalOffset(), rest.getTotalOffset());
        Assert.assertEquals(orig.getTotalEndOffset(), rest.getTotalEndOffset());
        Assert.assertEquals(orig.getTotalLength(), rest.getTotalLength());
        Assert.assertSame(orig.getGrammarElement(), rest.getGrammarElement());
        Assert.assertTrue((((orig.getSemanticElement() != null) && (rest.getSemanticElement() != null)) || ((orig.getSemanticElement() == null) && (rest.getSemanticElement() == null))));
        EObject _semanticElement = orig.getSemanticElement();
        boolean _tripleNotEquals = (_semanticElement != null);
        if (_tripleNotEquals) {
          Assert.assertEquals(file.eResource().getURIFragment(orig.getSemanticElement()), resource.getURIFragment(rest.getSemanticElement()));
        }
        Assert.assertEquals(orig.getText(), rest.getText());
      }
    }
    Assert.assertFalse(originalNodes.hasNext());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #29
Source File: N4JSSyntaxValidator.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the first keyword with the given value, or null if no such keyword is found.
 */
private ILeafNode doFindLeafWithKeyword(EObject semanticElement, String stopAtKeyword, ICompositeNode node,
		String keyWord,
		boolean commaAlternative, int hitNumber) {
	EObject grammarElement;
	int foundHits = 0;

	for (BidiTreeIterator<INode> iter = node.getAsTreeIterable().iterator(); iter.hasNext();) {
		INode child = iter.next();
		EObject childSemElement = child.getSemanticElement();
		if (child != node && childSemElement != null && childSemElement != semanticElement) {
			iter.prune();
		} else if (child instanceof ILeafNode) {
			ILeafNode leaf = (ILeafNode) child;
			grammarElement = leaf.getGrammarElement();
			if (grammarElement instanceof Keyword) {
				String value = ((Keyword) grammarElement).getValue();
				if (stopAtKeyword.equals(value)) {
					return null;
				}
				if (keyWord.equals(value)) {
					if (grammarElement.eContainer() instanceof Alternatives) {
						AbstractElement first = ((Alternatives) (grammarElement.eContainer())).getElements().get(0);
						boolean inCommaAlternative = (first instanceof Keyword && ",".equals(((Keyword) first)
								.getValue()));
						if (inCommaAlternative == commaAlternative) {
							foundHits++;
							if (foundHits >= hitNumber) {
								return leaf;
							}
						}
					} else {
						if (!commaAlternative) {
							foundHits++;
							if (foundHits >= hitNumber) {
								return leaf;
							}
						}
					}
				}
			}
		}
	}
	return null;
}