Search in sources :

Example 1 with CompilationUnit

use of lombok.ast.CompilationUnit in project android by JetBrains.

the class LintIdeJavaParserTest method testResolve.

public void testResolve() {
    String source1Path = "src/p1/p2/Target.java";
    String source1 = "package p1.p2;\n" + "\n" + "public class Target {\n" + "    public void foo(int f) {\n" + "    }\n" + "    public int myField = 5;\n" + "    public static class Target2 extends java.io.File {\n" + "        public Target2() {\n" + "            super(null, null);\n" + "        }\n" + "    }\n" + "}";
    myFixture.addFileToProject(source1Path, source1);
    String source2Path = "src/p1/p2/Caller.java";
    String source2 = "package p1.p2;\n" + "\n" + "public final class Caller extends Target.Target2 {\n" + "    public String call(Target target) {\n" + "        target.foo(42);\n" + "        target.myField = 6;\n" + "    }\n" + "}";
    PsiFile file2 = myFixture.addFileToProject(source2Path, source2);
    PsiCall call = PsiTreeUtil.findChildrenOfType(file2, PsiCall.class).iterator().next();
    ResolvedNode resolved = LintIdeJavaParser.resolve(call);
    assertNotNull(resolved);
    assertTrue(resolved instanceof ResolvedMethod);
    ResolvedMethod method = (ResolvedMethod) resolved;
    assertEquals("foo", method.getName());
    assertEquals("p1.p2.Target", method.getContainingClass().getName());
    assertTrue(method.isInPackage("p1.p2", true));
    assertTrue(method.isInPackage("p1.p2", false));
    assertTrue(method.isInPackage("p1", true));
    assertFalse(method.isInPackage("p1", false));
    // Resolve "target" as a reference expression in the call() method
    PsiElement element = ((PsiMethodCallExpression) call).getMethodExpression().getQualifier();
    assertNotNull(element);
    resolved = LintIdeJavaParser.resolve(element);
    assertTrue(resolved instanceof ResolvedVariable);
    ResolvedVariable resolvedVariable = (ResolvedVariable) resolved;
    assertEquals("target", resolvedVariable.getName());
    assertEquals("p1.p2.Target", resolvedVariable.getType().getName());
    PsiMethod callMethod = PsiTreeUtil.findChildrenOfType(file2, PsiMethod.class).iterator().next();
    assertNotNull(callMethod);
    PsiVariable variable = callMethod.getParameterList().getParameters()[0];
    resolved = LintIdeJavaParser.resolve(variable);
    assertTrue(resolved instanceof ResolvedVariable);
    resolvedVariable = (ResolvedVariable) resolved;
    assertEquals("target", resolvedVariable.getName());
    assertEquals("p1.p2.Target", resolvedVariable.getType().getName());
    @SuppressWarnings("ConstantConditions") PsiStatement fieldReferenceStatement = callMethod.getBody().getStatements()[1];
    PsiExpression lExpression = ((PsiAssignmentExpression) ((PsiExpressionStatement) fieldReferenceStatement).getExpression()).getLExpression();
    resolved = LintIdeJavaParser.resolve(lExpression);
    assertTrue(resolved instanceof ResolvedField);
    ResolvedField field = (ResolvedField) resolved;
    assertEquals("myField", field.getName());
    assertEquals("int", field.getType().getName());
    assertEquals("p1.p2.Target", field.getContainingClass().getName());
    assertTrue(field.isInPackage("p1.p2", true));
    assertTrue(field.isInPackage("p1.p2", false));
    assertTrue(field.isInPackage("p1", true));
    assertFalse(field.isInPackage("p1", false));
    PsiClass cls = PsiTreeUtil.findChildrenOfType(file2, PsiClass.class).iterator().next();
    @SuppressWarnings("ConstantConditions") PsiJavaCodeReferenceElement superReference = cls.getExtendsList().getReferenceElements()[0];
    resolved = LintIdeJavaParser.resolve(superReference);
    assertTrue(resolved instanceof ResolvedClass);
    ResolvedClass rc = (ResolvedClass) resolved;
    assertTrue(rc.getName().equals("p1.p2.Target.Target2"));
    assertTrue(rc.isInPackage("p1.p2", true));
    assertTrue(rc.isInPackage("p1.p2", false));
    assertTrue(rc.isInPackage("p1", true));
    assertFalse(rc.isInPackage("p1", false));
    CompilationUnit unit = LombokPsiConverter.convert((PsiJavaFile) file2);
    //noinspection ConstantConditions
    TypeDeclaration first = unit.astTypeDeclarations().first();
    resolved = LintIdeJavaParser.resolve((PsiElement) first.getNativeNode());
    assertTrue(resolved instanceof ResolvedClass);
    rc = (ResolvedClass) resolved;
    assertEquals("p1.p2.Caller", rc.getName());
    //noinspection ConstantConditions
    assertEquals("p1.p2.Target.Target2", rc.getSuperClass().getName());
    assertNull(rc.getContainingClass());
}
Also used : CompilationUnit(lombok.ast.CompilationUnit) TypeDeclaration(lombok.ast.TypeDeclaration)

