Search in sources :

Example 6 with Node

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

the class LintIdeJavaParser method parseJava.

@Nullable
@Override
public Node parseJava(@NonNull final JavaContext context) {
    assert myLock == null;
    myLock = ApplicationManager.getApplication().acquireReadActionLock();
    try {
        Node node = parse(context);
        if (node != null) {
            return node;
        }
    } catch (Throwable ignore) {
    }
    myLock.finish();
    myLock = null;
    return null;
}
Also used : Node(lombok.ast.Node) Nullable(com.android.annotations.Nullable)

Example 7 with Node

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

the class LombokPsiConverterTest method parse.

@Nullable
private static Node parse(String code) {
    CompilerOptions options = new CompilerOptions();
    options.complianceLevel = options.sourceLevel = options.targetJDK = ClassFileConstants.JDK1_7;
    options.parseLiteralExpressionsAsConstants = true;
    ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitOnFirstError(), options, new DefaultProblemFactory());
    Parser parser = new Parser(problemReporter, options.parseLiteralExpressionsAsConstants);
    parser.javadocParser.checkDocComment = false;
    EcjTreeConverter converter = new EcjTreeConverter();
    org.eclipse.jdt.internal.compiler.batch.CompilationUnit sourceUnit = new org.eclipse.jdt.internal.compiler.batch.CompilationUnit(code.toCharArray(), "unitTest", "UTF-8");
    CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0);
    CompilationUnitDeclaration unit = parser.parse(sourceUnit, compilationResult);
    if (unit == null) {
        return null;
    }
    converter.visit(code, unit);
    List<? extends Node> nodes = converter.getAll();
    for (lombok.ast.Node node : nodes) {
        if (node instanceof lombok.ast.CompilationUnit) {
            return node;
        }
    }
    return null;
}
Also used : CompilationUnit(lombok.ast.CompilationUnit) ProblemReporter(org.eclipse.jdt.internal.compiler.problem.ProblemReporter) Node(lombok.ast.Node) Parser(org.eclipse.jdt.internal.compiler.parser.Parser) EcjTreeConverter(lombok.ast.ecj.EcjTreeConverter) CompilationUnitDeclaration(org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) CompilationResult(org.eclipse.jdt.internal.compiler.CompilationResult) Nullable(com.android.annotations.Nullable)

Example 8 with Node

use of lombok.ast.Node in project kotlin by JetBrains.

the class TypeEvaluator method evaluate.

/**
     * Returns the inferred type of the given node
     * @deprecated Use {@link #evaluate(PsiElement)} instead
     */
