Java Code Examples for com.sun.tools.javac.util.Name

The following examples show how to use com.sun.tools.javac.util.Name. 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: netbeans   Source File: PostFlowAnalysis.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visitApply(JCMethodInvocation tree) {
    boolean prevCheckThis = checkThis;
    try {
        Symbol meth = TreeInfo.symbol(tree.meth);
        Name methName = TreeInfo.name(tree.meth);
        if (meth != null && meth.name == names.init) {
            Symbol c = meth.owner;
            if (c.hasOuterInstance()) {
                checkThis = false;
                if (tree.meth.getTag() != JCTree.Tag.SELECT && (c.isLocal() || methName == names._this)) {
                    checkThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
                }
            }
        }
        super.visitApply(tree);
    } finally {
        checkThis = prevCheckThis;
    }
}
 
Example 2
Source Project: bazel   Source File: TreePruner.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean delegatingConstructor(List<JCStatement> stats) {
  if (stats.isEmpty()) {
    return false;
  }
  JCStatement stat = stats.get(0);
  if (stat.getKind() != Kind.EXPRESSION_STATEMENT) {
    return false;
  }
  JCExpression expr = ((JCExpressionStatement) stat).getExpression();
  if (expr.getKind() != Kind.METHOD_INVOCATION) {
    return false;
  }
  JCExpression method = ((JCMethodInvocation) expr).getMethodSelect();
  Name name;
  switch (method.getKind()) {
    case IDENTIFIER:
      name = ((JCIdent) method).getName();
      break;
    case MEMBER_SELECT:
      name = ((JCFieldAccess) method).getIdentifier();
      break;
    default:
      return false;
  }
  return name.contentEquals("this") || name.contentEquals("super");
}
 
Example 3
Source Project: javaide   Source File: Attribute.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a string representation of this annotation.
 * String is of one of the forms:
 *     @com.example.foo(name1=val1, name2=val2)
 *     @com.example.foo(val)
 *     @com.example.foo
 * Omit parens for marker annotations, and omit "value=" when allowed.
 */
public String toString() {
    StringBuilder buf = new StringBuilder();
    buf.append("@");
    buf.append(type);
    int len = values.length();
    if (len > 0) {
        buf.append('(');
        boolean first = true;
        for (Pair<MethodSymbol, Attribute> value : values) {
            if (!first) buf.append(", ");
            first = false;

            Name name = value.fst.name;
            if (len > 1 || name != name.table.names.value) {
                buf.append(name);
                buf.append('=');
            }
            buf.append(value.snd);
        }
        buf.append(')');
    }
    return buf.toString();
}
 
Example 4
Source Project: netbeans   Source File: VeryPretty.java    License: Apache License 2.0 6 votes vote down vote up
public void printImportsBlock(java.util.List<? extends JCTree> imports, boolean maybeAppendNewLine) {
    boolean hasImports = !imports.isEmpty();
    CodeStyle.ImportGroups importGroups = null;
    if (hasImports) {
        blankLines(Math.max(cs.getBlankLinesBeforeImports(), diffContext.origUnit.getPackageName() != null ? cs.getBlankLinesAfterPackage() : 0));
        if (cs.separateImportGroups())
            importGroups = cs.getImportGroups();
    }
    int lastGroup = -1;
    for (JCTree importStat : imports) {
        if (importGroups != null) {
            Name name = fullName(((JCImport)importStat).qualid);
            int group = name != null ? importGroups.getGroupId(name.toString(), ((JCImport)importStat).staticImport) : -1;
            if (lastGroup >= 0 && lastGroup != group)
                blankline();
            lastGroup = group;
        }
        printStat(importStat);
        newline();
    }
    if (hasImports && maybeAppendNewLine) {
        blankLines(cs.getBlankLinesAfterImports());
    }
}
 
