Search in sources :

Example 11 with CtNamedElement

use of spoon.reflect.declaration.CtNamedElement in project spoon by INRIA.

the class GenericsTest method testModelBuildingSimilarSignatureMethods.

@Test
public void testModelBuildingSimilarSignatureMethods() throws Exception {
    CtClass<?> type = build("spoon.test.generics", "SimilarSignatureMethodes");
    List<CtNamedElement> methods = type.getElements(new NamedElementFilter<>(CtNamedElement.class, "methode"));
    assertEquals(2, methods.size());
    CtTypeParameter typeParameter = ((CtMethod<?>) methods.get(0)).getFormalCtTypeParameters().get(0);
    assertEquals("E", typeParameter.getSimpleName());
    CtParameter<?> param = ((CtMethod<?>) methods.get(0)).getParameters().get(0);
    assertEquals("E", param.getType().toString());
}
Also used : CtTypeParameter(spoon.reflect.declaration.CtTypeParameter) CtNamedElement(spoon.reflect.declaration.CtNamedElement) MainTest(spoon.test.main.MainTest) Test(org.junit.Test)

Example 12 with CtNamedElement

use of spoon.reflect.declaration.CtNamedElement in project spoon by INRIA.

the class APITest method testOverrideOutputWriter.

@Test
public void testOverrideOutputWriter() throws Exception {
    // this test that we can correctly set the Java output processor
    final List<Object> l = new ArrayList<Object>();
    Launcher spoon = new Launcher() {

        @Override
        public JavaOutputProcessor createOutputWriter() {
            return new JavaOutputProcessor() {

                @Override
                public void process(CtNamedElement e) {
                    l.add(e);
                }

                @Override
                public void init() {
                // we do nothing
                }
            };
        }
    };
    spoon.run(new String[] { "-i", "src/test/resources/spoon/test/api/", // we shouldn't write anything anyway
    "-o", // we shouldn't write anything anyway
    "fancy/fake/apitest" });
    Assert.assertEquals(3, l.size());
}
Also used : ArrayList(java.util.ArrayList) Launcher(spoon.Launcher) CtNamedElement(spoon.reflect.declaration.CtNamedElement) JavaOutputProcessor(spoon.support.JavaOutputProcessor) Test(org.junit.Test)

Example 13 with CtNamedElement

use of spoon.reflect.declaration.CtNamedElement in project spoon by INRIA.

the class CommentTest method testDocumentationContract.

