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 Project: xtext-core   Author: eclipse   File: FileAwareTestLanguageFormatter.java    License: 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 #2
Source Project: n4js   Author: eclipse   File: LSPIssueConverter.java    License: 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 #3
Source Project: xtext-xtend   Author: eclipse   File: LinkingTest.java    License: 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 #4
Source Project: xtext-xtend   Author: eclipse   File: ActiveAnnotationsRuntimeTest.java    License: 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 #5
Source Project: xtext-core   Author: eclipse   File: XtextLinkerTest.java    License: 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 #6
Source Project: xtext-xtend   Author: eclipse   File: JavaDocTypeReferenceProviderTest.java    License: 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 #7
Source Project: sarl   Author: sarl   File: FormatterFacadeTest.java    License: 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 #8
Source Project: xtext-eclipse   Author: eclipse   File: AbstractXtextTests.java    License: 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 #9
Source Project: xtext-core   Author: eclipse   File: Xtext2EcoreTransformerTest.java    License: 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 #10
Source Project: xtext-eclipse   Author: eclipse   File: ReplAutoEdit.java    License: 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 #11
Source Project: n4js   Author: eclipse   File: QuickFixXpectMethod.java    License: 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 #12
Source Project: xtext-extras   Author: eclipse   File: InferredTypeIndicator.java    License: 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 #13
Source Project: xtext-eclipse   Author: eclipse   File: RenamedElementTrackerTest.java    License: 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 Project: xtext-xtend   Author: eclipse   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 #15
Source Project: xtext-core   Author: eclipse   File: PartialParserTest.java    License: 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 #16
Source Project: xtext-core   Author: eclipse   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 #17
Source Project: xtext-extras   Author: eclipse   File: Xtext2EcoreTransformerTest.java    License: 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 #18
Source Project: xtext-core   Author: eclipse   File: XtextValidationTest.java    License: 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 Project: xtext-core   Author: eclipse   File: Xtext2EcoreTransformerTest.java    License: 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 #20
Source Project: dsl-devkit   Author: dsldevkit   File: FixedHighlightingReconciler.java    License: 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 #21
@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 #22
Source Project: dsl-devkit   Author: dsldevkit   File: CheckHyperlinkHelper.java    License: 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 #23
Source Project: xtext-xtend   Author: eclipse   File: FormatterSmokeSuite.java    License: 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 #24
Source Project: xtext-core   Author: eclipse   File: EncodingTest.java    License: 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 #25
Source Project: xtext-eclipse   Author: eclipse   File: JdtRefactoringContextFactory.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IRenameElementContext createExternalRenameElementContext(EObject targetElement, XtextEditor editor,
		ITextSelection selection, XtextResource resource) {
	if (isJvmMember(targetElement) && isTypeResource(targetElement)) {
		IJavaElement javaElement;
		if(targetElement instanceof JvmConstructor)
			javaElement = getJavaElementFinder().findExactElementFor(((JvmConstructor) targetElement).getDeclaringType());
		else 
			javaElement = getJavaElementFinder().findExactElementFor((JvmMember) targetElement);
		if (javaElement != null)
			return new JdtRefactoringContext(targetElement, javaElement, editor,
					selection, resource, true);
	}
	return super.createExternalRenameElementContext(targetElement, editor, selection, resource);
}
 
Example #26
Source Project: xtext-extras   Author: eclipse   File: TypeUsageCollector.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public TypeUsages collectTypeUsages(XtextResource resource) {
	if(resource != null && !resource.getContents().isEmpty()) {
		this.resource = resource;
		this.implicitStaticImports = implicitImports.getStaticImportClasses(resource);
		this.implicitExtensionImports = implicitImports.getExtensionClasses(resource);
		collectAllReferences(resource.getContents().get(0));
	}
	return typeUsages; 
}
 
Example #27
Source Project: n4js   Author: eclipse   File: LinkingXpectMethod.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Similar to {@link #linkedName(IStringExpectation, ICrossEReferenceAndEObject)} but concatenating the fully
 * qualified name again instead of using the qualified name provider, as the latter may not create a valid name for
 * non-globally available elements.
 * <p>
 * The qualified name created by retrieving all "name" properties of the target and its containers, using '/' as
 * separator.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void linkedPathname(@StringExpectation IStringExpectation expectation,
		ICrossEReferenceAndEObject arg1) {
	EObject targetObject = (EObject) arg1.getEObject().eGet(arg1.getCrossEReference());
	if (targetObject == null) {
		Assert.fail("Reference is null");
		return; // to avoid warnings in the following
	}
	if (targetObject.eIsProxy())
		Assert.fail("Reference is a Proxy: " + ((InternalEObject) targetObject).eProxyURI());
	Resource targetResource = targetObject.eResource();
	if (targetResource instanceof TypeResource)
		targetResource = arg1.getEObject().eResource();
	if (!(targetResource instanceof XtextResource))
		Assert.fail("Referenced EObject is not in an XtextResource.");

	Deque<String> segments = new ArrayDeque<>();
	do {
		EStructuralFeature nameFeature = targetObject.eClass().getEStructuralFeature("name");
		if (nameFeature != null) {
			Object obj = targetObject.eGet(nameFeature);
			if (obj instanceof String) {
				segments.push((String) obj);
			}
		} else {
			if (targetObject instanceof NamedElement) {
				segments.push(((NamedElement) targetObject).getName());
			}
		}
		targetObject = targetObject.eContainer();
	} while (targetObject != null);
	String pathname = Joiner.on('/').join(segments);
	expectation.assertEquals(pathname);
}
 
Example #28
Source Project: xtext-eclipse   Author: eclipse   File: EncodingTest.java    License: 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 #29
Source Project: xtext-core   Author: eclipse   File: ToEcoreTrafoTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private XtextResource getResource(String uri) {
	XtextResourceSet set = get(XtextResourceSet.class);
	URI nsURI = URI.createURI(EcorePackage.eNS_URI);
	URI platformURI = URI.createURI("platform:/resource/org.eclipse.emf.ecore/model/Ecore.ecore");
	set.getURIConverter().getURIMap().put(platformURI, nsURI);
	set.getURIResourceMap().put(platformURI, set.getResource(nsURI, true));
	set.setClasspathURIContext(getClass().getClassLoader());
	// if(AllTests.isPluginContext) {
	// set.setClasspathUriResolver(new BundleClasspathUriResolver());
	// set.setClasspathURIContext(Activator.getDefault());
	// }
	XtextResource r = (XtextResource) set.getResource(URI.createURI(uri), true);
	return r;
}
 
Example #30
Source Project: xtext-core   Author: eclipse   File: EncodingTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	with(EncodingTestLanguageStandaloneSetup.class);
	model = "�cl�p� M�del�ng Fr�mw�rk";
	utfBytes = model.getBytes(UTF_8);
	isoBytes = model.getBytes(ISO_8859_1);
	isoOptions = Collections.singletonMap(XtextResource.OPTION_ENCODING, ISO_8859_1);
	utfOptions = Collections.singletonMap(XtextResource.OPTION_ENCODING, UTF_8);
}