Search in sources :

Example 6 with ClassOrInterfaceDeclaration

use of com.github.javaparser.ast.body.ClassOrInterfaceDeclaration in project checker-framework by typetools.

the class AnnotationFileParser method putNewElement.

// Used only by getMembers().
/**
 * If {@code typeElt} contains an element for {@code member}, adds to {@code elementsToDecl} a
 * mapping from member's element to member. Does nothing if a mapping already exists.
 *
 * <p>Otherwise (if there is no element for {@code member}), adds to {@code fakeOverrideDecls}
 * zero or more mappings. Each mapping is from an element that {@code member} would override to
 * {@code member}.
 *
 * <p>This method does not read or write field {@link annotationFileAnnos}.
 *
 * @param elementsToDecl the mapping that is side-effected by this method
 * @param fakeOverrideDecls fake overrides, also side-effected by this method
 * @param typeElt the class in which {@code member} is declared
 * @param member the stub file declaration of a method
 * @param typeDeclName used only for debugging
 * @param astNode where to report errors
 */
private void putNewElement(Map<Element, BodyDeclaration<?>> elementsToDecl, Map<Element, List<BodyDeclaration<?>>> fakeOverrideDecls, TypeElement typeElt, BodyDeclaration<?> member, String typeDeclName, NodeWithRange<?> astNode) {
    if (member instanceof MethodDeclaration) {
        MethodDeclaration method = (MethodDeclaration) member;
        Element elt = findElement(typeElt, method, /*noWarn=*/
        true);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, method);
        } else {
            ExecutableElement overriddenMethod = fakeOverriddenMethod(typeElt, method);
            if (overriddenMethod == null) {
                // Didn't find the element and it isn't a fake override.  Issue a warning.
                findElement(typeElt, method, /*noWarn=*/
                false);
            } else {
                List<BodyDeclaration<?>> l = fakeOverrideDecls.computeIfAbsent(overriddenMethod, __ -> new ArrayList<>());
                l.add(member);
            }
        }
    } else if (member instanceof ConstructorDeclaration) {
        Element elt = findElement(typeElt, (ConstructorDeclaration) member);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, member);
        }
    } else if (member instanceof FieldDeclaration) {
        FieldDeclaration fieldDecl = (FieldDeclaration) member;
        for (VariableDeclarator var : fieldDecl.getVariables()) {
            Element varelt = findElement(typeElt, var);
            if (varelt != null) {
                putIfAbsent(elementsToDecl, varelt, fieldDecl);
            }
        }
    } else if (member instanceof EnumConstantDeclaration) {
        Element elt = findElement(typeElt, (EnumConstantDeclaration) member, astNode);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, member);
        }
    } else if (member instanceof ClassOrInterfaceDeclaration) {
        Element elt = findElement(typeElt, (ClassOrInterfaceDeclaration) member);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, member);
        }
    } else if (member instanceof EnumDeclaration) {
        Element elt = findElement(typeElt, (EnumDeclaration) member);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, member);
        }
    } else {
        stubDebug(String.format("Ignoring element of type %s in %s", member.getClass(), typeDeclName));
    }
}
Also used : EnumConstantDeclaration(com.github.javaparser.ast.body.EnumConstantDeclaration) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration)

Example 7 with ClassOrInterfaceDeclaration

use of com.github.javaparser.ast.body.ClassOrInterfaceDeclaration in project checker-framework by typetools.

the class AnnotationFileParser method processType.

/**
 * Process the type's declaration: copy its annotations to {@code #annotationFileAnnos}. Does not
 * process any of its members. Returns the type's type parameter declarations.
 *
 * @param decl a type declaration
 * @param elt the type's element
 * @return the type's type parameter declarations
 */
private List<AnnotatedTypeVariable> processType(TypeDeclaration<?> decl, TypeElement elt) {
    recordDeclAnnotation(elt, decl.getAnnotations(), decl);
    AnnotatedDeclaredType type = atypeFactory.fromElement(elt);
    annotate(type, decl.getAnnotations(), decl);
    final List<? extends AnnotatedTypeMirror> typeArguments = type.getTypeArguments();
    final List<TypeParameter> typeParameters;
    if (decl instanceof NodeWithTypeParameters) {
        typeParameters = ((NodeWithTypeParameters<?>) decl).getTypeParameters();
    } else {
        typeParameters = Collections.emptyList();
    }
    if (debugAnnotationFileParser) {
        int numParams = (typeParameters == null ? 0 : typeParameters.size());
        int numArgs = (typeArguments == null ? 0 : typeArguments.size());
        if (numParams != numArgs) {
            stubDebug(String.format("parseType:  mismatched sizes for typeParameters=%s (size %d) and typeArguments=%s" + " (size %d); decl=%s; elt=%s (%s); type=%s (%s); typeBeingParsed=%s", typeParameters, numParams, typeArguments, numArgs, decl.toString().replace(LINE_SEPARATOR, " "), elt.toString().replace(LINE_SEPARATOR, " "), elt.getClass(), type, type.getClass(), typeBeingParsed));
            stubDebug("Proceeding despite mismatched sizes");
        }
    }
    annotateTypeParameters(decl, elt, typeArguments, typeParameters);
    if (decl instanceof ClassOrInterfaceDeclaration) {
        annotateSupertypes((ClassOrInterfaceDeclaration) decl, type);
    }
    putMerge(annotationFileAnnos.atypes, elt, type);
    List<AnnotatedTypeVariable> typeVariables = new ArrayList<>(type.getTypeArguments().size());
    for (AnnotatedTypeMirror typeV : type.getTypeArguments()) {
        if (typeV.getKind() != TypeKind.TYPEVAR) {
            warn(decl, "expected an AnnotatedTypeVariable but found type kind " + typeV.getKind() + ": " + typeV);
        } else {
            typeVariables.add((AnnotatedTypeVariable) typeV);
        }
    }
    return typeVariables;
}
Also used : NodeWithTypeParameters(com.github.javaparser.ast.nodeTypes.NodeWithTypeParameters) TypeParameter(com.github.javaparser.ast.type.TypeParameter) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) AnnotatedDeclaredType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) ArrayList(java.util.ArrayList) AnnotatedTypeVariable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror)