@Deprecated
@Nullable
public TypeDescriptor evaluate(@NonNull Node node) {
    ResolvedNode resolved = null;
    if (mContext != null) {
        resolved = mContext.resolve(node);
    }
    if (resolved instanceof ResolvedMethod) {
        TypeDescriptor type;
        ResolvedMethod method = (ResolvedMethod) resolved;
        if (method.isConstructor()) {
            ResolvedClass containingClass = method.getContainingClass();
            type = containingClass.getType();
        } else {
            type = method.getReturnType();
        }
        return type;
    }
    if (resolved instanceof ResolvedField) {
        ResolvedField field = (ResolvedField) resolved;
        Node astNode = field.findAstNode();
        if (astNode instanceof VariableDeclaration) {
            VariableDeclaration declaration = (VariableDeclaration) astNode;
            VariableDefinition definition = declaration.astDefinition();
            if (definition != null) {
                VariableDefinitionEntry first = definition.astVariables().first();
                if (first != null) {
                    Expression initializer = first.astInitializer();
                    if (initializer != null) {
                        TypeDescriptor type = evaluate(initializer);
                        if (type != null) {
                            return type;
                        }
                    }
                }
            }
        }
        return field.getType();
    }
    if (node instanceof VariableReference) {
        Statement statement = getParentOfType(node, Statement.class, false);
        if (statement != null) {
            ListIterator<Node> iterator = statement.getParent().getChildren().listIterator();
            while (iterator.hasNext()) {
                if (iterator.next() == statement) {
                    if (iterator.hasPrevious()) {
                        // should always be true
                        iterator.previous();
                    }
                    break;
                }
            }
            String targetName = ((VariableReference) node).astIdentifier().astValue();
            while (iterator.hasPrevious()) {
                Node previous = iterator.previous();
                if (previous instanceof VariableDeclaration) {
                    VariableDeclaration declaration = (VariableDeclaration) previous;
                    VariableDefinition definition = declaration.astDefinition();
                    for (VariableDefinitionEntry entry : definition.astVariables()) {
                        if (entry.astInitializer() != null && entry.astName().astValue().equals(targetName)) {
                            return evaluate(entry.astInitializer());
                        }
                    }
                } else if (previous instanceof ExpressionStatement) {
                    ExpressionStatement expressionStatement = (ExpressionStatement) previous;
                    Expression expression = expressionStatement.astExpression();
                    if (expression instanceof BinaryExpression && ((BinaryExpression) expression).astOperator() == BinaryOperator.ASSIGN) {
                        BinaryExpression binaryExpression = (BinaryExpression) expression;
                        if (targetName.equals(binaryExpression.astLeft().toString())) {
                            return evaluate(binaryExpression.astRight());
                        }
                    }
                }
            }
        }
    } else if (node instanceof Cast) {
        Cast cast = (Cast) node;
        if (mContext != null) {
            ResolvedNode typeReference = mContext.resolve(cast.astTypeReference());
            if (typeReference instanceof ResolvedClass) {
                return ((ResolvedClass) typeReference).getType();
            }
        }
        TypeDescriptor viewType = evaluate(cast.astOperand());
        if (viewType != null) {
            return viewType;
        }
    } else if (node instanceof Literal) {
        if (node instanceof NullLiteral) {
            return null;
        } else if (node instanceof BooleanLiteral) {
            return new DefaultTypeDescriptor(TYPE_BOOLEAN);
        } else if (node instanceof StringLiteral) {
            return new DefaultTypeDescriptor(TYPE_STRING);
        } else if (node instanceof CharLiteral) {
            return new DefaultTypeDescriptor(TYPE_CHAR);
        } else if (node instanceof IntegralLiteral) {
            IntegralLiteral literal = (IntegralLiteral) node;
            // Don't combine to ?: since that will promote astIntValue to a long
            if (literal.astMarkedAsLong()) {
                return new DefaultTypeDescriptor(TYPE_LONG);
            } else {
                return new DefaultTypeDescriptor(TYPE_INT);
            }
        } else if (node instanceof FloatingPointLiteral) {
            FloatingPointLiteral literal = (FloatingPointLiteral) node;
            // Don't combine to ?: since that will promote astFloatValue to a double
            if (literal.astMarkedAsFloat()) {
                return new DefaultTypeDescriptor(TYPE_FLOAT);
            } else {
                return new DefaultTypeDescriptor(TYPE_DOUBLE);
            }
        }
    } else if (node instanceof UnaryExpression) {
        return evaluate(((UnaryExpression) node).astOperand());
    } else if (node instanceof InlineIfExpression) {
        InlineIfExpression expression = (InlineIfExpression) node;
        if (expression.astIfTrue() != null) {
            return evaluate(expression.astIfTrue());
        } else if (expression.astIfFalse() != null) {
            return evaluate(expression.astIfFalse());
        }
    } else if (node instanceof BinaryExpression) {
        BinaryExpression expression = (BinaryExpression) node;
        BinaryOperator operator = expression.astOperator();
        switch(operator) {
            case LOGICAL_OR:
            case LOGICAL_AND:
            case EQUALS:
            case NOT_EQUALS:
            case GREATER:
            case GREATER_OR_EQUAL:
            case LESS:
            case LESS_OR_EQUAL:
                return new DefaultTypeDescriptor(TYPE_BOOLEAN);
        }
        TypeDescriptor type = evaluate(expression.astLeft());
        if (type != null) {
            return type;
        }
        return evaluate(expression.astRight());
    }
    if (resolved instanceof ResolvedVariable) {
        ResolvedVariable variable = (ResolvedVariable) resolved;
        return variable.getType();
    }
    return null;
}
Also used : Cast(lombok.ast.Cast) VariableDefinition(lombok.ast.VariableDefinition) BooleanLiteral(lombok.ast.BooleanLiteral) Node(lombok.ast.Node) ResolvedNode(com.android.tools.klint.client.api.JavaParser.ResolvedNode) UnaryExpression(lombok.ast.UnaryExpression) DefaultTypeDescriptor(com.android.tools.klint.client.api.JavaParser.DefaultTypeDescriptor) IntegralLiteral(lombok.ast.IntegralLiteral) ResolvedNode(com.android.tools.klint.client.api.JavaParser.ResolvedNode) ResolvedField(com.android.tools.klint.client.api.JavaParser.ResolvedField) BinaryExpression(lombok.ast.BinaryExpression) IntegralLiteral(lombok.ast.IntegralLiteral) BooleanLiteral(lombok.ast.BooleanLiteral) Literal(lombok.ast.Literal) FloatingPointLiteral(lombok.ast.FloatingPointLiteral) CharLiteral(lombok.ast.CharLiteral) StringLiteral(lombok.ast.StringLiteral) NullLiteral(lombok.ast.NullLiteral) VariableDeclaration(lombok.ast.VariableDeclaration) InlineIfExpression(lombok.ast.InlineIfExpression) BinaryOperator(lombok.ast.BinaryOperator) ResolvedVariable(com.android.tools.klint.client.api.JavaParser.ResolvedVariable) VariableReference(lombok.ast.VariableReference) CharLiteral(lombok.ast.CharLiteral) Statement(lombok.ast.Statement) PsiStatement(com.intellij.psi.PsiStatement) PsiExpressionStatement(com.intellij.psi.PsiExpressionStatement) ExpressionStatement(lombok.ast.ExpressionStatement) PsiDeclarationStatement(com.intellij.psi.PsiDeclarationStatement) ResolvedClass(com.android.tools.klint.client.api.JavaParser.ResolvedClass) ResolvedMethod(com.android.tools.klint.client.api.JavaParser.ResolvedMethod) TypeDescriptor(com.android.tools.klint.client.api.JavaParser.TypeDescriptor) DefaultTypeDescriptor(com.android.tools.klint.client.api.JavaParser.DefaultTypeDescriptor) StringLiteral(lombok.ast.StringLiteral) VariableDefinitionEntry(lombok.ast.VariableDefinitionEntry) UExpression(org.jetbrains.uast.UExpression) UCallExpression(org.jetbrains.uast.UCallExpression) PsiAssignmentExpression(com.intellij.psi.PsiAssignmentExpression) UReferenceExpression(org.jetbrains.uast.UReferenceExpression) UnaryExpression(lombok.ast.UnaryExpression) InlineIfExpression(lombok.ast.InlineIfExpression) PsiExpression(com.intellij.psi.PsiExpression) PsiReferenceExpression(com.intellij.psi.PsiReferenceExpression) Expression(lombok.ast.Expression) BinaryExpression(lombok.ast.BinaryExpression) FloatingPointLiteral(lombok.ast.FloatingPointLiteral) PsiExpressionStatement(com.intellij.psi.PsiExpressionStatement) ExpressionStatement(lombok.ast.ExpressionStatement) NullLiteral(lombok.ast.NullLiteral) Nullable(com.android.annotations.Nullable)

