Search in sources :

Example 11 with DefaultJavaPrettyPrinter

use of spoon.reflect.visitor.DefaultJavaPrettyPrinter in project spoon by INRIA.

the class JDTBasedSpoonCompiler method getCompilationUnitInputStream.

protected InputStream getCompilationUnitInputStream(String path) {
    Environment env = factory.getEnvironment();
    spoon.reflect.cu.CompilationUnit cu = factory.CompilationUnit().getMap().get(path);
    List<CtType<?>> toBePrinted = cu.getDeclaredTypes();
    PrettyPrinter printer = new DefaultJavaPrettyPrinter(env);
    printer.calculate(cu, toBePrinted);
    return new ByteArrayInputStream(printer.getResult().toString().getBytes());
}
Also used : PrettyPrinter(spoon.reflect.visitor.PrettyPrinter) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) CtType(spoon.reflect.declaration.CtType) ByteArrayInputStream(java.io.ByteArrayInputStream) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) Environment(spoon.compiler.Environment) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter)

Example 12 with DefaultJavaPrettyPrinter

use of spoon.reflect.visitor.DefaultJavaPrettyPrinter in project spoon by INRIA.

the class CtElementImpl method toString.

@Override
public String toString() {
    DefaultJavaPrettyPrinter printer = new DefaultJavaPrettyPrinter(getFactory().getEnvironment());
    String errorMessage = "";
    try {
        // we do not want to compute imports of a CtImport as it may change the print of a reference
        if (!(this instanceof CtImport)) {
            printer.computeImports(this);
        }
        printer.scan(this);
    } catch (ParentNotInitializedException ignore) {
        LOGGER.error(ERROR_MESSAGE_TO_STRING, ignore);
        errorMessage = ERROR_MESSAGE_TO_STRING;
    }
    // removing them from the toString() representation
    return printer.toString().replaceFirst("^\\s+", "") + errorMessage;
}
Also used : CtImport(spoon.reflect.declaration.CtImport) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter)

Example 13 with DefaultJavaPrettyPrinter

use of spoon.reflect.visitor.DefaultJavaPrettyPrinter in project spoon by INRIA.

the class LauncherTest method testInitEnvironmentDefault.

@Test
public void testInitEnvironmentDefault() throws Exception {
    final Launcher launcher = new Launcher();
    launcher.setArgs(new String[0]);
    launcher.processArguments();
    final Environment environment = launcher.getEnvironment();
    // specify the default values
    Assert.assertFalse(environment.isAutoImports());
    Assert.assertFalse(environment.isUsingTabulations());
    Assert.assertFalse(environment.isPreserveLineNumbers());
    assertEquals(4, environment.getTabulationSize());
    Assert.assertTrue(environment.isCopyResources());
    JavaOutputProcessor processor = (JavaOutputProcessor) environment.getDefaultFileGenerator();
    Assert.assertTrue(processor.getPrinter() instanceof DefaultJavaPrettyPrinter);
    // now assertions on the model builder
    final SpoonModelBuilder builder = launcher.getModelBuilder();
    assertEquals(new File("spooned").getCanonicalFile(), builder.getSourceOutputDirectory());
    assertEquals(0, builder.getInputSources().size());
    assertEquals("UTF-8", environment.getEncoding().displayName());
}
Also used : Environment(spoon.compiler.Environment) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) File(java.io.File) JavaOutputProcessor(spoon.support.JavaOutputProcessor) Test(org.junit.Test)

Example 14 with DefaultJavaPrettyPrinter

use of spoon.reflect.visitor.DefaultJavaPrettyPrinter in project spoon by INRIA.

the class PrinterTest method testPrinterTokenListener.