Example 2 with CompilationUnit

use of lombok.ast.CompilationUnit in project android by JetBrains.

the class LombokPsiConverterTest method testJava7.

public void testJava7() {
    @Language("JAVA") String testClass = "package test.pkg;\n" + "\n" + "import java.io.BufferedReader;\n" + "import java.io.FileReader;\n" + "import java.io.IOException;\n" + "import java.lang.reflect.InvocationTargetException;\n" + "import java.util.List;\n" + "import java.util.Map;\n" + "import java.util.TreeMap;\n" + "\n" + "public class Java7LanguageFeatureTest {\n" + "    public void testDiamondOperator() {\n" + "        Map<String, List<Integer>> map = new TreeMap<>();\n" + "    }\n" + "\n" + "    public int testStringSwitches(String value) {\n" + "        final String first = \"first\";\n" + "        final String second = \"second\";\n" + "\n" + "        switch (value) {\n" + "            case first:\n" + "                return 41;\n" + "            case second:\n" + "                return 42;\n" + "            default:\n" + "                return 0;\n" + "        }\n" + "    }\n" + "\n" + "    public String testTryWithResources(String path) throws IOException {\n" + "        try (BufferedReader br = new BufferedReader(new FileReader(path))) {\n" + "            return br.readLine();\n" + "        }\n" + "    }\n" + "\n" + "    public void testNumericLiterals() {\n" + "        int thousand = 1_000;\n" + "        int million = 1_000_000;\n" + "        int binary = 0B01010101;\n" + "    }\n" + "\n" + "    public void testMultiCatch() {\n" + "\n" + "        try {\n" + "            Class.forName(\"java.lang.Integer\").getMethod(\"toString\").invoke(null);\n" + "        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {\n" + "            e.printStackTrace();\n" + "        } catch (ClassNotFoundException e) {\n" + "            // TODO: Logging here\n" + "        }\n" + "    }\n" + "}\n";
    PsiFile psiFile = myFixture.addFileToProject("src/test/pkg/R9.java", testClass);
    // Can't call check(psiFile, testClass) here; the source code won't parse
    // with Lombok's parser since it doesn't support Java 7, so we just manually
    // check that the LombokPsiConverter doesn't abort, and format it's view of
    // the Lombok AST and check that it looks like what we expect; an AST containing
    // fragments usable by lint, but not providing support for syntactic constructs
    // such as try with resources or containing type variables where the diamond operator
    // should have been etc.
    assertTrue(psiFile.getClass().getName(), psiFile instanceof PsiJavaFile);
    PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile;
    CompilationUnit node = LombokPsiConverter.convert(psiJavaFile);
    assertNotNull(node);
    TextFormatter formatter = new TextFormatter();
    node.accept(new SourcePrinter(formatter));
    String actual = formatter.finish();
    assertEquals("package test.pkg;\n" + "\n" + "import java.io.BufferedReader;\n" + "import java.io.FileReader;\n" + "import java.io.IOException;\n" + "import java.lang.reflect.InvocationTargetException;\n" + "import java.util.List;\n" + "import java.util.Map;\n" + "import java.util.TreeMap;\n" + "\n" + "public class Java7LanguageFeatureTest {\n" + "    public void testDiamondOperator() {\n" + "        Map<String, List<Integer>> map = new TreeMap();\n" + "    }\n" + "    \n" + "    public int testStringSwitches(String value) {\n" + "        final String first = \"first\";\n" + "        final String second = \"second\";\n" + "        switch (value) {\n" + "        case first:\n" + "            return 41;\n" + "        case second:\n" + "            return 42;\n" + "        case :\n" + "            return 0;\n" + "        }\n" + "    }\n" + "    \n" + "    public String testTryWithResources(String path) throws IOException {\n" + "        try {\n" + "            return br.readLine();\n" + "        }\n" + "    }\n" + "    \n" + "    public void testNumericLiterals() {\n" + "        int thousand = 1_000;\n" + "        int million = 1_000_000;\n" + "        int binary = 0B01010101;\n" + "    }\n" + "    \n" + "    public void testMultiCatch() {\n" + "        try {\n" + "            Class.forName(\"java.lang.Integer\").getMethod(\"toString\").invoke(null);\n" + "        } catch (?!?INVALID_IDENTIFIER: IllegalAccessException | InvocationTargetException | NoSuchMethodException?!? e) {\n" + "            e.printStackTrace();\n" + "        } catch (ClassNotFoundException e) {\n" + "        }\n" + "    }\n" + "}", actual);
}
Also used : CompilationUnit(lombok.ast.CompilationUnit) SourcePrinter(lombok.ast.printer.SourcePrinter) TextFormatter(lombok.ast.printer.TextFormatter) Language(org.intellij.lang.annotations.Language) PsiFile(com.intellij.psi.PsiFile) PsiJavaFile(com.intellij.psi.PsiJavaFile)

