org.eclipse.xtext.resource.XtextResource Java Examples

The following examples show how to use org.eclipse.xtext.resource.XtextResource. 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: FixedHighlightingReconciler.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Update the presentation.
 *
 * @param textPresentation
 *          the text presentation
 * @param addedPositions
 *          the added positions
 * @param removedPositions
 *          the removed positions
 * @param resource
 *          the resource for which the positions have been computed
 */
private void updatePresentation(final TextPresentation textPresentation, final List<AttributedPosition> addedPositions, final List<AttributedPosition> removedPositions, final XtextResource resource) {
  final Runnable runnable = presenter.createUpdateRunnable(textPresentation, addedPositions, removedPositions);
  if (runnable == null) {
    return;
  }
  final XtextResourceSet resourceSet = (XtextResourceSet) resource.getResourceSet();
  final int modificationStamp = resourceSet.getModificationStamp();
  Display display = getDisplay();
  display.asyncExec(new Runnable() {
    @Override
    public void run() {
      // never apply outdated highlighting
      if (sourceViewer != null && modificationStamp == resourceSet.getModificationStamp()) {
        runnable.run();
      }
    }
  });
}
 
Example #2
Source File: XtextLinkerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testQualifiedRuleCall_03() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate test \'http://test\'");
  _builder.newLine();
  _builder.append("Rule: name=ID;");
  _builder.newLine();
  _builder.append("terminal STRING: super;");
  _builder.newLine();
  _builder.append("terminal super: \'super\';");
  _builder.newLine();
  final String grammarAsString = _builder.toString();
  final XtextResource resource = this.getResourceFromString(grammarAsString);
  EObject _get = resource.getContents().get(0);
  Grammar grammar = ((Grammar) _get);
  AbstractRule _get_1 = grammar.getRules().get(1);
  final TerminalRule string = ((TerminalRule) _get_1);
  AbstractElement _alternatives = string.getAlternatives();
  final RuleCall callToSuper = ((RuleCall) _alternatives);
  Assert.assertEquals(IterableExtensions.<AbstractRule>last(grammar.getRules()), callToSuper.getRule());
}
 
Example #3
Source File: FileAwareTestLanguageFormatter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public void format(final Object element, final IFormattableDocument document) {
  if (element instanceof XtextResource) {
    _format((XtextResource)element, document);
    return;
  } else if (element instanceof Element) {
    _format((Element)element, document);
    return;
  } else if (element instanceof PackageDeclaration) {
    _format((PackageDeclaration)element, document);
    return;
  } else if (element instanceof EObject) {
    _format((EObject)element, document);
    return;
  } else if (element == null) {
    _format((Void)null, document);
    return;
  } else if (element != null) {
    _format(element, document);
    return;
  } else {
    throw new IllegalArgumentException("Unhandled parameter types: " +
      Arrays.<Object>asList(element, document).toString());
  }
}
 
Example #4
Source File: LSPIssueConverter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
public List<LSPIssue> convertToLSPIssues(Resource resource, Collection<? extends Issue> issues,
		CancelIndicator cancelIndicator) {

	List<LSPIssue> result = new ArrayList<>(issues.size());
	XDocument document = null; // create only if necessary
	for (Issue issue : issues) {
		operationCanceledManager.checkCanceled(cancelIndicator);
		LSPIssue lspIssue;
		if (issue instanceof LSPIssue) {
			lspIssue = (LSPIssue) issue;
		} else {
			if (!(resource instanceof XtextResource)) {
				continue;
			}
			document = createDocument((XtextResource) resource);
			lspIssue = convertToLSPIssue(issue, document);
		}
		result.add(lspIssue);
	}
	return result;
}
 