Example 8 with ClassOrInterfaceDeclaration

use of com.github.javaparser.ast.body.ClassOrInterfaceDeclaration in project checker-framework by typetools.

the class WholeProgramInferenceJavaParserStorage method addExplicitReceiver.

/**
 * Adds an explicit receiver type to a JavaParser method declaration.
 *
 * @param methodDeclaration declaration to add a receiver to
 */
private static void addExplicitReceiver(MethodDeclaration methodDeclaration) {
    if (methodDeclaration.getReceiverParameter().isPresent()) {
        return;
    }
    com.github.javaparser.ast.Node parent = methodDeclaration.getParentNode().get();
    if (!(parent instanceof TypeDeclaration)) {
        return;
    }
    TypeDeclaration<?> parentDecl = (TypeDeclaration<?>) parent;
    ClassOrInterfaceType receiver = new ClassOrInterfaceType();
    receiver.setName(parentDecl.getName());
    if (parentDecl.isClassOrInterfaceDeclaration()) {
        ClassOrInterfaceDeclaration parentClassDecl = parentDecl.asClassOrInterfaceDeclaration();
        if (!parentClassDecl.getTypeParameters().isEmpty()) {
            NodeList<Type> typeArgs = new NodeList<>();
            for (TypeParameter typeParam : parentClassDecl.getTypeParameters()) {
                ClassOrInterfaceType typeArg = new ClassOrInterfaceType();
                typeArg.setName(typeParam.getNameAsString());
                typeArgs.add(typeArg);
            }
            receiver.setTypeArguments(typeArgs);
        }
    }
    methodDeclaration.setReceiverParameter(new ReceiverParameter(receiver, "this"));
}
Also used : ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) AnnotatedArrayType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType) Type(com.github.javaparser.ast.type.Type) TypeParameter(com.github.javaparser.ast.type.TypeParameter) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ReceiverParameter(com.github.javaparser.ast.body.ReceiverParameter) NodeList(com.github.javaparser.ast.NodeList) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration)

Example 9 with ClassOrInterfaceDeclaration

use of com.github.javaparser.ast.body.ClassOrInterfaceDeclaration in project AndroidLife by CaMnter.

the class FinalRClassBuilder method brewJava.

/**
 * JavaPoet 生成 R2
 *
 * @param rFile R.java File
 * @param outputDir R2.java 输出文件夹
 * @param packageName 包名
 * @param className R2 name
 * @throws Exception
 */
public static void brewJava(File rFile, File outputDir, String packageName, String className) throws Exception {
    /*
     * JavaParser 解析 R.java File
     * 获取到 TypeDeclaration
     */
    CompilationUnit compilationUnit = JavaParser.parse(rFile);
    TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);
    /*
     * 定义 R2.java class
     */
    TypeSpec.Builder result = TypeSpec.classBuilder(className).addModifiers(PUBLIC).addModifiers(FINAL);
    /*
     * 遍历 R.java File 的每一个节点( 内部类或者接口 --> ClassOrInterfaceDeclaration )
     * 添加到 R2.java 内
     * 这里是给 TypeSpec 添加生成 内部类 的 语句
     */
    for (Node node : resourceClass.getChildNodes()) {
        if (node instanceof ClassOrInterfaceDeclaration) {
            addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node);
        }
    }
    JavaFile finalR = JavaFile.builder(packageName, result.build()).addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!").build();
    finalR.writeTo(outputDir);
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Node(com.github.javaparser.ast.Node) JavaFile(com.squareup.javapoet.JavaFile) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 10 with ClassOrInterfaceDeclaration

use of com.github.javaparser.ast.body.ClassOrInterfaceDeclaration in project drools by kiegroup.

the class AccumulateInline method initInlineAccumulateTemplate.

