/** * Test the element keyword of an element. Examples of element keyword are getter, setter, field etc. */ @ParameterParser(syntax = "('at' arg1=OFFSET)?") @Xpect public void elementKeyword( @StringExpectation IStringExpectation expectation, IEObjectCoveringRegion offset) { EObject context = offset.getEObject(); // Identical behavior as in hover in the IDE! See class N4JSHoverProvider // Get the cross-referenced element at the offset. EObject element = offsetHelper .resolveCrossReferencedElementAt((XtextResource) context.eResource(), offset.getOffset()); // If not a cross-reference element, use context instead if (element == null) element = context; String actual = calculateElementKeyword(element); expectation.assertEquals(actual); }
/** * 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); }
/** * CollectAll resolutions under the cursor at offset. * */ List<IssueResolution> collectAllResolutions(XtextResource resource, RegionWithCursor offset, Multimap<Integer, Issue> offset2issue) { EObject script = resource.getContents().get(0); ICompositeNode scriptNode = NodeModelUtils.getNode(script); ILeafNode offsetNode = NodeModelUtils.findLeafNodeAtOffset(scriptNode, offset.getGlobalCursorOffset()); int offStartLine = offsetNode.getTotalStartLine(); List<Issue> allIssues = QuickFixTestHelper.extractAllIssuesInLine(offStartLine, offset2issue); List<IssueResolution> resolutions = Lists.newArrayList(); for (Issue issue : allIssues) { if (issue.getLineNumber() == offsetNode.getStartLine() && issue.getLineNumber() <= offsetNode.getEndLine()) { Display.getDefault().syncExec(() -> resolutions.addAll(quickfixProvider.getResolutions(issue))); } } return resolutions; }
/** * Remove OutdatedStateAdapter from provided{@link XtextResource} and return it. * * @return {@link XtextResource} */ public static XtextResource cleanXtextResource(XtextResource xtextResource) { // Since here we are reusing the same xtextresource and not reparsing the stream, // we must take care that stale Xtext-documents associated with this resource do not effect us. // An assertion looks for org.eclipse.xtext.ui.editor.model.XtextDocument.OutdatedStateAdapter // in org.eclipse.xtext.ui.editor.model.XtextDocument.setInput(XtextResource) // To reuse the resource we remove it here: // Adapter toBeRemoved = null; // for (Adapter a : xtextResource.eAdapters()) { // if (a instanceof OutdatedStateAdapter) // toBeRemoved = a; // } // if (toBeRemoved != null) // xtextResource.eAdapters().remove(toBeRemoved); return xtextResource; }
/*** * This method modifies the super method to handle NullPointerException when state is null. */ @Override public <R> R readOnly(final URI targetURI, final IUnitOfWork<R, ResourceSet> work) { IXtextDocument document = openDocumentTracker.getOpenDocument(targetURI.trimFragment()); if (document != null) { return document.readOnly(new IUnitOfWork<R, XtextResource>() { @Override public R exec(XtextResource state) throws Exception { // For some reason, sometimes state can be null at this point, // The resource set must be retrieved by other means in delegate.readOnly if (state == null) { return delegate.readOnly(targetURI, work); } ResourceSet localContext = state.getResourceSet(); if (localContext != null) return work.exec(localContext); return null; } }); } else { return delegate.readOnly(targetURI, work); } }
private List<Resource> collectTransitivelyDependentResources(XtextResource resource, Set<URI> deltaURIs) { List<Resource> result = Lists.newArrayList(); ResourceSet resourceSet = resource.getResourceSet(); for (Resource candidate : resourceSet.getResources()) { if (candidate != resource) { URI uri = candidate.getURI(); if (deltaURIs.contains(uri)) { // the candidate is contained in the delta list // schedule it for unloading result.add(candidate); } else if (candidate instanceof N4JSResource) { // the candidate does depend on one of the changed resources // schedule it for unloading if (canLoadFromDescriptionHelper.dependsOnAny(candidate, deltaURIs)) { result.add(candidate); } } } } return result; }
@Override public final void apply(IModificationContext context) throws Exception { context.getXtextDocument().modify(new IUnitOfWork.Void<XtextResource>() { @Override public void process(XtextResource resource) throws Exception { final IMarker marker = issue instanceof N4JSIssue ? ((N4JSIssue) issue).getMarker() : null; final EObject element = resource.getEObject(issue.getUriToProblem().fragment()); final Collection<? extends IChange> changes = modification.computeChanges( context, marker, issue.getOffset(), issue.getLength(), element); modification.computeFinalChanges(); changeManager.applyAll(changes); } }); }
@Override protected void buildMap(Resource resource, Map<QualifiedName, IEObjectDescription> elements) { IDefaultResourceDescriptionStrategy strategy = ((XtextResource) resource).getResourceServiceProvider() .get(IDefaultResourceDescriptionStrategy.class); TreeIterator<EObject> allProperContents = EcoreUtil.getAllProperContents(resource, false); IAcceptor<IEObjectDescription> acceptor = new IAcceptor<IEObjectDescription>() { @Override public void accept(IEObjectDescription description) { elements.put(description.getQualifiedName(), description); } }; while (allProperContents.hasNext()) { EObject content = allProperContents.next(); if (!strategy.createEObjectDescriptions(content, acceptor)) { allProperContents.prune(); } } }
protected LaunchConfig getLaunchConfigFromEditor(ExecutionEvent event) { XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event); if (activeXtextEditor == null) { return null; } final ITextSelection selection = (ITextSelection) activeXtextEditor.getSelectionProvider().getSelection(); return activeXtextEditor.getDocument().priorityReadOnly(new IUnitOfWork<LaunchConfig, XtextResource>() { @Override public LaunchConfig exec(XtextResource xTextResource) throws Exception { EObject lc = eObjectAtOffsetHelper.resolveContainedElementAt(xTextResource, selection.getOffset()); return findParentLaunchConfig(lc); } }); }
public static void loadGexpressionTestFile() { // Getting the serializer GExpressionsStandaloneSetup setup = new GExpressionsStandaloneSetup(); Injector injector = setup.createInjectorAndDoEMFRegistration(); GexpressionsPackage.eINSTANCE.eClass(); Serializer serializer = injector.getInstance(Serializer.class); // Load the model URI modelURI = URI .createFileURI("/home/flatombe/thesis/gemoc/git/gemoc-dev/org/eclipse/gemoc/GEL/org.eclipse.gemoc.gel.gexpressions.test/model/test.gexpressions"); XtextResourceSet resSet = injector.getInstance(XtextResourceSet.class); resSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE); Resource resource = resSet.getResource(modelURI, true); GProgram program = (GProgram) resource.getContents().get(0); List<GExpression> exps = program.getExpressions(); for (GExpression exp : exps) { // Serializing String s = serializer.serialize(exp); System.out.println(s); } }
@Override public void provideHighlightingFor(XtextResource resource, org.eclipse.xtext.ui.editor.syntaxcoloring.IHighlightedPositionAcceptor acceptor) { TreeIterator<EObject> allContents = resource.getAllContents(); while (allContents.hasNext()) { EObject next = allContents.next(); if (next.eIsProxy()) { continue; } if (next instanceof ElementReferenceExpression) { if (next instanceof ElementReferenceExpression) { ElementReferenceExpression expression = (ElementReferenceExpression) next; provideHighligtingFor(expression, acceptor); } } } }
public void format(final Object restaurante, final IFormattableDocument document) { if (restaurante instanceof XtextResource) { _format((XtextResource)restaurante, document); return; } else if (restaurante instanceof Restaurante) { _format((Restaurante)restaurante, document); return; } else if (restaurante instanceof EObject) { _format((EObject)restaurante, document); return; } else if (restaurante == null) { _format((Void)null, document); return; } else if (restaurante != null) { _format(restaurante, document); return; } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(restaurante, document).toString()); } }
/** * Returns with {@code true} if the AST element selected from the resource * can provide document highlights, otherwise returns with {@code false}. * * <p> * Clients may override this method to change the default behavior. * * @param selectedElemnt * the selected element resolved via the offset from the * resource. Can be {@code null}. * @param resource * the resource for the document. * @param offset * the offset of the selection. * * @return {@code true} if the document highlight is available for the * selected element, otherwise {@code false}. * */ protected boolean isDocumentHighlightAvailableFor(final EObject selectedElemnt, final XtextResource resource, final int offset) { if (selectedElemnt == null || !getSelectedElementFilter().apply(selectedElemnt)) { return false; } final EObject containedElement = offsetHelper.resolveContainedElementAt(resource, offset); // Special handling to avoid such cases when the selection is not // exactly on the desired element. if (selectedElemnt == containedElement) { final ITextRegion region = locationInFileProvider.getSignificantTextRegion(containedElement); return !isNullOrEmpty(region) // Region is comparable to a selection in an editor, // therefore the end position is exclusive. && (region.contains(offset) || (region.getOffset() + region.getLength()) == offset); } return true; }
protected void doValidation() { if (allErrorsAndWarnings == null) { doLinking(); allErrorsAndWarnings = newArrayList(); // validation for (Resource resource : sources) { if (resource instanceof XtextResource) { XtextResource xtextResource = (XtextResource) resource; List<Issue> issues = xtextResource.getResourceServiceProvider().getResourceValidator().validate(xtextResource, checkMode, CancelIndicator.NullImpl); for (Issue issue : issues) { allErrorsAndWarnings.add(issue); } } } } }
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()); }
@Test public void testPartialParseConcreteRuleFirstToken_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 children = findLeafNodeByText(root, model, "children"); // change the model and undo the change resource.update(model.indexOf("n {") + 2, 1, " {"); resource.update(model.indexOf("n {") + 2, 2, "{"); assertSame(root, resource.getParseResult().getRootNode()); assertNotSame(children, findLeafNodeByText(root, model, "children")); }
@Test public void testNoException_03() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar test with org.eclipse.xtext.common.Terminals import \'http://www.eclipse.org/emf/2002/Ecore\' as ecore generate test \'http://test\'"); _builder.newLine(); _builder.append("CompositeModel: (type+=EClassifier)+;"); _builder.newLine(); _builder.append("EClassifier returns ecore::EClassifier: EDataType | EClass;"); _builder.newLine(); _builder.append("EClass returns ecore::EClass: \'class\' name=ID;"); _builder.newLine(); _builder.append("EDataType returns ecore::EDataType: \'dt\' name=ID;"); String grammar = _builder.toString(); final XtextResource resource = this.getResourceFromString(grammar); Assert.assertTrue(resource.getErrors().isEmpty()); }
/** * Semantic quickfix removing the override flag for a rule. * * @param issue * the issue * @param acceptor * the acceptor */ @Fix(FormatJavaValidator.OVERRIDE_ILLEGAL_CODE) public void removeOverride(final Issue issue, final IssueResolutionAcceptor acceptor) { acceptor.accept(issue, "Remove override", "Remove override.", null, new IModification() { @Override public void apply(final IModificationContext context) throws BadLocationException { context.getXtextDocument().modify(new IUnitOfWork<Void, XtextResource>() { @Override public java.lang.Void exec(final XtextResource state) { Rule rule = (Rule) state.getEObject(issue.getUriToProblem().fragment()); rule.setOverride(false); return null; } }); } }); }
@Test public void testFindCurrentType_01() throws Exception { this.with(XtextStandaloneSetup.class); StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar myLang with org.eclipse.xtext.common.Terminals"); _builder.newLine(); _builder.append("generate g \'http://1\'"); _builder.newLine(); _builder.append("Rule:"); _builder.newLine(); _builder.append("\t"); _builder.append("Fragment;"); _builder.newLine(); _builder.append("fragment Fragment*: name=ID;"); _builder.newLine(); String model = _builder.toString(); final XtextResource r = this.getResourceFromString(model); EObject _get = r.getContents().get(0); final Grammar grammar = ((Grammar) _get); final AbstractRule rule = IterableExtensions.<AbstractRule>head(grammar.getRules()); final AbstractElement fragmentCall = rule.getAlternatives(); final EClassifier currentType = GrammarUtil.findCurrentType(fragmentCall); Assert.assertEquals("Rule", currentType.getName()); }
@Test public void testPartialParseConcreteRuleInnerToken() 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 cLeaf = findLeafNodeByText(root, model, "C"); resource.update(model.indexOf("C"), 1, "C"); resource.update(model.indexOf("C"), 1, "C"); assertSame(root, resource.getParseResult().getRootNode()); assertSame(childrenLeaf, findLeafNodeByText(root, model, "children")); assertNotSame(cLeaf, findLeafNodeByText(root, model, "ch1")); }
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()); } }
@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"))); }
@Test public void testBug_266807() throws Exception { final XtextResourceSet rs = this.<XtextResourceSet>get(XtextResourceSet.class); rs.setClasspathURIContext(this.getClass()); StringConcatenation _builder = new StringConcatenation(); _builder.append("classpath:/"); String _replace = this.getClass().getPackage().getName().replace(Character.valueOf('.').charValue(), Character.valueOf('/').charValue()); _builder.append(_replace); _builder.append("/Test.xtext"); Resource _createResource = rs.createResource( URI.createURI(_builder.toString()), ContentHandler.UNSPECIFIED_CONTENT_TYPE); final XtextResource resource = ((XtextResource) _createResource); resource.load(null); EList<Resource.Diagnostic> _errors = resource.getErrors(); for (final Resource.Diagnostic d : _errors) { Assert.fail(d.getMessage()); } }
public IVisibilityHelper getVisibilityHelper(final Resource resource) { IVisibilityHelper _switchResult = null; boolean _matched = false; if (resource instanceof XtextResource) { _matched=true; IVisibilityHelper _xblockexpression = null; { final String packageName = this._iImportsConfiguration.getPackageName(((XtextResource)resource)); IVisibilityHelper _xifexpression = null; if ((packageName == null)) { _xifexpression = this.visibilityHelper; } else { _xifexpression = new ContextualVisibilityHelper(this.visibilityHelper, packageName); } _xblockexpression = _xifexpression; } _switchResult = _xblockexpression; } if (!_matched) { _switchResult = this.visibilityHelper; } return _switchResult; }
@Test public void testBug_272566_1() 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("Model:"); _builder.newLine(); _builder.append(" "); _builder.append("test=Test"); _builder.newLine(); _builder.append(";"); _builder.newLine(); _builder.newLine(); _builder.append("Test:"); _builder.newLine(); _builder.append(" "); _builder.append("\"keyword\" WS name=ID"); _builder.newLine(); _builder.append(";"); _builder.newLine(); String grammar = _builder.toString(); final XtextResource resource = this.getResourceFromString(grammar); Assert.assertTrue(resource.getErrors().toString(), resource.getErrors().isEmpty()); }
public void format(final Object obj, final IFormattableDocument document) { if (obj instanceof XtextResource) { _format((XtextResource)obj, document); return; } else if (obj instanceof EObject) { _format((EObject)obj, document); return; } else if (obj == null) { _format((Void)null, document); return; } else if (obj != null) { _format(obj, document); return; } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(obj, document).toString()); } }
protected void assertBug322875(XtextResource resource) { Diagnostic diag = Diagnostician.INSTANCE.validate(resource.getContents().get(0)); assertNotNull("diag", diag); assertEquals(diag.toString(), 0, diag.getChildren().size()); assertEquals("diag.isOk", Diagnostic.OK, diag.getSeverity()); int xtextPackageCounter = 0; int validationTestCounter = 0; for(Resource packResource: resource.getResourceSet().getResources()) { EObject object = packResource.getContents().get(0); if (object instanceof EPackage) { String nsURI = ((EPackage) object).getNsURI(); if (nsURI.equals("http://www.eclipse.org/2008/Xtext")) xtextPackageCounter++; if (nsURI.equals("http://XtextValidationBugs")) { validationTestCounter++; } } } assertEquals(1, xtextPackageCounter); assertEquals(1, validationTestCounter); }
@Test public void testBug_287698_01() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar language with org.eclipse.xtext.common.Terminals"); _builder.newLine(); _builder.append("generate myDsl \"http://example.xtext.org/MyDsl\""); _builder.newLine(); _builder.append("Model returns Namespace: {Model} elements+=NamespaceElement;"); _builder.newLine(); _builder.append("NamespaceElement: Type | Namespace ;"); _builder.newLine(); _builder.append("Type: \'type\' name=ID \';\';"); _builder.newLine(); _builder.append("Namespace: \'namespace\' name=ID \'{\' elements+=Type \'}\';"); _builder.newLine(); String grammar = _builder.toString(); final XtextResource resource = this.getResourceFromString(grammar); Assert.assertEquals(resource.getErrors().toString(), 0, resource.getErrors().size()); }
@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, "->")); }
/** * Returns the first non-whitespace leaf node in the file if it is a multi-line comment node. * * @since 2.3 * @return a list with exactly one node or an empty list if there is no header is undocumented. */ /* @NonNull */ @Override public List<INode> getFileHeaderNodes(Resource resource) { if (resource instanceof XtextResource) { IParseResult parseResult = ((XtextResource) resource).getParseResult(); if(parseResult != null) { for(ILeafNode leafNode: parseResult.getRootNode().getLeafNodes()) { EObject grammarElement = leafNode.getGrammarElement(); if(grammarElement instanceof TerminalRule) { String terminalRuleName = ((TerminalRule) grammarElement).getName(); if (ruleName.equalsIgnoreCase(terminalRuleName)) { return singletonList((INode) leafNode); } else if(wsRuleName.equals(terminalRuleName)) { continue; } } break; } } } return Collections.emptyList(); }
@Test public void testTheBug2() throws Exception { with(new Bug302128TestLanguageStandaloneSetup()); String text = "VARIABLE += value.val value2.val\n" + "VARIABLE2 += value3.val value4.val\n\n" + "#Comment comment comment\n\n" + "VARIABLE3 += value5.val value6.val\n" + "VARIABLE4 += value.val value2.val\n" + "VARIABLE5 += value3.val value4.val\n\n" + "#Comment comment comment\n\n" + "VARIABLE.varible += value5.val value6.val\n"; XtextResource resource = getResource(new StringInputStream(text)); Model model = (Model) resource.getContents().get(0); model.getElements().get(2).setValue("+= value5.val value6.val\n"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); resource.save(outputStream, null); assertEquals(text, new String(outputStream.toByteArray())); }
public void format(final Object model, final IFormattableDocument document) { if (model instanceof XtextResource) { _format((XtextResource)model, document); return; } else if (model instanceof Model) { _format((Model)model, document); return; } else if (model instanceof EObject) { _format((EObject)model, document); return; } else if (model == null) { _format((Void)null, document); return; } else if (model != null) { _format(model, document); return; } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(model, document).toString()); } }
@Test public void test1() { try { this.with(ReferenceGrammarTestLanguageStandaloneSetup.class); final String model = "kind (Hugo 13)"; final ParserRule kindRule = this.<ReferenceGrammarTestLanguageGrammarAccess>get(ReferenceGrammarTestLanguageGrammarAccess.class).getKindRule(); final XtextResource resource = this.createResource(); resource.setEntryPoint(kindRule); StringInputStream _stringInputStream = new StringInputStream(model); resource.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap()); Assert.assertTrue(resource.getErrors().isEmpty()); Assert.assertEquals(kindRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode())); final String originalNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false); resource.update(0, model.length(), ((" " + model) + " ")); final String reparsedNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false); Assert.assertEquals(originalNodeModel, reparsedNodeModel); final ParserRule erwachsenerRule = this.<ReferenceGrammarTestLanguageGrammarAccess>get(ReferenceGrammarTestLanguageGrammarAccess.class).getErwachsenerRule(); resource.setEntryPoint(erwachsenerRule); resource.update(0, model.length(), "erwachsener (Peter 30)"); Assert.assertEquals(erwachsenerRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode())); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
@Test public void testPartialParseConcreteRuleInnermostToken_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 ch1Leaf = findLeafNodeByText(root, model, "ch1"); // change the model and undo the change resource.update(model.indexOf("ch1") + 1, 1, "x"); resource.update(model.indexOf("ch1") + 1, 1, "h"); assertSame(root, resource.getParseResult().getRootNode()); assertSame(childrenLeaf, findLeafNodeByText(root, model, "children")); assertNotSame(ch1Leaf, findLeafNodeByText(root, model, "ch1")); }
@Test public void testParseWithComments() { try { StringConcatenation _builder = new StringConcatenation(); _builder.append("// hello"); _builder.newLine(); _builder.append("some token"); _builder.newLine(); _builder.append("import java.util.Set"); _builder.newLine(); final ImportSectionTestLanguageRoot root = this._parseHelper.parse(_builder.toString().replaceAll("\r\n", "\n")); Resource _eResource = root.eResource(); Assert.assertEquals(19, this.importsConfiguration.getImportSectionOffset(((XtextResource) _eResource))); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
@Override public final List<ITextReplacement> format(FormatterRequest request) { try { initialize(request); XtextResource xtextResource = request.getTextRegionAccess().getResource(); IFormattableDocument document = createFormattableRootDocument(); try { format(xtextResource, document); } catch (RegionTraceMissingException e) { document = handleTraceMissing(document, e); } List<ITextReplacement> rendered = document.renderToTextReplacements(); List<ITextReplacement> postprocessed = postProcess(document, rendered); return postprocessed; } finally { reset(); } }
public void format(final Object model, final IFormattableDocument document) { if (model instanceof XtextResource) { _format((XtextResource)model, document); return; } else if (model instanceof IDList) { _format((IDList)model, document); return; } else if (model instanceof EObject) { _format((EObject)model, document); return; } else if (model == null) { _format((Void)null, document); return; } else if (model != null) { _format(model, document); return; } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(model, document).toString()); } }
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)) { SerializerTestHelper tester = get(SerializerTestHelper.class); EObject obj = resource.getContents().get(0); tester.assertSerializeWithNodeModel(obj); tester.assertSerializeWithoutNodeModel(obj); } return resource; }
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()); }
@Test public void testMultiInheritance_01() throws Exception { StringConcatenation _builder = new StringConcatenation(); _builder.append("grammar test with org.eclipse.xtext.enumrules.EnumRulesTestLanguage"); _builder.newLine(); _builder.append("import \'http://www.eclipse.org/xtext/common/JavaVMTypes\' as types"); _builder.newLine(); _builder.append("generate myDsl \"http://example.xtext.org/MyDsl\" as mydsl"); _builder.newLine(); _builder.append("Array returns mydsl::Array: componentType=ComponentType componentType=DeclaredType;"); _builder.newLine(); _builder.append("DeclaredType returns types::JvmDeclaredType: members+=DeclaredType;"); _builder.newLine(); _builder.append("ComponentType returns types::JvmComponentType: \'ignore\';"); _builder.newLine(); final String grammarAsString = _builder.toString(); final XtextResource resource = this.getResourceFromString(grammarAsString); EObject _head = IterableExtensions.<EObject>head(resource.getContents()); final Grammar grammar = ((Grammar) _head); EClassifier _classifier = IterableExtensions.<AbstractRule>head(grammar.getRules()).getType().getClassifier(); EClass array = ((EClass) _classifier); Assert.assertEquals("JvmComponentType", this.<EStructuralFeature>feature(array, "componentType").getEType().getName()); }