@Test
public void testDocumentationContract() throws Exception {
    // contract: all metamodel classes must be commented with an example.
    final Launcher launcher = new Launcher();
    launcher.getEnvironment().setNoClasspath(true);
    launcher.getEnvironment().setCommentEnabled(true);
    // interfaces.
    launcher.addInputResource("./src/main/java/spoon/reflect/");
    launcher.addInputResource("./src/main/java/spoon/support/reflect/");
    launcher.buildModel();
    StringBuffer codeElementsDocumentationPage = new StringBuffer();
    codeElementsDocumentationPage.append(IOUtils.toString(new FileReader("doc/code_elements_header.md")));
    codeElementsDocumentationPage.append("\n\n");
    launcher.getModel().getElements(new TypeFilter<>(CtInterface.class)).stream().forEach(x -> {
        assertTrue(x.getSimpleName() + " has no documentation", x.getDocComment() != null);
        assertTrue(x.getSimpleName() + " has no documentation", x.getDocComment().length() > 0);
        // we only consider instantiable interfaces
        if (launcher.getModel().getElements(new AbstractFilter<CtElement>() {

            @Override
            public boolean matches(CtElement element) {
                return (element instanceof CtNamedElement) && ((CtNamedElement) element).getSimpleName().equals(x.getSimpleName() + "Impl") && (element instanceof CtClass) && !((CtClass) element).hasModifier(ModifierKind.ABSTRACT);
            }
        }).size() == 0) {
            return;
        }
        // we don't consider references
        if (x.getSimpleName().endsWith("Reference")) {
            return;
        }
        if (x.isSubtypeOf(launcher.getFactory().Type().get(CtStatement.class).getReference()) || x.isSubtypeOf(launcher.getFactory().Type().get(CtExpression.class).getReference())) {
            // no meaningful snippet
            if (x.getSimpleName().equals("CtCodeSnippetStatement")) {
                return;
            }
            // no meaningful snippet
            if (x.getSimpleName().equals("CtCodeSnippetExpression")) {
                return;
            }
            // no comment in snippet mode
            if (x.getSimpleName().equals("CtComment")) {
                return;
            }
            // a statement in really rare cases
            if (x.getSimpleName().equals("CtEnum")) {
                return;
            }
            // too hard to snippetize
            if (x.getSimpleName().equals("CtAnnotationFieldAccess")) {
                return;
            }
            codeElementsDocumentationPage.append("### " + x.getSimpleName() + "\n");
            codeElementsDocumentationPage.append("[(javadoc)](http://spoon.gforge.inria.fr/mvnsites/spoon-core/apidocs/" + x.getQualifiedName().replace('.', '/') + ".html)\n\n");
            codeElementsDocumentationPage.append("```java" + "\n");
            Pattern p = Pattern.compile("<pre>(.*?)</pre>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE | Pattern.UNIX_LINES);
            Matcher m = p.matcher(x.getDocComment());
            m.find();
            do {
                String snippet = null;
                try {
                    snippet = m.group(1);
                } catch (IllegalStateException e) {
                    fail(x + " does not have code snippet");
                }
                snippet = StringEscapeUtils.unescapeHtml4(snippet);
                // it must compile
                CtElement el = launcher.getFactory().Code().createCodeSnippetStatement(snippet).compile();
                // the snippet contains this element
                assertTrue(snippet + " does not contain a " + x.getSimpleName(), el.getElements(new TypeFilter<>(x.getActualClass())).size() > 0);
                codeElementsDocumentationPage.append(snippet + "\n");
            } while (m.find());
            codeElementsDocumentationPage.append("```" + "\n");
        }
    });
    try {
        assertEquals("doc outdated, please commit doc/code_elements.md", codeElementsDocumentationPage.toString(), IOUtils.toString(new FileReader("doc/code_elements.md")));
    } finally {
        write(codeElementsDocumentationPage.toString(), new FileOutputStream("doc/code_elements.md"));
    }
}
Also used : CtInterface(spoon.reflect.declaration.CtInterface) Pattern(java.util.regex.Pattern) CtExpression(spoon.reflect.code.CtExpression) Matcher(java.util.regex.Matcher) CtElement(spoon.reflect.declaration.CtElement) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtClass(spoon.reflect.declaration.CtClass) CtStatement(spoon.reflect.code.CtStatement) FileOutputStream(java.io.FileOutputStream) Launcher(spoon.Launcher) FileReader(java.io.FileReader) CtNamedElement(spoon.reflect.declaration.CtNamedElement) Test(org.junit.Test)

Example 14 with CtNamedElement

use of spoon.reflect.declaration.CtNamedElement in project spoon by INRIA.

the class SpoonTreeBuilder method createNode.

private void createNode(Object o, CtRole roleInParent) {
    String prefix = roleInParent == null ? "" : roleInParent.getCamelCaseName() + ": ";
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(o) {

        private static final long serialVersionUID = 1L;

        private String getASTNodeName() {
            // the end user needs to know the interface, not the implementation
            return getUserObject().getClass().getSimpleName().replaceAll("Impl$", "");
        }

        @Override
        public String toString() {
            String nodeName;
            if (getUserObject() instanceof CtNamedElement) {
                nodeName = getASTNodeName() + " - " + ((CtNamedElement) getUserObject()).getSimpleName();
            } else {
                String objectRepresentation;
                try {
                    objectRepresentation = getUserObject().toString();
                } catch (Exception e) {
                    objectRepresentation = "Failed:" + e.getMessage();
                }
                nodeName = getASTNodeName() + " - " + objectRepresentation;
            }
            return prefix + nodeName;
        }
    };
    nodes.peek().add(node);
    nodes.push(node);
}
Also used : DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) CtNamedElement(spoon.reflect.declaration.CtNamedElement)

Example 15 with CtNamedElement

use of spoon.reflect.declaration.CtNamedElement in project spoon by INRIA.

the class TemplateMatcher method helperMatch.

/**
 * Detects whether `template` AST node and `target` AST node are matching.
 * This method is called for each node of to be matched template
 * and for appropriate node of `target`
 *
 * @param target actually checked AST node from target model
 * @param template actually checked AST node from template
 *
 * @return true if template matches this node, false if it does not matches
 *
 * note: Made private to hide the Objects.
 */
