com.sun.tools.javac.code.Flags Java Examples

The following examples show how to use com.sun.tools.javac.code.Flags. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HandleGetter.java    From EasyMPermission with MIT License 6 votes vote down vote up
public void generateGetterForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean checkForTypeLevelGetter) {
	if (checkForTypeLevelGetter) {
		if (hasAnnotation(Getter.class, typeNode)) {
			//The annotation will make it happen, so we can skip it.
			return;
		}
	}
	
	JCClassDecl typeDecl = null;
	if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get();
	long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags;
	boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION)) != 0;
	
	if (typeDecl == null || notAClass) {
		errorNode.addError("@Getter is only supported on a class, an enum, or a field.");
		return;
	}
	
	for (JavacNode field : typeNode.down()) {
		if (fieldQualifiesForGetterGeneration(field)) generateGetterForField(field, errorNode.get(), level, false);
	}
}
 
Example #2
Source File: JavacTrees.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public Symbol getElement(TreePath path) {
    JCTree tree = (JCTree) path.getLeaf();
    Symbol sym = TreeInfo.symbolFor(tree);
    if (sym == null) {
        if (TreeInfo.isDeclaration(tree)) {
            for (TreePath p = path; p != null; p = p.getParentPath()) {
                JCTree t = (JCTree) p.getLeaf();
                if (t.hasTag(JCTree.Tag.CLASSDEF)) {
                    JCClassDecl ct = (JCClassDecl) t;
                    if (ct.sym != null) {
                        if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
                            attr.attribClass(ct.pos(), ct.sym);
                            sym = TreeInfo.symbolFor(tree);
                        }
                        break;
                    }
                }
            }
        }
    }
    return sym;
}
 
Example #3
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private void addWithMethod( SrcLinkedClass srcClass, NamedNode node, @SuppressWarnings("unused") String propName, SrcType type )
{
  //noinspection unused
  String actualName = ensure$included( node );

  //noinspection unused
  StringBuilder propertyType = type.render( new StringBuilder(), 0, false );
  SrcMethod withMethod = new SrcMethod()
    .modifiers( Flags.PUBLIC )
    .name( "with$propName" )
    .addParam( "${'$'}value", type )
    .returns( new SrcType( srcClass.getSimpleName() ) )
    .body( new SrcStatementBlock()
      .addStatement( "_result.getBindings().put(\"${remove$(actualName)}\", " + RuntimeMethods.class.getSimpleName() + ".coerceToBindingValue(${'$'}value));" )
      .addStatement( "return this;" ) );
  addActualNameAnnotation( withMethod, actualName, true );
  addSourcePositionAnnotation( srcClass, node, actualName, withMethod );

  srcClass.addMethod( withMethod );
}
 
Example #4
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 6 votes vote down vote up
public JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source, List<JCAnnotation> onParam) {
	/* public boolean canEqual(final java.lang.Object other) {
	 *     return other instanceof Outer.Inner.MyType;
	 * }
	 */
	JavacTreeMaker maker = typeNode.getTreeMaker();
	
	JCModifiers mods = maker.Modifiers(Flags.PROTECTED, List.<JCAnnotation>nil());
	JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
	Name canEqualName = typeNode.toName("canEqual");
	JCExpression objectType = genJavaLangTypeRef(typeNode, "Object");
	Name otherName = typeNode.toName("other");
	long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext());
	List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(flags, onParam), otherName, objectType, null));
	
	JCBlock body = maker.Block(0, List.<JCStatement>of(
			maker.Return(maker.TypeTest(maker.Ident(otherName), createTypeReference(typeNode)))));
	
	return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
 