Example 3 with CompilationUnit

use of lombok.ast.CompilationUnit in project android by JetBrains.

the class LombokPsiConverterTest method check.

private static void check(PsiFile psiFile, @Language("JAVA") String source) {
    assertTrue(psiFile.getClass().getName(), psiFile instanceof PsiJavaFile);
    PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile;
    CompilationUnit node = LombokPsiConverter.convert(psiJavaFile);
    assertNotNull(node);
    String actualStructure;
    if (CHECK_POSITIONS) {
        StructureFormatter structureFormatter = StructureFormatter.formatterWithPositions();
        node.accept(new SourcePrinter(structureFormatter));
        actualStructure = structureFormatter.finish();
    }
    TextFormatter formatter = new TextFormatter();
    node.accept(new SourcePrinter(formatter));
    String actual = formatter.finish();
    Node expectedNode = parse(source);
    assertNotNull(expectedNode);
    if (CHECK_POSITIONS) {
        StructureFormatter structureFormatter = StructureFormatter.formatterWithPositions();
        expectedNode.accept(new SourcePrinter(structureFormatter));
        String masterStructure = structureFormatter.finish();
        assertEquals(masterStructure, actualStructure);
    }
    formatter = new TextFormatter();
    expectedNode.accept(new SourcePrinter(formatter));
    String master = formatter.finish();
    assertEquals(master, actual);
    // Check for resilience to error nodes being present in the AST
    Project project = psiFile.getProject();
    final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
    final Document document = manager.getDocument(psiFile);
    assertNotNull(document);
    // fixed seed for test reproducibility
    final Random random = new Random(0L);
    for (int i = 0; i < 500; i++) {
        WriteCommandAction.runWriteCommandAction(project, new Runnable() {

            @Override
            public void run() {
                int pos = random.nextInt(document.getTextLength() - 1);
                char ch = (char) (random.nextInt(64) + 32);
                double operation = random.nextDouble();
                if (operation < 0.33) {
                    document.insertString(pos, Character.toString(ch));
                } else if (operation < 0.67) {
                    document.replaceString(pos, pos + 1, Character.toString(ch));
                } else {
                    document.deleteString(pos, pos + 1);
                }
                manager.commitDocument(document);
            }
        });
        node = LombokPsiConverter.convert(psiJavaFile);
        assertNotNull(psiJavaFile.getText(), node);
    }
}
Also used : CompilationUnit(lombok.ast.CompilationUnit) SourcePrinter(lombok.ast.printer.SourcePrinter) TextFormatter(lombok.ast.printer.TextFormatter) StructureFormatter(lombok.ast.printer.StructureFormatter) Node(lombok.ast.Node) PsiJavaFile(com.intellij.psi.PsiJavaFile) Document(com.intellij.openapi.editor.Document) Project(com.intellij.openapi.project.Project) Random(java.util.Random) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Aggregations

CompilationUnit (lombok.ast.CompilationUnit)3 PsiJavaFile (com.intellij.psi.PsiJavaFile)2 SourcePrinter (lombok.ast.printer.SourcePrinter)2 TextFormatter (lombok.ast.printer.TextFormatter)2 Document (com.intellij.openapi.editor.Document)1 Project (com.intellij.openapi.project.Project)1 PsiDocumentManager (com.intellij.psi.PsiDocumentManager)1 PsiFile (com.intellij.psi.PsiFile)1 Random (java.util.Random)1 Node (lombok.ast.Node)1 TypeDeclaration (lombok.ast.TypeDeclaration)1 StructureFormatter (lombok.ast.printer.StructureFormatter)1 Language (org.intellij.lang.annotations.Language)1