@Test
public void testPrinterTokenListener() throws Exception {
    Launcher spoon = new Launcher();
    Factory factory = spoon.createFactory();
    spoon.createCompiler(factory, SpoonResourceHelper.resources("./src/test/java/spoon/test/annotation/testclasses/", "./src/test/java/spoon/test/prettyprinter/")).build();
    assertTrue(factory.Type().getAll().size() > 0);
    for (CtType<?> t : factory.Type().getAll()) {
        // create DefaultJavaPrettyPrinter with standard DefaultTokenWriter
        DefaultJavaPrettyPrinter pp = new DefaultJavaPrettyPrinter(factory.getEnvironment());
        pp.calculate(t.getPosition().getCompilationUnit(), Collections.singletonList(t));
        // result of printing using standard DefaultTokenWriter
        String standardPrintedResult = pp.getResult();
        StringBuilder allTokens = new StringBuilder();
        // print type with custom listener
        // 1) register custom TokenWriter which checks the TokenWriter contract
        pp.setPrinterTokenWriter(new TokenWriter() {

            String lastToken;

            PrinterHelper printerHelper = new PrinterHelper(factory.getEnvironment());

            @Override
            public TokenWriter writeSeparator(String separator) {
                checkRepeatingOfTokens("writeSeparator");
                checkTokenWhitespace(separator, false);
                // one of the separators
                assertTrue("Unexpected separator: " + separator, separators.contains(separator));
                handleTabs();
                allTokens.append(separator);
                return this;
            }

            @Override
            public TokenWriter writeOperator(String operator) {
                checkRepeatingOfTokens("writeOperator");
                checkTokenWhitespace(operator, false);
                assertTrue("Unexpected operator: " + operator, operators.contains(operator));
                handleTabs();
                allTokens.append(operator);
                return this;
            }

            @Override
            public TokenWriter writeLiteral(String literal) {
                checkRepeatingOfTokens("writeLiteral");
                assertTrue(literal.length() > 0);
                handleTabs();
                allTokens.append(literal);
                return this;
            }

            @Override
            public TokenWriter writeKeyword(String keyword) {
                checkRepeatingOfTokens("writeKeyword");
                checkTokenWhitespace(keyword, false);
                assertTrue("Unexpected java keyword: " + keyword, javaKeywords.contains(keyword));
                handleTabs();
                allTokens.append(keyword);
                return this;
            }

            @Override
            public TokenWriter writeIdentifier(String identifier) {
                checkRepeatingOfTokens("writeIdentifier");
                checkTokenWhitespace(identifier, false);
                for (int i = 0; i < identifier.length(); i++) {
                    char c = identifier.charAt(i);
                    if (i == 0) {
                        assertTrue(Character.isJavaIdentifierStart(c));
                    } else {
                        assertTrue(Character.isJavaIdentifierPart(c));
                    }
                }
                assertTrue("Keyword found in Identifier: " + identifier, javaKeywords.contains(identifier) == false);
                handleTabs();
                allTokens.append(identifier);
                return this;
            }

            @Override
            public TokenWriter writeComment(CtComment comment) {
                checkRepeatingOfTokens("writeComment");
                DefaultTokenWriter sptw = new DefaultTokenWriter(new PrinterHelper(factory.getEnvironment()));
                PrinterHelper ph = sptw.getPrinterHelper();
                ph.setLineSeparator(getPrinterHelper().getLineSeparator());
                ph.setTabCount(getPrinterHelper().getTabCount());
                sptw.writeComment(comment);
                handleTabs();
                allTokens.append(sptw.getPrinterHelper().toString());
                return this;
            }

            @Override
            public TokenWriter writeln() {
                checkRepeatingOfTokens("writeln");
                allTokens.append(getPrinterHelper().getLineSeparator());
                lastTokenWasEOL = true;
                return this;
            }

            private boolean lastTokenWasEOL = true;

            private int tabCount = 0;

            public TokenWriter handleTabs() {
                if (lastTokenWasEOL) {
                    lastTokenWasEOL = false;
                    for (int i = 0; i < tabCount; i++) {
                        if (factory.getEnvironment().isUsingTabulations()) {
                            allTokens.append('\t');
                        } else {
                            for (int j = 0; j < factory.getEnvironment().getTabulationSize(); j++) {
                                allTokens.append(' ');
                            }
                        }
                    }
                }
                return this;
            }

            @Override
            public TokenWriter writeCodeSnippet(String token) {
                checkRepeatingOfTokens("writeCodeSnippet");
                assertTrue(token.length() > 0);
                handleTabs();
                allTokens.append(token);
                return this;
            }

            @Override
            public TokenWriter incTab() {
                tabCount++;
                return this;
            }

            @Override
            public TokenWriter decTab() {
                tabCount--;
                return this;
            }

            @Override
            public PrinterHelper getPrinterHelper() {
                return printerHelper;
            }

            @Override
            public void reset() {
                printerHelper.reset();
            }

            @Override
            public TokenWriter writeSpace() {
                checkRepeatingOfTokens("writeWhitespace");
                allTokens.append(' ');
                return this;
            }

            // checks that token types are changing. There must be no two tokens of the same type in queue
            private void checkRepeatingOfTokens(String tokenType) {
                if ("writeln".equals(tokenType) || "writeIdentifier".equals(tokenType) || "writeSeparator".equals(tokenType) || "writeWhitespace".equals(tokenType)) {
                // nothing
                } else {
                    // check only other tokens then writeln, which is the only one which can repeat
                    assertTrue("Two tokens of same type current:" + tokenType + " " + allTokens.toString(), tokenType.equals(this.lastToken) == false);
                }
                this.lastToken = tokenType;
            }
        });
        // 2) print type using PrettyPrinter with listener
        pp.calculate(t.getPosition().getCompilationUnit(), Collections.singletonList(t));
        String withEmptyListenerResult = pp.getResult();
        // contract: each printed character is handled by listener. PrinterHelper is not called directly
        // and because PrinterTokenListener above does not use PrinterHelper, the result must be empty
        assertEquals(0, withEmptyListenerResult.length());
        // contract: result built manually from tokens is same like the one made by DefaultTokenWriter
        assertEquals(standardPrintedResult, allTokens.toString());
    }
}
Also used : CtComment(spoon.reflect.code.CtComment) DefaultTokenWriter(spoon.reflect.visitor.DefaultTokenWriter) TokenWriter(spoon.reflect.visitor.TokenWriter) Factory(spoon.reflect.factory.Factory) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) ElementPrinterHelper(spoon.reflect.visitor.ElementPrinterHelper) PrinterHelper(spoon.reflect.visitor.PrinterHelper) Launcher(spoon.Launcher) DefaultTokenWriter(spoon.reflect.visitor.DefaultTokenWriter) Test(org.junit.Test)