Example #5
Source File: SerializedForm.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void addMethodIfExist(DocEnv env, ClassSymbol def, String methodName) {
    Names names = def.name.table.names;

    for (Scope.Entry e = def.members().lookup(names.fromString(methodName)); e.scope != null; e = e.next()) {
        if (e.sym.kind == Kinds.MTH) {
            MethodSymbol md = (MethodSymbol)e.sym;
            if ((md.flags() & Flags.STATIC) == 0) {
                /*
                 * WARNING: not robust if unqualifiedMethodName is overloaded
                 *          method. Signature checking could make more robust.
                 * READOBJECT takes a single parameter, java.io.ObjectInputStream.
                 * WRITEOBJECT takes a single parameter, java.io.ObjectOutputStream.
                 */
                methods.append(env.getMethodDoc(md));
            }
        }
    }
}
 
Example #6
Source File: SerializedForm.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private VarSymbol getDefinedSerializableFields(ClassSymbol def) {
    Names names = def.name.table.names;

    /* SERIALIZABLE_FIELDS can be private,
     * so must lookup by ClassSymbol, not by ClassDocImpl.
     */
    for (Scope.Entry e = def.members().lookup(names.fromString(SERIALIZABLE_FIELDS)); e.scope != null; e = e.next()) {
        if (e.sym.kind == Kinds.VAR) {
            VarSymbol f = (VarSymbol)e.sym;
            if ((f.flags() & Flags.STATIC) != 0 &&
                (f.flags() & Flags.PRIVATE) != 0) {
                return f;
            }
        }
    }
    return null;
}
 
Example #7
Source File: JavacTrees.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public Symbol getElement(TreePath path) {
    JCTree tree = (JCTree) path.getLeaf();
    Symbol sym = TreeInfo.symbolFor(tree);
    if (sym == null) {
        for (TreePath p = path; p != null; p = p.getParentPath()) {
            JCTree t = (JCTree) p.getLeaf();
            if (t.hasTag(JCTree.Tag.CLASSDEF)) {
                JCClassDecl ct = (JCClassDecl) t;
                if (ct.sym != null) {
                    if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
                        attr.attribClass(ct.pos(), ct.sym);
                        sym = TreeInfo.symbolFor(tree);
                    }
                    break;
                }
            }
        }
    }
    return sym;
}
 
Example #8
Source File: GenStubs.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #9
Source File: T6889255.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void verify(MethodSymbol m, boolean expectNames) {
    if ((m.flags() & Flags.SYNTHETIC) != 0 && !testSyntheticMethods)
        return;

    //System.err.println("verify: " + m.params());
    int i = 1;
    for (VarSymbol v: m.params()) {
        String expectName;
        if (expectNames)
            expectName = getExpectedName(v, i);
        else
            expectName = "arg" + (i - 1);
        checkEqual(expectName, v.name.toString());
        i++;
    }
}
 
Example #10
Source File: GenStubs.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #11
Source File: GenStubs.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #12
Source File: JNIWriter.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private boolean needsHeader(ClassSymbol c, boolean checkNestedClasses) {
    if (c.isLocal() || (c.flags() & Flags.SYNTHETIC) != 0)
        return false;

    for (Scope.Entry i = c.members_field.elems; i != null; i = i.sibling) {
        if (i.sym.kind == Kinds.MTH && (i.sym.flags() & Flags.NATIVE) != 0)
            return true;
        for (Attribute.Compound a: i.sym.getDeclarationAttributes()) {
            if (a.type.tsym == syms.nativeHeaderType.tsym)
                return true;
        }
    }
    if (checkNestedClasses) {
        for (Scope.Entry i = c.members_field.elems; i != null; i = i.sibling) {
            if ((i.sym.kind == Kinds.TYP) && needsHeader(((ClassSymbol) i.sym), true))
                return true;
        }
    }
    return false;
}
 
Example #13
Source File: JavacTrees.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
public Element getElement(TreePath path) {
    JCTree tree = (JCTree) path.getLeaf();
    Symbol sym = TreeInfo.symbolFor(tree);
    if (sym == null && TreeInfo.isDeclaration(tree)) {
        for (TreePath p = path; p != null; p = p.getParentPath()) {
            JCTree t = (JCTree) p.getLeaf();
            if (t.getTag() == JCTree.CLASSDEF) {
                JCClassDecl ct = (JCClassDecl) t;
                if (ct.sym != null) {
                    if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
                        attr.attribClass(ct.pos(), ct.sym);
                        sym = TreeInfo.symbolFor(tree);
                    }
                    break;
                }
            }
        }
    }
    return sym;
}
 