private boolean helperMatch(Object target, Object template) {
    if ((target == null) && (template == null)) {
        return true;
    }
    if ((target == null) || (template == null)) {
        return false;
    }
    if (containsSame(variables, template) || containsSame(typeVariables, template)) {
        /*
			 * we are just matching a template parameter.
			 * Check that defined ParameterMatcher matches the target too
			 */
        boolean add = invokeCallBack(target, template);
        if (add) {
            // ParameterMatcher matches the target too, add that match
            return addMatch(template, target);
        }
        return false;
    }
    if (target.getClass() != template.getClass()) {
        return false;
    }
    if ((template instanceof CtTypeReference) && template.equals(templateType.getReference())) {
        return true;
    }
    if ((template instanceof CtPackageReference) && template.equals(templateType.getPackage())) {
        return true;
    }
    if (template instanceof CtReference) {
        CtReference tRef = (CtReference) template;
        /*
			 * Check whether name of a template reference matches with name of target reference
			 * after replacing of variables in template name
			 */
        boolean ok = matchNames(tRef.getSimpleName(), ((CtReference) target).getSimpleName());
        if (ok && !template.equals(target)) {
            boolean remove = !invokeCallBack(target, template);
            if (remove) {
                matches.remove(tRef.getSimpleName());
                return false;
            }
            return true;
        }
    }
    if (template instanceof CtNamedElement) {
        CtNamedElement named = (CtNamedElement) template;
        boolean ok = matchNames(named.getSimpleName(), ((CtNamedElement) target).getSimpleName());
        if (ok && !template.equals(target)) {
            boolean remove = !invokeCallBack(target, template);
            if (remove) {
                matches.remove(named.getSimpleName());
                return false;
            }
        }
    }
    if (template instanceof Collection) {
        return matchCollections((Collection<?>) target, (Collection<?>) template);
    }
    if (template instanceof Map) {
        if (template.equals(target)) {
            return true;
        }
        Map<?, ?> temMap = (Map<?, ?>) template;
        Map<?, ?> tarMap = (Map<?, ?>) target;
        if (!temMap.keySet().equals(tarMap.keySet())) {
            return false;
        }
        return matchCollections(tarMap.values(), temMap.values());
    }
    if (template instanceof CtBlock<?>) {
        final List<CtStatement> statements = ((CtBlock) template).getStatements();
        if (statements.size() == 1 && statements.get(0) instanceof CtInvocation) {
            final CtInvocation ctStatement = (CtInvocation) statements.get(0);
            if ("S".equals(ctStatement.getExecutable().getSimpleName()) && CtBlock.class.equals(ctStatement.getType().getActualClass())) {
                return true;
            }
        }
    }
    if (target instanceof CtElement) {
        for (Field f : RtHelper.getAllFields(target.getClass())) {
            f.setAccessible(true);
            if (Modifier.isStatic(f.getModifiers())) {
                continue;
            }
            if (f.getName().equals("parent")) {
                continue;
            }
            if (f.getName().equals("position")) {
                continue;
            }
            if (f.getName().equals("docComment")) {
                continue;
            }
            if (f.getName().equals("factory")) {
                continue;
            }
            if (f.getName().equals("comments")) {
                continue;
            }
            if (f.getName().equals("metadata")) {
                continue;
            }
            try {
                if (!helperMatch(f.get(target), f.get(template))) {
                    return false;
                }
            } catch (IllegalAccessException ignore) {
            }
        }
        return true;
    } else if (target instanceof String) {
        return matchNames((String) template, (String) target);
    } else {
        return target.equals(template);
    }
}
Also used : CtElement(spoon.reflect.declaration.CtElement) CtField(spoon.reflect.declaration.CtField) Field(java.lang.reflect.Field) CtInvocation(spoon.reflect.code.CtInvocation) CtPackageReference(spoon.reflect.reference.CtPackageReference) CtBlock(spoon.reflect.code.CtBlock) CtReference(spoon.reflect.reference.CtReference) CtStatement(spoon.reflect.code.CtStatement) CtTypeReference(spoon.reflect.reference.CtTypeReference) Collection(java.util.Collection) CtNamedElement(spoon.reflect.declaration.CtNamedElement) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

CtNamedElement (spoon.reflect.declaration.CtNamedElement)16 Test (org.junit.Test)5 File (java.io.File)4 Map (java.util.Map)4 CtType (spoon.reflect.declaration.CtType)4 FileReader (java.io.FileReader)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 CtElement (spoon.reflect.declaration.CtElement)3 CtReference (spoon.reflect.reference.CtReference)3 Gson (com.google.gson.Gson)2 GsonBuilder (com.google.gson.GsonBuilder)2 AutomaticBuilderFactory (fr.inria.diversify.automaticbuilder.AutomaticBuilderFactory)2 TestCaseJSON (fr.inria.diversify.dspot.selector.json.coverage.TestCaseJSON)2 TestClassJSON (fr.inria.diversify.dspot.selector.json.coverage.TestClassJSON)2 AmplificationHelper (fr.inria.diversify.utils.AmplificationHelper)2 Counter (fr.inria.diversify.utils.Counter)2 DSpotUtils (fr.inria.diversify.utils.DSpotUtils)2 DSpotCompiler (fr.inria.diversify.utils.compilation.DSpotCompiler)2 InputConfiguration (fr.inria.diversify.utils.sosiefier.InputConfiguration)2