Example 5
@Test
public void testConvertNameCandidates(Path base) throws Exception {
    Context ctx = new Context();
    Names names = Names.instance(ctx);
    Name name = names.fromString("com.sun.tools.javac.Attr.BreakAttr");

    com.sun.tools.javac.util.List<String> actual =
            Convert.classCandidates(name).map(n -> n.toString());
    List<String> expected = Arrays.asList(
            "com.sun$tools$javac$Attr$BreakAttr",
            "com.sun.tools$javac$Attr$BreakAttr",
            "com.sun.tools.javac$Attr$BreakAttr",
            "com.sun.tools.javac.Attr$BreakAttr",
            "com.sun.tools.javac.Attr.BreakAttr"
    );

    if (!expected.equals(actual)) {
        throw new Exception("Expected names not generated: " + actual);
    }
}
 
Example 6
Source Project: TencentKona-8   Source File: Dependencies.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fetch the set of dependencies that are relevant to the compile
 * that has just been performed. I.e. we are only interested in
 * dependencies for classes that were explicitly compiled.
 * @return
 */
public Map<String,Set<String>> getDependencies() {
    Map<String,Set<String>> new_deps = new HashMap<String,Set<String>>();
    if (explicitPackages == null) return new_deps;
    for (Name pkg : explicitPackages) {
        Set<Name> set = deps.get(pkg);
        if (set != null) {
            Set<String> new_set = new_deps.get(pkg.toString());
            if (new_set == null) {
                new_set = new HashSet<String>();
                // Modules beware....
                new_deps.put(":"+pkg.toString(), new_set);
            }
            for (Name d : set) {
                new_set.add(":"+d.toString());
            }
        }
    }
    return new_deps;
}
 
Example 7
Source Project: hottub   Source File: Dependencies.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Collect a dependency. curr_pkg is marked as depending on dep_pkg.
 */
public void collect(Name currPkg, Name depPkg) {
    if (!currPkg.equals(depPkg)) {
        Set<Name> theset = deps.get(currPkg);
        if (theset==null) {
            theset = new HashSet<Name>();
            deps.put(currPkg, theset);
        }
        theset.add(depPkg);
    }
}
 
Example 8
Source Project: EasyMPermission   Source File: HandleCleanup.java    License: MIT License 5 votes vote down vote up
public void doAssignmentCheck0(JavacNode node, JCTree statement, Name name) {
	if (statement instanceof JCAssign) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name);
	if (statement instanceof JCExpressionStatement) doAssignmentCheck0(node,
			((JCExpressionStatement)statement).expr, name);
	if (statement instanceof JCVariableDecl) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name);
	if (statement instanceof JCTypeCast) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name);
	if (statement instanceof JCIdent) {
		if (((JCIdent)statement).name.contentEquals(name)) {
			JavacNode problemNode = node.getNodeFor(statement);
			if (problemNode != null) problemNode.addWarning(
			"You're assigning an auto-cleanup variable to something else. This is a bad idea.");
		}
	}
}
 
Example 9
Source Project: openjdk-jdk9   Source File: Operators.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an operator symbol.
 */
private OperatorSymbol makeOperator(Name name, List<OperatorType> formals, OperatorType res, int... opcodes) {
    MethodType opType = new MethodType(
            formals.stream()
                    .map(o -> o.asType(syms))
                    .collect(List.collector()),
            res.asType(syms), List.nil(), syms.methodClass);
    return new OperatorSymbol(name, opType, mergeOpcodes(opcodes), syms.noSymbol);
}
 
Example 10
/**
 * Complete the initialization of an operator helper by storing it into the corresponding operator map.
 */
@SafeVarargs
private final <O extends OperatorHelper> void initOperators(Map<Name, List<O>> opsMap, O... ops) {
    for (O o : ops) {
        Name opName = o.name;
        List<O> helpers = Maps.getOrDefault(opsMap,opName, List.nil());
        opsMap.put(opName, helpers.prepend(o));
    }
}
 