Example 15 with DefaultJavaPrettyPrinter

use of spoon.reflect.visitor.DefaultJavaPrettyPrinter in project spoon by INRIA.

the class QualifiedThisRefTest method testPrintCtFieldAccessWorkEvenWhenParentNotInitialized.

@Test
public void testPrintCtFieldAccessWorkEvenWhenParentNotInitialized() throws Exception {
    CtClass zeclass = factory.Class().get(QualifiedThisRef.class);
    List<CtMethod> methods = zeclass.getMethodsByName("bla");
    assertEquals(1, methods.size());
    CtStatement invocation = methods.get(0).getBody().getStatement(0);
    assertTrue(invocation instanceof CtInvocation);
    CtInvocation<?> arg0 = (CtInvocation) invocation;
    CtExpression param = arg0.getArguments().get(0);
    CtExecutableReference execref = factory.Core().createExecutableReference();
    execref.setDeclaringType(factory.Type().createReference("java.util.Map"));
    execref.setSimpleName("exorcise");
    execref.setStatic(true);
    CtTypeReference tmp = param.getType();
    CtExpression arg = null;
    CtFieldReference ctfe = factory.createFieldReference();
    ctfe.setSimpleName("class");
    ctfe.setDeclaringType(tmp.box());
    arg = factory.Core().createFieldRead();
    ((CtFieldAccessImpl) arg).setVariable(ctfe);
    CtLiteral location = factory.Core().createLiteral();
    location.setType(factory.Type().createReference(String.class));
    CtTypeReference tmpref = factory.Core().clone(tmp);
    CtInvocation invoc = factory.Core().createInvocation();
    invoc.setExecutable(execref);
    invoc.setArguments(Arrays.asList(new CtExpression[] { param, arg, location }));
    execref.setActualTypeArguments(Arrays.asList(new CtTypeReference<?>[] { tmpref }));
    // succeeds
    arg0.getArguments().set(0, invoc);
    DefaultJavaPrettyPrinter printer = new DefaultJavaPrettyPrinter(factory.getEnvironment());
    printer.visitCtClass(zeclass);
    assertFalse(printer.getResult().isEmpty());
}
Also used : CtExpression(spoon.reflect.code.CtExpression) CtFieldReference(spoon.reflect.reference.CtFieldReference) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) CtClass(spoon.reflect.declaration.CtClass) CtInvocation(spoon.reflect.code.CtInvocation) CtLiteral(spoon.reflect.code.CtLiteral) CtStatement(spoon.reflect.code.CtStatement) CtFieldAccessImpl(spoon.support.reflect.code.CtFieldAccessImpl) CtTypeReference(spoon.reflect.reference.CtTypeReference) CtExecutableReference(spoon.reflect.reference.CtExecutableReference) CtMethod(spoon.reflect.declaration.CtMethod) Test(org.junit.Test)

Aggregations

DefaultJavaPrettyPrinter (spoon.reflect.visitor.DefaultJavaPrettyPrinter)16 Test (org.junit.Test)11 Launcher (spoon.Launcher)6 Environment (spoon.compiler.Environment)4 CtClass (spoon.reflect.declaration.CtClass)3 CtType (spoon.reflect.declaration.CtType)3 PrettyPrinter (spoon.reflect.visitor.PrettyPrinter)3 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)3 ArrayList (java.util.ArrayList)2 CtImport (spoon.reflect.declaration.CtImport)2 CtPackage (spoon.reflect.declaration.CtPackage)2 Factory (spoon.reflect.factory.Factory)2 DefaultTokenWriter (spoon.reflect.visitor.DefaultTokenWriter)2 ElementPrinterHelper (spoon.reflect.visitor.ElementPrinterHelper)2 PrinterHelper (spoon.reflect.visitor.PrinterHelper)2 TokenWriter (spoon.reflect.visitor.TokenWriter)2 JavaOutputProcessor (spoon.support.JavaOutputProcessor)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 INameEnvironment (org.eclipse.jdt.internal.compiler.env.INameEnvironment)1