Java Code Examples for org.eclipse.xtext.resource.XtextResource#update()

The following examples show how to use org.eclipse.xtext.resource.XtextResource#update() . 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
@Override
public void reloadAllModelsOfType(final String modelType) {
    synchronized (resourceSet) {
        // Make a copy to avoid ConcurrentModificationException
        List<Resource> resourceListCopy = new ArrayList<Resource>(resourceSet.getResources());
        for (Resource resource : resourceListCopy) {
            if (resource != null && resource.getURI().lastSegment().contains(".") && resource.isLoaded()) {
                if (modelType.equalsIgnoreCase(resource.getURI().fileExtension())) {
                    XtextResource xtextResource = (XtextResource) resource;
                    // It's not sufficient to discard the derived state.
                    // The quick & dirts solution is to reparse the whole resource.
                    // We trigger this by dummy updating the resource.
                    logger.debug("Refreshing resource '{}'", resource.getURI().lastSegment());
                    xtextResource.update(1, 0, "");
                    notifyListeners(resource.getURI().lastSegment(), EventType.MODIFIED);
                }
            }
        }
    }
}
 
Example 2
@Override
public void reloadAllModelsOfType(final String modelType) {
    synchronized (resourceSet) {
        // Make a copy to avoid ConcurrentModificationException
        List<Resource> resourceListCopy = new ArrayList<>(resourceSet.getResources());
        for (Resource resource : resourceListCopy) {
            if (resource.getURI().lastSegment().contains(".") && resource.isLoaded()
                    && modelType.equalsIgnoreCase(resource.getURI().fileExtension())
                    && !resource.getURI().lastSegment().startsWith("tmp_")) {
                XtextResource xtextResource = (XtextResource) resource;
                // It's not sufficient to discard the derived state.
                // The quick & dirts solution is to reparse the whole resource.
                // We trigger this by dummy updating the resource.
                logger.debug("Refreshing resource '{}'", resource.getURI().lastSegment());
                xtextResource.update(1, 0, "");
                notifyListeners(resource.getURI().lastSegment(), EventType.MODIFIED);
            }
        }
    }
}
 
Example 3
@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 4
@Test public void testCheckParsing() throws Exception {
	String string = "spielplatz 34 'holla' {\n"
		+ "  kind (Horst 3)\n"
		+ "  erwachsener (Julia 45)\n"
		+ "  erwachsener (Herrmann 50)\n" 
		+ "  erwachsener (Herrmann 50)\n" 
		+ "  erwachsener (Herrmann 50)\n" 
		+ "  erwachsener (Herrmann 50)\n" 
		+ "  erwachsener (Herrmann 50)\n" 
		+ "}";
	XtextResource resource = getResource(new StringInputStream(string));
	ICompositeNode rootNode = resource.getParseResult().getRootNode();
	
	for (int i=0;i<string.length()/2;i++) {
		String substring = string.substring(i, string.length()-i);
		resource.update(i, substring.length(), substring);
		ICompositeNode model = resource.getParseResult().getRootNode();
		new InvariantChecker().checkInvariant(model);
		assertSameStructure(rootNode, model);
	}
	
}
 
Example 5
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 6
@Test public void testPartialParseConcreteRuleFirstToken_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 children = findLeafNodeByText(root, model, "children");
	resource.update(model.indexOf("n {") + 2, 1, "{");
	resource.update(model.indexOf("n {") + 2, 1, "{");
	assertSame(root, resource.getParseResult().getRootNode());
	assertSame(children, findLeafNodeByText(root, model, "children"));
}
 
Example 7
Source Project: xtext-xtend   File: ParserTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test 
public void testAllGrammarElementsUniqueAfterReparse() throws Exception {
	String text = "class Foo { def m() { newArrayList() } }";
	XtendClass clazz = clazz(text);
	XtextResource resource = (XtextResource) clazz.eResource();
	resource.update(text.indexOf('m'), 0, "m");
	ICompositeNode root = resource.getParseResult().getRootNode();
	assertSame(root, root.getRootNode());
	Set<EObject> grammarElements = Sets.newHashSet();
	for(INode node: root.getAsTreeIterable()) {
		if (node instanceof ICompositeNode) {
			if (node.getGrammarElement() == null) {
				fail("node without grammar element");
			}
			if (!grammarElements.add(node.getGrammarElement())) {
				fail(node.getGrammarElement().toString());
			}
		}
	}
}
 
Example 8
@Test public void testPartialParseConcreteRuleInnermostToken_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 ch1Leaf = findLeafNodeByText(root, model, "ch1");
	resource.update(model.indexOf("ch1") + 1, 1, "h");
	resource.update(model.indexOf("ch1") + 1, 1, "h");
	assertSame(root, resource.getParseResult().getRootNode());
	assertSame(childrenLeaf, findLeafNodeByText(root, model, "children"));
	assertSame(ch1Leaf, findLeafNodeByText(root, model, "ch1"));
}
 