Example 11
Source Project: javaide   Source File: Symbol.java    License: GNU General Public License v3.0 5 votes vote down vote up
public ClassSymbol(long flags, Name name, Type type, Symbol owner) {
    super(flags, name, type, owner);
    this.members_field = null;
    this.fullname = formFullName(name, owner);
    this.flatname = formFlatName(name, owner);
    this.sourcefile = null;
    this.classfile = null;
    this.pool = null;
}
 
Example 12
Source Project: jdk8u60   Source File: DocCommentParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected Name readIdentifier() {
    int start = bp;
    nextChar();
    while (bp < buflen && Character.isUnicodeIdentifierPart(ch))
        nextChar();
    return names.fromChars(buf, start, bp - start);
}
 
Example 13
Source Project: EasyMPermission   Source File: HandleBuilder.java    License: MIT License 5 votes vote down vote up
public void generateBuilderFields(JavacNode builderType, java.util.List<BuilderFieldData> builderFields, JCTree source) {
	int len = builderFields.size();
	java.util.List<JavacNode> existing = new ArrayList<JavacNode>();
	for (JavacNode child : builderType.down()) {
		if (child.getKind() == Kind.FIELD) existing.add(child);
	}
	
	top:
	for (int i = len - 1; i >= 0; i--) {
		BuilderFieldData bfd = builderFields.get(i);
		if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
			bfd.createdFields.addAll(bfd.singularData.getSingularizer().generateFields(bfd.singularData, builderType, source));
		} else {
			for (JavacNode exists : existing) {
				Name n = ((JCVariableDecl) exists.get()).name;
				if (n.equals(bfd.name)) {
					bfd.createdFields.add(exists);
					continue top;
				}
			}
			JavacTreeMaker maker = builderType.getTreeMaker();
			JCModifiers mods = maker.Modifiers(Flags.PRIVATE);
			JCVariableDecl newField = maker.VarDef(mods, bfd.name, cloneType(maker, bfd.type, source, builderType.getContext()), null);
			bfd.createdFields.add(injectFieldAndMarkGenerated(builderType, newField));
		}
	}
}
 
Example 14
/**
 * Read a single block tag, including its content.
 * Standard tags parse their content appropriately.
 * Non-standard tags are represented by {@link UnknownBlockTag}.
 */
protected DCTree blockTag() {
    int p = bp;
    try {
        nextChar();
        if (isIdentifierStart(ch)) {
            Name name = readTagName();
            TagParser tp = tagParsers.get(name);
            if (tp == null) {
                List<DCTree> content = blockContent();
                return m.at(p).UnknownBlockTag(name, content);
            } else {
                switch (tp.getKind()) {
                    case BLOCK:
                        return tp.parse(p);
                    case INLINE:
                        return erroneous("dc.bad.inline.tag", p);
                }
            }
        }
        blockContent();

        return erroneous("dc.no.tag.name", p);
    } catch (ParseException e) {
        blockContent();
        return erroneous(e.getMessage(), p);
    }
}
 
Example 15
Source Project: javaide   Source File: Symbol.java    License: GNU General Public License v3.0 5 votes vote down vote up
public ClassSymbol(long flags, Name name, Symbol owner) {
    this(
        flags,
        name,
        new ClassType(Type.noType, null, null),
        owner);
    this.type.tsym = this;
}
 