private void initInlineAccumulateTemplate() {
    accumulateInlineClassName = StringUtil.toId(context.getRuleDescr().getName()) + "Accumulate" + accumulateDescr.getLine();
    CompilationUnit templateCU;
    try {
        templateCU = StaticJavaParser.parseResource("AccumulateInlineTemplate.java");
    } catch (IOException e) {
        throw new InvalidInlineTemplateException(e);
    }
    ClassOrInterfaceDeclaration parsedClass = templateCU.getClassByName("AccumulateInlineFunction").orElseThrow(InvalidInlineTemplateException::new);
    parsedClass.setName(accumulateInlineClassName);
    parsedClass.findAll(ClassOrInterfaceType.class, c -> "CONTEXT_DATA_GENERIC".equals(c.asString())).forEach(c -> c.setName(accumulateInlineClassName + ".ContextData"));
    this.accumulateInlineClass = parsedClass;
    contextData = this.accumulateInlineClass.findFirst(ClassOrInterfaceDeclaration.class, c -> "ContextData".equals(c.getNameAsString())).orElseThrow(InvalidInlineTemplateException::new);
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassExpr(com.github.javaparser.ast.expr.ClassExpr) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) DrlxParseUtil.createMvelCompiler(org.drools.modelcompiler.builder.generator.DrlxParseUtil.createMvelCompiler) PatternSourceDescr(org.drools.drl.ast.descr.PatternSourceDescr) DeclarationSpec(org.drools.modelcompiler.builder.generator.DeclarationSpec) DrlxParseUtil(org.drools.modelcompiler.builder.generator.DrlxParseUtil) CompiledBlockResult(org.drools.mvelcompiler.CompiledBlockResult) PatternDescr(org.drools.drl.ast.descr.PatternDescr) DeclarativeInvokerDescr(org.drools.drl.ast.descr.DeclarativeInvokerDescr) DrlxParseUtil.forceCastForName(org.drools.modelcompiler.builder.generator.DrlxParseUtil.forceCastForName) Type(com.github.javaparser.ast.type.Type) DrlxParseUtil.addSemicolon(org.drools.modelcompiler.builder.generator.DrlxParseUtil.addSemicolon) Expression(com.github.javaparser.ast.expr.Expression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Node(com.github.javaparser.ast.Node) PackageModel(org.drools.modelcompiler.builder.PackageModel) NodeList(com.github.javaparser.ast.NodeList) StaticJavaParser.parseStatement(com.github.javaparser.StaticJavaParser.parseStatement) Collection(java.util.Collection) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) Set(java.util.Set) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) Modifier(com.github.javaparser.ast.Modifier) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) List(java.util.List) StaticJavaParser(com.github.javaparser.StaticJavaParser) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) AccumulateVisitor.collectNamesInBlock(org.drools.modelcompiler.builder.generator.visitor.accumulate.AccumulateVisitor.collectNamesInBlock) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) DrlxParseUtil.addCurlyBracesToBlock(org.drools.modelcompiler.builder.generator.DrlxParseUtil.addCurlyBracesToBlock) DrlxParseUtil.rescopeNamesToNewScope(org.drools.modelcompiler.builder.generator.DrlxParseUtil.rescopeNamesToNewScope) ArrayList(java.util.ArrayList) ACC_FUNCTION_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.ACC_FUNCTION_CALL) HashSet(java.util.HashSet) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) StringUtil(org.drools.modelcompiler.util.StringUtil) FromDescr(org.drools.drl.ast.descr.FromDescr) AccumulateDescr(org.drools.drl.ast.descr.AccumulateDescr) DslMethodNames.createDslTopLevelMethod(org.drools.modelcompiler.builder.generator.DslMethodNames.createDslTopLevelMethod) MvelCompiler(org.drools.mvelcompiler.MvelCompiler) BIND_AS_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.BIND_AS_CALL) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) DrlxParseUtil.toClassOrInterfaceType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toClassOrInterfaceType) IOException(java.io.IOException) NameExpr(com.github.javaparser.ast.expr.NameExpr) Statement(com.github.javaparser.ast.stmt.Statement) MethodReferenceExpr(com.github.javaparser.ast.expr.MethodReferenceExpr) RuleContext(org.drools.modelcompiler.builder.generator.RuleContext) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) IOException(java.io.IOException) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) DrlxParseUtil.toClassOrInterfaceType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toClassOrInterfaceType)

Aggregations

ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)261 Test (org.junit.Test)174 CompilationUnit (com.github.javaparser.ast.CompilationUnit)164 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)84 ReflectionTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver)79 AbstractResolutionTest (com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest)71 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)52 Context (com.github.javaparser.symbolsolver.core.resolution.Context)39 ClassOrInterfaceDeclarationContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.ClassOrInterfaceDeclarationContext)38 CompilationUnitContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.CompilationUnitContext)37 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)36 Expression (com.github.javaparser.ast.expr.Expression)33 TypeSolver (com.github.javaparser.symbolsolver.model.resolution.TypeSolver)28 JavaParserFacade (com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade)27 MemoryTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.MemoryTypeSolver)24 HashMap (java.util.HashMap)21 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)20 ResolvedMethodDeclaration (com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)20 KiePMMLException (org.kie.pmml.api.exceptions.KiePMMLException)20 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)19