Example 9 with Node

use of lombok.ast.Node in project kotlin by JetBrains.

the class JavaVisitor method visitFile.

void visitFile(@NonNull JavaContext context) {
    Node compilationUnit = null;
    try {
        compilationUnit = mParser.parseJava(context);
        if (compilationUnit == null) {
            // with details, location, etc.
            return;
        }
        context.setCompilationUnit(compilationUnit);
        for (VisitingDetector v : mAllDetectors) {
            v.setContext(context);
            v.getDetector().beforeCheckFile(context);
        }
        if (!mSuperClassDetectors.isEmpty()) {
            SuperclassVisitor visitor = new SuperclassVisitor(context);
            compilationUnit.accept(visitor);
        }
        for (VisitingDetector v : mFullTreeDetectors) {
            AstVisitor visitor = v.getVisitor();
            compilationUnit.accept(visitor);
        }
        if (!mMethodDetectors.isEmpty() || !mResourceFieldDetectors.isEmpty() || !mConstructorDetectors.isEmpty()) {
            AstVisitor visitor = new DelegatingJavaVisitor(context);
            compilationUnit.accept(visitor);
        } else if (!mNodeTypeDetectors.isEmpty()) {
            AstVisitor visitor = new DispatchVisitor();
            compilationUnit.accept(visitor);
        }
        for (VisitingDetector v : mAllDetectors) {
            v.getDetector().afterCheckFile(context);
        }
    } catch (RuntimeException e) {
        if (sExceptionCount++ > MAX_REPORTED_CRASHES) {
            // are tripping up ECJ, they get the picture.
            return;
        }
        if (e.getClass().getSimpleName().equals("IndexNotReadyException")) {
            // See http://b.android.com/176644 for an example.
            return;
        } else if (e.getClass().getSimpleName().equals("ProcessCanceledException")) {
            // Cancelling inspections in the IDE
            context.getDriver().cancel();
            return;
        }
        // Work around ECJ bugs; see https://code.google.com/p/android/issues/detail?id=172268
        // Don't allow lint bugs to take down the whole build. TRY to log this as a
        // lint error instead!
        StringBuilder sb = new StringBuilder(100);
        sb.append("Unexpected failure during lint analysis of ");
        sb.append(context.file.getName());
        sb.append(" (this is a bug in lint or one of the libraries it depends on)\n");
        sb.append(e.getClass().getSimpleName());
        sb.append(':');
        StackTraceElement[] stackTrace = e.getStackTrace();
        int count = 0;
        for (StackTraceElement frame : stackTrace) {
            if (count > 0) {
                sb.append("<-");
            }
            String className = frame.getClassName();
            sb.append(className.substring(className.lastIndexOf('.') + 1));
            sb.append('.').append(frame.getMethodName());
            sb.append('(');
            sb.append(frame.getFileName()).append(':').append(frame.getLineNumber());
            sb.append(')');
            count++;
            // Only print the top 3-4 frames such that we can identify the bug
            if (count == 4) {
                break;
            }
        }
        // NOT e: this makes for very noisy logs
        Throwable throwable = null;
        //noinspection ConstantConditions
        context.log(throwable, sb.toString());
    } finally {
        if (compilationUnit != null) {
            mParser.dispose(context, compilationUnit);
        }
    }
}
Also used : Node(lombok.ast.Node) ResolvedNode(com.android.tools.klint.client.api.JavaParser.ResolvedNode) AstVisitor(lombok.ast.AstVisitor) ForwardingAstVisitor(lombok.ast.ForwardingAstVisitor)