Example 16
Source Project: EasyMPermission   Source File: JavacGuavaSingularizer.java    License: MIT License 5 votes vote down vote up
@Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName) {
	JavacTreeMaker maker = builderType.getTreeMaker();
	List<JCExpression> jceBlank = List.nil();
	boolean mapMode = isMap();
	
	JCExpression varType = chainDotsString(builderType, data.getTargetFqn());
	varType = addTypeArgs(mapMode ? 2 : 1, false, builderType, varType, data.getTypeArgs(), source);
	
	JCExpression empty; {
		//ImmutableX.of()
		JCExpression emptyMethod = chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), "of");
		List<JCExpression> invokeTypeArgs = createTypeArgs(mapMode ? 2 : 1, false, builderType, data.getTypeArgs(), source);
		empty = maker.Apply(invokeTypeArgs, emptyMethod, jceBlank);
	}
	
	JCExpression invokeBuild; {
		//this.pluralName.build();
		invokeBuild = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName().toString(), "build"), jceBlank);
	}
	
	JCExpression isNull; {
		//this.pluralName == null
		isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()), maker.Literal(CTC_BOT, null));
	}
	
	JCExpression init = maker.Conditional(isNull, empty, invokeBuild); // this.pluralName == null ? ImmutableX.of() : this.pluralName.build()
	
	JCStatement jcs = maker.VarDef(maker.Modifiers(0), data.getPluralName(), varType, init);
	statements.append(jcs);
}
 
Example 17
/**
 * @return Method name in a form that can be folded into a
 * component of a synthetic method name
 */
String syntheticMethodNameComponent(Name name) {
    if (name == null) {
        return "null";
    }
    String methodName = name.toString();
    if (methodName.equals("<clinit>")) {
        methodName = "static";
    } else if (methodName.equals("<init>")) {
        methodName = "new";
    }
    return methodName;
}
 
Example 18
protected Name readJavaIdentifier() {
    int start = bp;
    nextChar();
    while (bp < buflen && Character.isJavaIdentifierPart(ch))
        nextChar();
    return names.fromChars(buf, start, bp - start);
}
 
Example 19
Source Project: EasyMPermission   Source File: JavacJavaUtilListSetSingularizer.java    License: MIT License 5 votes vote down vote up
@Override public java.util.List<Name> listMethodsToBeGenerated(SingularData data, JavacNode builderType) {
	if (useGuavaInstead(builderType)) {
		return guavaListSetSingularizer.listMethodsToBeGenerated(data, builderType);
	}
	
	return super.listMethodsToBeGenerated(data, builderType);
}
 
Example 20
public void visitArray(Attribute.Array a) {
    Name elemName = ((ArrayType) a.type).elemtype.tsym.getQualifiedName();

    if (elemName.equals(elemName.table.names.java_lang_Class)) {   // Class[]
        // Construct a proxy for a MirroredTypesException
        ListBuffer<TypeMirror> elems = new ListBuffer<>();
        for (Attribute value : a.values) {
            Type elem = ((Attribute.Class) value).classType;
            elems.append(elem);
        }
        value = new MirroredTypesExceptionProxy(elems.toList());

    } else {
        int len = a.values.length;
        Class<?> returnClassSaved = returnClass;
        returnClass = returnClass.getComponentType();
        try {
            Object res = Array.newInstance(returnClass, len);
            for (int i = 0; i < len; i++) {
                a.values[i].accept(this);
                if (value == null || value instanceof ExceptionProxy) {
                    return;
                }
                try {
                    Array.set(res, i, value);
                } catch (IllegalArgumentException e) {
                    value = null;       // indicates a type mismatch
                    return;
                }
            }
            value = res;
        } finally {
            returnClass = returnClassSaved;
        }
    }
}
 
Example 21
Source Project: openjdk-jdk9   Source File: DocEnv.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load ClassDoc by qualified name.
 */
public ClassDocImpl loadClass(String name) {
    try {
        Name nameImpl = names.fromString(name);
        ModuleSymbol mod = syms.inferModule(Convert.packagePart(nameImpl));
        ClassSymbol c = finder.loadClass(mod != null ? mod : syms.errModule, nameImpl);
        return getClassDoc(c);
    } catch (CompletionFailure ex) {
        chk.completionError(null, ex);
        return null;
    }
}
 
