Search in sources :

Example 1 with PrinterHelper

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

the class MainTest method checkModelIsTree.

/*
	 * contract: each element is used only once
	 * For example this is always true: field.getType() != field.getDeclaringType()
	 */
@Test
public void checkModelIsTree() {
    Exception dummyException = new Exception("STACK");
    PrinterHelper problems = new PrinterHelper(rootPackage.getFactory().getEnvironment());
    Map<CtElement, Exception> allElements = new IdentityHashMap<>();
    rootPackage.filterChildren(null).forEach((CtElement ele) -> {
        // uncomment this line to get stacktrace of real problem. The dummyException is used to avoid OutOfMemoryException
        // Exception secondStack = new Exception("STACK");
        Exception secondStack = dummyException;
        Exception firstStack = allElements.put(ele, secondStack);
        if (firstStack != null) {
            if (firstStack == dummyException) {
                Assert.fail("The Spoon model is not a tree. The " + ele.getClass().getSimpleName() + ":" + ele.toString() + " is shared");
            }
            // the element ele was already visited. It means it used on more places
            // report the stacktrace of first and second usage, so that place can be found easily
            problems.write("The element " + ele.getClass().getSimpleName()).writeln().incTab().write(ele.toString()).writeln().write("Is linked by these stacktraces").writeln().write("1) " + getStackTrace(firstStack)).writeln().write("2) " + getStackTrace(secondStack)).writeln().decTab();
        }
    });
    String report = problems.toString();
    if (report.length() > 0) {
        Assert.fail(report);
    }
}
Also used : CtElement(spoon.reflect.declaration.CtElement) IdentityHashMap(java.util.IdentityHashMap) CtPathException(spoon.reflect.path.CtPathException) ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) PrinterHelper(spoon.reflect.visitor.PrinterHelper) Test(org.junit.Test) ParentTest(spoon.test.parent.ParentTest)

Example 2 with PrinterHelper

use of spoon.reflect.visitor.PrinterHelper 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 3 with PrinterHelper

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

the class RoleHandlersGenerator method process.

@Override
public void process() {
    SpoonMetaModel metaModel = new SpoonMetaModel(getFactory());
    // all root super MMFields
    List<MetamodelProperty> superFields = new ArrayList<>();
    metaModel.getConcepts().forEach(mmConcept -> {
        mmConcept.getRoleToProperty().forEach((role, rim) -> {
            addUniqueObject(superFields, rim.getRootSuperField());
        });
    });
    superFields.sort((a, b) -> {
        int d = a.getRole().name().compareTo(b.getRole().name());
        if (d != 0) {
            return d;
        }
        return a.getOwnerConcept().getName().compareTo(b.getOwnerConcept().getName());
    });
    PrinterHelper concept = new PrinterHelper(getFactory().getEnvironment());
    superFields.forEach(mmField -> {
        concept.write(mmField.getOwnerConcept().getName() + " CtRole." + mmField.getRole().name()).writeln().incTab().write("ItemType: ").write(mmField.getValueType().toString()).writeln();
        for (MMMethodKind mk : MMMethodKind.values()) {
            MMMethod mmMethod = mmField.getMethod(mk);
            if (mmMethod != null) {
                concept.write(mk.name()).write(": ").write(mmMethod.getSignature()).write(" : ").write(mmMethod.getReturnType().toString()).writeln();
            }
        }
        concept.decTab();
        concept.write("----------------------------------------------------------").writeln();
    });
    try (Writer w = new OutputStreamWriter(new FileOutputStream(file("target/report/concept.txt")))) {
        w.write(concept.toString());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    CtType<?> template = getTemplate("spoon.generating.meta.ModelRoleHandlerTemplate");
    CtClass<?> modelRoleHandlersClass = Substitution.createTypeFromTemplate(TARGET_PACKAGE + ".ModelRoleHandlers", template, new HashMap<>());
    CtNewArray<?> roleHandlersFieldExpr = (CtNewArray<?>) modelRoleHandlersClass.getField("roleHandlers").getDefaultExpression();
    superFields.forEach(rim -> {
        Map<String, Object> params = new HashMap<>();
        params.put("$getterName$", rim.getMethod(MMMethodKind.GET).getName());
        if (rim.getMethod(MMMethodKind.SET) != null) {
            params.put("$setterName$", rim.getMethod(MMMethodKind.SET).getName());
        }
        params.put("$Role$", getFactory().Type().createReference(CtRole.class));
        params.put("ROLE", rim.getRole().name());
        params.put("$TargetType$", rim.getOwnerConcept().getModelInterface().getReference());
        // params.put("AbstractHandler", getFactory().Type().createReference("spoon.reflect.meta.impl.AbstractRoleHandler"));
        params.put("AbstractHandler", getRoleHandlerSuperTypeQName(rim));
        params.put("Node", rim.getOwnerConcept().getModelInterface().getReference());
        params.put("ValueType", fixMainValueType(getRoleHandlerSuperTypeQName(rim).endsWith("SingleHandler") ? rim.getValueType() : rim.getItemValueType()));
        CtClass<?> modelRoleHandlerClass = Substitution.createTypeFromTemplate(getHandlerName(rim), getTemplate("spoon.generating.meta.RoleHandlerTemplate"), params);
        if (rim.getMethod(MMMethodKind.SET) == null) {
            modelRoleHandlerClass.getMethodsByName("setValue").forEach(m -> m.delete());
        }
        modelRoleHandlerClass.addModifier(ModifierKind.STATIC);
        modelRoleHandlersClass.addNestedType(modelRoleHandlerClass);
        roleHandlersFieldExpr.addElement(getFactory().createCodeSnippetExpression("new " + modelRoleHandlerClass.getSimpleName() + "()"));
    });
}
Also used : SpoonMetaModel(spoon.test.metamodel.SpoonMetaModel) MMMethod(spoon.test.metamodel.MMMethod) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CtNewArray(spoon.reflect.code.CtNewArray) PrinterHelper(spoon.reflect.visitor.PrinterHelper) FileOutputStream(java.io.FileOutputStream) MetamodelProperty(spoon.test.metamodel.MetamodelProperty) CtRole(spoon.reflect.path.CtRole) OutputStreamWriter(java.io.OutputStreamWriter) MMMethodKind(spoon.test.metamodel.MMMethodKind) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer)

Example 4 with PrinterHelper

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

PrinterHelper (spoon.reflect.visitor.PrinterHelper)4 Test (org.junit.Test)3 Launcher (spoon.Launcher)2 DefaultJavaPrettyPrinter (spoon.reflect.visitor.DefaultJavaPrettyPrinter)2 DefaultTokenWriter (spoon.reflect.visitor.DefaultTokenWriter)2 ElementPrinterHelper (spoon.reflect.visitor.ElementPrinterHelper)2 TokenWriter (spoon.reflect.visitor.TokenWriter)2 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Writer (java.io.Writer)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 IdentityHashMap (java.util.IdentityHashMap)1 CtComment (spoon.reflect.code.CtComment)1 CtNewArray (spoon.reflect.code.CtNewArray)1 CtElement (spoon.reflect.declaration.CtElement)1 ParentNotInitializedException (spoon.reflect.declaration.ParentNotInitializedException)1 Factory (spoon.reflect.factory.Factory)1 CtPathException (spoon.reflect.path.CtPathException)1