Example 10 with Node

use of lombok.ast.Node 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

Node (lombok.ast.Node)10 Nullable (com.android.annotations.Nullable)5 ResolvedNode (com.android.tools.klint.client.api.JavaParser.ResolvedNode)3 ExpressionStatement (lombok.ast.ExpressionStatement)3 InlineIfExpression (lombok.ast.InlineIfExpression)3 ResolvedField (com.android.tools.klint.client.api.JavaParser.ResolvedField)2 PsiAssignmentExpression (com.intellij.psi.PsiAssignmentExpression)2 PsiDeclarationStatement (com.intellij.psi.PsiDeclarationStatement)2 PsiExpression (com.intellij.psi.PsiExpression)2 PsiExpressionStatement (com.intellij.psi.PsiExpressionStatement)2 PsiReferenceExpression (com.intellij.psi.PsiReferenceExpression)2 PsiStatement (com.intellij.psi.PsiStatement)2 BinaryExpression (lombok.ast.BinaryExpression)2 BinaryOperator (lombok.ast.BinaryOperator)2 BooleanLiteral (lombok.ast.BooleanLiteral)2 Cast (lombok.ast.Cast)2 CharLiteral (lombok.ast.CharLiteral)2 CompilationUnit (lombok.ast.CompilationUnit)2 Expression (lombok.ast.Expression)2 FloatingPointLiteral (lombok.ast.FloatingPointLiteral)2