Example #14
Source File: T6889255.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void verify(MethodSymbol m, boolean expectNames) {
    if ((m.flags() & Flags.SYNTHETIC) != 0 && !testSyntheticMethods)
        return;

    //System.err.println("verify: " + m.params());
    int i = 1;
    for (VarSymbol v: m.params()) {
        String expectName;
        if (expectNames)
            expectName = getExpectedName(v, i);
        else
            expectName = "arg" + (i - 1);
        checkEqual(expectName, v.name.toString());
        i++;
    }
}
 
Example #15
Source File: TreeMaker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public ModifiersTree removeModifiersModifier(ModifiersTree modifiers, Modifier modifier) {
    long c = ((JCModifiers) modifiers).flags & ~Flags.GENERATEDCONSTR;
    switch (modifier) {
        case ABSTRACT: c = c & ~Flags.ABSTRACT; break;
        case FINAL: c = c & ~Flags.FINAL; break;
        case NATIVE: c = c & ~Flags.NATIVE; break;
        case PRIVATE: c = c & ~Flags.PRIVATE; break;
        case PROTECTED: c = c & ~Flags.PROTECTED; break;
        case PUBLIC: c = c & ~Flags.PUBLIC; break;
        case STATIC: c = c & ~Flags.STATIC; break;
        case STRICTFP: c = c & ~Flags.STRICTFP; break;
        case SYNCHRONIZED: c = c & ~Flags.SYNCHRONIZED; break;
        case TRANSIENT: c = c & ~Flags.TRANSIENT; break;
        case VOLATILE: c = c & ~Flags.VOLATILE; break;
        case DEFAULT: c = c & ~Flags.DEFAULT; break;
        default:
            break;
    }
    return Modifiers(c, modifiers.getAnnotations());
}
 
Example #16
Source File: T6889255.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
void verify(MethodSymbol m, boolean expectNames) {
    if ((m.flags() & Flags.SYNTHETIC) != 0 && !testSyntheticMethods)
        return;

    //System.err.println("verify: " + m.params());
    int i = 1;
    for (VarSymbol v: m.params()) {
        String expectName;
        if (expectNames)
            expectName = getExpectedName(v, i);
        else
            expectName = "arg" + (i - 1);
        checkEqual(expectName, v.name.toString());
        i++;
    }
}
 
Example #17
Source File: GenStubs.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * methods: remove method bodies, make methods native
 */
@Override
public void visitMethodDef(JCMethodDecl tree) {
    tree.mods = translate(tree.mods);
    tree.restype = translate(tree.restype);
    tree.typarams = translateTypeParams(tree.typarams);
    tree.params = translateVarDefs(tree.params);
    tree.thrown = translate(tree.thrown);
    if (tree.body != null) {
        if ((currClassMods & Flags.INTERFACE) != 0) {
            tree.mods.flags &= ~(Flags.DEFAULT | Flags.STATIC);
        } else {
            tree.mods.flags |= Flags.NATIVE;
        }
        tree.body = null;
    }
    result = tree;
}
 
Example #18
Source File: JavacTrees.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public Symbol getElement(TreePath path) {
    JCTree tree = (JCTree) path.getLeaf();
    Symbol sym = TreeInfo.symbolFor(tree);
    if (sym == null) {
        for (TreePath p = path; p != null; p = p.getParentPath()) {
            JCTree t = (JCTree) p.getLeaf();
            if (t.hasTag(JCTree.Tag.CLASSDEF)) {
                JCClassDecl ct = (JCClassDecl) t;
                if (ct.sym != null) {
                    if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
                        attr.attribClass(ct.pos(), ct.sym);
                        sym = TreeInfo.symbolFor(tree);
                    }
                    break;
                }
            }
        }
    }
    return sym;
}
 
