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

The following examples show how to use com.sun.tools.javac.code.Flags. These examples are extracted from open source projects. 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 Project: EasyMPermission   Source File: HandleGetter.java    License: 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 Project: TencentKona-8   Source File: GenStubs.java    License: 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 3
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 4
Source Project: EasyMPermission   Source File: HandleEqualsAndHashCode.java    License: 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 Project: manifold   Source File: GqlParentType.java    License: 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 6
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 Project: openjdk-jdk9   Source File: T6889255.java    License: 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 8
Source Project: openjdk-8   Source File: GenStubs.java    License: 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 Project: jdk8u60   Source File: GenStubs.java    License: 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 10
Source Project: openjdk-8   Source File: T6889255.java    License: 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 11
Source Project: netbeans   Source File: TreeMaker.java    License: 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 12
Source Project: javaide   Source File: JavacTrees.java    License: 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 13
Source Project: jdk8u60   Source File: JNIWriter.java    License: 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 14
Source Project: jdk8u60   Source File: T6889255.java    License: 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
@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 16
Source Project: openjdk-jdk8u   Source File: GenStubs.java    License: 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 17
Source Project: openjdk-jdk9   Source File: JavacTrees.java    License: 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 18
Source Project: openjdk-8-source   Source File: JavacTrees.java    License: 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 19
Source Project: openjdk-jdk9   Source File: ClassDocImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return true if this is an enumeration.
 * (For legacy doclets, return false.)
 */
@Override
public boolean isEnum() {
    return (getFlags() & Flags.ENUM) != 0
           &&
           !env.legacyDoclet;
}
 
Example 20
Source Project: openjdk-jdk9   Source File: WorkArounds.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void computeDefaultSerializableFields(ClassSymbol te) {
    for (Symbol sym : te.members().getSymbols(NON_RECURSIVE)) {
        if (sym != null && sym.kind == VAR) {
            VarSymbol f = (VarSymbol) sym;
            if ((f.flags() & Flags.STATIC) == 0
                    && (f.flags() & Flags.TRANSIENT) == 0) {
                //### No modifier filtering applied here.
                //### Add to beginning.
                //### Preserve order used by old 'javadoc'.
                fields.add(f);
            }
        }
    }
}
 
