@SuppressWarnings({ "unused", "deprecation" }) private AliasLocation enhanceExistingImportDeclaration(ImportDeclaration importDeclaration, QualifiedName qualifiedName, String optionalAlias, MultiTextEdit result) { addImportSpecifier(importDeclaration, qualifiedName, optionalAlias); ICompositeNode replaceMe = NodeModelUtils.getNode(importDeclaration); int offset = replaceMe.getOffset(); AliasLocationAwareBuffer observableBuffer = new AliasLocationAwareBuffer( optionalAlias, offset, grammarAccess); try { serializer.serialize( importDeclaration, observableBuffer, SaveOptions.newBuilder().noValidation().getOptions()); } catch (IOException e) { throw new RuntimeException("Should never happen since we write into memory", e); } result.addChild(new ReplaceEdit(offset, replaceMe.getLength(), observableBuffer.toString())); return observableBuffer.getAliasLocation(); }
public TreeConstructionReport serialize(EObject obj, ITokenStream tokenStream, SaveOptions options) throws IOException { if (options.isValidating()) { List<Diagnostic> diagnostics = new ArrayList<Diagnostic>(); validator.validateRecursive(obj, new IConcreteSyntaxValidator.DiagnosticListAcceptor(diagnostics), new HashMap<Object, Object>()); if (!diagnostics.isEmpty()) throw new IConcreteSyntaxValidator.InvalidConcreteSyntaxException( "These errors need to be fixed before the model can be serialized.", diagnostics); } ITokenStream formatterTokenStream; if(formatter instanceof IFormatterExtension) formatterTokenStream = ((IFormatterExtension) formatter).createFormatterStream(obj, null, tokenStream, !options.isFormatting()); else formatterTokenStream = formatter.createFormatterStream(null, tokenStream, !options.isFormatting()); TreeConstructionReport report = parseTreeReconstructor.serializeSubtree(obj, formatterTokenStream); formatterTokenStream.flush(); return report; }
@Override public String serialize(EObject obj, SaveOptions options) { checkNotNull(obj, "obj must not be null."); checkNotNull(options, "options must not be null."); try { if (formatter2Provider != null) { StringBuilder builder = new StringBuilder(); serialize(obj, builder, options); return builder.toString(); } else { TokenStringBuffer tokenStringBuffer = new TokenStringBuffer(); serialize(obj, tokenStringBuffer, options); return tokenStringBuffer.toString(); } } catch (IOException e) { throw new RuntimeException(e); } }
/** * @noreference */ public static String grammarFragmentToString(final ISerializer serializer, final EObject object, final String prefix) { String s = null; try { final SaveOptions options = SaveOptions.newBuilder().format().getOptions(); s = serializer.serialize(object, options); } catch (final Throwable _t) { if (_t instanceof Exception) { final Exception e = (Exception)_t; s = e.toString(); } else { throw Exceptions.sneakyThrow(_t); } } String _replace = s.trim().replaceAll("(\\r?\\n)", ("$1" + prefix)).replace("\\u", "\\\\u"); String _plus = (prefix + _replace); s = _plus; return s; }
@Test public void testXtextFormatting() throws IOException { String path = getClass().getPackage().getName().replace('.', '/'); URI u = URI.createURI("classpath:/" + path + "/XtextFormatterMessy.xtext"); XtextResourceSet resourceSet = new XtextResourceSet(); resourceSet.setClasspathURIContext(getClass()); Resource r = resourceSet.getResource(u, true); // System.out.println(r.getWarnings()); // System.out.println(r.getErrors()); ByteArrayOutputStream formatted = new ByteArrayOutputStream(); r.save(formatted, SaveOptions.newBuilder().format().getOptions().toOptionsMap()); // System.out.println(EmfFormatter.listToStr(r.getContents())); // System.out.println(formatted.toString()); URI expectedURI = URI.createURI("classpath:/" + path + "/XtextFormatterExpected.xtext"); XtextResource expectedResource = (XtextResource) resourceSet.getResource(expectedURI, true); String expected = expectedResource.getParseResult().getRootNode().getText(); assertEquals(expected.replaceAll(System.lineSeparator(), "\n"), formatted.toString().replaceAll(System.lineSeparator(), "\n")); }
@Test public void testSimple() throws Exception { // this fails see bug #252181 String model = "grammar foo with org.eclipse.xtext.common.Terminals Honolulu : name=ID;"; // load grammar model XtextResourceSet rs = get(XtextResourceSet.class); Resource resource = rs.createResource(URI.createURI("foo.xtext"), ContentHandler.UNSPECIFIED_CONTENT_TYPE); resource.load(new StringInputStream(model), null); Grammar object = (Grammar) resource.getContents().get(0); // modify first rule object.getRules().get(0).setName("HONOLULU"); // save ByteArrayOutputStream out = new ByteArrayOutputStream(); resource.save(out, SaveOptions.newBuilder().format().getOptions().toOptionsMap()); String result = new String(out.toByteArray()); // check assertFalse(model.equals(result)); String expectedModel = LineDelimiters.toPlatform("grammar foo with org.eclipse.xtext.common.Terminals\n\nHONOLULU:\n name=ID;"); assertEquals(expectedModel, result); }
/** * Serialize the given object into tokenStream using save options. * The initial indentation is passed on to the formatter. * This implementation is based on {@link Serializer#serialize(EObject, ITokenStream, SaveOptions)}. * * @param obj * the obj * @param tokenStream * the token stream * @param options * the options * @param initialIndentation * the initial indentation * @throws IOException * Signals that an I/O exception has occurred. */ protected void serialize(final EObject obj, final ITokenStream tokenStream, final SaveOptions options, final String initialIndentation) throws IOException { if (options.isValidating()) { List<Diagnostic> diagnostics = new ArrayList<Diagnostic>(); validator.validateRecursive(obj, new IConcreteSyntaxValidator.DiagnosticListAcceptor(diagnostics), new HashMap<Object, Object>()); if (!diagnostics.isEmpty()) { throw new IConcreteSyntaxValidator.InvalidConcreteSyntaxException("These errors need to be fixed before the model can be serialized.", diagnostics); //$NON-NLS-1$ } } ISerializationDiagnostic.Acceptor errors = ISerializationDiagnostic.EXCEPTION_THROWING_ACCEPTOR; ITokenStream formatterTokenStream; if (formatter instanceof IFormatterExtension) { formatterTokenStream = ((IFormatterExtension) formatter).createFormatterStream(obj, initialIndentation, tokenStream, !options.isFormatting()); } else { formatterTokenStream = formatter.createFormatterStream(initialIndentation, tokenStream, !options.isFormatting()); } EObject context = getContext(obj); ISequenceAcceptor acceptor = new TokenStreamSequenceAdapter(formatterTokenStream, errors); serialize(obj, context, acceptor, errors); formatterTokenStream.flush(); }
/** * @since 2.7 */ protected void prettyPrint(String absoluteGrammarFileName, Charset encoding) { try { String content = readFileIntoString(absoluteGrammarFileName, encoding); final ILineSeparatorInformation lineSeparatorInformation = new ILineSeparatorInformation() { @Override public String getLineSeparator() { return DebugAntlrGeneratorFragment.this.getLineDelimiter(); } }; Injector injector = new SimpleAntlrStandaloneSetup() { @Override public Injector createInjector() { return Guice.createInjector(new SimpleAntlrRuntimeModule() { @Override public void configure(Binder binder) { super.configure(binder); binder.bind(ILineSeparatorInformation.class).toInstance(lineSeparatorInformation); } }); } }.createInjectorAndDoEMFRegistration(); XtextResource resource = injector.getInstance(XtextResource.class); resource.setURI(URI.createFileURI(absoluteGrammarFileName)); resource.load(new StringInputStream(content, encoding.name()), Collections.singletonMap(XtextResource.OPTION_ENCODING, encoding.name())); if (!resource.getErrors().isEmpty()) { String errors = Joiner.on(getLineDelimiter()).join(resource.getErrors()); throw new GeneratorWarning("Non fatal problem: Debug grammar could not be formatted due to:" + getLineDelimiter() + errors); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(content.length()); resource.save(outputStream, SaveOptions.newBuilder().format().getOptions().toOptionsMap()); String toBeWritten = new NewlineNormalizer(getLineDelimiter()).normalizeLineDelimiters( new String(outputStream.toByteArray(), encoding.name())); writeStringIntoFile(absoluteGrammarFileName, toBeWritten, encoding); } catch(IOException e) { throw new GeneratorWarning(e.getMessage()); } }
@Override public String serialize(EObject obj, SaveOptions options) { TokenStringBuffer tokenStringBuffer = new TokenStringBuffer(); try { serialize(obj, tokenStringBuffer, options); } catch (IOException e) { throw new RuntimeException(e); } return tokenStringBuffer.toString(); }
@Override public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options) { TokenStringBuffer tokenStringBuffer = new TokenStringBuffer(); try { TreeConstructionReport report = serialize(obj, tokenStringBuffer, options); return new ReplaceRegion(report.getPreviousLocation(), tokenStringBuffer.toString()); } catch (IOException e) { throw new RuntimeException(e); } }
public SaveOptions toSaveOptions() { SaveOptions.Builder builder = SaveOptions.newBuilder(); if (!isValidateConcreteSyntax()) builder.noValidation(); if (isFormatting()) builder.format(); return builder.getOptions(); }
protected void serialize(EObject obj, ITokenStream tokenStream, SaveOptions options) throws IOException { ISerializationDiagnostic.Acceptor errors = ISerializationDiagnostic.EXCEPTION_THROWING_ACCEPTOR; ITokenStream formatterTokenStream; if (formatter instanceof IFormatterExtension) formatterTokenStream = ((IFormatterExtension) formatter).createFormatterStream(obj, null, tokenStream, !options.isFormatting()); else formatterTokenStream = formatter.createFormatterStream(null, tokenStream, !options.isFormatting()); ISerializationContext context = getIContext(obj); ISequenceAcceptor acceptor = new TokenStreamSequenceAdapter(formatterTokenStream, grammar.getGrammar(), errors); serialize(context, obj, acceptor, errors); formatterTokenStream.flush(); }
protected void serialize(EObject obj, Appendable appendable, SaveOptions options) throws IOException { ITextRegionAccess regionAccess = serializeToRegions(obj); FormatterRequest request = formatterRequestProvider.get(); request.setFormatUndefinedHiddenRegionsOnly(!options.isFormatting()); request.setTextRegionAccess(regionAccess); IFormatter2 formatter2 = formatter2Provider.get(); List<ITextReplacement> replacements = formatter2.format(request); regionAccess.getRewriter().renderToAppendable(replacements, appendable); }
@Override public void serialize(EObject obj, Writer writer, SaveOptions options) throws IOException { checkNotNull(obj, "obj must not be null."); checkNotNull(writer, "writer must not be null."); checkNotNull(options, "options must not be null."); if (formatter2Provider != null) { serialize(obj, (Appendable) writer, options); writer.flush(); } else { serialize(obj, new WriterTokenStream(writer), options); } }
@Override public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options) { ICompositeNode node = NodeModelUtils.findActualNodeFor(obj); if (node == null) { throw new IllegalStateException("Cannot replace an obj that has no associated node"); } String text = serialize(obj, options); return new ReplaceRegion(node.getTotalOffset(), node.getTotalLength(), text); }
protected String saveResource(Resource resource) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(content.length()); try { Map<Object, Object> options = Maps.newHashMap(); options.put(XtextResource.OPTION_ENCODING, INTERNAL_ENCODING); SaveOptions.defaultOptions().addTo(options); resource.save(out, options); String result = new String(out.toByteArray(), INTERNAL_ENCODING); return result; } finally { out.close(); } }
@Test public void testLinewrapDefault() throws Exception { FormattertestlanguageFactory f = FormattertestlanguageFactory.eINSTANCE; TestLinewrapMinMax m = f.createTestLinewrapMinMax(); Decl d = f.createDecl(); d.getType().add("xxx"); d.getName().add("yyy"); m.getItems().add(d); String actual = getSerializer().serialize(m, SaveOptions.newBuilder().format().getOptions()); final String expected = convertLineBreaks("test wrapminmax\n\n\nxxx yyy;"); assertEquals(expected, actual); }
private void checkReplaceRegion(Element element, String expectedText, String completeModel) { Serializer serializer = get(Serializer.class); ReplaceRegion replacement = serializer.serializeReplacement(element, SaveOptions.defaultOptions()); assertEquals(expectedText, replacement.getText()); assertEquals(completeModel.indexOf(expectedText), replacement.getOffset()); assertEquals(expectedText.length(), replacement.getLength()); }
private void doTestSerialization(final String model, final String expectedModel) throws Exception { final XtextResource resource = this.getResourceFromString(model); Assert.assertTrue(resource.getErrors().isEmpty()); EObject _rootASTElement = resource.getParseResult().getRootASTElement(); final Grammar g = ((Grammar) _rootASTElement); Assert.assertNotNull(g); final OutputStream outputStream = new ByteArrayOutputStream(); resource.save(outputStream, SaveOptions.newBuilder().format().getOptions().toOptionsMap()); final String serializedModel = outputStream.toString(); Assert.assertEquals(LineDelimiters.toPlatform(expectedModel), serializedModel); }
/** * This test is copied from * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest. * * @throws IOException */ @Test public void linewrapDefault() { FormatterTestLanguageFactory f = FormatterTestLanguageFactory.eINSTANCE; TestLinewrapMinMax m = f.createTestLinewrapMinMax(); Decl d = f.createDecl(); d.getType().add("xxx"); d.getName().add("yyy"); m.getItems().add(d); String actual = getSerializer().serialize(m, SaveOptions.newBuilder().format().getOptions()); String expected = "test wrapminmax\n\n\nxxx yyy;"; Assert.assertEquals(expected, actual); }
/** * This method implementation is copied from {@link Serializer#serialize(EObject, SaveOptions)} with the addition of the indentation parameter. {@inheritDoc} */ @Override public String serialize(final EObject obj, final SaveOptions options, final String initialIndentation) { TokenStringBuffer tokenStringBuffer = new TokenStringBuffer(); try { serialize(obj, tokenStringBuffer, options, initialIndentation); } catch (IOException e) { throw new RuntimeException(e);// NOPMD } return tokenStringBuffer.toString(); }
public ECLDocument getEclDocument(ImportInterfaceStatement importInterfaceStatement){ //init Xtext String modelPath = importInterfaceStatement.getImportURI(); EclStandaloneSetup ess= new EclStandaloneSetup(); Injector injector = ess.createInjector(); XtextResourceSet aSet = injector.getInstance(XtextResourceSet.class); aSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.FALSE); EcoreUtil.resolveAll(aSet); EclStandaloneSetup.doSetup(); URI uri =null; //filter URI if (modelPath.startsWith("platform:/plugin")){ uri = URI.createPlatformPluginURI(modelPath.replace("platform:/plugin", ""), false); }else if(modelPath.startsWith("platform:/resource")){ uri = URI.createPlatformResourceURI(modelPath.replace("platform:/resource", ""),false); }else{//relative path // throw new IllegalArgumentException("the path of the library must be platform based (platform:/resource or platform:/plugin)"); uri = URI.createFileURI(modelPath); } //load the corresponding resource Resource eclResource = aSet.getResource(uri, true); HashMap<Object, Object> saveOptions = new HashMap<Object, Object>(); Builder aBuilder = SaveOptions.newBuilder(); SaveOptions anOption = aBuilder.getOptions(); anOption.addTo(saveOptions); try { eclResource.load(saveOptions); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ECLDocument eclDoc = (ECLDocument)eclResource.getContents().get(0); return eclDoc; }
public ECLDocument getEclDocumentfromURI(String modelPath){ //init Xtext EclStandaloneSetup ess= new EclStandaloneSetup(); Injector injector = ess.createInjector(); XtextResourceSet aSet = injector.getInstance(XtextResourceSet.class); aSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE); EcoreUtil.resolveAll(aSet); EclStandaloneSetup.doSetup(); URI uri =null; //filter URI if (modelPath.startsWith("platform:/plugin")){ uri = URI.createPlatformPluginURI(modelPath.replace("platform:/plugin", ""), false); }else if(modelPath.startsWith("platform:/resource")){ uri = URI.createPlatformResourceURI(modelPath.replace("platform:/resource", ""),false); }else{//relative path // throw new IllegalArgumentException("the path of the library must be platform based (platform:/resource or platform:/plugin)"); uri = URI.createFileURI(modelPath); } //load the corresponding resource Resource eclResource = aSet.getResource(uri, true); HashMap<Object, Object> saveOptions = new HashMap<Object, Object>(); Builder aBuilder = SaveOptions.newBuilder(); SaveOptions anOption = aBuilder.getOptions(); anOption.addTo(saveOptions); try { eclResource.load(saveOptions); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ECLDocument eclDoc = (ECLDocument)eclResource.getContents().get(0); return eclDoc; }
protected void loadResource(Resource model2Resource) { HashMap<Object, Object> saveOptions2 = new HashMap<Object, Object>(); Builder aBuilder2 = SaveOptions.newBuilder(); SaveOptions anOption2 = aBuilder2.getOptions(); anOption2.addTo(saveOptions2); try { model2Resource.load(saveOptions2); } catch (IOException e1) { e1.printStackTrace(); } }
@Override public void serialize(EObject obj, ITokenStream tokenStream, SaveOptions options) throws IOException { super.serialize(obj, tokenStream, options); }
@Override public void serialize(EObject obj, Writer writer, SaveOptions options) throws IOException { serialize(obj, new WriterTokenStream(writer), options); }
@Override public String serialize(EObject obj) { return serialize(obj, SaveOptions.defaultOptions()); }
@Override public String serialize(EObject obj) { checkNotNull(obj, "obj must not be null."); return serialize(obj, SaveOptions.defaultOptions()); }
protected void assertFormattedPTC(String expected, String model) throws Exception { EObject m = getModel(convertLineBreaks(model)); String res = getSerializer().serialize(m, SaveOptions.newBuilder().format().getOptions()); assertEquals(revealLineBreaks(convertLineBreaks(expected)), revealLineBreaks(res)); }
protected void assertPreserved(final String modelP) throws Exception { String model = convertLineBreaks(modelP); EObject m = getModel(model); String res = getSerializer().serialize(m, SaveOptions.newBuilder().getOptions()); assertEquals(revealLineBreaks(model), revealLineBreaks(res)); }
public void _testXtextXtext() { Serializer serializer = get(Serializer.class); IGrammarAccess grammar = get(IGrammarAccess.class); SaveOptions opt = SaveOptions.newBuilder().format().getOptions(); System.out.println(serializer.serialize(grammar.getGrammar(), opt)); }
private String parseAndSerialize(String model) throws Exception { EObject result = getModel(model); return getSerializer().serialize(result, SaveOptions.defaultOptions()); }
private String parseAndSerialize(String model) throws Exception { EObject result = getModel(model); if (logger.isTraceEnabled()) logger.trace(EmfFormatter.objToStr(result)); return getSerializer().serialize(result, SaveOptions.defaultOptions()); }
protected void assertFormattedPTC(final String expected, final String model) throws IOException { EObject m = getModel(model); String res = getSerializer().serialize(m, SaveOptions.newBuilder().format().getOptions()); Assert.assertEquals(expected, res); }
protected void assertPreserved(final String model) throws IOException { EObject m = getModel(model); String res = getSerializer().serialize(m, SaveOptions.newBuilder().getOptions()); Assert.assertEquals(model, res); }
/** {@inheritDoc} */ @Override public void serialize(final EObject obj, final ITokenStream tokenStream, final SaveOptions options) throws IOException { serialize(obj, tokenStream, options, null); }
protected SaveOptions getSaveOptions() { return SaveOptions.defaultOptions(); }
protected void refresh(final EObject object, final Notification notification) { boolean _or = false; if (this.refreshing) { _or = true; } else { _or = this.mergingBack; } if (_or) { return; } this.refreshing = true; try { if (((object == this.currentViewedObject) && (notification != null))) { final EObject mergeResult = this.mergeForward(object, notification); if ((mergeResult != null)) { org.eclipse.emf.ecore.resource.Resource _eResource = mergeResult.eResource(); final String uriFragment = _eResource.getURIFragment(mergeResult); EObject _eContainer = mergeResult.eContainer(); SaveOptions.Builder _newBuilder = SaveOptions.newBuilder(); SaveOptions.Builder _format = _newBuilder.format(); SaveOptions _options = _format.getOptions(); final String serializedModel = this.serializer.serialize(_eContainer, _options); this.modelAccess.updateModel(serializedModel, uriFragment); String _editablePart = this.modelAccess.getEditablePart(); this.lastMergedContent = _editablePart; return; } } if ((this.currentViewedObject != null)) { final String content = this.modelAccess.getEditablePart(); boolean _notEquals = (!Objects.equal(content, this.lastMergedContent)); if (_notEquals) { EObject mergeSource = null; boolean _and = false; if (!(object != this.currentViewedObject)) { _and = false; } else { boolean _isEmpty = this.validationErrors.isEmpty(); _and = _isEmpty; } if (_and) { EObject _mergeBack = this.mergeBack(this.currentViewedObject, this.editingDomain); mergeSource = _mergeBack; } if ((mergeSource == null)) { this.handleDiscardedChanges(); } } } this.resourceValidator.setOriginalObject(object); if ((object == null)) { this.lastMergedContent = ""; this.modelAccess.updateModel(this.lastMergedContent); } else { org.eclipse.emf.ecore.resource.Resource _eResource_1 = object.eResource(); final String uriFragment_1 = _eResource_1.getURIFragment(object); EObject _eContainer_1 = object.eContainer(); SaveOptions.Builder _newBuilder_1 = SaveOptions.newBuilder(); SaveOptions.Builder _format_1 = _newBuilder_1.format(); SaveOptions _options_1 = _format_1.getOptions(); final String serializedModel_1 = this.serializer.serialize(_eContainer_1, _options_1); this.modelAccess.updateModel(serializedModel_1, uriFragment_1); this.viewer.setSelectedRange(0, 0); String _editablePart_1 = this.modelAccess.getEditablePart(); this.lastMergedContent = _editablePart_1; } this.currentViewedObject = object; } finally { this.refreshing = false; } }
/** * Serialize the given object with an initial indentation. * * @param obj * the obj * @param options * the options * @param initialIndentation * the initial indentation * @return the serialized object */ String serialize(EObject obj, SaveOptions options, String initialIndentation);
/** * Test formatting based on the ParseTreeConstructor. * * @param model * the model to be serialized and compared with expected string * @param expected * Expected formatted String */ private void assertFormattedParseTreeConstructor(final EObject model, final String expected) { String actual = getXtextTestUtil().getSerializer().serialize(model, SaveOptions.newBuilder().format().getOptions()); Assert.assertEquals(expected.replaceAll(CR_LF, LF), actual.replaceAll(CR_LF, LF)); }