Example #19
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void handleMethod(JavacNode annotation, JCMethodDecl method, Collection<String> exceptions) {
	JavacNode methodNode = annotation.up();
	
	if ( (method.mods.flags & Flags.ABSTRACT) != 0) {
		annotation.addError("@SneakyThrows can only be used on concrete methods.");
		return;
	}
	
	if (method.body == null || method.body.stats.isEmpty()) {
		generateEmptyBlockWarning(methodNode, annotation, false);
		return;
	}
	
	final JCStatement constructorCall = method.body.stats.get(0);
	final boolean isConstructorCall = isConstructorCall(constructorCall);
	List<JCStatement> contents = isConstructorCall ? method.body.stats.tail : method.body.stats;
	
	if (contents == null || contents.isEmpty()) {
		generateEmptyBlockWarning(methodNode, annotation, true);
		return;
	}
	
	for (String exception : exceptions) {
		contents = List.of(buildTryCatchBlock(methodNode, contents, exception, annotation.get()));
	}
	
	method.body.stats = isConstructorCall ? List.of(constructorCall).appendList(contents) : contents;
	methodNode.rebuild();
}
 
Example #20
Source File: DPrinter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected void printSymbol(String label, Symbol sym, Details details) {
    if (sym == null) {
        printNull(label);
    } else {
        switch (details) {
        case SUMMARY:
            printString(label, toString(sym));
            break;

        case FULL:
            indent();
            out.print(label);
            out.println(": " +
                    info(sym.getClass(),
                        String.format("0x%x--%s", sym.kind, Kinds.kindName(sym)),
                        sym.getKind())
                    + " " + sym.name
                    + " " + hashString(sym));

            indent(+1);
            if (showSrc) {
                JCTree tree = (JCTree) trees.getTree(sym);
                if (tree != null)
                    printSource("src", tree);
            }
            printString("flags", String.format("0x%x--%s",
                    sym.flags_field, Flags.toString(sym.flags_field)));
            printObject("completer", sym.completer, Details.SUMMARY); // what if too long?
            printSymbol("owner", sym.owner, Details.SUMMARY);
            printType("type", sym.type, Details.SUMMARY);
            printType("erasure", sym.erasure_field, Details.SUMMARY);
            sym.accept(symVisitor, null);
            printAnnotations("annotations", sym.getAnnotations(), Details.SUMMARY);
            indent(-1);
        }
    }
}
 