Example 21
/**
 * 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 22
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 23
Source Project: openjdk-8-source   Source File: JNIWriter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean needsHeader(ClassSymbol c) {
    if (c.isLocal() || (c.flags() & Flags.SYNTHETIC) != 0)
        return false;

    if (checkAll)
        return needsHeader(c.outermostClass(), true);
    else
        return needsHeader(c, false);
}
 
Example 24
Source Project: bazel   Source File: TreePruner.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isFinal(JCClassDecl enclClass, JCVariableDecl tree) {
  if ((tree.mods.flags & Flags.FINAL) == Flags.FINAL) {
    return true;
  }
  if (enclClass != null && (enclClass.mods.flags & (Flags.ANNOTATION | Flags.INTERFACE)) != 0) {
    // Fields in annotation declarations and interfaces are implicitly final
    return true;
  }
  return false;
}
 
Example 25
Source Project: EasyMPermission   Source File: JavacHandlerUtil.java    License: MIT License 5 votes vote down vote up
public static <T extends JCTree> T setGeneratedBy(T node, JCTree source, Context context) {
	if (node == null) return null;
	if (source == null) JCTree_generatedNode.clear(node);
	else JCTree_generatedNode.set(node, source);
	if (source != null && (!inNetbeansEditor(context) || (node instanceof JCVariableDecl && (((JCVariableDecl) node).mods.flags & Flags.PARAMETER) != 0))) node.pos = source.pos;
	return node;
}
 
Example 26
Source Project: openjdk-8   Source File: ResolveHarness.java    License: 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 27
Source Project: netbeans   Source File: VanillaPartialReparser.java    License: Apache License 2.0 5 votes vote down vote up
public BlockTree reattrMethodBody(Context context, Scope scope, MethodTree methodToReparse, BlockTree block) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Attr attr = Attr.instance(context);
//        assert ((JCTree.JCMethodDecl)methodToReparse).localEnv != null;
        JCTree.JCMethodDecl tree = (JCTree.JCMethodDecl) methodToReparse;
        final Names names = Names.instance(context);
        final Symtab syms = Symtab.instance(context);
        final TypeEnter typeEnter = TypeEnter.instance(context);
        final Log log = Log.instance(context);
        final TreeMaker make = TreeMaker.instance(context);
        final Env<AttrContext> env = ((JavacScope) scope).getEnv();//this is a copy anyway...
        final Symbol.ClassSymbol owner = env.enclClass.sym;
        if (tree.name == names.init && !owner.type.isErroneous() && owner.type != syms.objectType) {
            JCTree.JCBlock body = tree.body;
            if (body.stats.isEmpty() || !TreeInfo.isSelfCall(body.stats.head)) {
                body.stats = body.stats.
                prepend(make.at(body.pos).Exec(make.Apply(com.sun.tools.javac.util.List.nil(), make.Ident(names._super), com.sun.tools.javac.util.List.nil())));
            } else if ((env.enclClass.sym.flags() & Flags.ENUM) != 0 &&
                (tree.mods.flags & Flags.GENERATEDCONSTR) == 0 &&
                TreeInfo.isSuperCall(body.stats.head)) {
                // enum constructors are not allowed to call super
                // directly, so make sure there aren't any super calls
                // in enum constructors, except in the compiler
                // generated one.
                log.error(tree.body.stats.head.pos(),
                          new JCDiagnostic.Error("compiler",
                                    "call.to.super.not.allowed.in.enum.ctor",
                                    env.enclClass.sym));
                    }
        }
        attr.attribStat((JCTree.JCBlock)block, env);
        return block;
    }
 
Example 28
Source Project: annotation-tools   Source File: TreeFinder.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the start position of the method's name.  In particular,
 * works properly for constructors, for which the name field in the
 * AST is always "<init>" instead of the name from the source.
 *
 * @param node AST node of method declaration
 * @return position of method name (from {@link JCMethodDecl#sym}) in source
 */
private int findMethodName(JCMethodDecl node) {
  String sym = node.sym.toString();
  String name = sym.substring(0, sym.indexOf('('));
  JCModifiers mods = node.getModifiers();
  JCBlock body = node.body;
  if ((mods.flags & Flags.GENERATEDCONSTR) != 0) { return Position.NOPOS; }
  int nodeStart = node.getStartPosition();
  int nodeEnd = node.getEndPosition(tree.endPositions);
  int nodeLength = nodeEnd - nodeStart;
  int modsLength = mods.getEndPosition(tree.endPositions)
      - mods.getStartPosition();  // can't trust string length!
  int bodyLength = body == null ? 1
      : body.getEndPosition(tree.endPositions) - body.getStartPosition();
  int start = nodeStart + modsLength;
  int end = nodeStart + nodeLength - bodyLength;
  int angle = name.lastIndexOf('>');  // check for type params
  if (angle >= 0) { name = name.substring(angle + 1); }

  try {
    CharSequence s = tree.getSourceFile().getCharContent(true);
    String regex = "\\b" + Pattern.quote(name) + "\\b";  // sufficient?
    Pattern pat = Pattern.compile(regex, Pattern.MULTILINE);
    Matcher mat = pat.matcher(s).region(start, end);
    return mat.find() ? mat.start() : Position.NOPOS;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 29
Source Project: openjdk-jdk9   Source File: GenStubs.java    License: 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 30
private Attribute getAnnotationEnumValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
    Type result = attr.attribTree(tree, env, annotationValueInfo(expectedElementType));
    Symbol sym = TreeInfo.symbol(tree);
    if (sym == null ||
            TreeInfo.nonstaticSelect(tree) ||
            sym.kind != VAR ||
            (sym.flags() & Flags.ENUM) == 0) {
        log.error(tree.pos(), Errors.EnumAnnotationMustBeEnumConstant);
        return new Attribute.Error(result.getOriginalType());
    }
    VarSymbol enumerator = (VarSymbol) sym;
    return new Attribute.Enum(expectedElementType, enumerator);
}