Example #5
Source File: LinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug345433_02() throws Exception {
	String classAsString = 
		"import static extension org.eclipse.xtext.GrammarUtil.*\n" +
		"class Foo {" +
		"	org.eclipse.xtext.Grammar grammar\n" +
		"	def function1() {\n" + 
		"		grammar.containedRuleCalls.filter(e0 | " +
		"			!e0.isAssigned() && !e0.isEObjectRuleCall()" +
		"		).map(e1 | e1.rule)\n" + 
		"	}\n" +
		"}";
	XtendClass clazz = clazz(classAsString);
	IResourceValidator validator = ((XtextResource) clazz.eResource()).getResourceServiceProvider().getResourceValidator();
	List<Issue> issues = validator.validate(clazz.eResource(), CheckMode.ALL, CancelIndicator.NullImpl);
	assertTrue("Resource contained errors : " + issues.toString(), issues.isEmpty());
	XtendFunction function = (XtendFunction) clazz.getMembers().get(1);
	XExpression body = function.getExpression();
	LightweightTypeReference bodyType = getType(body);
	assertEquals("java.lang.Iterable<org.eclipse.xtext.AbstractRule>", bodyType.getIdentifier());
	XBlockExpression block = (XBlockExpression) body;
	XMemberFeatureCall featureCall = (XMemberFeatureCall) block.getExpressions().get(0);
	XClosure closure = (XClosure) featureCall.getMemberCallArguments().get(0);
	JvmFormalParameter e1 = closure.getFormalParameters().get(0);
	assertEquals("e1", e1.getSimpleName());
	assertEquals("org.eclipse.xtext.RuleCall", getType(e1).getIdentifier());
}
 
Example #6
Source File: ActiveAnnotationsRuntimeTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public void assertIssues(final Pair<String, String> macroFile, final Pair<String, String> clientFile, final Procedure1<? super List<Issue>> expectations) {
  try {
    final XtextResourceSet resourceSet = this.compileMacroResourceSet(macroFile, clientFile);
    Resource _head = IterableExtensions.<Resource>head(resourceSet.getResources());
    final XtextResource singleResource = ((XtextResource) _head);
    boolean _isLoaded = singleResource.isLoaded();
    boolean _not = (!_isLoaded);
    if (_not) {
      singleResource.load(resourceSet.getLoadOptions());
    }
    final IResourceValidator validator = singleResource.getResourceServiceProvider().getResourceValidator();
    expectations.apply(validator.validate(singleResource, CheckMode.ALL, CancelIndicator.NullImpl));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #7
Source File: JavaDocTypeReferenceProviderTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testComputation_7() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo");
    _builder.newLine();
    _builder.newLine();
    _builder.append("/**");
    _builder.newLine();
    _builder.append("* {@link    String}");
    _builder.newLine();
    _builder.append("*/");
    _builder.newLine();
    _builder.append("class Foo{}");
    _builder.newLine();
    final String input = _builder.toString();
    Resource _eResource = this.clazz(input).eResource();
    final XtextResource resource = ((XtextResource) _eResource);
    final ICompositeNode rootNode = resource.getParseResult().getRootNode();
    final List<ReplaceRegion> regions = this.javaDocTypeReferenceProvider.computeTypeRefRegions(rootNode);
    Assert.assertEquals(1, regions.size());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #8
Source File: FormatterFacadeTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
private void assertResourceContentFormat(String source, String expected) throws IOException {
	final ResourceSet resourceSet = new XtextResourceSet();
	final URI createURI = URI.createURI("synthetic://to-be-formatted.sarl"); //$NON-NLS-1$
	final XtextResource resource = (XtextResource) this.resourceFactory.createResource(createURI);
	resourceSet.getResources().add(resource);
	try (StringInputStream stringInputStream = new StringInputStream(source)) {
		resource.load(stringInputStream, Collections.emptyMap());
	}
	this.facade.format(resource);
	final String actual; 
	try (ByteArrayOutputStream stringOutputStream = new ByteArrayOutputStream()) {
		resource.save(stringOutputStream, Collections.emptyMap());
		stringOutputStream.flush();
		actual = stringOutputStream.toString();
	}
	assertEquals(expected, actual);
}
 
Example #9
Source File: AbstractXtextTests.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
	XtextResource resource = doGetResource(in, uri);
	checkNodeModel(resource);
	if (expectedErrors != UNKNOWN_EXPECTATION) {
		if (expectedErrors == EXPECT_ERRORS)
			assertFalse(Joiner.on('\n').join(resource.getErrors()), resource.getErrors().isEmpty());
		else
			assertEquals(Joiner.on('\n').join(resource.getErrors()), expectedErrors, resource.getErrors().size());
	}
	for(Diagnostic d: resource.getErrors()) {
		if (d instanceof ExceptionDiagnostic)
			fail(d.getMessage());
	}
	if (expectedErrors == 0 && resource.getContents().size() > 0 && shouldTestSerializer(resource)) {
		SerializerTester tester = get(SerializerTester.class);
		EObject obj = resource.getContents().get(0);
		tester.assertSerializeWithNodeModel(obj);
		tester.assertSerializeWithoutNodeModel(obj);
	}
	return resource;
}
 
Example #10
Source File: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testContainmentVsReference_06() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("import \'http://www.eclipse.org/emf/2002/Ecore\'");
  _builder.newLine();
  _builder.append("EReference: name=ID eContainingClass=EClass;");
  _builder.newLine();
  _builder.append("EClass: name=ID;");
  _builder.newLine();
  final String grammar = _builder.toString();
  final XtextResource resource = this.getResourceFromStringAndExpect(grammar, 1);
  Assert.assertEquals(resource.getErrors().toString(), 1, 
    resource.getErrors().size());
}
 