Example #21
Source File: HandleBuilder.java    From EasyMPermission with MIT License 5 votes vote down vote up
public JCMethodDecl generateBuilderMethod(String builderMethodName, String builderClassName, JavacNode type, List<JCTypeParameter> typeParams) {
	JavacTreeMaker maker = type.getTreeMaker();
	
	ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
	for (JCTypeParameter typeParam : typeParams) {
		typeArgs.append(maker.Ident(typeParam.name));
	}
	
	JCExpression call = maker.NewClass(null, List.<JCExpression>nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCExpression>nil(), null);
	JCStatement statement = maker.Return(call);
	
	JCBlock body = maker.Block(0, List.<JCStatement>of(statement));
	return maker.MethodDef(maker.Modifiers(Flags.STATIC | Flags.PUBLIC), type.toName(builderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), copyTypeParams(maker, typeParams), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
}
 
Example #22
Source File: ResolveHarness.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
void process(Diagnostic<? extends JavaFileObject> diagnostic) {
    Symbol methodSym = (Symbol)methodSym(diagnostic);
    if ((methodSym.flags() & Flags.GENERATEDCONSTR) != 0) {
        //skip resolution of default constructor (put there by javac)
        return;
    }
    Candidate c = getCandidateAtPos(methodSym,
            asJCDiagnostic(diagnostic).getLineNumber(),
            asJCDiagnostic(diagnostic).getColumnNumber());
    if (c == null) {
        return; //nothing to check
    }

    if (c.applicable().length == 0 && c.mostSpecific()) {
        error("Inapplicable method cannot be most specific " + methodSym);
    }

    if (isApplicable(diagnostic) != Arrays.asList(c.applicable()).contains(phase)) {
        error("Invalid candidate's applicability " + methodSym);
    }

    if (success) {
        for (Phase p : c.applicable()) {
            if (phase.ordinal() < p.ordinal()) {
                error("Invalid phase " + p + " on method " + methodSym);
            }
        }
    }

    if (Arrays.asList(c.applicable()).contains(phase)) { //applicable
        if (c.mostSpecific() != mostSpecific) {
            error("Invalid most specific value for method " + methodSym + " " + new ElementKey(methodSym).key);
        }
        MethodType mtype = getSig(diagnostic);
        if (mtype != null) {
            checkSig(c, methodSym, mtype);
        }
    }
}
 
Example #23
Source File: HandleFieldDefaults.java    From EasyMPermission with MIT License 5 votes vote down vote up
public boolean generateFieldDefaultsForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean makeFinal, boolean checkForTypeLevelFieldDefaults) {
	if (checkForTypeLevelFieldDefaults) {
		if (hasAnnotation(FieldDefaults.class, typeNode)) {
			//The annotation will make it happen, so we can skip it.
			return true;
		}
	}
	
	JCClassDecl typeDecl = null;
	if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get();
	long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags;
	boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION)) != 0;
	
	if (typeDecl == null || notAClass) {
		errorNode.addError("@FieldDefaults is only supported on a class or an enum.");
		return false;
	}
	
	for (JavacNode field : typeNode.down()) {
		if (field.getKind() != Kind.FIELD) continue;
		JCVariableDecl fieldDecl = (JCVariableDecl) field.get();
		//Skip fields that start with $
		if (fieldDecl.name.toString().startsWith("$")) continue;
		
		setFieldDefaultsForField(field, errorNode.get(), level, makeFinal);
	}
	
	return true;
}
 
Example #24
Source File: HandleGetter.java    From EasyMPermission with MIT License 5 votes vote down vote up
public boolean fieldQualifiesForGetterGeneration(JavacNode field) {
	if (field.getKind() != Kind.FIELD) return false;
	JCVariableDecl fieldDecl = (JCVariableDecl) field.get();
	//Skip fields that start with $
	if (fieldDecl.name.toString().startsWith("$")) return false;
	//Skip static fields.
	if ((fieldDecl.mods.flags & Flags.STATIC) != 0) return false;
	return true;
}
 
Example #25
Source File: T6397044.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void check(CharSequence name, ModifiersTree modifiers) {
    long sysflags = ((JCModifiers) modifiers).flags;
    System.err.println(name + ": " + modifiers.getFlags() + " | " + Flags.toString(sysflags));
    if (name.toString().startsWith("x_")) {
        String expected = "[" + name.toString().substring(2) + "]";
        String found = modifiers.getFlags().toString();
        if (!found.equals(expected))
            throw new AssertionError("expected: " + expected + "; found: " + found);
    }
}
 
Example #26
Source File: JavacJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public java.util.List<JavacNode> generateFields(SingularData data, JavacNode builderType, JCTree source) {
	if (useGuavaInstead(builderType)) {
		return guavaListSetSingularizer.generateFields(data, builderType, source);
	}
	
	JavacTreeMaker maker = builderType.getTreeMaker();
	JCExpression type = JavacHandlerUtil.chainDots(builderType, "java", "util", "ArrayList");
	type = addTypeArgs(1, false, builderType, type, data.getTypeArgs(), source);
	
	JCVariableDecl buildField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), data.getPluralName(), type, null);
	return Collections.singletonList(injectFieldAndMarkGenerated(builderType, buildField));
}
 
Example #27
Source File: GenStubs.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * field definitions: replace initializers with 0, 0.0, false etc
 * when possible -- i.e. leave public, protected initializers alone
 */
