Search in sources :

Example 1 with TokenWriter

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

the class PrinterTest method testListPrinter.

@Test
public void testListPrinter() {
    Launcher spoon = new Launcher();
    DefaultJavaPrettyPrinter pp = (DefaultJavaPrettyPrinter) spoon.createPrettyPrinter();
    PrinterHelper ph = new PrinterHelper(spoon.getEnvironment());
    TokenWriter tw = new DefaultTokenWriter(ph);
    pp.setPrinterTokenWriter(tw);
    ElementPrinterHelper elementPrinterHelper = pp.getElementPrinterHelper();
    String[] listString = new String[] { "un", "deux", "trois" };
    try (ListPrinter listPrinter = elementPrinterHelper.createListPrinter(true, "start", true, true, "next", true, true, "end")) {
        for (String s : listString) {
            listPrinter.printSeparatorIfAppropriate();
            tw.writeIdentifier(s);
        }
    }
    String expectedResult = " start un next deux next trois end";
    assertEquals(expectedResult, pp.toString());
}
Also used : ElementPrinterHelper(spoon.reflect.visitor.ElementPrinterHelper) DefaultTokenWriter(spoon.reflect.visitor.DefaultTokenWriter) TokenWriter(spoon.reflect.visitor.TokenWriter) Launcher(spoon.Launcher) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) DefaultTokenWriter(spoon.reflect.visitor.DefaultTokenWriter) ListPrinter(spoon.reflect.visitor.ListPrinter) ElementPrinterHelper(spoon.reflect.visitor.ElementPrinterHelper) PrinterHelper(spoon.reflect.visitor.PrinterHelper) Test(org.junit.Test)

Example 2 with TokenWriter

use of spoon.reflect.visitor.TokenWriter 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)

Aggregations

Test (org.junit.Test)2 Launcher (spoon.Launcher)2 DefaultJavaPrettyPrinter (spoon.reflect.visitor.DefaultJavaPrettyPrinter)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 CtComment (spoon.reflect.code.CtComment)1 Factory (spoon.reflect.factory.Factory)1 ListPrinter (spoon.reflect.visitor.ListPrinter)1