Example #11
Source File: ReplAutoEdit.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void customizeDocumentCommand(final IDocument document, final DocumentCommand command) {
	if (!isLineDelimiter(document, command)) {
		return;
	}
	try {
		IXtextDocument doc = xtextDocumentUtil.getXtextDocument(document);
		String result = doc.tryReadOnly(new IUnitOfWork<String, XtextResource>() {
			@Override
			public String exec(XtextResource resource) throws Exception {
				return computeResultText(document, command, resource);
			}
		});
		if (result == null)
			return;
		command.text = result;
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #12
Source File: FormatterSmokeSuite.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void processFile(String data) throws Exception {
	byte[] hash = ((MessageDigest) messageDigest.clone()).digest(data.getBytes("UTF-8"));
	if (seen.add(new BigInteger(hash))) {
		XtextResourceSet resourceSet = resourceSetProvider.get();
		resourceSet.setClasspathURIContext(classLoader);
		XtendFile file = parseHelper.parse(data, resourceSet);
		if (file != null) {
			try {
				XtextResource resource = (XtextResource) file.eResource();
				ITextRegionAccess regions = regionBuilder.get().forNodeModel(resource).create();
				FormatterRequest request = new FormatterRequest().setTextRegionAccess(regions);
				request.setExceptionHandler(ExceptionAcceptor.IGNORING);
				formatter.format(request);
			} catch (Exception e) {
				e.printStackTrace();
				ComparisonFailure error = new ComparisonFailure(e.getMessage(), data, "");
				error.setStackTrace(e.getStackTrace());
				throw error;
			}
		}
	}
}
 
Example #13
Source File: RenamedElementTrackerTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testResolveElements() throws Exception {
	URI resourceURI = URI.createFileURI("testresource.refactoringtestlanguage");
	String textualModel = "A { B { C { ref A.B } } ref B }";
	XtextResource resource = getResource(textualModel, resourceURI.toString());
	Element elementA = (Element) resource.getContents().get(0).eContents().get(0);
	Element elementB = elementA.getContained().get(0);
	Element elementC = elementB.getContained().get(0);

	URI uriB = EcoreUtil.getURI(elementB);
	URI uriC = EcoreUtil.getURI(elementC);
	String newName = "newB";

	List<URI> renamedElementURIs = newArrayList(uriB, uriC);
	IRenameStrategy renameStrategy = getInjector().getInstance(IRenameStrategy.Provider.class).get(elementB, null);

	IRenamedElementTracker renamedElementTracker = new RenamedElementTracker();
	Map<URI, URI> original2newElementURIs = renamedElementTracker.renameAndTrack(renamedElementURIs, newName,
			resource.getResourceSet(), renameStrategy, new NullProgressMonitor());

	assertEquals("B", elementB.getName());
	assertEquals(2, original2newElementURIs.size());
	assertEquals(resourceURI.appendFragment(newName), original2newElementURIs.get(uriB));
	assertEquals(uriC, original2newElementURIs.get(uriC));
}
 
Example #14
Source File: QuickFixXpectMethod.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Example: {@code // XPECT quickFixList  at 'a.<|>method' --> 'import A','do other things' }
 *
 * @param expectation
 *            comma separated strings, which are proposed as quick fix
 * @param resource
 *            injected xtext-file
 * @param offset
 *            cursor position at '<|>'
 * @param checkType
 *            'display': verify list of provided proposals comparing their user-displayed strings.
 * @param selected
 *            which proposal to pick
 * @param mode
 *            modus of operation
 * @param offset2issue
 *            mapping of offset(!) to issues.
 * @throws Exception
 *             if failing
 */
@Xpect
@ParameterParser(syntax = "('at' (arg2=STRING (arg3=ID  (arg4=STRING)?  (arg5=ID)? )? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFixList(
		@CommaSeparatedValuesExpectation(quoted = true, ordered = true) ICommaSeparatedValuesExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		RegionWithCursor offset, // arg2
		String checkType, // arg3
		String selected, // arg4
		String mode, // arg5
		@IssuesByLine Multimap<Integer, Issue> offset2issue) throws Exception {

	List<IssueResolution> resolutions = collectAllResolutions(resource, offset, offset2issue);

	List<String> resolutionNames = Lists.newArrayList();
	for (IssueResolution resolution : resolutions) {
		resolutionNames.add(resolution.getLabel());
	}

	expectation.assertEquals(resolutionNames);
}
 
Example #15
Source File: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testBug_285140_01() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.sublang with org.eclipse.xtext.testlanguages.ActionTestLanguage");
  _builder.newLine();
  _builder.newLine();
  _builder.append("import \"http://www.eclipse.org/2008/tmf/xtext/ActionLang\" as actionLang");
  _builder.newLine();
  _builder.append("generate sub \"http://www.sublang.org\"");
  _builder.newLine();
  _builder.newLine();
  _builder.append("Model returns actionLang::Model:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("Child ({actionLang::Parent.left=current} right=Child)?;");
  _builder.newLine();
  final String grammar = _builder.toString();
  final XtextResource resource = this.getResourceFromString(grammar);
  Assert.assertEquals(resource.getErrors().toString(), 0, resource.getErrors().size());
}
 
Example #16
Source File: ImportedNamespaceAwareLocalScopeProviderTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testImports_02() throws Exception {
	XtextResource resource = getResource(new StringInputStream("import foo.* "), URI
			.createURI("import.indextestlanguage"));
	resource.getResourceSet().createResource(URI.createURI("foo.indextestlanguage")).load(
			new StringInputStream(
					"foo.bar { " 
					+ "  entity Person {  " 
					+ "    String name " 
					+ "  } "
					+ "  datatype String " 
					+ "}"), null);

	IScope scope = scopeProvider.getScope(resource.getContents().get(0), IndexTestLanguagePackage.eINSTANCE
			.getFile_Elements());
	List<QualifiedName> names = toListOfNames(scope.getAllElements());
	assertEquals(names.toString(), 6, names.size());
	assertTrue(names.contains(nameConverter.toQualifiedName("bar.Person")));
	assertTrue(names.contains(nameConverter.toQualifiedName("bar.String")));
	assertTrue(names.contains(nameConverter.toQualifiedName("bar")));
	assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar")));
	assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar.Person")));
	assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar.String")));
}
 
Example #17
Source File: CheckHyperlinkHelper.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void createHyperlinksByOffset(final XtextResource resource, final int offset, final IHyperlinkAcceptor acceptor) {
  IEditorPart activeEditor = workbench.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
  if (activeEditor.getEditorInput() instanceof XtextReadonlyEditorInput) {
    INode crossRefNode = eObjectAtOffsetHelper.getCrossReferenceNode(resource, new TextRegion(offset, 0));
    if (crossRefNode == null) {
      return;
    }
    EObject crossLinkedEObject = eObjectAtOffsetHelper.getCrossReferencedElement(crossRefNode);
    if (crossLinkedEObject != null && crossLinkedEObject.eClass().getEPackage() != CheckPackage.eINSTANCE) {
      return;
    }
    // if EPackage of referenced object is CheckPackage, try to provide hyperlinks: works for included catalogs
  }
  super.createHyperlinksByOffset(resource, offset, acceptor);
}
 
Example #18
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testOverrideDeprecated_1() throws Exception {
	XtextResourceSet rs = get(XtextResourceSet.class);
	getResourceFromString("grammar org.xtext.Supergrammar with org.eclipse.xtext.common.Terminals\n" + 
			"generate supergrammar \"http://org.xtext.supergrammar\"\n" + 
			"@Deprecated\n" + 
			"RuleDeprecated: name=ID;\n" + 
			"Rule: name=ID;","superGrammar.xtext", rs);
	XtextResource resource = getResourceFromString(
			"grammar org.foo.Bar with org.xtext.Supergrammar\n" +
			"generate bar \"http://org.xtext.Bar\"\n" + 
			"@Override RuleDeprecated: name=ID;",  "foo.xtext", rs);
	Diagnostic diag = Diagnostician.INSTANCE.validate(resource.getContents().get(0));
	List<Diagnostic> issues = diag.getChildren();
	assertEquals(issues.toString(), 1, issues.size());
	assertEquals("This rule overrides RuleDeprecated in org.xtext.Supergrammar which is deprecated.", issues.get(0).getMessage());
	assertEquals("diag.isWarning", diag.getSeverity(), Diagnostic.WARNING);
}
 
Example #19
Source File: Xtext2EcoreTransformerTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testMultiInheritance_01() throws Exception {
	// @formatter:off
	String grammarAsString =
		"grammar test with org.eclipse.xtext.enumrules.EnumRulesTestLanguage\n" +
		"import 'http://www.eclipse.org/xtext/common/JavaVMTypes' as types\n" +
		"generate myDsl 'http://example.xtext.org/MyDsl' as mydsl\n" +
		"Array returns mydsl::Array: componentType=ComponentType componentType=DeclaredType;\n" +
		"DeclaredType returns types::JvmDeclaredType: members+=DeclaredType;\n" +
		"ComponentType returns types::JvmComponentType: 'ignore';\n";
	// @formatter:on
	XtextResource resource = getResourceFromString(grammarAsString);
	Grammar grammar = ((Grammar) resource.getContents().get(0));
	EClass array = ((EClass) grammar.getRules().get(0).getType().getClassifier());
	Assert.assertEquals("JvmComponentType", feature(array, "componentType").getEType().getName());
}
 
Example #20
Source File: PartialParserTest.java    From xtext-core with 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 #21
Source File: PartialParserTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 #22
Source File: XtendQuickfixProvider.java    From xtext-xtend with 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 #23
Source File: InferredTypeIndicator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public JvmTypeReference getTypeReference(/* @NonNull */ XComputedTypeReferenceImplCustom context) {
	Resource resource = context.eResource();
	IResolvedTypes resolvedTypes = null;
	if (resource instanceof XtextResource) {
		IBatchTypeResolver typeResolver = ((XtextResource) resource).getResourceServiceProvider().get(IBatchTypeResolver.class);
		if (typeResolver == null) {
			throw new IllegalStateException("typeResolver may not be null");
		}
		resolvedTypes = typeResolver.resolveTypes(context);
	}
	if (context.eIsSet(TypesPackage.Literals.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT)) {
		return context.getEquivalent();
	}
	if (expression != null && resolvedTypes != null) {
		LightweightTypeReference expressionType = resolvedTypes.getActualType(expression);
		if (expressionType != null) {
			JvmTypeReference result = expressionType.toJavaCompliantTypeReference();
			return result;
		}
	}
	throw new IllegalStateException("equivalent could not be computed");
}
 
Example #24
Source File: XtextHyperlinkHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void createHyperlinksByOffset(XtextResource resource, int offset, IHyperlinkAcceptor acceptor) {
	super.createHyperlinksByOffset(resource, offset, acceptor);
	EObject objectAtOffset = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
	if (objectAtOffset instanceof AbstractRule) {
		ITextRegion nameLocation = locationInFileProvider.getSignificantTextRegion(objectAtOffset, XtextPackage.Literals.ABSTRACT_RULE__NAME, 0);
		if (nameLocation != null && nameLocation.contains(offset)) {
			AbstractRule rule = (AbstractRule) objectAtOffset;
			createLinksToBase(nameLocation, rule, acceptor);
			if (rule.getType() != null && rule.getType().getClassifier() != null && NodeModelUtils.getNode(rule.getType()) == null) {
				createHyperlinksTo(resource, toRegion(nameLocation), rule.getType().getClassifier(), acceptor);
			}
		}
	}
}
 
Example #25
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testLeftRecursion_Bug_285605_15() throws Exception {
	XtextResource resource = getResourceFromString(
			"grammar org.foo.Bar with org.eclipse.xtext.common.Terminals\n" +
			"generate foo 'http://foo/bar'\n" +
			"RuleA : ruleB=RuleB;\n" +
			"RuleB : ruleC=RuleC;\n" +
			"RuleC : (name=ID & value=STRING)? ruleA=RuleA;\n");
	assertTrue(resource.getErrors().toString(), resource.getErrors().isEmpty());
	assertTrue(resource.getWarnings().toString(), resource.getWarnings().isEmpty());

	Diagnostic diag = Diagnostician.INSTANCE.validate(resource.getContents().get(0));
	assertNotNull("diag", diag);
	assertEquals(diag.getChildren().toString(), 4, diag.getChildren().size());
	assertEquals("diag.isError", diag.getSeverity(), Diagnostic.ERROR);
}
 
Example #26
Source File: CrossReferenceProposalTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testBug276742_09b() throws Exception {
	String modelAsString = "Foo {}";
	ContentAssistProcessorTestBuilder builder = newBuilder();
	XtextContentAssistProcessor processor = get(XtextContentAssistProcessor.class);
	XtextResource resource = getResourceFromString(modelAsString);

	ITextViewer viewer = builder.getSourceViewer(modelAsString, builder.getDocument(resource, modelAsString));
	ContentAssistContext[] contexts = processor.getContextFactory().create(viewer, 0, resource);
	assertEquals(1, contexts.length);
	for (ContentAssistContext context : contexts) {
		assertEquals(CrossReferenceProposalTestPackage.Literals.MODEL, context.getCurrentModel().eClass());
	}
}
 
Example #27
Source File: EncodingTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSaveUtfToUtf() throws Exception {
	XtextResource resource = createXtextResource();
	resource.load(new ByteArrayInputStream(utfBytes), utfOptions);
	ByteArrayOutputStream utfSaveStream = new ByteArrayOutputStream();
	resource.save(utfSaveStream, null);
	utfSaveStream.close();
	byte[] savedUtfBytes = utfSaveStream.toByteArray();
	assertTrue(Arrays.equals(utfBytes, savedUtfBytes));
}
 
Example #28
Source File: FormatterTestHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected XtextResource parse(String document) {
	try {
		return (XtextResource) parseHelper.parse(document).eResource();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #29
Source File: EncodingTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void openEditorAndCheckEncoding(IFile file, final String charset) throws CoreException, Exception {
	XtextEditor openedEditor = openEditor(file);
	assertNotNull(openedEditor);
	IXtextDocument document = openedEditor.getDocument();
	document.readOnly(new IUnitOfWork.Void<XtextResource>() {
		@Override
		public void process(XtextResource resource) throws Exception {
			assertEquals(charset, resource.getEncoding());
		}
	});
	openedEditor.close(false);
	openedEditor.dispose();
}
 
Example #30
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testEnumRuleReturnsEClass() throws Exception {
	XtextResource resource = getResourceFromStringAndExpect(
			"grammar org.foo.Bar with org.eclipse.xtext.common.Terminals\n" +
			"generate testLanguage 'http://www.eclipse.org/2011/xtext/bug348749'\n" +
			"Model: element=Enum;\n" +
			"enum Enum returns Model: A | B;", 1);
	assertEquals(resource.getErrors().toString(), 1, resource.getErrors().size());
	assertTrue(resource.getWarnings().toString(), resource.getWarnings().isEmpty());

	Diagnostic diag = Diagnostician.INSTANCE.validate(resource.getContents().get(0));
	assertNotNull("diag", diag);
	assertEquals(diag.getChildren().toString(), 0, diag.getChildren().size());
	assertEquals("diag.isOk", diag.getSeverity(), Diagnostic.OK);
}