Example 22
/** Create a fresh synthetic name within a given scope - the unique name is
 *  obtained by appending '$' chars at the end of the name until no match
 *  is found.
 *
 * @param name base name
 * @param s scope in which the name has to be unique
 * @return fresh synthetic name
 */
private Name makeSyntheticName(Name name, Scope s) {
    do {
        name = name.append(
                target.syntheticNameChar(),
                names.empty);
    } while (lookupSynthetic(name, s) != null);
    return name;
}
 
Example 23
/**
 * Report an operator lookup error.
 */
private OperatorSymbol reportErrorIfNeeded(DiagnosticPosition pos, Tag tag, Type... args) {
    if (Stream.of(args).noneMatch(Type::isErroneous)) {
        Name opName = operatorName(tag);
        JCDiagnostic.Error opError = (args.length) == 1 ?
                Errors.OperatorCantBeApplied(opName, args[0]) :
                Errors.OperatorCantBeApplied1(opName, args[0], args[1]);
        log.error(pos, opError);
    }
    return noOpSymbol;
}
 
Example 24
Source Project: openjdk-jdk9   Source File: ElementsTable.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ModuleSymbol findModuleOfPackageName(String packageName) {
        Name pack = names.fromString(packageName);
        for (ModuleSymbol msym : modules.allModules()) {
            PackageSymbol p = syms.getPackage(msym, pack);
            if (p != null && !p.members().isEmpty()) {
                return msym;
            }
        }
        return null;
}
 
Example 25
Source Project: openjdk-jdk8u   Source File: Symbol.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ClassSymbol(long flags, Name name, Symbol owner) {
    this(
        flags,
        name,
        new ClassType(Type.noType, null, null),
        owner);
    this.type.tsym = this;
}
 
Example 26
/** The name of a this$n field
 *  @param type   The class referenced by the this$n field
 */
Name outerThisName(Type type, Symbol owner) {
    Type t = type.getEnclosingType();
    int nestingLevel = 0;
    while (t.hasTag(CLASS)) {
        t = t.getEnclosingType();
        nestingLevel++;
    }
    Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
    while (owner.kind == TYP && ((ClassSymbol)owner).members().findFirst(result) != null)
        result = names.fromString(result.toString() + target.syntheticNameChar());
    return result;
}
 
Example 27
public ModuleSymbol getObservableModule(Name name) {
    ModuleSymbol mod = syms.getModule(name);

    if (allModules().contains(mod)) {
        return mod;
    }

    return null;
}
 
Example 28
/**
 * Get the bounds of a type variable as listed in the "extends" clause.
 */
private static List<Type> getBounds(TypeVar v, DocEnv env) {
    final Type upperBound = v.getUpperBound();
    Name boundname = upperBound.tsym.getQualifiedName();
    if (boundname == boundname.table.names.java_lang_Object
        && !upperBound.isAnnotated()) {
        return List.nil();
    } else {
        return env.types.getBounds(v);
    }
}
 
Example 29
Source Project: java-n-IDE-for-Android   Source File: Types.java    License: Apache License 2.0 5 votes vote down vote up
public RetentionPolicy getRetention(Attribute.Compound a) {
    RetentionPolicy vis = RetentionPolicy.CLASS; // the default
    Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
    if (c != null) {
        Attribute value = c.member(names.value);
        if (value != null && value instanceof Attribute.Enum) {
            Name levelName = ((Attribute.Enum)value).value.name;
            if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
            else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
            else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
            else ;// /* fail soft */ throw new AssertionError(levelName);
        }
    }
    return vis;
}
 
Example 30
/**
 * Get the bounds of a type variable as listed in the "extends" clause.
 */
private static List<Type> getBounds(TypeVar v, DocEnv env) {
    final Type upperBound = v.getUpperBound();
    Name boundname = upperBound.tsym.getQualifiedName();
    if (boundname == boundname.table.names.java_lang_Object
        && !upperBound.isAnnotated()) {
        return List.nil();
    } else {
        return env.types.getBounds(v);
    }
}