Example 9
protected void replaceAndReparse(String model, int offset, int length, String inserted, boolean expectSameRoot) throws Exception {
	final XtextResource resource = getResourceFromString(model);
	resource.setUnloader(new IReferableElementsUnloader() {
		@Override
		public void unloadRoot(EObject root) {
			InternalEObject internalEObject = (InternalEObject) root;
			internalEObject.eSetProxyURI(resource.getURI().appendFragment(resource.getURIFragment(internalEObject)));
		    internalEObject.eAdapters().clear();
		}});
	assertEquals(1, resource.getContents().size());
	EObject wasObject = resource.getContents().get(0);
	assertNotNull(wasObject.eContainer());
	assertNotSame(wasObject.eResource(), wasObject.eContainer().eResource());
	resource.update(offset, length, inserted);
	assertEquals(1, resource.getContents().size());
	EObject newRoot = resource.getContents().get(0);
	assertEquals(expectSameRoot, wasObject == newRoot);
	if (!expectSameRoot) {
		assertTrue(((InternalEObject)wasObject).eIsProxy());
		assertNotSame(resource, wasObject.eResource());
	}
	assertSame(resource, newRoot.eResource());
}
 
Example 10
@Test
public void testBrokenInput_02() throws Exception {
	ContentAssistFragmentTestLanguageRoot result = parseHelper.parse("}} abc");
	XtextResource res = (XtextResource) result.eResource();
	InvariantChecker invariantChecker = new InvariantChecker();
	invariantChecker.checkInvariant(res.getParseResult().getRootNode());
	res.update(0, 0, "newArrayList()");
	invariantChecker.checkInvariant(res.getParseResult().getRootNode());
	EObject first = Iterables.getFirst(res.getContents(), null);
	Assert.assertTrue(first.eClass().getName(), first instanceof ContentAssistFragmentTestLanguageRoot);
	res.update("newArrayList(".length(), 0, "1");
	invariantChecker.checkInvariant(res.getParseResult().getRootNode());
	EObject second = Iterables.getFirst(res.getContents(), null);
	Assert.assertTrue(second.eClass().getName(), second instanceof ContentAssistFragmentTestLanguageRoot);
}
 
Example 11
private void checkRegisteredPackageNotUnloadedAfterGrammarChange(final String originalGrammar, final int offset, final int length, final String replacement) throws Exception {
  final XtextResource resource = this.getResourceFromString(originalGrammar);
  EObject _get = resource.getContents().get(0);
  final Grammar grammar = ((Grammar) _get);
  final AbstractMetamodelDeclaration generatedMetamodel = grammar.getMetamodelDeclarations().get(0);
  final EPackage ePackage = generatedMetamodel.getEPackage();
  Assert.assertNull(((InternalEObject) ePackage).eProxyURI());
  resource.update(offset, length, replacement);
  Assert.assertNull(((InternalEObject) ePackage).eProxyURI());
}
 
Example 12
@Test public void testFixedLinkingProblem() throws Exception {
	String modelAsText = "type A extends B \n type B extends C";
	XtextResource resource = getResourceFromStringAndExpect(modelAsText, 0);
	assertTrue(resource.getErrors().isEmpty());
	assertEquals(1, resource.getWarnings().size());

	resource.update(modelAsText.indexOf('C'), 1, "A");
	
	assertTrue(resource.getErrors().isEmpty());
	assertTrue(resource.getWarnings().isEmpty());
}
 
Example 13
@Test
public void testExplicitRuleCallsAreTracked() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test.Lang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate test \'http://test\'");
  _builder.newLine();
  _builder.append("Rule: name=super::ID name=ID;");
  _builder.newLine();
  _builder.append("terminal ID: super;");
  _builder.newLine();
  _builder.append("terminal _super: \'s\';");
  _builder.newLine();
  final String grammarAsString = _builder.toString();
  final XtextResource resource = this.getResourceFromString(grammarAsString);
  EObject _get = resource.getContents().get(0);
  Grammar grammar = ((Grammar) _get);
  final AbstractRule firstRule = IterableExtensions.<AbstractRule>head(grammar.getRules());
  final RuleCall firstRuleCall = IteratorExtensions.<RuleCall>head(Iterators.<RuleCall>filter(firstRule.eAllContents(), RuleCall.class));
  Assert.assertTrue(firstRuleCall.isExplicitlyCalled());
  final RuleCall secondRuleCall = IteratorExtensions.<RuleCall>last(Iterators.<RuleCall>filter(firstRule.eAllContents(), RuleCall.class));
  Assert.assertFalse(secondRuleCall.isExplicitlyCalled());
  final RuleCall thirdRuleCall = IteratorExtensions.<RuleCall>head(Iterators.<RuleCall>filter(grammar.getRules().get(1).eAllContents(), RuleCall.class));
  Assert.assertTrue(thirdRuleCall.isExplicitlyCalled());
  resource.update(grammarAsString.indexOf("_super"), 1, " ");
  Assert.assertEquals(resource, firstRuleCall.eResource());
  Assert.assertEquals(resource, secondRuleCall.eResource());
  Assert.assertEquals(resource, thirdRuleCall.eResource());
  resource.getContents();
  Assert.assertFalse(thirdRuleCall.isExplicitlyCalled());
  Assert.assertEquals(IterableExtensions.<AbstractRule>last(grammar.getRules()), thirdRuleCall.getRule());
}
 