@Override
public void visitVarDef(JCVariableDecl tree) {
    tree.mods = translate(tree.mods);
    tree.vartype = translate(tree.vartype);
    if (tree.init != null) {
        if ((tree.mods.flags & (Flags.PUBLIC | Flags.PROTECTED)) != 0)
            tree.init = translate(tree.init);
        else {
            String t = tree.vartype.toString();
            if (t.equals("boolean"))
                tree.init = new JCLiteral(TypeTag.BOOLEAN, 0) { };
            else if (t.equals("byte"))
                tree.init = new JCLiteral(TypeTag.BYTE, 0) { };
            else if (t.equals("char"))
                tree.init = new JCLiteral(TypeTag.CHAR, 0) { };
            else if (t.equals("double"))
                tree.init = new JCLiteral(TypeTag.DOUBLE, 0.d) { };
            else if (t.equals("float"))
                tree.init = new JCLiteral(TypeTag.FLOAT, 0.f) { };
            else if (t.equals("int"))
                tree.init = new JCLiteral(TypeTag.INT, 0) { };
            else if (t.equals("long"))
                tree.init = new JCLiteral(TypeTag.LONG, 0) { };
            else if (t.equals("short"))
                tree.init = new JCLiteral(TypeTag.SHORT, 0) { };
            else
                tree.init = new JCLiteral(TypeTag.BOT, null) { };
        }
    }
    result = tree;
}
 
Example #28
Source File: SourceUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the method is a main method
 * @param method to be checked
 * @return true when the method is a main method
 */
public static boolean isMainMethod (final ExecutableElement method) {
    if (!"main".contentEquals(method.getSimpleName())) {                //NOI18N
        return false;
    }
    long flags = ((Symbol.MethodSymbol)method).flags();                 //faster
    if (((flags & Flags.PUBLIC) == 0) || ((flags & Flags.STATIC) == 0)) {
        return false;
    }
    if (method.getReturnType().getKind() != TypeKind.VOID) {
        return false;
    }
    List<? extends VariableElement> params = method.getParameters();
    if (params.size() != 1) {
        return false;
    }
    TypeMirror param = params.get(0).asType();
    if (param.getKind() != TypeKind.ARRAY) {
        return false;
    }
    ArrayType array = (ArrayType) param;
    TypeMirror compound = array.getComponentType();
    if (compound.getKind() != TypeKind.DECLARED) {
        return false;
    }
    return "java.lang.String".contentEquals(((TypeElement)((DeclaredType)compound).asElement()).getQualifiedName());   //NOI18N
}
 
Example #29
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	boolean mapMode = isMap();
	
	Name keyName = !mapMode ? data.getSingularName() : builderType.toName(data.getSingularName() + "$key");
	Name valueName = !mapMode ? null : builderType.toName(data.getSingularName() + "$value");
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, mapMode, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), mapMode ? "put" : "add");
	List<JCExpression> invokeAddExpr;
	if (mapMode) {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName), maker.Ident(valueName));
	} else {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName));
	}
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, invokeAddExpr);
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name methodName = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(mapMode ? "put" : "add", methodName.toString()));
	List<JCVariableDecl> params;
	if (mapMode) {
		JCExpression keyType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		JCExpression valueType = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
		JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, keyType, null);
		JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, valueType, null);
		params = List.of(paramKey, paramValue);
	} else {
		JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		params = List.of(maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null));
	}
	JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #30
Source File: JavacElements.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override @DefinedBy(Api.LANGUAGE_MODEL)
public Origin getOrigin(Element e) {
    Symbol sym = cast(Symbol.class, e);
    if ((sym.flags() & Flags.GENERATEDCONSTR) != 0)
        return Origin.MANDATED;
    //TypeElement.getEnclosedElements does not return synthetic elements,
    //and most synthetic elements are not read from the classfile anyway:
    return Origin.EXPLICIT;
}