Example 14
@Test
public void testRemoveSpace() throws Exception {
	ContentAssistFragmentTestLanguageRoot result = parseHelper.parse(" newArrayList(1) ");
	XtextResource res = (XtextResource) result.eResource();
	res.update(0, 1, "");
	EObject first = Iterables.getFirst(res.getContents(), null);
	Assert.assertTrue(first instanceof ContentAssistFragmentTestLanguageRoot);
}
 
Example 15
@Test
public void testResourceUpdate_02() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("a");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("x");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("b // two tabs");
    _builder.newLine();
    _builder.append("\t         ");
    _builder.append("// tab and 8 spaces (eq 2 tabs)");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("y");
    _builder.newLine();
    final String model = _builder.toString();
    final Tree tree = this.parseHelper.parse(model);
    Resource _eResource = tree.eResource();
    final XtextResource resource = ((XtextResource) _eResource);
    final int idx = model.indexOf(" // tab");
    resource.update(idx, 0, "c");
    EObject _head = IterableExtensions.<EObject>head(resource.getContents());
    final Tree reparsed = ((Tree) _head);
    Assert.assertNotSame(tree, reparsed);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 16
public void performTest(String toBeDeleted) throws Exception {
	String grammarAsText = 
		"grammar TestLanguage with org.eclipse.xtext.common.Terminals\n" +
		"generate test 'myEcoreModel'\n" +
		"Root: value=Test;\n" +
		"Test: (" + toBeDeleted.trim() + " 'foo')*;";
	XtextResource resource = getResourceFromString(grammarAsText);
	Grammar g = (Grammar) resource.getContents().get(0);
	ParserRule rule = (ParserRule) g.getRules().get(1);
	assertEquals("*", rule.getAlternatives().getCardinality());
	resource.update(grammarAsText.indexOf(toBeDeleted), toBeDeleted.length(), "");
	// make sure we did a partial parse pass
	assertSame(rule, ((Grammar) resource.getContents().get(0)).getRules().get(1));
	assertEquals("*", rule.getAlternatives().getCardinality());
}
 
Example 17
@Test public void testParseIsPartial() throws Exception {
	with(ReferenceGrammarTestLanguageStandaloneSetup.class);
	String model = "spielplatz 1 {kind (k 1)\n}";
	XtextResource resource = getResourceFromString(model);
	ICompositeNode rootNode = resource.getParseResult().getRootNode();
	resource.update(model.indexOf("k 1"), 3, "l 2");
	assertSame(rootNode, resource.getParseResult().getRootNode());
}
 
Example 18
@Test public void testParseIsPartialTwice() throws Exception {
	with(ReferenceGrammarTestLanguageStandaloneSetup.class);
	String model = "spielplatz 1 {kind (k 1)\n}";
	XtextResource resource = getResourceFromString(model);
	ICompositeNode rootNode = resource.getParseResult().getRootNode();
	resource.update(model.indexOf("k 1"), 3, "l 2");
	resource.update(model.indexOf("k 1"), 3, "m 3");
	assertSame(rootNode, resource.getParseResult().getRootNode());
}
 
Example 19
@Test
public void testPartialParsingChangeIndent() throws Exception {
	String modelAsString = "({tworequired a b})";
	Model model = (Model) getModel(modelAsString);
	XtextResource res = ((XtextResource) model.eResource());
	res.update(modelAsString.indexOf("a"), 1, "b");
	Assert.assertSame(model, res.getContents().get(0));
}
 
Example 20
@Test
public void testIssue219() throws Exception {
	with(PartialParserTestLanguageStandaloneSetup.class);
	String model = "container c1 {\n" + "  children {\n" + "-> C ( ch1 )\n" + "  }" + "}";
	XtextResource resource = getResourceFromString(model);
	assertTrue(resource.getErrors().isEmpty());
	((PartialParsingHelper) ((AbstractAntlrParser) resource.getParser()).getPartialParser())
			.setTokenRegionProvider(null);
	resource.update(model.indexOf("ch1") + 1, 1, "x");
}