file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
Check.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/comp/Check.java | /*
* Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.comp;
import java.util.*;
import java.util.Set;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.code.Lint;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.code.Symbol.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.main.OptionName.*;
/** Type checking helper class for the attribution phase.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Check {
protected static final Context.Key<Check> checkKey =
new Context.Key<Check>();
private final Names names;
private final Log log;
private final Symtab syms;
private final Enter enter;
private final Infer infer;
private final Types types;
private final JCDiagnostic.Factory diags;
private final boolean skipAnnotations;
private boolean warnOnSyntheticConflicts;
private boolean suppressAbortOnBadClassFile;
private boolean enableSunApiLintControl;
private final TreeInfo treeinfo;
// The set of lint options currently in effect. It is initialized
// from the context, and then is set/reset as needed by Attr as it
// visits all the various parts of the trees during attribution.
private Lint lint;
// The method being analyzed in Attr - it is set/reset as needed by
// Attr as it visits new method declarations.
private MethodSymbol method;
public static Check instance(Context context) {
Check instance = context.get(checkKey);
if (instance == null)
instance = new Check(context);
return instance;
}
protected Check(Context context) {
context.put(checkKey, this);
names = Names.instance(context);
log = Log.instance(context);
syms = Symtab.instance(context);
enter = Enter.instance(context);
infer = Infer.instance(context);
this.types = Types.instance(context);
diags = JCDiagnostic.Factory.instance(context);
Options options = Options.instance(context);
lint = Lint.instance(context);
treeinfo = TreeInfo.instance(context);
Source source = Source.instance(context);
allowGenerics = source.allowGenerics();
allowAnnotations = source.allowAnnotations();
allowCovariantReturns = source.allowCovariantReturns();
allowSimplifiedVarargs = source.allowSimplifiedVarargs();
complexInference = options.isSet(COMPLEXINFERENCE);
skipAnnotations = options.isSet("skipAnnotations");
warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
enableSunApiLintControl = options.isSet("enableSunApiLintControl");
Target target = Target.instance(context);
syntheticNameChar = target.syntheticNameChar();
boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
enforceMandatoryWarnings, "sunapi", null);
deferredLintHandler = DeferredLintHandler.immediateHandler;
}
/** Switch: generics enabled?
*/
boolean allowGenerics;
/** Switch: annotations enabled?
*/
boolean allowAnnotations;
/** Switch: covariant returns enabled?
*/
boolean allowCovariantReturns;
/** Switch: simplified varargs enabled?
*/
boolean allowSimplifiedVarargs;
/** Switch: -complexinference option set?
*/
boolean complexInference;
/** Character for synthetic names
*/
char syntheticNameChar;
/** A table mapping flat names of all compiled classes in this run to their
* symbols; maintained from outside.
*/
public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
/** A handler for messages about deprecated usage.
*/
private MandatoryWarningHandler deprecationHandler;
/** A handler for messages about unchecked or unsafe usage.
*/
private MandatoryWarningHandler uncheckedHandler;
/** A handler for messages about using proprietary API.
*/
private MandatoryWarningHandler sunApiHandler;
/** A handler for deferred lint warnings.
*/
private DeferredLintHandler deferredLintHandler;
/* *************************************************************************
* Errors and Warnings
**************************************************************************/
Lint setLint(Lint newLint) {
Lint prev = lint;
lint = newLint;
return prev;
}
DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
DeferredLintHandler prev = deferredLintHandler;
deferredLintHandler = newDeferredLintHandler;
return prev;
}
MethodSymbol setMethod(MethodSymbol newMethod) {
MethodSymbol prev = method;
method = newMethod;
return prev;
}
/** Warn about deprecated symbol.
* @param pos Position to be used for error reporting.
* @param sym The deprecated symbol.
*/
void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
if (!lint.isSuppressed(LintCategory.DEPRECATION))
deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
}
/** Warn about unchecked operation.
* @param pos Position to be used for error reporting.
* @param msg A string describing the problem.
*/
public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
if (!lint.isSuppressed(LintCategory.UNCHECKED))
uncheckedHandler.report(pos, msg, args);
}
/** Warn about unsafe vararg method decl.
* @param pos Position to be used for error reporting.
* @param sym The deprecated symbol.
*/
void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
log.warning(LintCategory.VARARGS, pos, key, args);
}
/** Warn about using proprietary API.
* @param pos Position to be used for error reporting.
* @param msg A string describing the problem.
*/
public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
if (!lint.isSuppressed(LintCategory.SUNAPI))
sunApiHandler.report(pos, msg, args);
}
public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
if (lint.isEnabled(LintCategory.STATIC))
log.warning(LintCategory.STATIC, pos, msg, args);
}
/**
* Report any deferred diagnostics.
*/
public void reportDeferredDiagnostics() {
deprecationHandler.reportDeferredDiagnostic();
uncheckedHandler.reportDeferredDiagnostic();
sunApiHandler.reportDeferredDiagnostic();
}
/** Report a failure to complete a class.
* @param pos Position to be used for error reporting.
* @param ex The failure to report.
*/
public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
if (ex instanceof ClassReader.BadClassFile
&& !suppressAbortOnBadClassFile) throw new Abort();
else return syms.errType;
}
/** Report a type error.
* @param pos Position to be used for error reporting.
* @param problem A string describing the error.
* @param found The type that was found.
* @param req The type that was required.
*/
Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
log.error(pos, "prob.found.req",
problem, found, req);
return types.createErrorType(found);
}
Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
log.error(pos, "prob.found.req.1", problem, found, req, explanation);
return types.createErrorType(found);
}
/** Report an error that wrong type tag was found.
* @param pos Position to be used for error reporting.
* @param required An internationalized string describing the type tag
* required.
* @param found The type that was found.
*/
Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
// this error used to be raised by the parser,
// but has been delayed to this point:
if (found instanceof Type && ((Type)found).tag == VOID) {
log.error(pos, "illegal.start.of.type");
return syms.errType;
}
log.error(pos, "type.found.req", found, required);
return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
}
/** Report an error that symbol cannot be referenced before super
* has been called.
* @param pos Position to be used for error reporting.
* @param sym The referenced symbol.
*/
void earlyRefError(DiagnosticPosition pos, Symbol sym) {
log.error(pos, "cant.ref.before.ctor.called", sym);
}
/** Report duplicate declaration error.
*/
void duplicateError(DiagnosticPosition pos, Symbol sym) {
if (!sym.type.isErroneous()) {
Symbol location = sym.location();
if (location.kind == MTH &&
((MethodSymbol)location).isStaticOrInstanceInit()) {
log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
kindName(sym.location()), kindName(sym.location().enclClass()),
sym.location().enclClass());
} else {
log.error(pos, "already.defined", kindName(sym), sym,
kindName(sym.location()), sym.location());
}
}
}
/** Report array/varargs duplicate declaration
*/
void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
}
}
/* ************************************************************************
* duplicate declaration checking
*************************************************************************/
/** Check that variable does not hide variable with same name in
* immediately enclosing local scope.
* @param pos Position for error reporting.
* @param v The symbol.
* @param s The scope.
*/
void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
if (s.next != null) {
for (Scope.Entry e = s.next.lookup(v.name);
e.scope != null && e.sym.owner == v.owner;
e = e.next()) {
if (e.sym.kind == VAR &&
(e.sym.owner.kind & (VAR | MTH)) != 0 &&
v.name != names.error) {
duplicateError(pos, e.sym);
return;
}
}
}
}
/** Check that a class or interface does not hide a class or
* interface with same name in immediately enclosing local scope.
* @param pos Position for error reporting.
* @param c The symbol.
* @param s The scope.
*/
void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
if (s.next != null) {
for (Scope.Entry e = s.next.lookup(c.name);
e.scope != null && e.sym.owner == c.owner;
e = e.next()) {
if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
(e.sym.owner.kind & (VAR | MTH)) != 0 &&
c.name != names.error) {
duplicateError(pos, e.sym);
return;
}
}
}
}
/** Check that class does not have the same name as one of
* its enclosing classes, or as a class defined in its enclosing scope.
* return true if class is unique in its enclosing scope.
* @param pos Position for error reporting.
* @param name The class name.
* @param s The enclosing scope.
*/
boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
if (e.sym.kind == TYP && e.sym.name != names.error) {
duplicateError(pos, e.sym);
return false;
}
}
for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
duplicateError(pos, sym);
return true;
}
}
return true;
}
/* *************************************************************************
* Class name generation
**************************************************************************/
/** Return name of local class.
* This is of the form <enclClass> $ n <classname>
* where
* enclClass is the flat name of the enclosing class,
* classname is the simple name of the local class
*/
Name localClassName(ClassSymbol c) {
for (int i=1; ; i++) {
Name flatname = names.
fromString("" + c.owner.enclClass().flatname +
syntheticNameChar + i +
c.name);
if (compiled.get(flatname) == null) return flatname;
}
}
/* *************************************************************************
* Type Checking
**************************************************************************/
/** Check that a given type is assignable to a given proto-type.
* If it is, return the type, otherwise return errType.
* @param pos Position to be used for error reporting.
* @param found The type that was found.
* @param req The type that was required.
*/
Type checkType(DiagnosticPosition pos, Type found, Type req) {
return checkType(pos, found, req, "incompatible.types");
}
Type checkType(DiagnosticPosition pos, Type found, Type req, String errKey) {
if (req.tag == ERROR)
return req;
if (found.tag == FORALL)
return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
if (req.tag == NONE)
return found;
if (types.isAssignable(found, req, convertWarner(pos, found, req)))
return found;
if (found.tag <= DOUBLE && req.tag <= DOUBLE)
return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
if (found.isSuperBound()) {
log.error(pos, "assignment.from.super-bound", found);
return types.createErrorType(found);
}
if (req.isExtendsBound()) {
log.error(pos, "assignment.to.extends-bound", req);
return types.createErrorType(found);
}
return typeError(pos, diags.fragment(errKey), found, req);
}
/** Instantiate polymorphic type to some prototype, unless
* prototype is `anyPoly' in which case polymorphic type
* is returned unchanged.
*/
Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
if (pt == Infer.anyPoly && complexInference) {
return t;
} else if (pt == Infer.anyPoly || pt.tag == NONE) {
Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
return instantiatePoly(pos, t, newpt, warn);
} else if (pt.tag == ERROR) {
return pt;
} else {
try {
return infer.instantiateExpr(t, pt, warn);
} catch (Infer.NoInstanceException ex) {
if (ex.isAmbiguous) {
JCDiagnostic d = ex.getDiagnostic();
log.error(pos,
"undetermined.type" + (d!=null ? ".1" : ""),
t, d);
return types.createErrorType(pt);
} else {
JCDiagnostic d = ex.getDiagnostic();
return typeError(pos,
diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
t, pt);
}
} catch (Infer.InvalidInstanceException ex) {
JCDiagnostic d = ex.getDiagnostic();
log.error(pos, "invalid.inferred.types", t.tvars, d);
return types.createErrorType(pt);
}
}
}
/** Check that a given type can be cast to a given target type.
* Return the result of the cast.
* @param pos Position to be used for error reporting.
* @param found The type that is being cast.
* @param req The target type of the cast.
*/
Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
if (found.tag == FORALL) {
instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
return req;
} else if (types.isCastable(found, req, castWarner(pos, found, req))) {
return req;
} else {
return typeError(pos,
diags.fragment("inconvertible.types"),
found, req);
}
}
//where
/** Is type a type variable, or a (possibly multi-dimensional) array of
* type variables?
*/
boolean isTypeVar(Type t) {
return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
}
/** Check that a type is within some bounds.
*
* Used in TypeApply to verify that, e.g., X in V<X> is a valid
* type argument.
* @param pos Position to be used for error reporting.
* @param a The type that should be bounded by bs.
* @param bs The bound.
*/
private boolean checkExtends(Type a, TypeVar bs) {
if (a.isUnbound()) {
return true;
} else if (a.tag != WILDCARD) {
a = types.upperBound(a);
return types.isSubtype(a, bs.bound);
} else if (a.isExtendsBound()) {
return types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings);
} else if (a.isSuperBound()) {
return !types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound());
}
return true;
}
/** Check that type is different from 'void'.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkNonVoid(DiagnosticPosition pos, Type t) {
if (t.tag == VOID) {
log.error(pos, "void.not.allowed.here");
return types.createErrorType(t);
} else {
return t;
}
}
/** Check that type is a class or interface type.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkClassType(DiagnosticPosition pos, Type t) {
if (t.tag != CLASS && t.tag != ERROR)
return typeTagError(pos,
diags.fragment("type.req.class"),
(t.tag == TYPEVAR)
? diags.fragment("type.parameter", t)
: t);
else
return t;
}
/** Check that type is a class or interface type.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
* @param noBounds True if type bounds are illegal here.
*/
Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
t = checkClassType(pos, t);
if (noBounds && t.isParameterized()) {
List<Type> args = t.getTypeArguments();
while (args.nonEmpty()) {
if (args.head.tag == WILDCARD)
return typeTagError(pos,
diags.fragment("type.req.exact"),
args.head);
args = args.tail;
}
}
return t;
}
/** Check that type is a reifiable class, interface or array type.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
return typeTagError(pos,
diags.fragment("type.req.class.array"),
t);
} else if (!types.isReifiable(t)) {
log.error(pos, "illegal.generic.type.for.instof");
return types.createErrorType(t);
} else {
return t;
}
}
/** Check that type is a reference type, i.e. a class, interface or array type
* or a type variable.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkRefType(DiagnosticPosition pos, Type t) {
switch (t.tag) {
case CLASS:
case ARRAY:
case TYPEVAR:
case WILDCARD:
case ERROR:
return t;
default:
return typeTagError(pos,
diags.fragment("type.req.ref"),
t);
}
}
/** Check that each type is a reference type, i.e. a class, interface or array type
* or a type variable.
* @param trees Original trees, used for error reporting.
* @param types The types to be checked.
*/
List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
List<JCExpression> tl = trees;
for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
l.head = checkRefType(tl.head.pos(), l.head);
tl = tl.tail;
}
return types;
}
/** Check that type is a null or reference type.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
switch (t.tag) {
case CLASS:
case ARRAY:
case TYPEVAR:
case WILDCARD:
case BOT:
case ERROR:
return t;
default:
return typeTagError(pos,
diags.fragment("type.req.ref"),
t);
}
}
/** Check that flag set does not contain elements of two conflicting sets. s
* Return true if it doesn't.
* @param pos Position to be used for error reporting.
* @param flags The set of flags to be checked.
* @param set1 Conflicting flags set #1.
* @param set2 Conflicting flags set #2.
*/
boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
if ((flags & set1) != 0 && (flags & set2) != 0) {
log.error(pos,
"illegal.combination.of.modifiers",
asFlagSet(TreeInfo.firstFlag(flags & set1)),
asFlagSet(TreeInfo.firstFlag(flags & set2)));
return false;
} else
return true;
}
/** Check that usage of diamond operator is correct (i.e. diamond should not
* be used with non-generic classes or in anonymous class creation expressions)
*/
Type checkDiamond(JCNewClass tree, Type t) {
if (!TreeInfo.isDiamond(tree) ||
t.isErroneous()) {
return checkClassType(tree.clazz.pos(), t, true);
} else if (tree.def != null) {
log.error(tree.clazz.pos(),
"cant.apply.diamond.1",
t, diags.fragment("diamond.and.anon.class", t));
return types.createErrorType(t);
} else if (t.tsym.type.getTypeArguments().isEmpty()) {
log.error(tree.clazz.pos(),
"cant.apply.diamond.1",
t, diags.fragment("diamond.non.generic", t));
return types.createErrorType(t);
} else if (tree.typeargs != null &&
tree.typeargs.nonEmpty()) {
log.error(tree.clazz.pos(),
"cant.apply.diamond.1",
t, diags.fragment("diamond.and.explicit.params", t));
return types.createErrorType(t);
} else {
return t;
}
}
void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
MethodSymbol m = tree.sym;
if (!allowSimplifiedVarargs) return;
boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
Type varargElemType = null;
if (m.isVarArgs()) {
varargElemType = types.elemtype(tree.params.last().type);
}
if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
if (varargElemType != null) {
log.error(tree,
"varargs.invalid.trustme.anno",
syms.trustMeType.tsym,
diags.fragment("varargs.trustme.on.virtual.varargs", m));
} else {
log.error(tree,
"varargs.invalid.trustme.anno",
syms.trustMeType.tsym,
diags.fragment("varargs.trustme.on.non.varargs.meth", m));
}
} else if (hasTrustMeAnno && varargElemType != null &&
types.isReifiable(varargElemType)) {
warnUnsafeVararg(tree,
"varargs.redundant.trustme.anno",
syms.trustMeType.tsym,
diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
}
else if (!hasTrustMeAnno && varargElemType != null &&
!types.isReifiable(varargElemType)) {
warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
}
}
//where
private boolean isTrustMeAllowedOnMethod(Symbol s) {
return (s.flags() & VARARGS) != 0 &&
(s.isConstructor() ||
(s.flags() & (STATIC | FINAL)) != 0);
}
/**
* Check that vararg method call is sound
* @param pos Position to be used for error reporting.
* @param argtypes Actual arguments supplied to vararg method.
*/
void checkVararg(DiagnosticPosition pos, List<Type> argtypes, Symbol msym) {
Type argtype = argtypes.last();
if (!types.isReifiable(argtype) &&
(!allowSimplifiedVarargs ||
msym.attribute(syms.trustMeType.tsym) == null ||
!isTrustMeAllowedOnMethod(msym))) {
warnUnchecked(pos,
"unchecked.generic.array.creation",
argtype);
}
}
/**
* Check that type 't' is a valid instantiation of a generic class
* (see JLS 4.5)
*
* @param t class type to be checked
* @return true if 't' is well-formed
*/
public boolean checkValidGenericType(Type t) {
return firstIncompatibleTypeArg(t) == null;
}
//WHERE
private Type firstIncompatibleTypeArg(Type type) {
List<Type> formals = type.tsym.type.allparams();
List<Type> actuals = type.allparams();
List<Type> args = type.getTypeArguments();
List<Type> forms = type.tsym.type.getTypeArguments();
ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
// For matching pairs of actual argument types `a' and
// formal type parameters with declared bound `b' ...
while (args.nonEmpty() && forms.nonEmpty()) {
// exact type arguments needs to know their
// bounds (for upper and lower bound
// calculations). So we create new TypeVars with
// bounds substed with actuals.
tvars_buf.append(types.substBound(((TypeVar)forms.head),
formals,
actuals));
args = args.tail;
forms = forms.tail;
}
args = type.getTypeArguments();
List<Type> tvars_cap = types.substBounds(formals,
formals,
types.capture(type).allparams());
while (args.nonEmpty() && tvars_cap.nonEmpty()) {
// Let the actual arguments know their bound
args.head.withTypeVar((TypeVar)tvars_cap.head);
args = args.tail;
tvars_cap = tvars_cap.tail;
}
args = type.getTypeArguments();
List<Type> tvars = tvars_buf.toList();
while (args.nonEmpty() && tvars.nonEmpty()) {
Type actual = types.subst(args.head,
type.tsym.type.getTypeArguments(),
tvars_buf.toList());
if (!isTypeArgErroneous(actual) &&
!tvars.head.getUpperBound().isErroneous() &&
!checkExtends(actual, (TypeVar)tvars.head)) {
return args.head;
}
args = args.tail;
tvars = tvars.tail;
}
args = type.getTypeArguments();
tvars = tvars_buf.toList();
for (Type arg : types.capture(type).getTypeArguments()) {
if (arg.tag == TYPEVAR &&
arg.getUpperBound().isErroneous() &&
!tvars.head.getUpperBound().isErroneous() &&
!isTypeArgErroneous(args.head)) {
return args.head;
}
tvars = tvars.tail;
args = args.tail;
}
return null;
}
//where
boolean isTypeArgErroneous(Type t) {
return isTypeArgErroneous.visit(t);
}
Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
public Boolean visitType(Type t, Void s) {
return t.isErroneous();
}
@Override
public Boolean visitTypeVar(TypeVar t, Void s) {
return visit(t.getUpperBound());
}
@Override
public Boolean visitCapturedType(CapturedType t, Void s) {
return visit(t.getUpperBound()) ||
visit(t.getLowerBound());
}
@Override
public Boolean visitWildcardType(WildcardType t, Void s) {
return visit(t.type);
}
};
/** Check that given modifiers are legal for given symbol and
* return modifiers together with any implicit modififiers for that symbol.
* Warning: we can't use flags() here since this method
* is called during class enter, when flags() would cause a premature
* completion.
* @param pos Position to be used for error reporting.
* @param flags The set of modifiers given in a definition.
* @param sym The defined symbol.
*/
long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
long mask;
long implicit = 0;
switch (sym.kind) {
case VAR:
if (sym.owner.kind != TYP)
mask = LocalVarFlags;
else if ((sym.owner.flags_field & INTERFACE) != 0)
mask = implicit = InterfaceVarFlags;
else
mask = VarFlags;
break;
case MTH:
if (sym.name == names.init) {
if ((sym.owner.flags_field & ENUM) != 0) {
// enum constructors cannot be declared public or
// protected and must be implicitly or explicitly
// private
implicit = PRIVATE;
mask = PRIVATE;
} else
mask = ConstructorFlags;
} else if ((sym.owner.flags_field & INTERFACE) != 0)
mask = implicit = InterfaceMethodFlags;
else {
mask = MethodFlags;
}
// Imply STRICTFP if owner has STRICTFP set.
if (((flags|implicit) & Flags.ABSTRACT) == 0)
implicit |= sym.owner.flags_field & STRICTFP;
break;
case TYP:
if (sym.isLocal()) {
mask = LocalClassFlags;
if (sym.name.isEmpty()) { // Anonymous class
// Anonymous classes in static methods are themselves static;
// that's why we admit STATIC here.
mask |= STATIC;
// JLS: Anonymous classes are final.
implicit |= FINAL;
}
if ((sym.owner.flags_field & STATIC) == 0 &&
(flags & ENUM) != 0)
log.error(pos, "enums.must.be.static");
} else if (sym.owner.kind == TYP) {
mask = MemberClassFlags;
if (sym.owner.owner.kind == PCK ||
(sym.owner.flags_field & STATIC) != 0)
mask |= STATIC;
else if ((flags & ENUM) != 0)
log.error(pos, "enums.must.be.static");
// Nested interfaces and enums are always STATIC (Spec ???)
if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
} else {
mask = ClassFlags;
}
// Interfaces are always ABSTRACT
if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
if ((flags & ENUM) != 0) {
// enums can't be declared abstract or final
mask &= ~(ABSTRACT | FINAL);
implicit |= implicitEnumFinalFlag(tree);
}
// Imply STRICTFP if owner has STRICTFP set.
implicit |= sym.owner.flags_field & STRICTFP;
break;
default:
throw new AssertionError();
}
long illegal = flags & StandardFlags & ~mask;
if (illegal != 0) {
if ((illegal & INTERFACE) != 0) {
log.error(pos, "intf.not.allowed.here");
mask |= INTERFACE;
}
else {
log.error(pos,
"mod.not.allowed.here", asFlagSet(illegal));
}
}
else if ((sym.kind == TYP ||
// ISSUE: Disallowing abstract&private is no longer appropriate
// in the presence of inner classes. Should it be deleted here?
checkDisjoint(pos, flags,
ABSTRACT,
PRIVATE | STATIC))
&&
checkDisjoint(pos, flags,
ABSTRACT | INTERFACE,
FINAL | NATIVE | SYNCHRONIZED)
&&
checkDisjoint(pos, flags,
PUBLIC,
PRIVATE | PROTECTED)
&&
checkDisjoint(pos, flags,
PRIVATE,
PUBLIC | PROTECTED)
&&
checkDisjoint(pos, flags,
FINAL,
VOLATILE)
&&
(sym.kind == TYP ||
checkDisjoint(pos, flags,
ABSTRACT | NATIVE,
STRICTFP))) {
// skip
}
return flags & (mask | ~StandardFlags) | implicit;
}
/** Determine if this enum should be implicitly final.
*
* If the enum has no specialized enum contants, it is final.
*
* If the enum does have specialized enum contants, it is
* <i>not</i> final.
*/
private long implicitEnumFinalFlag(JCTree tree) {
if (tree.getTag() != JCTree.CLASSDEF) return 0;
class SpecialTreeVisitor extends JCTree.Visitor {
boolean specialized;
SpecialTreeVisitor() {
this.specialized = false;
};
@Override
public void visitTree(JCTree tree) { /* no-op */ }
@Override
public void visitVarDef(JCVariableDecl tree) {
if ((tree.mods.flags & ENUM) != 0) {
if (tree.init instanceof JCNewClass &&
((JCNewClass) tree.init).def != null) {
specialized = true;
}
}
}
}
SpecialTreeVisitor sts = new SpecialTreeVisitor();
JCClassDecl cdef = (JCClassDecl) tree;
for (JCTree defs: cdef.defs) {
defs.accept(sts);
if (sts.specialized) return 0;
}
return FINAL;
}
/* *************************************************************************
* Type Validation
**************************************************************************/
/** Validate a type expression. That is,
* check that all type arguments of a parametric type are within
* their bounds. This must be done in a second phase after type attributon
* since a class might have a subclass as type parameter bound. E.g:
*
* class B<A extends C> { ... }
* class C extends B<C> { ... }
*
* and we can't make sure that the bound is already attributed because
* of possible cycles.
*
* Visitor method: Validate a type expression, if it is not null, catching
* and reporting any completion failures.
*/
void validate(JCTree tree, Env<AttrContext> env) {
validate(tree, env, true);
}
void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
new Validator(env).validateTree(tree, checkRaw, true);
}
/** Visitor method: Validate a list of type expressions.
*/
void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
validate(l.head, env);
}
/** A visitor class for type validation.
*/
class Validator extends JCTree.Visitor {
boolean isOuter;
Env<AttrContext> env;
Validator(Env<AttrContext> env) {
this.env = env;
}
@Override
public void visitTypeArray(JCArrayTypeTree tree) {
tree.elemtype.accept(this);
}
@Override
public void visitTypeApply(JCTypeApply tree) {
if (tree.type.tag == CLASS) {
List<JCExpression> args = tree.arguments;
List<Type> forms = tree.type.tsym.type.getTypeArguments();
Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
if (incompatibleArg != null) {
for (JCTree arg : tree.arguments) {
if (arg.type == incompatibleArg) {
log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
}
forms = forms.tail;
}
}
forms = tree.type.tsym.type.getTypeArguments();
boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
// For matching pairs of actual argument types `a' and
// formal type parameters with declared bound `b' ...
while (args.nonEmpty() && forms.nonEmpty()) {
validateTree(args.head,
!(isOuter && is_java_lang_Class),
false);
args = args.tail;
forms = forms.tail;
}
// Check that this type is either fully parameterized, or
// not parameterized at all.
if (tree.type.getEnclosingType().isRaw())
log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
if (tree.clazz.getTag() == JCTree.SELECT)
visitSelectInternal((JCFieldAccess)tree.clazz);
}
}
@Override
public void visitTypeParameter(JCTypeParameter tree) {
validateTrees(tree.bounds, true, isOuter);
checkClassBounds(tree.pos(), tree.type);
}
@Override
public void visitWildcard(JCWildcard tree) {
if (tree.inner != null)
validateTree(tree.inner, true, isOuter);
}
@Override
public void visitSelect(JCFieldAccess tree) {
if (tree.type.tag == CLASS) {
visitSelectInternal(tree);
// Check that this type is either fully parameterized, or
// not parameterized at all.
if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
log.error(tree.pos(), "improperly.formed.type.param.missing");
}
}
public void visitSelectInternal(JCFieldAccess tree) {
if (tree.type.tsym.isStatic() &&
tree.selected.type.isParameterized()) {
// The enclosing type is not a class, so we are
// looking at a static member type. However, the
// qualifying expression is parameterized.
log.error(tree.pos(), "cant.select.static.class.from.param.type");
} else {
// otherwise validate the rest of the expression
tree.selected.accept(this);
}
}
/** Default visitor method: do nothing.
*/
@Override
public void visitTree(JCTree tree) {
}
public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
try {
if (tree != null) {
this.isOuter = isOuter;
tree.accept(this);
if (checkRaw)
checkRaw(tree, env);
}
} catch (CompletionFailure ex) {
completionError(tree.pos(), ex);
}
}
public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
validateTree(l.head, checkRaw, isOuter);
}
void checkRaw(JCTree tree, Env<AttrContext> env) {
if (lint.isEnabled(LintCategory.RAW) &&
tree.type.tag == CLASS &&
!TreeInfo.isDiamond(tree) &&
!env.enclClass.name.isEmpty() && //anonymous or intersection
tree.type.isRaw()) {
log.warning(LintCategory.RAW,
tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
}
}
}
/* *************************************************************************
* Exception checking
**************************************************************************/
/* The following methods treat classes as sets that contain
* the class itself and all their subclasses
*/
/** Is given type a subtype of some of the types in given list?
*/
boolean subset(Type t, List<Type> ts) {
for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
if (types.isSubtype(t, l.head)) return true;
return false;
}
/** Is given type a subtype or supertype of
* some of the types in given list?
*/
boolean intersects(Type t, List<Type> ts) {
for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
return false;
}
/** Add type set to given type list, unless it is a subclass of some class
* in the list.
*/
List<Type> incl(Type t, List<Type> ts) {
return subset(t, ts) ? ts : excl(t, ts).prepend(t);
}
/** Remove type set from type set list.
*/
List<Type> excl(Type t, List<Type> ts) {
if (ts.isEmpty()) {
return ts;
} else {
List<Type> ts1 = excl(t, ts.tail);
if (types.isSubtype(ts.head, t)) return ts1;
else if (ts1 == ts.tail) return ts;
else return ts1.prepend(ts.head);
}
}
/** Form the union of two type set lists.
*/
List<Type> union(List<Type> ts1, List<Type> ts2) {
List<Type> ts = ts1;
for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
ts = incl(l.head, ts);
return ts;
}
/** Form the difference of two type lists.
*/
List<Type> diff(List<Type> ts1, List<Type> ts2) {
List<Type> ts = ts1;
for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
ts = excl(l.head, ts);
return ts;
}
/** Form the intersection of two type lists.
*/
public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
List<Type> ts = List.nil();
for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
if (subset(l.head, ts2)) ts = incl(l.head, ts);
for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
if (subset(l.head, ts1)) ts = incl(l.head, ts);
return ts;
}
/** Is exc an exception symbol that need not be declared?
*/
boolean isUnchecked(ClassSymbol exc) {
return
exc.kind == ERR ||
exc.isSubClass(syms.errorType.tsym, types) ||
exc.isSubClass(syms.runtimeExceptionType.tsym, types);
}
/** Is exc an exception type that need not be declared?
*/
boolean isUnchecked(Type exc) {
return
(exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
(exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
exc.tag == BOT;
}
/** Same, but handling completion failures.
*/
boolean isUnchecked(DiagnosticPosition pos, Type exc) {
try {
return isUnchecked(exc);
} catch (CompletionFailure ex) {
completionError(pos, ex);
return true;
}
}
/** Is exc handled by given exception list?
*/
boolean isHandled(Type exc, List<Type> handled) {
return isUnchecked(exc) || subset(exc, handled);
}
/** Return all exceptions in thrown list that are not in handled list.
* @param thrown The list of thrown exceptions.
* @param handled The list of handled exceptions.
*/
List<Type> unhandled(List<Type> thrown, List<Type> handled) {
List<Type> unhandled = List.nil();
for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
return unhandled;
}
/* *************************************************************************
* Overriding/Implementation checking
**************************************************************************/
/** The level of access protection given by a flag set,
* where PRIVATE is highest and PUBLIC is lowest.
*/
static int protection(long flags) {
switch ((short)(flags & AccessFlags)) {
case PRIVATE: return 3;
case PROTECTED: return 1;
default:
case PUBLIC: return 0;
case 0: return 2;
}
}
/** A customized "cannot override" error message.
* @param m The overriding method.
* @param other The overridden method.
* @return An internationalized string.
*/
Object cannotOverride(MethodSymbol m, MethodSymbol other) {
String key;
if ((other.owner.flags() & INTERFACE) == 0)
key = "cant.override";
else if ((m.owner.flags() & INTERFACE) == 0)
key = "cant.implement";
else
key = "clashes.with";
return diags.fragment(key, m, m.location(), other, other.location());
}
/** A customized "override" warning message.
* @param m The overriding method.
* @param other The overridden method.
* @return An internationalized string.
*/
Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
String key;
if ((other.owner.flags() & INTERFACE) == 0)
key = "unchecked.override";
else if ((m.owner.flags() & INTERFACE) == 0)
key = "unchecked.implement";
else
key = "unchecked.clash.with";
return diags.fragment(key, m, m.location(), other, other.location());
}
/** A customized "override" warning message.
* @param m The overriding method.
* @param other The overridden method.
* @return An internationalized string.
*/
Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
String key;
if ((other.owner.flags() & INTERFACE) == 0)
key = "varargs.override";
else if ((m.owner.flags() & INTERFACE) == 0)
key = "varargs.implement";
else
key = "varargs.clash.with";
return diags.fragment(key, m, m.location(), other, other.location());
}
/** Check that this method conforms with overridden method 'other'.
* where `origin' is the class where checking started.
* Complications:
* (1) Do not check overriding of synthetic methods
* (reason: they might be final).
* todo: check whether this is still necessary.
* (2) Admit the case where an interface proxy throws fewer exceptions
* than the method it implements. Augment the proxy methods with the
* undeclared exceptions in this case.
* (3) When generics are enabled, admit the case where an interface proxy
* has a result type
* extended by the result type of the method it implements.
* Change the proxies result type to the smaller type in this case.
*
* @param tree The tree from which positions
* are extracted for errors.
* @param m The overriding method.
* @param other The overridden method.
* @param origin The class of which the overriding method
* is a member.
*/
void checkOverride(JCTree tree,
MethodSymbol m,
MethodSymbol other,
ClassSymbol origin) {
// Don't check overriding of synthetic methods or by bridge methods.
if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
return;
}
// Error if static method overrides instance method (JLS 8.4.6.2).
if ((m.flags() & STATIC) != 0 &&
(other.flags() & STATIC) == 0) {
log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
cannotOverride(m, other));
return;
}
// Error if instance method overrides static or final
// method (JLS 8.4.6.1).
if ((other.flags() & FINAL) != 0 ||
(m.flags() & STATIC) == 0 &&
(other.flags() & STATIC) != 0) {
log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
cannotOverride(m, other),
asFlagSet(other.flags() & (FINAL | STATIC)));
return;
}
if ((m.owner.flags() & ANNOTATION) != 0) {
// handled in validateAnnotationMethod
return;
}
// Error if overriding method has weaker access (JLS 8.4.6.3).
if ((origin.flags() & INTERFACE) == 0 &&
protection(m.flags()) > protection(other.flags())) {
log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
cannotOverride(m, other),
other.flags() == 0 ?
Flag.PACKAGE :
asFlagSet(other.flags() & AccessFlags));
return;
}
Type mt = types.memberType(origin.type, m);
Type ot = types.memberType(origin.type, other);
// Error if overriding result type is different
// (or, in the case of generics mode, not a subtype) of
// overridden result type. We have to rename any type parameters
// before comparing types.
List<Type> mtvars = mt.getTypeArguments();
List<Type> otvars = ot.getTypeArguments();
Type mtres = mt.getReturnType();
Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
overrideWarner.clear();
boolean resultTypesOK =
types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
if (!resultTypesOK) {
if (!allowCovariantReturns &&
m.owner != origin &&
m.owner.isSubClass(other.owner, types)) {
// allow limited interoperability with covariant returns
} else {
log.error(TreeInfo.diagnosticPositionFor(m, tree),
"override.incompatible.ret",
cannotOverride(m, other),
mtres, otres);
return;
}
} else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
"override.unchecked.ret",
uncheckedOverrides(m, other),
mtres, otres);
}
// Error if overriding method throws an exception not reported
// by overridden method.
List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
if (unhandledErased.nonEmpty()) {
log.error(TreeInfo.diagnosticPositionFor(m, tree),
"override.meth.doesnt.throw",
cannotOverride(m, other),
unhandledUnerased.head);
return;
}
else if (unhandledUnerased.nonEmpty()) {
warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
"override.unchecked.thrown",
cannotOverride(m, other),
unhandledUnerased.head);
return;
}
// Optional warning if varargs don't agree
if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
&& lint.isEnabled(LintCategory.OVERRIDES)) {
log.warning(TreeInfo.diagnosticPositionFor(m, tree),
((m.flags() & Flags.VARARGS) != 0)
? "override.varargs.missing"
: "override.varargs.extra",
varargsOverrides(m, other));
}
// Warn if instance method overrides bridge method (compiler spec ??)
if ((other.flags() & BRIDGE) != 0) {
log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
uncheckedOverrides(m, other));
}
// Warn if a deprecated method overridden by a non-deprecated one.
if (!isDeprecatedOverrideIgnorable(other, origin)) {
checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
}
}
// where
private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
// If the method, m, is defined in an interface, then ignore the issue if the method
// is only inherited via a supertype and also implemented in the supertype,
// because in that case, we will rediscover the issue when examining the method
// in the supertype.
// If the method, m, is not defined in an interface, then the only time we need to
// address the issue is when the method is the supertype implemementation: any other
// case, we will have dealt with when examining the supertype classes
ClassSymbol mc = m.enclClass();
Type st = types.supertype(origin.type);
if (st.tag != CLASS)
return true;
MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
List<Type> intfs = types.interfaces(origin.type);
return (intfs.contains(mc.type) ? false : (stimpl != null));
}
else
return (stimpl != m);
}
// used to check if there were any unchecked conversions
Warner overrideWarner = new Warner();
/** Check that a class does not inherit two concrete methods
* with the same signature.
* @param pos Position to be used for error reporting.
* @param site The class type to be checked.
*/
public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
Type sup = types.supertype(site);
if (sup.tag != CLASS) return;
for (Type t1 = sup;
t1.tsym.type.isParameterized();
t1 = types.supertype(t1)) {
for (Scope.Entry e1 = t1.tsym.members().elems;
e1 != null;
e1 = e1.sibling) {
Symbol s1 = e1.sym;
if (s1.kind != MTH ||
(s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
!s1.isInheritedIn(site.tsym, types) ||
((MethodSymbol)s1).implementation(site.tsym,
types,
true) != s1)
continue;
Type st1 = types.memberType(t1, s1);
int s1ArgsLength = st1.getParameterTypes().length();
if (st1 == s1.type) continue;
for (Type t2 = sup;
t2.tag == CLASS;
t2 = types.supertype(t2)) {
for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
e2.scope != null;
e2 = e2.next()) {
Symbol s2 = e2.sym;
if (s2 == s1 ||
s2.kind != MTH ||
(s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
s2.type.getParameterTypes().length() != s1ArgsLength ||
!s2.isInheritedIn(site.tsym, types) ||
((MethodSymbol)s2).implementation(site.tsym,
types,
true) != s2)
continue;
Type st2 = types.memberType(t2, s2);
if (types.overrideEquivalent(st1, st2))
log.error(pos, "concrete.inheritance.conflict",
s1, t1, s2, t2, sup);
}
}
}
}
}
/** Check that classes (or interfaces) do not each define an abstract
* method with same name and arguments but incompatible return types.
* @param pos Position to be used for error reporting.
* @param t1 The first argument type.
* @param t2 The second argument type.
*/
public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
Type t1,
Type t2) {
return checkCompatibleAbstracts(pos, t1, t2,
types.makeCompoundType(t1, t2));
}
public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
Type t1,
Type t2,
Type site) {
return firstIncompatibility(pos, t1, t2, site) == null;
}
/** Return the first method which is defined with same args
* but different return types in two given interfaces, or null if none
* exists.
* @param t1 The first type.
* @param t2 The second type.
* @param site The most derived type.
* @returns symbol from t2 that conflicts with one in t1.
*/
private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
closure(t1, interfaces1);
Map<TypeSymbol,Type> interfaces2;
if (t1 == t2)
interfaces2 = interfaces1;
else
closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
for (Type t3 : interfaces1.values()) {
for (Type t4 : interfaces2.values()) {
Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
if (s != null) return s;
}
}
return null;
}
/** Compute all the supertypes of t, indexed by type symbol. */
private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
if (t.tag != CLASS) return;
if (typeMap.put(t.tsym, t) == null) {
closure(types.supertype(t), typeMap);
for (Type i : types.interfaces(t))
closure(i, typeMap);
}
}
/** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
if (t.tag != CLASS) return;
if (typesSkip.get(t.tsym) != null) return;
if (typeMap.put(t.tsym, t) == null) {
closure(types.supertype(t), typesSkip, typeMap);
for (Type i : types.interfaces(t))
closure(i, typesSkip, typeMap);
}
}
/** Return the first method in t2 that conflicts with a method from t1. */
private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
Symbol s1 = e1.sym;
Type st1 = null;
if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
Symbol s2 = e2.sym;
if (s1 == s2) continue;
if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
if (st1 == null) st1 = types.memberType(t1, s1);
Type st2 = types.memberType(t2, s2);
if (types.overrideEquivalent(st1, st2)) {
List<Type> tvars1 = st1.getTypeArguments();
List<Type> tvars2 = st2.getTypeArguments();
Type rt1 = st1.getReturnType();
Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
boolean compat =
types.isSameType(rt1, rt2) ||
rt1.tag >= CLASS && rt2.tag >= CLASS &&
(types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
checkCommonOverriderIn(s1,s2,site);
if (!compat) {
log.error(pos, "types.incompatible.diff.ret",
t1, t2, s2.name +
"(" + types.memberType(t2, s2).getParameterTypes() + ")");
return s2;
}
} else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
!checkCommonOverriderIn(s1, s2, site)) {
log.error(pos,
"name.clash.same.erasure.no.override",
s1, s1.location(),
s2, s2.location());
return s2;
}
}
}
return null;
}
//WHERE
boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
Type st1 = types.memberType(site, s1);
Type st2 = types.memberType(site, s2);
closure(site, supertypes);
for (Type t : supertypes.values()) {
for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
Symbol s3 = e.sym;
if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
Type st3 = types.memberType(site,s3);
if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
if (s3.owner == site.tsym) {
return true;
}
List<Type> tvars1 = st1.getTypeArguments();
List<Type> tvars2 = st2.getTypeArguments();
List<Type> tvars3 = st3.getTypeArguments();
Type rt1 = st1.getReturnType();
Type rt2 = st2.getReturnType();
Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
boolean compat =
rt13.tag >= CLASS && rt23.tag >= CLASS &&
(types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
types.covariantReturnType(rt23, rt2, Warner.noWarnings));
if (compat)
return true;
}
}
}
return false;
}
/** Check that a given method conforms with any method it overrides.
* @param tree The tree from which positions are extracted
* for errors.
* @param m The overriding method.
*/
void checkOverride(JCTree tree, MethodSymbol m) {
ClassSymbol origin = (ClassSymbol)m.owner;
if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
log.error(tree.pos(), "enum.no.finalize");
return;
}
for (Type t = origin.type; t.tag == CLASS;
t = types.supertype(t)) {
if (t != origin.type) {
checkOverride(tree, t, origin, m);
}
for (Type t2 : types.interfaces(t)) {
checkOverride(tree, t2, origin, m);
}
}
}
void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
TypeSymbol c = site.tsym;
Scope.Entry e = c.members().lookup(m.name);
while (e.scope != null) {
if (m.overrides(e.sym, origin, types, false)) {
if ((e.sym.flags() & ABSTRACT) == 0) {
checkOverride(tree, m, (MethodSymbol)e.sym, origin);
}
}
e = e.next();
}
}
private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
ClashFilter cf = new ClashFilter(origin.type);
return (cf.accepts(s1) &&
cf.accepts(s2) &&
types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
}
/** Check that all abstract members of given class have definitions.
* @param pos Position to be used for error reporting.
* @param c The class.
*/
void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
try {
MethodSymbol undef = firstUndef(c, c);
if (undef != null) {
if ((c.flags() & ENUM) != 0 &&
types.supertype(c.type).tsym == syms.enumSym &&
(c.flags() & FINAL) == 0) {
// add the ABSTRACT flag to an enum
c.flags_field |= ABSTRACT;
} else {
MethodSymbol undef1 =
new MethodSymbol(undef.flags(), undef.name,
types.memberType(c.type, undef), undef.owner);
log.error(pos, "does.not.override.abstract",
c, undef1, undef1.location());
}
}
} catch (CompletionFailure ex) {
completionError(pos, ex);
}
}
//where
/** Return first abstract member of class `c' that is not defined
* in `impl', null if there is none.
*/
private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
MethodSymbol undef = null;
// Do not bother to search in classes that are not abstract,
// since they cannot have abstract members.
if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
Scope s = c.members();
for (Scope.Entry e = s.elems;
undef == null && e != null;
e = e.sibling) {
if (e.sym.kind == MTH &&
(e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
MethodSymbol absmeth = (MethodSymbol)e.sym;
MethodSymbol implmeth = absmeth.implementation(impl, types, true);
if (implmeth == null || implmeth == absmeth)
undef = absmeth;
}
}
if (undef == null) {
Type st = types.supertype(c.type);
if (st.tag == CLASS)
undef = firstUndef(impl, (ClassSymbol)st.tsym);
}
for (List<Type> l = types.interfaces(c.type);
undef == null && l.nonEmpty();
l = l.tail) {
undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
}
}
return undef;
}
void checkNonCyclicDecl(JCClassDecl tree) {
CycleChecker cc = new CycleChecker();
cc.scan(tree);
if (!cc.errorFound && !cc.partialCheck) {
tree.sym.flags_field |= ACYCLIC;
}
}
class CycleChecker extends TreeScanner {
List<Symbol> seenClasses = List.nil();
boolean errorFound = false;
boolean partialCheck = false;
private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
if (sym != null && sym.kind == TYP) {
Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
if (classEnv != null) {
DiagnosticSource prevSource = log.currentSource();
try {
log.useSource(classEnv.toplevel.sourcefile);
scan(classEnv.tree);
}
finally {
log.useSource(prevSource.getFile());
}
} else if (sym.kind == TYP) {
checkClass(pos, sym, List.<JCTree>nil());
}
} else {
//not completed yet
partialCheck = true;
}
}
@Override
public void visitSelect(JCFieldAccess tree) {
super.visitSelect(tree);
checkSymbol(tree.pos(), tree.sym);
}
@Override
public void visitIdent(JCIdent tree) {
checkSymbol(tree.pos(), tree.sym);
}
@Override
public void visitTypeApply(JCTypeApply tree) {
scan(tree.clazz);
}
@Override
public void visitTypeArray(JCArrayTypeTree tree) {
scan(tree.elemtype);
}
@Override
public void visitClassDef(JCClassDecl tree) {
List<JCTree> supertypes = List.nil();
if (tree.getExtendsClause() != null) {
supertypes = supertypes.prepend(tree.getExtendsClause());
}
if (tree.getImplementsClause() != null) {
for (JCTree intf : tree.getImplementsClause()) {
supertypes = supertypes.prepend(intf);
}
}
checkClass(tree.pos(), tree.sym, supertypes);
}
void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
if ((c.flags_field & ACYCLIC) != 0)
return;
if (seenClasses.contains(c)) {
errorFound = true;
noteCyclic(pos, (ClassSymbol)c);
} else if (!c.type.isErroneous()) {
try {
seenClasses = seenClasses.prepend(c);
if (c.type.tag == CLASS) {
if (supertypes.nonEmpty()) {
scan(supertypes);
}
else {
ClassType ct = (ClassType)c.type;
if (ct.supertype_field == null ||
ct.interfaces_field == null) {
//not completed yet
partialCheck = true;
return;
}
checkSymbol(pos, ct.supertype_field.tsym);
for (Type intf : ct.interfaces_field) {
checkSymbol(pos, intf.tsym);
}
}
if (c.owner.kind == TYP) {
checkSymbol(pos, c.owner);
}
}
} finally {
seenClasses = seenClasses.tail;
}
}
}
}
/** Check for cyclic references. Issue an error if the
* symbol of the type referred to has a LOCKED flag set.
*
* @param pos Position to be used for error reporting.
* @param t The type referred to.
*/
void checkNonCyclic(DiagnosticPosition pos, Type t) {
checkNonCyclicInternal(pos, t);
}
void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
checkNonCyclic1(pos, t, List.<TypeVar>nil());
}
private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
final TypeVar tv;
if (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
return;
if (seen.contains(t)) {
tv = (TypeVar)t;
tv.bound = types.createErrorType(t);
log.error(pos, "cyclic.inheritance", t);
} else if (t.tag == TYPEVAR) {
tv = (TypeVar)t;
seen = seen.prepend(tv);
for (Type b : types.getBounds(tv))
checkNonCyclic1(pos, b, seen);
}
}
/** Check for cyclic references. Issue an error if the
* symbol of the type referred to has a LOCKED flag set.
*
* @param pos Position to be used for error reporting.
* @param t The type referred to.
* @returns True if the check completed on all attributed classes
*/
private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
boolean complete = true; // was the check complete?
//- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
Symbol c = t.tsym;
if ((c.flags_field & ACYCLIC) != 0) return true;
if ((c.flags_field & LOCKED) != 0) {
noteCyclic(pos, (ClassSymbol)c);
} else if (!c.type.isErroneous()) {
try {
c.flags_field |= LOCKED;
if (c.type.tag == CLASS) {
ClassType clazz = (ClassType)c.type;
if (clazz.interfaces_field != null)
for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
complete &= checkNonCyclicInternal(pos, l.head);
if (clazz.supertype_field != null) {
Type st = clazz.supertype_field;
if (st != null && st.tag == CLASS)
complete &= checkNonCyclicInternal(pos, st);
}
if (c.owner.kind == TYP)
complete &= checkNonCyclicInternal(pos, c.owner.type);
}
} finally {
c.flags_field &= ~LOCKED;
}
}
if (complete)
complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
if (complete) c.flags_field |= ACYCLIC;
return complete;
}
/** Note that we found an inheritance cycle. */
private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
log.error(pos, "cyclic.inheritance", c);
for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
Type st = types.supertype(c.type);
if (st.tag == CLASS)
((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
c.type = types.createErrorType(c, c.type);
c.flags_field |= ACYCLIC;
}
/** Check that all methods which implement some
* method conform to the method they implement.
* @param tree The class definition whose members are checked.
*/
void checkImplementations(JCClassDecl tree) {
checkImplementations(tree, tree.sym);
}
//where
/** Check that all methods which implement some
* method in `ic' conform to the method they implement.
*/
void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
ClassSymbol origin = tree.sym;
for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
ClassSymbol lc = (ClassSymbol)l.head.tsym;
if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
if (e.sym.kind == MTH &&
(e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
MethodSymbol absmeth = (MethodSymbol)e.sym;
MethodSymbol implmeth = absmeth.implementation(origin, types, false);
if (implmeth != null && implmeth != absmeth &&
(implmeth.owner.flags() & INTERFACE) ==
(origin.flags() & INTERFACE)) {
// don't check if implmeth is in a class, yet
// origin is an interface. This case arises only
// if implmeth is declared in Object. The reason is
// that interfaces really don't inherit from
// Object it's just that the compiler represents
// things that way.
checkOverride(tree, implmeth, absmeth, origin);
}
}
}
}
}
}
/** Check that all abstract methods implemented by a class are
* mutually compatible.
* @param pos Position to be used for error reporting.
* @param c The class whose interfaces are checked.
*/
void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
List<Type> supertypes = types.interfaces(c);
Type supertype = types.supertype(c);
if (supertype.tag == CLASS &&
(supertype.tsym.flags() & ABSTRACT) != 0)
supertypes = supertypes.prepend(supertype);
for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
!checkCompatibleAbstracts(pos, l.head, l.head, c))
return;
for (List<Type> m = supertypes; m != l; m = m.tail)
if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
return;
}
checkCompatibleConcretes(pos, c);
}
void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
// VM allows methods and variables with differing types
if (sym.kind == e.sym.kind &&
types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
sym != e.sym &&
(sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
(sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
(sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
return;
}
}
}
}
/** Check that all non-override equivalent methods accessible from 'site'
* are mutually compatible (JLS 8.4.8/9.4.1).
*
* @param pos Position to be used for error reporting.
* @param site The class whose methods are checked.
* @param sym The method symbol to be checked.
*/
void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
ClashFilter cf = new ClashFilter(site);
//for each method m1 that is overridden (directly or indirectly)
//by method 'sym' in 'site'...
for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
if (!sym.overrides(m1, site.tsym, types, false)) continue;
//...check each method m2 that is a member of 'site'
for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
if (m2 == m1) continue;
//if (i) the signature of 'sym' is not a subsignature of m1 (seen as
//a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
sym.flags_field |= CLASH;
String key = m1 == sym ?
"name.clash.same.erasure.no.override" :
"name.clash.same.erasure.no.override.1";
log.error(pos,
key,
sym, sym.location(),
m2, m2.location(),
m1, m1.location());
return;
}
}
}
}
/** Check that all static methods accessible from 'site' are
* mutually compatible (JLS 8.4.8).
*
* @param pos Position to be used for error reporting.
* @param site The class whose methods are checked.
* @param sym The method symbol to be checked.
*/
void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
ClashFilter cf = new ClashFilter(site);
//for each method m1 that is a member of 'site'...
for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
//if (i) the signature of 'sym' is not a subsignature of m1 (seen as
//a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
log.error(pos,
"name.clash.same.erasure.no.hide",
sym, sym.location(),
s, s.location());
return;
}
}
}
//where
private class ClashFilter implements Filter<Symbol> {
Type site;
ClashFilter(Type site) {
this.site = site;
}
boolean shouldSkip(Symbol s) {
return (s.flags() & CLASH) != 0 &&
s.owner == site.tsym;
}
public boolean accepts(Symbol s) {
return s.kind == MTH &&
(s.flags() & SYNTHETIC) == 0 &&
!shouldSkip(s) &&
s.isInheritedIn(site.tsym, types) &&
!s.isConstructor();
}
}
/** Report a conflict between a user symbol and a synthetic symbol.
*/
private void syntheticError(DiagnosticPosition pos, Symbol sym) {
if (!sym.type.isErroneous()) {
if (warnOnSyntheticConflicts) {
log.warning(pos, "synthetic.name.conflict", sym, sym.location());
}
else {
log.error(pos, "synthetic.name.conflict", sym, sym.location());
}
}
}
/** Check that class c does not implement directly or indirectly
* the same parameterized interface with two different argument lists.
* @param pos Position to be used for error reporting.
* @param type The type whose interfaces are checked.
*/
void checkClassBounds(DiagnosticPosition pos, Type type) {
checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
}
//where
/** Enter all interfaces of type `type' into the hash table `seensofar'
* with their class symbol as key and their type as value. Make
* sure no class is entered with two different types.
*/
void checkClassBounds(DiagnosticPosition pos,
Map<TypeSymbol,Type> seensofar,
Type type) {
if (type.isErroneous()) return;
for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
Type it = l.head;
Type oldit = seensofar.put(it.tsym, it);
if (oldit != null) {
List<Type> oldparams = oldit.allparams();
List<Type> newparams = it.allparams();
if (!types.containsTypeEquivalent(oldparams, newparams))
log.error(pos, "cant.inherit.diff.arg",
it.tsym, Type.toString(oldparams),
Type.toString(newparams));
}
checkClassBounds(pos, seensofar, it);
}
Type st = types.supertype(type);
if (st != null) checkClassBounds(pos, seensofar, st);
}
/** Enter interface into into set.
* If it existed already, issue a "repeated interface" error.
*/
void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
if (its.contains(it))
log.error(pos, "repeated.interface");
else {
its.add(it);
}
}
/* *************************************************************************
* Check annotations
**************************************************************************/
/**
* Recursively validate annotations values
*/
void validateAnnotationTree(JCTree tree) {
class AnnotationValidator extends TreeScanner {
@Override
public void visitAnnotation(JCAnnotation tree) {
if (!tree.type.isErroneous()) {
super.visitAnnotation(tree);
validateAnnotation(tree);
}
}
}
tree.accept(new AnnotationValidator());
}
/** Annotation types are restricted to primitives, String, an
* enum, an annotation, Class, Class<?>, Class<? extends
* Anything>, arrays of the preceding.
*/
void validateAnnotationType(JCTree restype) {
// restype may be null if an error occurred, so don't bother validating it
if (restype != null) {
validateAnnotationType(restype.pos(), restype.type);
}
}
void validateAnnotationType(DiagnosticPosition pos, Type type) {
if (type.isPrimitive()) return;
if (types.isSameType(type, syms.stringType)) return;
if ((type.tsym.flags() & Flags.ENUM) != 0) return;
if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
if (types.lowerBound(type).tsym == syms.classType.tsym) return;
if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
validateAnnotationType(pos, types.elemtype(type));
return;
}
log.error(pos, "invalid.annotation.member.type");
}
/**
* "It is also a compile-time error if any method declared in an
* annotation type has a signature that is override-equivalent to
* that of any public or protected method declared in class Object
* or in the interface annotation.Annotation."
*
* @jls 9.6 Annotation Types
*/
void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
Scope s = sup.tsym.members();
for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
if (e.sym.kind == MTH &&
(e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
types.overrideEquivalent(m.type, e.sym.type))
log.error(pos, "intf.annotation.member.clash", e.sym, sup);
}
}
}
/** Check the annotations of a symbol.
*/
public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
if (skipAnnotations) return;
for (JCAnnotation a : annotations)
validateAnnotation(a, s);
}
/** Check an annotation of a symbol.
*/
public void validateAnnotation(JCAnnotation a, Symbol s) {
validateAnnotationTree(a);
if (!annotationApplicable(a, s))
log.error(a.pos(), "annotation.type.not.applicable");
if (a.annotationType.type.tsym == syms.overrideType.tsym) {
if (!isOverrider(s))
log.error(a.pos(), "method.does.not.override.superclass");
}
}
/** Is s a method symbol that overrides a method in a superclass? */
boolean isOverrider(Symbol s) {
if (s.kind != MTH || s.isStatic())
return false;
MethodSymbol m = (MethodSymbol)s;
TypeSymbol owner = (TypeSymbol)m.owner;
for (Type sup : types.closure(owner.type)) {
if (sup == owner.type)
continue; // skip "this"
Scope scope = sup.tsym.members();
for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
return true;
}
}
return false;
}
/** Is the annotation applicable to the symbol? */
boolean annotationApplicable(JCAnnotation a, Symbol s) {
Attribute.Compound atTarget =
a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
if (atTarget == null) return true;
Attribute atValue = atTarget.member(names.value);
if (!(atValue instanceof Attribute.Array)) return true; // error recovery
Attribute.Array arr = (Attribute.Array) atValue;
for (Attribute app : arr.values) {
if (!(app instanceof Attribute.Enum)) return true; // recovery
Attribute.Enum e = (Attribute.Enum) app;
if (e.value.name == names.TYPE)
{ if (s.kind == TYP) return true; }
else if (e.value.name == names.FIELD)
{ if (s.kind == VAR && s.owner.kind != MTH) return true; }
else if (e.value.name == names.METHOD)
{ if (s.kind == MTH && !s.isConstructor()) return true; }
else if (e.value.name == names.PARAMETER)
{ if (s.kind == VAR &&
s.owner.kind == MTH &&
(s.flags() & PARAMETER) != 0)
return true;
}
else if (e.value.name == names.CONSTRUCTOR)
{ if (s.kind == MTH && s.isConstructor()) return true; }
else if (e.value.name == names.LOCAL_VARIABLE)
{ if (s.kind == VAR && s.owner.kind == MTH &&
(s.flags() & PARAMETER) == 0)
return true;
}
else if (e.value.name == names.ANNOTATION_TYPE)
{ if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
return true;
}
else if (e.value.name == names.PACKAGE)
{ if (s.kind == PCK) return true; }
else if (e.value.name == names.TYPE_USE)
{ if (s.kind == TYP ||
s.kind == VAR ||
(s.kind == MTH && !s.isConstructor() &&
s.type.getReturnType().tag != VOID))
return true;
}
else
return true; // recovery
}
return false;
}
/** Check an annotation value.
*/
public void validateAnnotation(JCAnnotation a) {
// collect an inventory of the members (sorted alphabetically)
Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
public int compare(Symbol t, Symbol t1) {
return t.name.compareTo(t1.name);
}
});
for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
e != null;
e = e.sibling)
if (e.sym.kind == MTH)
members.add((MethodSymbol) e.sym);
// count them off as they're annotated
for (JCTree arg : a.args) {
if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
JCAssign assign = (JCAssign) arg;
Symbol m = TreeInfo.symbol(assign.lhs);
if (m == null || m.type.isErroneous()) continue;
if (!members.remove(m))
log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
m.name, a.type);
}
// all the remaining ones better have default values
ListBuffer<Name> missingDefaults = ListBuffer.lb();
for (MethodSymbol m : members) {
if (m.defaultValue == null && !m.type.isErroneous()) {
missingDefaults.append(m.name);
}
}
if (missingDefaults.nonEmpty()) {
String key = (missingDefaults.size() > 1)
? "annotation.missing.default.value.1"
: "annotation.missing.default.value";
log.error(a.pos(), key, a.type, missingDefaults);
}
// special case: java.lang.annotation.Target must not have
// repeated values in its value member
if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
a.args.tail == null)
return;
if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
JCAssign assign = (JCAssign) a.args.head;
Symbol m = TreeInfo.symbol(assign.lhs);
if (m.name != names.value) return;
JCTree rhs = assign.rhs;
if (rhs.getTag() != JCTree.NEWARRAY) return;
JCNewArray na = (JCNewArray) rhs;
Set<Symbol> targets = new HashSet<Symbol>();
for (JCTree elem : na.elems) {
if (!targets.add(TreeInfo.symbol(elem))) {
log.error(elem.pos(), "repeated.annotation.target");
}
}
}
void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
if (allowAnnotations &&
lint.isEnabled(LintCategory.DEP_ANN) &&
(s.flags() & DEPRECATED) != 0 &&
!syms.deprecatedType.isErroneous() &&
s.attribute(syms.deprecatedType.tsym) == null) {
log.warning(LintCategory.DEP_ANN,
pos, "missing.deprecated.annotation");
}
}
void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
if ((s.flags() & DEPRECATED) != 0 &&
(other.flags() & DEPRECATED) == 0 &&
s.outermostClass() != other.outermostClass()) {
deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
@Override
public void report() {
warnDeprecated(pos, s);
}
});
};
}
void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
if ((s.flags() & PROPRIETARY) != 0) {
deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
public void report() {
if (enableSunApiLintControl)
warnSunApi(pos, "sun.proprietary", s);
else
log.strictWarning(pos, "sun.proprietary", s);
}
});
}
}
/* *************************************************************************
* Check for recursive annotation elements.
**************************************************************************/
/** Check for cycles in the graph of annotation elements.
*/
void checkNonCyclicElements(JCClassDecl tree) {
if ((tree.sym.flags_field & ANNOTATION) == 0) return;
Assert.check((tree.sym.flags_field & LOCKED) == 0);
try {
tree.sym.flags_field |= LOCKED;
for (JCTree def : tree.defs) {
if (def.getTag() != JCTree.METHODDEF) continue;
JCMethodDecl meth = (JCMethodDecl)def;
checkAnnotationResType(meth.pos(), meth.restype.type);
}
} finally {
tree.sym.flags_field &= ~LOCKED;
tree.sym.flags_field |= ACYCLIC_ANN;
}
}
void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
if ((tsym.flags_field & ACYCLIC_ANN) != 0)
return;
if ((tsym.flags_field & LOCKED) != 0) {
log.error(pos, "cyclic.annotation.element");
return;
}
try {
tsym.flags_field |= LOCKED;
for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
Symbol s = e.sym;
if (s.kind != Kinds.MTH)
continue;
checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
}
} finally {
tsym.flags_field &= ~LOCKED;
tsym.flags_field |= ACYCLIC_ANN;
}
}
void checkAnnotationResType(DiagnosticPosition pos, Type type) {
switch (type.tag) {
case TypeTags.CLASS:
if ((type.tsym.flags() & ANNOTATION) != 0)
checkNonCyclicElementsInternal(pos, type.tsym);
break;
case TypeTags.ARRAY:
checkAnnotationResType(pos, types.elemtype(type));
break;
default:
break; // int etc
}
}
/* *************************************************************************
* Check for cycles in the constructor call graph.
**************************************************************************/
/** Check for cycles in the graph of constructors calling other
* constructors.
*/
void checkCyclicConstructors(JCClassDecl tree) {
Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
// enter each constructor this-call into the map
for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
if (app == null) continue;
JCMethodDecl meth = (JCMethodDecl) l.head;
if (TreeInfo.name(app.meth) == names._this) {
callMap.put(meth.sym, TreeInfo.symbol(app.meth));
} else {
meth.sym.flags_field |= ACYCLIC;
}
}
// Check for cycles in the map
Symbol[] ctors = new Symbol[0];
ctors = callMap.keySet().toArray(ctors);
for (Symbol caller : ctors) {
checkCyclicConstructor(tree, caller, callMap);
}
}
/** Look in the map to see if the given constructor is part of a
* call cycle.
*/
private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
Map<Symbol,Symbol> callMap) {
if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
if ((ctor.flags_field & LOCKED) != 0) {
log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
"recursive.ctor.invocation");
} else {
ctor.flags_field |= LOCKED;
checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
ctor.flags_field &= ~LOCKED;
}
ctor.flags_field |= ACYCLIC;
}
}
/* *************************************************************************
* Miscellaneous
**************************************************************************/
/**
* Return the opcode of the operator but emit an error if it is an
* error.
* @param pos position for error reporting.
* @param operator an operator
* @param tag a tree tag
* @param left type of left hand side
* @param right type of right hand side
*/
int checkOperator(DiagnosticPosition pos,
OperatorSymbol operator,
int tag,
Type left,
Type right) {
if (operator.opcode == ByteCodes.error) {
log.error(pos,
"operator.cant.be.applied.1",
treeinfo.operatorName(tag),
left, right);
}
return operator.opcode;
}
/**
* Check for division by integer constant zero
* @param pos Position for error reporting.
* @param operator The operator for the expression
* @param operand The right hand operand for the expression
*/
void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
if (operand.constValue() != null
&& lint.isEnabled(LintCategory.DIVZERO)
&& operand.tag <= LONG
&& ((Number) (operand.constValue())).longValue() == 0) {
int opc = ((OperatorSymbol)operator).opcode;
if (opc == ByteCodes.idiv || opc == ByteCodes.imod
|| opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
log.warning(LintCategory.DIVZERO, pos, "div.zero");
}
}
}
/**
* Check for empty statements after if
*/
void checkEmptyIf(JCIf tree) {
if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(LintCategory.EMPTY))
log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
}
/** Check that symbol is unique in given scope.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope.
*/
boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
if (sym.type.isErroneous())
return true;
if (sym.owner.name == names.any) return false;
for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
if (sym != e.sym &&
(e.sym.flags() & CLASH) == 0 &&
sym.kind == e.sym.kind &&
sym.name != names.error &&
(sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
varargsDuplicateError(pos, sym, e.sym);
return true;
} else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
duplicateErasureError(pos, sym, e.sym);
sym.flags_field |= CLASH;
return true;
} else {
duplicateError(pos, e.sym);
return false;
}
}
}
return true;
}
/** Report duplicate declaration error.
*/
void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
log.error(pos, "name.clash.same.erasure", sym1, sym2);
}
}
/** Check that single-type import is not already imported or top-level defined,
* but make an exception for two single-type imports which denote the same type.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope
*/
boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
return checkUniqueImport(pos, sym, s, false);
}
/** Check that static single-type import is not already imported or top-level defined,
* but make an exception for two single-type imports which denote the same type.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope
* @param staticImport Whether or not this was a static import
*/
boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
return checkUniqueImport(pos, sym, s, true);
}
/** Check that single-type import is not already imported or top-level defined,
* but make an exception for two single-type imports which denote the same type.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope.
* @param staticImport Whether or not this was a static import
*/
private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
// is encountered class entered via a class declaration?
boolean isClassDecl = e.scope == s;
if ((isClassDecl || sym != e.sym) &&
sym.kind == e.sym.kind &&
sym.name != names.error) {
if (!e.sym.type.isErroneous()) {
String what = e.sym.toString();
if (!isClassDecl) {
if (staticImport)
log.error(pos, "already.defined.static.single.import", what);
else
log.error(pos, "already.defined.single.import", what);
}
else if (sym != e.sym)
log.error(pos, "already.defined.this.unit", what);
}
return false;
}
}
return true;
}
/** Check that a qualified name is in canonical form (for import decls).
*/
public void checkCanonical(JCTree tree) {
if (!isCanonical(tree))
log.error(tree.pos(), "import.requires.canonical",
TreeInfo.symbol(tree));
}
// where
private boolean isCanonical(JCTree tree) {
while (tree.getTag() == JCTree.SELECT) {
JCFieldAccess s = (JCFieldAccess) tree;
if (s.sym.owner != TreeInfo.symbol(s.selected))
return false;
tree = s.selected;
}
return true;
}
private class ConversionWarner extends Warner {
final String uncheckedKey;
final Type found;
final Type expected;
public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
super(pos);
this.uncheckedKey = uncheckedKey;
this.found = found;
this.expected = expected;
}
@Override
public void warn(LintCategory lint) {
boolean warned = this.warned;
super.warn(lint);
if (warned) return; // suppress redundant diagnostics
switch (lint) {
case UNCHECKED:
Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
break;
case VARARGS:
if (method != null &&
method.attribute(syms.trustMeType.tsym) != null &&
isTrustMeAllowedOnMethod(method) &&
!types.isReifiable(method.type.getParameterTypes().last())) {
Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
}
break;
default:
throw new AssertionError("Unexpected lint: " + lint);
}
}
}
public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
}
public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
return new ConversionWarner(pos, "unchecked.assign", found, expected);
}
}
| 114,048 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
MemberEnter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.comp;
import java.util.*;
import java.util.Set;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.tree.JCTree.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
/** This is the second phase of Enter, in which classes are completed
* by entering their members into the class scope using
* MemberEnter.complete(). See Enter for an overview.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class MemberEnter extends JCTree.Visitor implements Completer {
protected static final Context.Key<MemberEnter> memberEnterKey =
new Context.Key<MemberEnter>();
/** A switch to determine whether we check for package/class conflicts
*/
final static boolean checkClash = true;
private final Names names;
private final Enter enter;
private final Log log;
private final Check chk;
private final Attr attr;
private final Symtab syms;
private final TreeMaker make;
private final ClassReader reader;
private final Todo todo;
private final Annotate annotate;
private final Types types;
private final JCDiagnostic.Factory diags;
private final Target target;
private final DeferredLintHandler deferredLintHandler;
private final boolean skipAnnotations;
public static MemberEnter instance(Context context) {
MemberEnter instance = context.get(memberEnterKey);
if (instance == null)
instance = new MemberEnter(context);
return instance;
}
protected MemberEnter(Context context) {
context.put(memberEnterKey, this);
names = Names.instance(context);
enter = Enter.instance(context);
log = Log.instance(context);
chk = Check.instance(context);
attr = Attr.instance(context);
syms = Symtab.instance(context);
make = TreeMaker.instance(context);
reader = ClassReader.instance(context);
todo = Todo.instance(context);
annotate = Annotate.instance(context);
types = Types.instance(context);
diags = JCDiagnostic.Factory.instance(context);
target = Target.instance(context);
deferredLintHandler = DeferredLintHandler.instance(context);
Options options = Options.instance(context);
skipAnnotations = options.isSet("skipAnnotations");
}
/** A queue for classes whose members still need to be entered into the
* symbol table.
*/
ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
/** Set to true only when the first of a set of classes is
* processed from the halfcompleted queue.
*/
boolean isFirst = true;
/** A flag to disable completion from time to time during member
* enter, as we only need to look up types. This avoids
* unnecessarily deep recursion.
*/
boolean completionEnabled = true;
/* ---------- Processing import clauses ----------------
*/
/** Import all classes of a class or package on demand.
* @param pos Position to be used for error reporting.
* @param tsym The class or package the members of which are imported.
* @param toScope The (import) scope in which imported classes
* are entered.
*/
private void importAll(int pos,
final TypeSymbol tsym,
Env<AttrContext> env) {
// Check that packages imported from exist (JLS ???).
if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
// If we can't find java.lang, exit immediately.
if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
throw new FatalError(msg);
} else {
log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
}
}
env.toplevel.starImportScope.importAll(tsym.members());
}
/** Import all static members of a class or package on demand.
* @param pos Position to be used for error reporting.
* @param tsym The class or package the members of which are imported.
* @param toScope The (import) scope in which imported classes
* are entered.
*/
private void importStaticAll(int pos,
final TypeSymbol tsym,
Env<AttrContext> env) {
final JavaFileObject sourcefile = env.toplevel.sourcefile;
final Scope toScope = env.toplevel.starImportScope;
final PackageSymbol packge = env.toplevel.packge;
final TypeSymbol origin = tsym;
// enter imported types immediately
new Object() {
Set<Symbol> processed = new HashSet<Symbol>();
void importFrom(TypeSymbol tsym) {
if (tsym == null || !processed.add(tsym))
return;
// also import inherited names
importFrom(types.supertype(tsym.type).tsym);
for (Type t : types.interfaces(tsym.type))
importFrom(t.tsym);
final Scope fromScope = tsym.members();
for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
Symbol sym = e.sym;
if (sym.kind == TYP &&
(sym.flags() & STATIC) != 0 &&
staticImportAccessible(sym, packge) &&
sym.isMemberOf(origin, types) &&
!toScope.includes(sym))
toScope.enter(sym, fromScope, origin.members());
}
}
}.importFrom(tsym);
// enter non-types before annotations that might use them
annotate.earlier(new Annotate.Annotator() {
Set<Symbol> processed = new HashSet<Symbol>();
public String toString() {
return "import static " + tsym + ".*" + " in " + sourcefile;
}
void importFrom(TypeSymbol tsym) {
if (tsym == null || !processed.add(tsym))
return;
// also import inherited names
importFrom(types.supertype(tsym.type).tsym);
for (Type t : types.interfaces(tsym.type))
importFrom(t.tsym);
final Scope fromScope = tsym.members();
for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
Symbol sym = e.sym;
if (sym.isStatic() && sym.kind != TYP &&
staticImportAccessible(sym, packge) &&
!toScope.includes(sym) &&
sym.isMemberOf(origin, types)) {
toScope.enter(sym, fromScope, origin.members());
}
}
}
public void enterAnnotation() {
importFrom(tsym);
}
});
}
// is the sym accessible everywhere in packge?
boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
int flags = (int)(sym.flags() & AccessFlags);
switch (flags) {
default:
case PUBLIC:
return true;
case PRIVATE:
return false;
case 0:
case PROTECTED:
return sym.packge() == packge;
}
}
/** Import statics types of a given name. Non-types are handled in Attr.
* @param pos Position to be used for error reporting.
* @param tsym The class from which the name is imported.
* @param name The (simple) name being imported.
* @param env The environment containing the named import
* scope to add to.
*/
private void importNamedStatic(final DiagnosticPosition pos,
final TypeSymbol tsym,
final Name name,
final Env<AttrContext> env) {
if (tsym.kind != TYP) {
log.error(pos, "static.imp.only.classes.and.interfaces");
return;
}
final Scope toScope = env.toplevel.namedImportScope;
final PackageSymbol packge = env.toplevel.packge;
final TypeSymbol origin = tsym;
// enter imported types immediately
new Object() {
Set<Symbol> processed = new HashSet<Symbol>();
void importFrom(TypeSymbol tsym) {
if (tsym == null || !processed.add(tsym))
return;
// also import inherited names
importFrom(types.supertype(tsym.type).tsym);
for (Type t : types.interfaces(tsym.type))
importFrom(t.tsym);
for (Scope.Entry e = tsym.members().lookup(name);
e.scope != null;
e = e.next()) {
Symbol sym = e.sym;
if (sym.isStatic() &&
sym.kind == TYP &&
staticImportAccessible(sym, packge) &&
sym.isMemberOf(origin, types) &&
chk.checkUniqueStaticImport(pos, sym, toScope))
toScope.enter(sym, sym.owner.members(), origin.members());
}
}
}.importFrom(tsym);
// enter non-types before annotations that might use them
annotate.earlier(new Annotate.Annotator() {
Set<Symbol> processed = new HashSet<Symbol>();
boolean found = false;
public String toString() {
return "import static " + tsym + "." + name;
}
void importFrom(TypeSymbol tsym) {
if (tsym == null || !processed.add(tsym))
return;
// also import inherited names
importFrom(types.supertype(tsym.type).tsym);
for (Type t : types.interfaces(tsym.type))
importFrom(t.tsym);
for (Scope.Entry e = tsym.members().lookup(name);
e.scope != null;
e = e.next()) {
Symbol sym = e.sym;
if (sym.isStatic() &&
staticImportAccessible(sym, packge) &&
sym.isMemberOf(origin, types)) {
found = true;
if (sym.kind == MTH ||
sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope))
toScope.enter(sym, sym.owner.members(), origin.members());
}
}
}
public void enterAnnotation() {
JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
try {
importFrom(tsym);
if (!found) {
log.error(pos, "cant.resolve.location",
KindName.STATIC,
name, List.<Type>nil(), List.<Type>nil(),
Kinds.typeKindName(tsym.type),
tsym.type);
}
} finally {
log.useSource(prev);
}
}
});
}
/** Import given class.
* @param pos Position to be used for error reporting.
* @param tsym The class to be imported.
* @param env The environment containing the named import
* scope to add to.
*/
private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
if (tsym.kind == TYP &&
chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
}
/** Construct method type from method signature.
* @param typarams The method's type parameters.
* @param params The method's value parameters.
* @param res The method's result type,
* null if it is a constructor.
* @param thrown The method's thrown exceptions.
* @param env The method's (local) environment.
*/
Type signature(List<JCTypeParameter> typarams,
List<JCVariableDecl> params,
JCTree res,
List<JCExpression> thrown,
Env<AttrContext> env) {
// Enter and attribute type parameters.
List<Type> tvars = enter.classEnter(typarams, env);
attr.attribTypeVariables(typarams, env);
// Enter and attribute value parameters.
ListBuffer<Type> argbuf = new ListBuffer<Type>();
for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
memberEnter(l.head, env);
argbuf.append(l.head.vartype.type);
}
// Attribute result type, if one is given.
Type restype = res == null ? syms.voidType : attr.attribType(res, env);
// Attribute thrown exceptions.
ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
Type exc = attr.attribType(l.head, env);
if (exc.tag != TYPEVAR)
exc = chk.checkClassType(l.head.pos(), exc);
thrownbuf.append(exc);
}
Type mtype = new MethodType(argbuf.toList(),
restype,
thrownbuf.toList(),
syms.methodClass);
return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
}
/* ********************************************************************
* Visitor methods for member enter
*********************************************************************/
/** Visitor argument: the current environment
*/
protected Env<AttrContext> env;
/** Enter field and method definitions and process import
* clauses, catching any completion failure exceptions.
*/
protected void memberEnter(JCTree tree, Env<AttrContext> env) {
Env<AttrContext> prevEnv = this.env;
try {
this.env = env;
tree.accept(this);
} catch (CompletionFailure ex) {
chk.completionError(tree.pos(), ex);
} finally {
this.env = prevEnv;
}
}
/** Enter members from a list of trees.
*/
void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
memberEnter(l.head, env);
}
/** Enter members for a class.
*/
void finishClass(JCClassDecl tree, Env<AttrContext> env) {
if ((tree.mods.flags & Flags.ENUM) != 0 &&
(types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
addEnumMembers(tree, env);
}
memberEnter(tree.defs, env);
}
/** Add the implicit members for an enum type
* to the symbol table.
*/
private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
// public static T[] values() { return ???; }
JCMethodDecl values = make.
MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
names.values,
valuesType,
List.<JCTypeParameter>nil(),
List.<JCVariableDecl>nil(),
List.<JCExpression>nil(), // thrown
null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
null);
memberEnter(values, env);
// public static T valueOf(String name) { return ???; }
JCMethodDecl valueOf = make.
MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
names.valueOf,
make.Type(tree.sym.type),
List.<JCTypeParameter>nil(),
List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
names.fromString("name"),
make.Type(syms.stringType), null)),
List.<JCExpression>nil(), // thrown
null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
null);
memberEnter(valueOf, env);
// the remaining members are for bootstrapping only
if (!target.compilerBootstrap(tree.sym)) return;
// public final int ordinal() { return ???; }
JCMethodDecl ordinal = make.at(tree.pos).
MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
names.ordinal,
make.Type(syms.intType),
List.<JCTypeParameter>nil(),
List.<JCVariableDecl>nil(),
List.<JCExpression>nil(),
null,
null);
memberEnter(ordinal, env);
// public final String name() { return ???; }
JCMethodDecl name = make.
MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
names._name,
make.Type(syms.stringType),
List.<JCTypeParameter>nil(),
List.<JCVariableDecl>nil(),
List.<JCExpression>nil(),
null,
null);
memberEnter(name, env);
// public int compareTo(E other) { return ???; }
MethodSymbol compareTo = new
MethodSymbol(Flags.PUBLIC,
names.compareTo,
new MethodType(List.of(tree.sym.type),
syms.intType,
List.<Type>nil(),
syms.methodClass),
tree.sym);
memberEnter(make.MethodDef(compareTo, null), env);
}
public void visitTopLevel(JCCompilationUnit tree) {
if (tree.starImportScope.elems != null) {
// we must have already processed this toplevel
return;
}
// check that no class exists with same fully qualified name as
// toplevel package
if (checkClash && tree.pid != null) {
Symbol p = tree.packge;
while (p.owner != syms.rootPackage) {
p.owner.complete(); // enter all class members of p
if (syms.classes.get(p.getQualifiedName()) != null) {
log.error(tree.pos,
"pkg.clashes.with.class.of.same.name",
p);
}
p = p.owner;
}
}
// process package annotations
annotateLater(tree.packageAnnotations, env, tree.packge);
// Import-on-demand java.lang.
importAll(tree.pos, reader.enterPackage(names.java_lang), env);
// Process all import clauses.
memberEnter(tree.defs, env);
}
// process the non-static imports and the static imports of types.
public void visitImport(JCImport tree) {
JCTree imp = tree.qualid;
Name name = TreeInfo.name(imp);
TypeSymbol p;
// Create a local environment pointing to this tree to disable
// effects of other imports in Resolve.findGlobalType
Env<AttrContext> localEnv = env.dup(tree);
// Attribute qualifying package or class.
JCFieldAccess s = (JCFieldAccess) imp;
p = attr.
attribTree(s.selected,
localEnv,
tree.staticImport ? TYP : (TYP | PCK),
Type.noType).tsym;
if (name == names.asterisk) {
// Import on demand.
chk.checkCanonical(s.selected);
if (tree.staticImport)
importStaticAll(tree.pos, p, env);
else
importAll(tree.pos, p, env);
} else {
// Named type import.
if (tree.staticImport) {
importNamedStatic(tree.pos(), p, name, localEnv);
chk.checkCanonical(s.selected);
} else {
TypeSymbol c = attribImportType(imp, localEnv).tsym;
chk.checkCanonical(imp);
importNamed(tree.pos(), c, env);
}
}
}
public void visitMethodDef(JCMethodDecl tree) {
Scope enclScope = enter.enterScope(env);
MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
tree.sym = m;
Env<AttrContext> localEnv = methodEnv(tree, env);
DeferredLintHandler prevLintHandler =
chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
try {
// Compute the method type
m.type = signature(tree.typarams, tree.params,
tree.restype, tree.thrown,
localEnv);
} finally {
chk.setDeferredLintHandler(prevLintHandler);
}
// Set m.params
ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
JCVariableDecl lastParam = null;
for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
JCVariableDecl param = lastParam = l.head;
params.append(Assert.checkNonNull(param.sym));
}
m.params = params.toList();
// mark the method varargs, if necessary
if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
m.flags_field |= Flags.VARARGS;
localEnv.info.scope.leave();
if (chk.checkUnique(tree.pos(), m, enclScope)) {
enclScope.enter(m);
}
annotateLater(tree.mods.annotations, localEnv, m);
if (tree.defaultValue != null)
annotateDefaultValueLater(tree.defaultValue, localEnv, m);
}
/** Create a fresh environment for method bodies.
* @param tree The method definition.
* @param env The environment current outside of the method definition.
*/
Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
Env<AttrContext> localEnv =
env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
localEnv.enclMethod = tree;
localEnv.info.scope.owner = tree.sym;
if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
return localEnv;
}
public void visitVarDef(JCVariableDecl tree) {
Env<AttrContext> localEnv = env;
if ((tree.mods.flags & STATIC) != 0 ||
(env.info.scope.owner.flags() & INTERFACE) != 0) {
localEnv = env.dup(tree, env.info.dup());
localEnv.info.staticLevel++;
}
DeferredLintHandler prevLintHandler =
chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
try {
attr.attribType(tree.vartype, localEnv);
} finally {
chk.setDeferredLintHandler(prevLintHandler);
}
if ((tree.mods.flags & VARARGS) != 0) {
//if we are entering a varargs parameter, we need to replace its type
//(a plain array type) with the more precise VarargsType --- we need
//to do it this way because varargs is represented in the tree as a modifier
//on the parameter declaration, and not as a distinct type of array node.
ArrayType atype = (ArrayType)tree.vartype.type;
tree.vartype.type = atype.makeVarargs();
}
Scope enclScope = enter.enterScope(env);
VarSymbol v =
new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
tree.sym = v;
if (tree.init != null) {
v.flags_field |= HASINIT;
if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
Env<AttrContext> initEnv = getInitEnv(tree, env);
initEnv.info.enclVar = v;
v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init);
}
}
if (chk.checkUnique(tree.pos(), v, enclScope)) {
chk.checkTransparentVar(tree.pos(), v, enclScope);
enclScope.enter(v);
}
annotateLater(tree.mods.annotations, localEnv, v);
v.pos = tree.pos;
}
/** Create a fresh environment for a variable's initializer.
* If the variable is a field, the owner of the environment's scope
* is be the variable itself, otherwise the owner is the method
* enclosing the variable definition.
*
* @param tree The variable definition.
* @param env The environment current outside of the variable definition.
*/
Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
if (tree.sym.owner.kind == TYP) {
localEnv.info.scope = new Scope.DelegatedScope(env.info.scope);
localEnv.info.scope.owner = tree.sym;
}
if ((tree.mods.flags & STATIC) != 0 ||
(env.enclClass.sym.flags() & INTERFACE) != 0)
localEnv.info.staticLevel++;
return localEnv;
}
/** Default member enter visitor method: do nothing
*/
public void visitTree(JCTree tree) {
}
public void visitErroneous(JCErroneous tree) {
if (tree.errs != null)
memberEnter(tree.errs, env);
}
public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
Env<AttrContext> mEnv = methodEnv(tree, env);
mEnv.info.lint = mEnv.info.lint.augment(tree.sym.attributes_field, tree.sym.flags());
for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
mEnv.info.scope.enterIfAbsent(l.head.sym);
return mEnv;
}
public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
Env<AttrContext> iEnv = initEnv(tree, env);
return iEnv;
}
/* ********************************************************************
* Type completion
*********************************************************************/
Type attribImportType(JCTree tree, Env<AttrContext> env) {
Assert.check(completionEnabled);
try {
// To prevent deep recursion, suppress completion of some
// types.
completionEnabled = false;
return attr.attribType(tree, env);
} finally {
completionEnabled = true;
}
}
/* ********************************************************************
* Annotation processing
*********************************************************************/
/** Queue annotations for later processing. */
void annotateLater(final List<JCAnnotation> annotations,
final Env<AttrContext> localEnv,
final Symbol s) {
if (annotations.isEmpty()) return;
if (s.kind != PCK) s.attributes_field = null; // mark it incomplete for now
annotate.later(new Annotate.Annotator() {
public String toString() {
return "annotate " + annotations + " onto " + s + " in " + s.owner;
}
public void enterAnnotation() {
Assert.check(s.kind == PCK || s.attributes_field == null);
JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
try {
if (s.attributes_field != null &&
s.attributes_field.nonEmpty() &&
annotations.nonEmpty())
log.error(annotations.head.pos,
"already.annotated",
kindName(s), s);
enterAnnotations(annotations, localEnv, s);
} finally {
log.useSource(prev);
}
}
});
}
/**
* Check if a list of annotations contains a reference to
* java.lang.Deprecated.
**/
private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
JCAnnotation a = al.head;
if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
return true;
}
return false;
}
/** Enter a set of annotations. */
private void enterAnnotations(List<JCAnnotation> annotations,
Env<AttrContext> env,
Symbol s) {
ListBuffer<Attribute.Compound> buf =
new ListBuffer<Attribute.Compound>();
Set<TypeSymbol> annotated = new HashSet<TypeSymbol>();
if (!skipAnnotations)
for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
JCAnnotation a = al.head;
Attribute.Compound c = annotate.enterAnnotation(a,
syms.annotationType,
env);
if (c == null) continue;
buf.append(c);
// Note: @Deprecated has no effect on local variables and parameters
if (!c.type.isErroneous()
&& s.owner.kind != MTH
&& types.isSameType(c.type, syms.deprecatedType))
s.flags_field |= Flags.DEPRECATED;
// Internally to java.lang.invoke, a @PolymorphicSignature annotation
// acts like a classfile attribute.
if (!c.type.isErroneous() &&
types.isSameType(c.type, syms.polymorphicSignatureType)) {
if (!target.hasMethodHandles()) {
// Somebody is compiling JDK7 source code to a JDK6 target.
// Make it an error, since it is unlikely but important.
log.error(env.tree.pos(),
"wrong.target.for.polymorphic.signature.definition",
target.name);
}
// Pull the flag through for better diagnostics, even on a bad target.
s.flags_field |= Flags.POLYMORPHIC_SIGNATURE;
}
if (!annotated.add(a.type.tsym))
log.error(a.pos, "duplicate.annotation");
}
s.attributes_field = buf.toList();
}
/** Queue processing of an attribute default value. */
void annotateDefaultValueLater(final JCExpression defaultValue,
final Env<AttrContext> localEnv,
final MethodSymbol m) {
annotate.later(new Annotate.Annotator() {
public String toString() {
return "annotate " + m.owner + "." +
m + " default " + defaultValue;
}
public void enterAnnotation() {
JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
try {
enterDefaultValue(defaultValue, localEnv, m);
} finally {
log.useSource(prev);
}
}
});
}
/** Enter a default value for an attribute method. */
private void enterDefaultValue(final JCExpression defaultValue,
final Env<AttrContext> localEnv,
final MethodSymbol m) {
m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
defaultValue,
localEnv);
}
/* ********************************************************************
* Source completer
*********************************************************************/
/** Complete entering a class.
* @param sym The symbol of the class to be completed.
*/
public void complete(Symbol sym) throws CompletionFailure {
// Suppress some (recursive) MemberEnter invocations
if (!completionEnabled) {
// Re-install same completer for next time around and return.
Assert.check((sym.flags() & Flags.COMPOUND) == 0);
sym.completer = this;
return;
}
ClassSymbol c = (ClassSymbol)sym;
ClassType ct = (ClassType)c.type;
Env<AttrContext> env = enter.typeEnvs.get(c);
JCClassDecl tree = (JCClassDecl)env.tree;
boolean wasFirst = isFirst;
isFirst = false;
JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
try {
// Save class environment for later member enter (2) processing.
halfcompleted.append(env);
// Mark class as not yet attributed.
c.flags_field |= UNATTRIBUTED;
// If this is a toplevel-class, make sure any preceding import
// clauses have been seen.
if (c.owner.kind == PCK) {
memberEnter(env.toplevel, env.enclosing(JCTree.TOPLEVEL));
todo.append(env);
}
if (c.owner.kind == TYP)
c.owner.complete();
// create an environment for evaluating the base clauses
Env<AttrContext> baseEnv = baseEnv(tree, env);
// Determine supertype.
Type supertype =
(tree.extending != null)
? attr.attribBase(tree.extending, baseEnv, true, false, true)
: ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c))
? attr.attribBase(enumBase(tree.pos, c), baseEnv,
true, false, false)
: (c.fullname == names.java_lang_Object)
? Type.noType
: syms.objectType;
ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
// Determine interfaces.
ListBuffer<Type> interfaces = new ListBuffer<Type>();
ListBuffer<Type> all_interfaces = null; // lazy init
Set<Type> interfaceSet = new HashSet<Type>();
List<JCExpression> interfaceTrees = tree.implementing;
if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) {
// add interface Comparable<T>
interfaceTrees =
interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(),
List.of(c.type),
syms.comparableType.tsym)));
// add interface Serializable
interfaceTrees =
interfaceTrees.prepend(make.Type(syms.serializableType));
}
for (JCExpression iface : interfaceTrees) {
Type i = attr.attribBase(iface, baseEnv, false, true, true);
if (i.tag == CLASS) {
interfaces.append(i);
if (all_interfaces != null) all_interfaces.append(i);
chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
} else {
if (all_interfaces == null)
all_interfaces = new ListBuffer<Type>().appendList(interfaces);
all_interfaces.append(modelMissingTypes(i, iface, true));
}
}
if ((c.flags_field & ANNOTATION) != 0) {
ct.interfaces_field = List.of(syms.annotationType);
ct.all_interfaces_field = ct.interfaces_field;
} else {
ct.interfaces_field = interfaces.toList();
ct.all_interfaces_field = (all_interfaces == null)
? ct.interfaces_field : all_interfaces.toList();
}
if (c.fullname == names.java_lang_Object) {
if (tree.extending != null) {
chk.checkNonCyclic(tree.extending.pos(),
supertype);
ct.supertype_field = Type.noType;
}
else if (tree.implementing.nonEmpty()) {
chk.checkNonCyclic(tree.implementing.head.pos(),
ct.interfaces_field.head);
ct.interfaces_field = List.nil();
}
}
// Annotations.
// In general, we cannot fully process annotations yet, but we
// can attribute the annotation types and then check to see if the
// @Deprecated annotation is present.
attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
if (hasDeprecatedAnnotation(tree.mods.annotations))
c.flags_field |= DEPRECATED;
annotateLater(tree.mods.annotations, baseEnv, c);
chk.checkNonCyclicDecl(tree);
attr.attribTypeVariables(tree.typarams, baseEnv);
// Add default constructor if needed.
if ((c.flags() & INTERFACE) == 0 &&
!TreeInfo.hasConstructors(tree.defs)) {
List<Type> argtypes = List.nil();
List<Type> typarams = List.nil();
List<Type> thrown = List.nil();
long ctorFlags = 0;
boolean based = false;
if (c.name.isEmpty()) {
JCNewClass nc = (JCNewClass)env.next.tree;
if (nc.constructor != null) {
Type superConstrType = types.memberType(c.type,
nc.constructor);
argtypes = superConstrType.getParameterTypes();
typarams = superConstrType.getTypeArguments();
ctorFlags = nc.constructor.flags() & VARARGS;
if (nc.encl != null) {
argtypes = argtypes.prepend(nc.encl.type);
based = true;
}
thrown = superConstrType.getThrownTypes();
}
}
JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
typarams, argtypes, thrown,
ctorFlags, based);
tree.defs = tree.defs.prepend(constrDef);
}
// If this is a class, enter symbols for this and super into
// current scope.
if ((c.flags_field & INTERFACE) == 0) {
VarSymbol thisSym =
new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
thisSym.pos = Position.FIRSTPOS;
env.info.scope.enter(thisSym);
if (ct.supertype_field.tag == CLASS) {
VarSymbol superSym =
new VarSymbol(FINAL | HASINIT, names._super,
ct.supertype_field, c);
superSym.pos = Position.FIRSTPOS;
env.info.scope.enter(superSym);
}
}
// check that no package exists with same fully qualified name,
// but admit classes in the unnamed package which have the same
// name as a top-level package.
if (checkClash &&
c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
reader.packageExists(c.fullname))
{
log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
}
} catch (CompletionFailure ex) {
chk.completionError(tree.pos(), ex);
} finally {
log.useSource(prev);
}
// Enter all member fields and methods of a set of half completed
// classes in a second phase.
if (wasFirst) {
try {
while (halfcompleted.nonEmpty()) {
finish(halfcompleted.next());
}
} finally {
isFirst = true;
}
// commit pending annotations
annotate.flush();
}
}
private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
Scope baseScope = new Scope(tree.sym);
//import already entered local classes into base scope
for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
if (e.sym.isLocal()) {
baseScope.enter(e.sym);
}
}
//import current type-parameters into base scope
if (tree.typarams != null)
for (List<JCTypeParameter> typarams = tree.typarams;
typarams.nonEmpty();
typarams = typarams.tail)
baseScope.enter(typarams.head.type.tsym);
Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
localEnv.baseClause = true;
localEnv.outer = outer;
localEnv.info.isSelfCall = false;
return localEnv;
}
/** Enter member fields and methods of a class
* @param env the environment current for the class block.
*/
private void finish(Env<AttrContext> env) {
JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
try {
JCClassDecl tree = (JCClassDecl)env.tree;
finishClass(tree, env);
} finally {
log.useSource(prev);
}
}
/** Generate a base clause for an enum type.
* @param pos The position for trees and diagnostics, if any
* @param c The class symbol of the enum
*/
private JCExpression enumBase(int pos, ClassSymbol c) {
JCExpression result = make.at(pos).
TypeApply(make.QualIdent(syms.enumSym),
List.<JCExpression>of(make.Type(c.type)));
return result;
}
Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
if (t.tag != ERROR)
return t;
return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) {
private Type modelType;
@Override
public Type getModelType() {
if (modelType == null)
modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
return modelType;
}
};
}
// where
private class Synthesizer extends JCTree.Visitor {
Type originalType;
boolean interfaceExpected;
List<ClassSymbol> synthesizedSymbols = List.nil();
Type result;
Synthesizer(Type originalType, boolean interfaceExpected) {
this.originalType = originalType;
this.interfaceExpected = interfaceExpected;
}
Type visit(JCTree tree) {
tree.accept(this);
return result;
}
List<Type> visit(List<? extends JCTree> trees) {
ListBuffer<Type> lb = new ListBuffer<Type>();
for (JCTree t: trees)
lb.append(visit(t));
return lb.toList();
}
@Override
public void visitTree(JCTree tree) {
result = syms.errType;
}
@Override
public void visitIdent(JCIdent tree) {
if (tree.type.tag != ERROR) {
result = tree.type;
} else {
result = synthesizeClass(tree.name, syms.unnamedPackage).type;
}
}
@Override
public void visitSelect(JCFieldAccess tree) {
if (tree.type.tag != ERROR) {
result = tree.type;
} else {
Type selectedType;
boolean prev = interfaceExpected;
try {
interfaceExpected = false;
selectedType = visit(tree.selected);
} finally {
interfaceExpected = prev;
}
ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
result = c.type;
}
}
@Override
public void visitTypeApply(JCTypeApply tree) {
if (tree.type.tag != ERROR) {
result = tree.type;
} else {
ClassType clazzType = (ClassType) visit(tree.clazz);
if (synthesizedSymbols.contains(clazzType.tsym))
synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
final List<Type> actuals = visit(tree.arguments);
result = new ErrorType(tree.type, clazzType.tsym) {
@Override
public List<Type> getTypeArguments() {
return actuals;
}
};
}
}
ClassSymbol synthesizeClass(Name name, Symbol owner) {
int flags = interfaceExpected ? INTERFACE : 0;
ClassSymbol c = new ClassSymbol(flags, name, owner);
c.members_field = new Scope.ErrorScope(c);
c.type = new ErrorType(originalType, c) {
@Override
public List<Type> getTypeArguments() {
return typarams_field;
}
};
synthesizedSymbols = synthesizedSymbols.prepend(c);
return c;
}
void synthesizeTyparams(ClassSymbol sym, int n) {
ClassType ct = (ClassType) sym.type;
Assert.check(ct.typarams_field.isEmpty());
if (n == 1) {
TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
ct.typarams_field = ct.typarams_field.prepend(v);
} else {
for (int i = n; i > 0; i--) {
TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
ct.typarams_field = ct.typarams_field.prepend(v);
}
}
}
}
/* ***************************************************************************
* tree building
****************************************************************************/
/** Generate default constructor for given class. For classes different
* from java.lang.Object, this is:
*
* c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
* super(x_0, ..., x_n)
* }
*
* or, if based == true:
*
* c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
* x_0.super(x_1, ..., x_n)
* }
*
* @param make The tree factory.
* @param c The class owning the default constructor.
* @param argtypes The parameter types of the constructor.
* @param thrown The thrown exceptions of the constructor.
* @param based Is first parameter a this$n?
*/
JCTree DefaultConstructor(TreeMaker make,
ClassSymbol c,
List<Type> typarams,
List<Type> argtypes,
List<Type> thrown,
long flags,
boolean based) {
List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol);
List<JCStatement> stats = List.nil();
if (c.type != syms.objectType)
stats = stats.prepend(SuperCall(make, typarams, params, based));
if ((c.flags() & ENUM) != 0 &&
(types.supertype(c.type).tsym == syms.enumSym ||
target.compilerBootstrap(c))) {
// constructors of true enums are private
flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
} else
flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
if (c.name.isEmpty()) flags |= ANONCONSTR;
JCTree result = make.MethodDef(
make.Modifiers(flags),
names.init,
null,
make.TypeParams(typarams),
params,
make.Types(thrown),
make.Block(0, stats),
null);
return result;
}
/** Generate call to superclass constructor. This is:
*
* super(id_0, ..., id_n)
*
* or, if based == true
*
* id_0.super(id_1,...,id_n)
*
* where id_0, ..., id_n are the names of the given parameters.
*
* @param make The tree factory
* @param params The parameters that need to be passed to super
* @param typarams The type parameters that need to be passed to super
* @param based Is first parameter a this$n?
*/
JCExpressionStatement SuperCall(TreeMaker make,
List<Type> typarams,
List<JCVariableDecl> params,
boolean based) {
JCExpression meth;
if (based) {
meth = make.Select(make.Ident(params.head), names._super);
params = params.tail;
} else {
meth = make.Ident(names._super);
}
List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));
}
}
| 52,420 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Lower.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.comp;
import java.util.*;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.main.RecognizedOptions.PkgInfo;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.jvm.Target;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.jvm.ByteCodes.*;
/** This pass translates away some syntactic sugar: inner classes,
* class literals, assertions, foreach loops, etc.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Lower extends TreeTranslator {
protected static final Context.Key<Lower> lowerKey =
new Context.Key<Lower>();
public static Lower instance(Context context) {
Lower instance = context.get(lowerKey);
if (instance == null)
instance = new Lower(context);
return instance;
}
private Names names;
private Log log;
private Symtab syms;
private Resolve rs;
private Check chk;
private Attr attr;
private TreeMaker make;
private DiagnosticPosition make_pos;
private ClassWriter writer;
private ClassReader reader;
private ConstFold cfolder;
private Target target;
private Source source;
private boolean allowEnums;
private final Name dollarAssertionsDisabled;
private final Name classDollar;
private Types types;
private boolean debugLower;
private PkgInfo pkginfoOpt;
protected Lower(Context context) {
context.put(lowerKey, this);
names = Names.instance(context);
log = Log.instance(context);
syms = Symtab.instance(context);
rs = Resolve.instance(context);
chk = Check.instance(context);
attr = Attr.instance(context);
make = TreeMaker.instance(context);
writer = ClassWriter.instance(context);
reader = ClassReader.instance(context);
cfolder = ConstFold.instance(context);
target = Target.instance(context);
source = Source.instance(context);
allowEnums = source.allowEnums();
dollarAssertionsDisabled = names.
fromString(target.syntheticNameChar() + "assertionsDisabled");
classDollar = names.
fromString("class" + target.syntheticNameChar());
types = Types.instance(context);
Options options = Options.instance(context);
debugLower = options.isSet("debuglower");
pkginfoOpt = PkgInfo.get(options);
}
/** The currently enclosing class.
*/
ClassSymbol currentClass;
/** A queue of all translated classes.
*/
ListBuffer<JCTree> translated;
/** Environment for symbol lookup, set by translateTopLevelClass.
*/
Env<AttrContext> attrEnv;
/** A hash table mapping syntax trees to their ending source positions.
*/
Map<JCTree, Integer> endPositions;
/**************************************************************************
* Global mappings
*************************************************************************/
/** A hash table mapping local classes to their definitions.
*/
Map<ClassSymbol, JCClassDecl> classdefs;
/** A hash table mapping virtual accessed symbols in outer subclasses
* to the actually referred symbol in superclasses.
*/
Map<Symbol,Symbol> actualSymbols;
/** The current method definition.
*/
JCMethodDecl currentMethodDef;
/** The current method symbol.
*/
MethodSymbol currentMethodSym;
/** The currently enclosing outermost class definition.
*/
JCClassDecl outermostClassDef;
/** The currently enclosing outermost member definition.
*/
JCTree outermostMemberDef;
/** A navigator class for assembling a mapping from local class symbols
* to class definition trees.
* There is only one case; all other cases simply traverse down the tree.
*/
class ClassMap extends TreeScanner {
/** All encountered class defs are entered into classdefs table.
*/
public void visitClassDef(JCClassDecl tree) {
classdefs.put(tree.sym, tree);
super.visitClassDef(tree);
}
}
ClassMap classMap = new ClassMap();
/** Map a class symbol to its definition.
* @param c The class symbol of which we want to determine the definition.
*/
JCClassDecl classDef(ClassSymbol c) {
// First lookup the class in the classdefs table.
JCClassDecl def = classdefs.get(c);
if (def == null && outermostMemberDef != null) {
// If this fails, traverse outermost member definition, entering all
// local classes into classdefs, and try again.
classMap.scan(outermostMemberDef);
def = classdefs.get(c);
}
if (def == null) {
// If this fails, traverse outermost class definition, entering all
// local classes into classdefs, and try again.
classMap.scan(outermostClassDef);
def = classdefs.get(c);
}
return def;
}
/** A hash table mapping class symbols to lists of free variables.
* accessed by them. Only free variables of the method immediately containing
* a class are associated with that class.
*/
Map<ClassSymbol,List<VarSymbol>> freevarCache;
/** A navigator class for collecting the free variables accessed
* from a local class.
* There is only one case; all other cases simply traverse down the tree.
*/
class FreeVarCollector extends TreeScanner {
/** The owner of the local class.
*/
Symbol owner;
/** The local class.
*/
ClassSymbol clazz;
/** The list of owner's variables accessed from within the local class,
* without any duplicates.
*/
List<VarSymbol> fvs;
FreeVarCollector(ClassSymbol clazz) {
this.clazz = clazz;
this.owner = clazz.owner;
this.fvs = List.nil();
}
/** Add free variable to fvs list unless it is already there.
*/
private void addFreeVar(VarSymbol v) {
for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail)
if (l.head == v) return;
fvs = fvs.prepend(v);
}
/** Add all free variables of class c to fvs list
* unless they are already there.
*/
private void addFreeVars(ClassSymbol c) {
List<VarSymbol> fvs = freevarCache.get(c);
if (fvs != null) {
for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
addFreeVar(l.head);
}
}
}
/** If tree refers to a variable in owner of local class, add it to
* free variables list.
*/
public void visitIdent(JCIdent tree) {
result = tree;
visitSymbol(tree.sym);
}
// where
private void visitSymbol(Symbol _sym) {
Symbol sym = _sym;
if (sym.kind == VAR || sym.kind == MTH) {
while (sym != null && sym.owner != owner)
sym = proxies.lookup(proxyName(sym.name)).sym;
if (sym != null && sym.owner == owner) {
VarSymbol v = (VarSymbol)sym;
if (v.getConstValue() == null) {
addFreeVar(v);
}
} else {
if (outerThisStack.head != null &&
outerThisStack.head != _sym)
visitSymbol(outerThisStack.head);
}
}
}
/** If tree refers to a class instance creation expression
* add all free variables of the freshly created class.
*/
public void visitNewClass(JCNewClass tree) {
ClassSymbol c = (ClassSymbol)tree.constructor.owner;
addFreeVars(c);
if (tree.encl == null &&
c.hasOuterInstance() &&
outerThisStack.head != null)
visitSymbol(outerThisStack.head);
super.visitNewClass(tree);
}
/** If tree refers to a qualified this or super expression
* for anything but the current class, add the outer this
* stack as a free variable.
*/
public void visitSelect(JCFieldAccess tree) {
if ((tree.name == names._this || tree.name == names._super) &&
tree.selected.type.tsym != clazz &&
outerThisStack.head != null)
visitSymbol(outerThisStack.head);
super.visitSelect(tree);
}
/** If tree refers to a superclass constructor call,
* add all free variables of the superclass.
*/
public void visitApply(JCMethodInvocation tree) {
if (TreeInfo.name(tree.meth) == names._super) {
addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner);
Symbol constructor = TreeInfo.symbol(tree.meth);
ClassSymbol c = (ClassSymbol)constructor.owner;
if (c.hasOuterInstance() &&
tree.meth.getTag() != JCTree.SELECT &&
outerThisStack.head != null)
visitSymbol(outerThisStack.head);
}
super.visitApply(tree);
}
}
/** Return the variables accessed from within a local class, which
* are declared in the local class' owner.
* (in reverse order of first access).
*/
List<VarSymbol> freevars(ClassSymbol c) {
if ((c.owner.kind & (VAR | MTH)) != 0) {
List<VarSymbol> fvs = freevarCache.get(c);
if (fvs == null) {
FreeVarCollector collector = new FreeVarCollector(c);
collector.scan(classDef(c));
fvs = collector.fvs;
freevarCache.put(c, fvs);
}
return fvs;
} else {
return List.nil();
}
}
Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<TypeSymbol,EnumMapping>();
EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) {
EnumMapping map = enumSwitchMap.get(enumClass);
if (map == null)
enumSwitchMap.put(enumClass, map = new EnumMapping(pos, enumClass));
return map;
}
/** This map gives a translation table to be used for enum
* switches.
*
* <p>For each enum that appears as the type of a switch
* expression, we maintain an EnumMapping to assist in the
* translation, as exemplified by the following example:
*
* <p>we translate
* <pre>
* switch(colorExpression) {
* case red: stmt1;
* case green: stmt2;
* }
* </pre>
* into
* <pre>
* switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) {
* case 1: stmt1;
* case 2: stmt2
* }
* </pre>
* with the auxiliary table initialized as follows:
* <pre>
* class Outer$0 {
* synthetic final int[] $EnumMap$Color = new int[Color.values().length];
* static {
* try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {}
* try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {}
* }
* }
* </pre>
* class EnumMapping provides mapping data and support methods for this translation.
*/
class EnumMapping {
EnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) {
this.forEnum = forEnum;
this.values = new LinkedHashMap<VarSymbol,Integer>();
this.pos = pos;
Name varName = names
.fromString(target.syntheticNameChar() +
"SwitchMap" +
target.syntheticNameChar() +
writer.xClassName(forEnum.type).toString()
.replace('/', '.')
.replace('.', target.syntheticNameChar()));
ClassSymbol outerCacheClass = outerCacheClass();
this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL,
varName,
new ArrayType(syms.intType, syms.arrayClass),
outerCacheClass);
enterSynthetic(pos, mapVar, outerCacheClass.members());
}
DiagnosticPosition pos = null;
// the next value to use
int next = 1; // 0 (unused map elements) go to the default label
// the enum for which this is a map
final TypeSymbol forEnum;
// the field containing the map
final VarSymbol mapVar;
// the mapped values
final Map<VarSymbol,Integer> values;
JCLiteral forConstant(VarSymbol v) {
Integer result = values.get(v);
if (result == null)
values.put(v, result = next++);
return make.Literal(result);
}
// generate the field initializer for the map
void translate() {
make.at(pos.getStartPosition());
JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
// synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
MethodSymbol valuesMethod = lookupMethod(pos,
names.values,
forEnum.type,
List.<Type>nil());
JCExpression size = make // Color.values().length
.Select(make.App(make.QualIdent(valuesMethod)),
syms.lengthVar);
JCExpression mapVarInit = make
.NewArray(make.Type(syms.intType), List.of(size), null)
.setType(new ArrayType(syms.intType, syms.arrayClass));
// try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
Symbol ordinalMethod = lookupMethod(pos,
names.ordinal,
forEnum.type,
List.<Type>nil());
List<JCCatch> catcher = List.<JCCatch>nil()
.prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
syms.noSuchFieldErrorType,
syms.noSymbol),
null),
make.Block(0, List.<JCStatement>nil())));
for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
VarSymbol enumerator = e.getKey();
Integer mappedValue = e.getValue();
JCExpression assign = make
.Assign(make.Indexed(mapVar,
make.App(make.Select(make.QualIdent(enumerator),
ordinalMethod))),
make.Literal(mappedValue))
.setType(syms.intType);
JCStatement exec = make.Exec(assign);
JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
stmts.append(_try);
}
owner.defs = owner.defs
.prepend(make.Block(STATIC, stmts.toList()))
.prepend(make.VarDef(mapVar, mapVarInit));
}
}
/**************************************************************************
* Tree building blocks
*************************************************************************/
/** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
* pos as make_pos, for use in diagnostics.
**/
TreeMaker make_at(DiagnosticPosition pos) {
make_pos = pos;
return make.at(pos);
}
/** Make an attributed tree representing a literal. This will be an
* Ident node in the case of boolean literals, a Literal node in all
* other cases.
* @param type The literal's type.
* @param value The literal's value.
*/
JCExpression makeLit(Type type, Object value) {
return make.Literal(type.tag, value).setType(type.constType(value));
}
/** Make an attributed tree representing null.
*/
JCExpression makeNull() {
return makeLit(syms.botType, null);
}
/** Make an attributed class instance creation expression.
* @param ctype The class type.
* @param args The constructor arguments.
*/
JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
JCNewClass tree = make.NewClass(null,
null, make.QualIdent(ctype.tsym), args, null);
tree.constructor = rs.resolveConstructor(
make_pos, attrEnv, ctype, TreeInfo.types(args), null, false, false);
tree.type = ctype;
return tree;
}
/** Make an attributed unary expression.
* @param optag The operators tree tag.
* @param arg The operator's argument.
*/
JCUnary makeUnary(int optag, JCExpression arg) {
JCUnary tree = make.Unary(optag, arg);
tree.operator = rs.resolveUnaryOperator(
make_pos, optag, attrEnv, arg.type);
tree.type = tree.operator.type.getReturnType();
return tree;
}
/** Make an attributed binary expression.
* @param optag The operators tree tag.
* @param lhs The operator's left argument.
* @param rhs The operator's right argument.
*/
JCBinary makeBinary(int optag, JCExpression lhs, JCExpression rhs) {
JCBinary tree = make.Binary(optag, lhs, rhs);
tree.operator = rs.resolveBinaryOperator(
make_pos, optag, attrEnv, lhs.type, rhs.type);
tree.type = tree.operator.type.getReturnType();
return tree;
}
/** Make an attributed assignop expression.
* @param optag The operators tree tag.
* @param lhs The operator's left argument.
* @param rhs The operator's right argument.
*/
JCAssignOp makeAssignop(int optag, JCTree lhs, JCTree rhs) {
JCAssignOp tree = make.Assignop(optag, lhs, rhs);
tree.operator = rs.resolveBinaryOperator(
make_pos, tree.getTag() - JCTree.ASGOffset, attrEnv, lhs.type, rhs.type);
tree.type = lhs.type;
return tree;
}
/** Convert tree into string object, unless it has already a
* reference type..
*/
JCExpression makeString(JCExpression tree) {
if (tree.type.tag >= CLASS) {
return tree;
} else {
Symbol valueOfSym = lookupMethod(tree.pos(),
names.valueOf,
syms.stringType,
List.of(tree.type));
return make.App(make.QualIdent(valueOfSym), List.of(tree));
}
}
/** Create an empty anonymous class definition and enter and complete
* its symbol. Return the class definition's symbol.
* and create
* @param flags The class symbol's flags
* @param owner The class symbol's owner
*/
ClassSymbol makeEmptyClass(long flags, ClassSymbol owner) {
// Create class symbol.
ClassSymbol c = reader.defineClass(names.empty, owner);
c.flatname = chk.localClassName(c);
c.sourcefile = owner.sourcefile;
c.completer = null;
c.members_field = new Scope(c);
c.flags_field = flags;
ClassType ctype = (ClassType) c.type;
ctype.supertype_field = syms.objectType;
ctype.interfaces_field = List.nil();
JCClassDecl odef = classDef(owner);
// Enter class symbol in owner scope and compiled table.
enterSynthetic(odef.pos(), c, owner.members());
chk.compiled.put(c.flatname, c);
// Create class definition tree.
JCClassDecl cdef = make.ClassDef(
make.Modifiers(flags), names.empty,
List.<JCTypeParameter>nil(),
null, List.<JCExpression>nil(), List.<JCTree>nil());
cdef.sym = c;
cdef.type = c.type;
// Append class definition tree to owner's definitions.
odef.defs = odef.defs.prepend(cdef);
return c;
}
/**************************************************************************
* Symbol manipulation utilities
*************************************************************************/
/** Enter a synthetic symbol in a given scope, but complain if there was already one there.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope.
*/
private void enterSynthetic(DiagnosticPosition pos, Symbol sym, Scope s) {
s.enter(sym);
}
/** 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;
}
/** Check whether synthetic symbols generated during lowering conflict
* with user-defined symbols.
*
* @param translatedTrees lowered class trees
*/
void checkConflicts(List<JCTree> translatedTrees) {
for (JCTree t : translatedTrees) {
t.accept(conflictsChecker);
}
}
JCTree.Visitor conflictsChecker = new TreeScanner() {
TypeSymbol currentClass;
@Override
public void visitMethodDef(JCMethodDecl that) {
chk.checkConflicts(that.pos(), that.sym, currentClass);
super.visitMethodDef(that);
}
@Override
public void visitVarDef(JCVariableDecl that) {
if (that.sym.owner.kind == TYP) {
chk.checkConflicts(that.pos(), that.sym, currentClass);
}
super.visitVarDef(that);
}
@Override
public void visitClassDef(JCClassDecl that) {
TypeSymbol prevCurrentClass = currentClass;
currentClass = that.sym;
try {
super.visitClassDef(that);
}
finally {
currentClass = prevCurrentClass;
}
}
};
/** Look up a synthetic name in a given scope.
* @param scope The scope.
* @param name The name.
*/
private Symbol lookupSynthetic(Name name, Scope s) {
Symbol sym = s.lookup(name).sym;
return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
}
/** Look up a method in a given scope.
*/
private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, null);
}
/** Look up a constructor.
*/
private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
}
/** Look up a field.
*/
private VarSymbol lookupField(DiagnosticPosition pos, Type qual, Name name) {
return rs.resolveInternalField(pos, attrEnv, qual, name);
}
/** Anon inner classes are used as access constructor tags.
* accessConstructorTag will use an existing anon class if one is available,
* and synthethise a class (with makeEmptyClass) if one is not available.
* However, there is a small possibility that an existing class will not
* be generated as expected if it is inside a conditional with a constant
* expression. If that is found to be the case, create an empty class here.
*/
private void checkAccessConstructorTags() {
for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) {
ClassSymbol c = l.head;
if (isTranslatedClassAvailable(c))
continue;
// Create class definition tree.
JCClassDecl cdef = make.ClassDef(
make.Modifiers(STATIC | SYNTHETIC), names.empty,
List.<JCTypeParameter>nil(),
null, List.<JCExpression>nil(), List.<JCTree>nil());
cdef.sym = c;
cdef.type = c.type;
// add it to the list of classes to be generated
translated.append(cdef);
}
}
// where
private boolean isTranslatedClassAvailable(ClassSymbol c) {
for (JCTree tree: translated) {
if (tree.getTag() == JCTree.CLASSDEF
&& ((JCClassDecl) tree).sym == c) {
return true;
}
}
return false;
}
/**************************************************************************
* Access methods
*************************************************************************/
/** Access codes for dereferencing, assignment,
* and pre/post increment/decrement.
* Access codes for assignment operations are determined by method accessCode
* below.
*
* All access codes for accesses to the current class are even.
* If a member of the superclass should be accessed instead (because
* access was via a qualified super), add one to the corresponding code
* for the current class, making the number odd.
* This numbering scheme is used by the backend to decide whether
* to issue an invokevirtual or invokespecial call.
*
* @see Gen.visitSelect(Select tree)
*/
private static final int
DEREFcode = 0,
ASSIGNcode = 2,
PREINCcode = 4,
PREDECcode = 6,
POSTINCcode = 8,
POSTDECcode = 10,
FIRSTASGOPcode = 12;
/** Number of access codes
*/
private static final int NCODES = accessCode(ByteCodes.lushrl) + 2;
/** A mapping from symbols to their access numbers.
*/
private Map<Symbol,Integer> accessNums;
/** A mapping from symbols to an array of access symbols, indexed by
* access code.
*/
private Map<Symbol,MethodSymbol[]> accessSyms;
/** A mapping from (constructor) symbols to access constructor symbols.
*/
private Map<Symbol,MethodSymbol> accessConstrs;
/** A list of all class symbols used for access constructor tags.
*/
private List<ClassSymbol> accessConstrTags;
/** A queue for all accessed symbols.
*/
private ListBuffer<Symbol> accessed;
/** Map bytecode of binary operation to access code of corresponding
* assignment operation. This is always an even number.
*/
private static int accessCode(int bytecode) {
if (ByteCodes.iadd <= bytecode && bytecode <= ByteCodes.lxor)
return (bytecode - iadd) * 2 + FIRSTASGOPcode;
else if (bytecode == ByteCodes.string_add)
return (ByteCodes.lxor + 1 - iadd) * 2 + FIRSTASGOPcode;
else if (ByteCodes.ishll <= bytecode && bytecode <= ByteCodes.lushrl)
return (bytecode - ishll + ByteCodes.lxor + 2 - iadd) * 2 + FIRSTASGOPcode;
else
return -1;
}
/** return access code for identifier,
* @param tree The tree representing the identifier use.
* @param enclOp The closest enclosing operation node of tree,
* null if tree is not a subtree of an operation.
*/
private static int accessCode(JCTree tree, JCTree enclOp) {
if (enclOp == null)
return DEREFcode;
else if (enclOp.getTag() == JCTree.ASSIGN &&
tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
return ASSIGNcode;
else if (JCTree.PREINC <= enclOp.getTag() && enclOp.getTag() <= JCTree.POSTDEC &&
tree == TreeInfo.skipParens(((JCUnary) enclOp).arg))
return (enclOp.getTag() - JCTree.PREINC) * 2 + PREINCcode;
else if (JCTree.BITOR_ASG <= enclOp.getTag() && enclOp.getTag() <= JCTree.MOD_ASG &&
tree == TreeInfo.skipParens(((JCAssignOp) enclOp).lhs))
return accessCode(((OperatorSymbol) ((JCAssignOp) enclOp).operator).opcode);
else
return DEREFcode;
}
/** Return binary operator that corresponds to given access code.
*/
private OperatorSymbol binaryAccessOperator(int acode) {
for (Scope.Entry e = syms.predefClass.members().elems;
e != null;
e = e.sibling) {
if (e.sym instanceof OperatorSymbol) {
OperatorSymbol op = (OperatorSymbol)e.sym;
if (accessCode(op.opcode) == acode) return op;
}
}
return null;
}
/** Return tree tag for assignment operation corresponding
* to given binary operator.
*/
private static int treeTag(OperatorSymbol operator) {
switch (operator.opcode) {
case ByteCodes.ior: case ByteCodes.lor:
return JCTree.BITOR_ASG;
case ByteCodes.ixor: case ByteCodes.lxor:
return JCTree.BITXOR_ASG;
case ByteCodes.iand: case ByteCodes.land:
return JCTree.BITAND_ASG;
case ByteCodes.ishl: case ByteCodes.lshl:
case ByteCodes.ishll: case ByteCodes.lshll:
return JCTree.SL_ASG;
case ByteCodes.ishr: case ByteCodes.lshr:
case ByteCodes.ishrl: case ByteCodes.lshrl:
return JCTree.SR_ASG;
case ByteCodes.iushr: case ByteCodes.lushr:
case ByteCodes.iushrl: case ByteCodes.lushrl:
return JCTree.USR_ASG;
case ByteCodes.iadd: case ByteCodes.ladd:
case ByteCodes.fadd: case ByteCodes.dadd:
case ByteCodes.string_add:
return JCTree.PLUS_ASG;
case ByteCodes.isub: case ByteCodes.lsub:
case ByteCodes.fsub: case ByteCodes.dsub:
return JCTree.MINUS_ASG;
case ByteCodes.imul: case ByteCodes.lmul:
case ByteCodes.fmul: case ByteCodes.dmul:
return JCTree.MUL_ASG;
case ByteCodes.idiv: case ByteCodes.ldiv:
case ByteCodes.fdiv: case ByteCodes.ddiv:
return JCTree.DIV_ASG;
case ByteCodes.imod: case ByteCodes.lmod:
case ByteCodes.fmod: case ByteCodes.dmod:
return JCTree.MOD_ASG;
default:
throw new AssertionError();
}
}
/** The name of the access method with number `anum' and access code `acode'.
*/
Name accessName(int anum, int acode) {
return names.fromString(
"access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
}
/** Return access symbol for a private or protected symbol from an inner class.
* @param sym The accessed private symbol.
* @param tree The accessing tree.
* @param enclOp The closest enclosing operation node of tree,
* null if tree is not a subtree of an operation.
* @param protAccess Is access to a protected symbol in another
* package?
* @param refSuper Is access via a (qualified) C.super?
*/
MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
boolean protAccess, boolean refSuper) {
ClassSymbol accOwner = refSuper && protAccess
// For access via qualified super (T.super.x), place the
// access symbol on T.
? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
// Otherwise pretend that the owner of an accessed
// protected symbol is the enclosing class of the current
// class which is a subclass of the symbol's owner.
: accessClass(sym, protAccess, tree);
Symbol vsym = sym;
if (sym.owner != accOwner) {
vsym = sym.clone(accOwner);
actualSymbols.put(vsym, sym);
}
Integer anum // The access number of the access method.
= accessNums.get(vsym);
if (anum == null) {
anum = accessed.length();
accessNums.put(vsym, anum);
accessSyms.put(vsym, new MethodSymbol[NCODES]);
accessed.append(vsym);
// System.out.println("accessing " + vsym + " in " + vsym.location());
}
int acode; // The access code of the access method.
List<Type> argtypes; // The argument types of the access method.
Type restype; // The result type of the access method.
List<Type> thrown; // The thrown exceptions of the access method.
switch (vsym.kind) {
case VAR:
acode = accessCode(tree, enclOp);
if (acode >= FIRSTASGOPcode) {
OperatorSymbol operator = binaryAccessOperator(acode);
if (operator.opcode == string_add)
argtypes = List.of(syms.objectType);
else
argtypes = operator.type.getParameterTypes().tail;
} else if (acode == ASSIGNcode)
argtypes = List.of(vsym.erasure(types));
else
argtypes = List.nil();
restype = vsym.erasure(types);
thrown = List.nil();
break;
case MTH:
acode = DEREFcode;
argtypes = vsym.erasure(types).getParameterTypes();
restype = vsym.erasure(types).getReturnType();
thrown = vsym.type.getThrownTypes();
break;
default:
throw new AssertionError();
}
// For references via qualified super, increment acode by one,
// making it odd.
if (protAccess && refSuper) acode++;
// Instance access methods get instance as first parameter.
// For protected symbols this needs to be the instance as a member
// of the type containing the accessed symbol, not the class
// containing the access method.
if ((vsym.flags() & STATIC) == 0) {
argtypes = argtypes.prepend(vsym.owner.erasure(types));
}
MethodSymbol[] accessors = accessSyms.get(vsym);
MethodSymbol accessor = accessors[acode];
if (accessor == null) {
accessor = new MethodSymbol(
STATIC | SYNTHETIC,
accessName(anum.intValue(), acode),
new MethodType(argtypes, restype, thrown, syms.methodClass),
accOwner);
enterSynthetic(tree.pos(), accessor, accOwner.members());
accessors[acode] = accessor;
}
return accessor;
}
/** The qualifier to be used for accessing a symbol in an outer class.
* This is either C.sym or C.this.sym, depending on whether or not
* sym is static.
* @param sym The accessed symbol.
*/
JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
return (sym.flags() & STATIC) != 0
? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
: makeOwnerThis(pos, sym, true);
}
/** Do we need an access method to reference private symbol?
*/
boolean needsPrivateAccess(Symbol sym) {
if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
return false;
} else if (sym.name == names.init && (sym.owner.owner.kind & (VAR | MTH)) != 0) {
// private constructor in local class: relax protection
sym.flags_field &= ~PRIVATE;
return false;
} else {
return true;
}
}
/** Do we need an access method to reference symbol in other package?
*/
boolean needsProtectedAccess(Symbol sym, JCTree tree) {
if ((sym.flags() & PROTECTED) == 0 ||
sym.owner.owner == currentClass.owner || // fast special case
sym.packge() == currentClass.packge())
return false;
if (!currentClass.isSubClass(sym.owner, types))
return true;
if ((sym.flags() & STATIC) != 0 ||
tree.getTag() != JCTree.SELECT ||
TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
return false;
return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
}
/** The class in which an access method for given symbol goes.
* @param sym The access symbol
* @param protAccess Is access to a protected symbol in another
* package?
*/
ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
if (protAccess) {
Symbol qualifier = null;
ClassSymbol c = currentClass;
if (tree.getTag() == JCTree.SELECT && (sym.flags() & STATIC) == 0) {
qualifier = ((JCFieldAccess) tree).selected.type.tsym;
while (!qualifier.isSubClass(c, types)) {
c = c.owner.enclClass();
}
return c;
} else {
while (!c.isSubClass(sym.owner, types)) {
c = c.owner.enclClass();
}
}
return c;
} else {
// the symbol is private
return sym.owner.enclClass();
}
}
/** Ensure that identifier is accessible, return tree accessing the identifier.
* @param sym The accessed symbol.
* @param tree The tree referring to the symbol.
* @param enclOp The closest enclosing operation node of tree,
* null if tree is not a subtree of an operation.
* @param refSuper Is access via a (qualified) C.super?
*/
JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
// Access a free variable via its proxy, or its proxy's proxy
while (sym.kind == VAR && sym.owner.kind == MTH &&
sym.owner.enclClass() != currentClass) {
// A constant is replaced by its constant value.
Object cv = ((VarSymbol)sym).getConstValue();
if (cv != null) {
make.at(tree.pos);
return makeLit(sym.type, cv);
}
// Otherwise replace the variable by its proxy.
sym = proxies.lookup(proxyName(sym.name)).sym;
Assert.check(sym != null && (sym.flags_field & FINAL) != 0);
tree = make.at(tree.pos).Ident(sym);
}
JCExpression base = (tree.getTag() == JCTree.SELECT) ? ((JCFieldAccess) tree).selected : null;
switch (sym.kind) {
case TYP:
if (sym.owner.kind != PCK) {
// Convert type idents to
// <flat name> or <package name> . <flat name>
Name flatname = Convert.shortName(sym.flatName());
while (base != null &&
TreeInfo.symbol(base) != null &&
TreeInfo.symbol(base).kind != PCK) {
base = (base.getTag() == JCTree.SELECT)
? ((JCFieldAccess) base).selected
: null;
}
if (tree.getTag() == JCTree.IDENT) {
((JCIdent) tree).name = flatname;
} else if (base == null) {
tree = make.at(tree.pos).Ident(sym);
((JCIdent) tree).name = flatname;
} else {
((JCFieldAccess) tree).selected = base;
((JCFieldAccess) tree).name = flatname;
}
}
break;
case MTH: case VAR:
if (sym.owner.kind == TYP) {
// Access methods are required for
// - private members,
// - protected members in a superclass of an
// enclosing class contained in another package.
// - all non-private members accessed via a qualified super.
boolean protAccess = refSuper && !needsPrivateAccess(sym)
|| needsProtectedAccess(sym, tree);
boolean accReq = protAccess || needsPrivateAccess(sym);
// A base has to be supplied for
// - simple identifiers accessing variables in outer classes.
boolean baseReq =
base == null &&
sym.owner != syms.predefClass &&
!sym.isMemberOf(currentClass, types);
if (accReq || baseReq) {
make.at(tree.pos);
// Constants are replaced by their constant value.
if (sym.kind == VAR) {
Object cv = ((VarSymbol)sym).getConstValue();
if (cv != null) return makeLit(sym.type, cv);
}
// Private variables and methods are replaced by calls
// to their access methods.
if (accReq) {
List<JCExpression> args = List.nil();
if ((sym.flags() & STATIC) == 0) {
// Instance access methods get instance
// as first parameter.
if (base == null)
base = makeOwnerThis(tree.pos(), sym, true);
args = args.prepend(base);
base = null; // so we don't duplicate code
}
Symbol access = accessSymbol(sym, tree,
enclOp, protAccess,
refSuper);
JCExpression receiver = make.Select(
base != null ? base : make.QualIdent(access.owner),
access);
return make.App(receiver, args);
// Other accesses to members of outer classes get a
// qualifier.
} else if (baseReq) {
return make.at(tree.pos).Select(
accessBase(tree.pos(), sym), sym).setType(tree.type);
}
}
}
}
return tree;
}
/** Ensure that identifier is accessible, return tree accessing the identifier.
* @param tree The identifier tree.
*/
JCExpression access(JCExpression tree) {
Symbol sym = TreeInfo.symbol(tree);
return sym == null ? tree : access(sym, tree, null, false);
}
/** Return access constructor for a private constructor,
* or the constructor itself, if no access constructor is needed.
* @param pos The position to report diagnostics, if any.
* @param constr The private constructor.
*/
Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
if (needsPrivateAccess(constr)) {
ClassSymbol accOwner = constr.owner.enclClass();
MethodSymbol aconstr = accessConstrs.get(constr);
if (aconstr == null) {
List<Type> argtypes = constr.type.getParameterTypes();
if ((accOwner.flags_field & ENUM) != 0)
argtypes = argtypes
.prepend(syms.intType)
.prepend(syms.stringType);
aconstr = new MethodSymbol(
SYNTHETIC,
names.init,
new MethodType(
argtypes.append(
accessConstructorTag().erasure(types)),
constr.type.getReturnType(),
constr.type.getThrownTypes(),
syms.methodClass),
accOwner);
enterSynthetic(pos, aconstr, accOwner.members());
accessConstrs.put(constr, aconstr);
accessed.append(constr);
}
return aconstr;
} else {
return constr;
}
}
/** Return an anonymous class nested in this toplevel class.
*/
ClassSymbol accessConstructorTag() {
ClassSymbol topClass = currentClass.outermostClass();
Name flatname = names.fromString("" + topClass.getQualifiedName() +
target.syntheticNameChar() +
"1");
ClassSymbol ctag = chk.compiled.get(flatname);
if (ctag == null)
ctag = makeEmptyClass(STATIC | SYNTHETIC, topClass);
// keep a record of all tags, to verify that all are generated as required
accessConstrTags = accessConstrTags.prepend(ctag);
return ctag;
}
/** Add all required access methods for a private symbol to enclosing class.
* @param sym The symbol.
*/
void makeAccessible(Symbol sym) {
JCClassDecl cdef = classDef(sym.owner.enclClass());
if (cdef == null) Assert.error("class def not found: " + sym + " in " + sym.owner);
if (sym.name == names.init) {
cdef.defs = cdef.defs.prepend(
accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
} else {
MethodSymbol[] accessors = accessSyms.get(sym);
for (int i = 0; i < NCODES; i++) {
if (accessors[i] != null)
cdef.defs = cdef.defs.prepend(
accessDef(cdef.pos, sym, accessors[i], i));
}
}
}
/** Construct definition of an access method.
* @param pos The source code position of the definition.
* @param vsym The private or protected symbol.
* @param accessor The access method for the symbol.
* @param acode The access code.
*/
JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
// System.err.println("access " + vsym + " with " + accessor);//DEBUG
currentClass = vsym.owner.enclClass();
make.at(pos);
JCMethodDecl md = make.MethodDef(accessor, null);
// Find actual symbol
Symbol sym = actualSymbols.get(vsym);
if (sym == null) sym = vsym;
JCExpression ref; // The tree referencing the private symbol.
List<JCExpression> args; // Any additional arguments to be passed along.
if ((sym.flags() & STATIC) != 0) {
ref = make.Ident(sym);
args = make.Idents(md.params);
} else {
ref = make.Select(make.Ident(md.params.head), sym);
args = make.Idents(md.params.tail);
}
JCStatement stat; // The statement accessing the private symbol.
if (sym.kind == VAR) {
// Normalize out all odd access codes by taking floor modulo 2:
int acode1 = acode - (acode & 1);
JCExpression expr; // The access method's return value.
switch (acode1) {
case DEREFcode:
expr = ref;
break;
case ASSIGNcode:
expr = make.Assign(ref, args.head);
break;
case PREINCcode: case POSTINCcode: case PREDECcode: case POSTDECcode:
expr = makeUnary(
((acode1 - PREINCcode) >> 1) + JCTree.PREINC, ref);
break;
default:
expr = make.Assignop(
treeTag(binaryAccessOperator(acode1)), ref, args.head);
((JCAssignOp) expr).operator = binaryAccessOperator(acode1);
}
stat = make.Return(expr.setType(sym.type));
} else {
stat = make.Call(make.App(ref, args));
}
md.body = make.Block(0, List.of(stat));
// Make sure all parameters, result types and thrown exceptions
// are accessible.
for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
l.head.vartype = access(l.head.vartype);
md.restype = access(md.restype);
for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
l.head = access(l.head);
return md;
}
/** Construct definition of an access constructor.
* @param pos The source code position of the definition.
* @param constr The private constructor.
* @param accessor The access method for the constructor.
*/
JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
make.at(pos);
JCMethodDecl md = make.MethodDef(accessor,
accessor.externalType(types),
null);
JCIdent callee = make.Ident(names._this);
callee.sym = constr;
callee.type = constr.type;
md.body =
make.Block(0, List.<JCStatement>of(
make.Call(
make.App(
callee,
make.Idents(md.params.reverse().tail.reverse())))));
return md;
}
/**************************************************************************
* Free variables proxies and this$n
*************************************************************************/
/** A scope containing all free variable proxies for currently translated
* class, as well as its this$n symbol (if needed).
* Proxy scopes are nested in the same way classes are.
* Inside a constructor, proxies and any this$n symbol are duplicated
* in an additional innermost scope, where they represent the constructor
* parameters.
*/
Scope proxies;
/** A scope containing all unnamed resource variables/saved
* exception variables for translated TWR blocks
*/
Scope twrVars;
/** A stack containing the this$n field of the currently translated
* classes (if needed) in innermost first order.
* Inside a constructor, proxies and any this$n symbol are duplicated
* in an additional innermost scope, where they represent the constructor
* parameters.
*/
List<VarSymbol> outerThisStack;
/** The name of a free variable proxy.
*/
Name proxyName(Name name) {
return names.fromString("val" + target.syntheticNameChar() + name);
}
/** Proxy definitions for all free variables in given list, in reverse order.
* @param pos The source code position of the definition.
* @param freevars The free variables.
* @param owner The class in which the definitions go.
*/
List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
long flags = FINAL | SYNTHETIC;
if (owner.kind == TYP &&
target.usePrivateSyntheticFields())
flags |= PRIVATE;
List<JCVariableDecl> defs = List.nil();
for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
VarSymbol v = l.head;
VarSymbol proxy = new VarSymbol(
flags, proxyName(v.name), v.erasure(types), owner);
proxies.enter(proxy);
JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
vd.vartype = access(vd.vartype);
defs = defs.prepend(vd);
}
return defs;
}
/** 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.tag == CLASS) {
t = t.getEnclosingType();
nestingLevel++;
}
Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
while (owner.kind == TYP && ((ClassSymbol)owner).members().lookup(result).scope != null)
result = names.fromString(result.toString() + target.syntheticNameChar());
return result;
}
/** Definition for this$n field.
* @param pos The source code position of the definition.
* @param owner The class in which the definition goes.
*/
JCVariableDecl outerThisDef(int pos, Symbol owner) {
long flags = FINAL | SYNTHETIC;
if (owner.kind == TYP &&
target.usePrivateSyntheticFields())
flags |= PRIVATE;
Type target = types.erasure(owner.enclClass().type.getEnclosingType());
VarSymbol outerThis = new VarSymbol(
flags, outerThisName(target, owner), target, owner);
outerThisStack = outerThisStack.prepend(outerThis);
JCVariableDecl vd = make.at(pos).VarDef(outerThis, null);
vd.vartype = access(vd.vartype);
return vd;
}
/** Return a list of trees that load the free variables in given list,
* in reverse order.
* @param pos The source code position to be used for the trees.
* @param freevars The list of free variables.
*/
List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
List<JCExpression> args = List.nil();
for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
args = args.prepend(loadFreevar(pos, l.head));
return args;
}
//where
JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
return access(v, make.at(pos).Ident(v), null, false);
}
/** Construct a tree simulating the expression <C.this>.
* @param pos The source code position to be used for the tree.
* @param c The qualifier class.
*/
JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
if (currentClass == c) {
// in this case, `this' works fine
return make.at(pos).This(c.erasure(types));
} else {
// need to go via this$n
return makeOuterThis(pos, c);
}
}
/**
* Optionally replace a try statement with the desugaring of a
* try-with-resources statement. The canonical desugaring of
*
* try ResourceSpecification
* Block
*
* is
*
* {
* final VariableModifiers_minus_final R #resource = Expression;
* Throwable #primaryException = null;
*
* try ResourceSpecificationtail
* Block
* catch (Throwable #t) {
* #primaryException = t;
* throw #t;
* } finally {
* if (#resource != null) {
* if (#primaryException != null) {
* try {
* #resource.close();
* } catch(Throwable #suppressedException) {
* #primaryException.addSuppressed(#suppressedException);
* }
* } else {
* #resource.close();
* }
* }
* }
*
* @param tree The try statement to inspect.
* @return A a desugared try-with-resources tree, or the original
* try block if there are no resources to manage.
*/
JCTree makeTwrTry(JCTry tree) {
make_at(tree.pos());
twrVars = twrVars.dup();
JCBlock twrBlock = makeTwrBlock(tree.resources, tree.body, 0);
if (tree.catchers.isEmpty() && tree.finalizer == null)
result = translate(twrBlock);
else
result = translate(make.Try(twrBlock, tree.catchers, tree.finalizer));
twrVars = twrVars.leave();
return result;
}
private JCBlock makeTwrBlock(List<JCTree> resources, JCBlock block, int depth) {
if (resources.isEmpty())
return block;
// Add resource declaration or expression to block statements
ListBuffer<JCStatement> stats = new ListBuffer<JCStatement>();
JCTree resource = resources.head;
JCExpression expr = null;
if (resource instanceof JCVariableDecl) {
JCVariableDecl var = (JCVariableDecl) resource;
expr = make.Ident(var.sym).setType(resource.type);
stats.add(var);
} else {
Assert.check(resource instanceof JCExpression);
VarSymbol syntheticTwrVar =
new VarSymbol(SYNTHETIC | FINAL,
makeSyntheticName(names.fromString("twrVar" +
depth), twrVars),
(resource.type.tag == TypeTags.BOT) ?
syms.autoCloseableType : resource.type,
currentMethodSym);
twrVars.enter(syntheticTwrVar);
JCVariableDecl syntheticTwrVarDecl =
make.VarDef(syntheticTwrVar, (JCExpression)resource);
expr = (JCExpression)make.Ident(syntheticTwrVar);
stats.add(syntheticTwrVarDecl);
}
// Add primaryException declaration
VarSymbol primaryException =
new VarSymbol(SYNTHETIC,
makeSyntheticName(names.fromString("primaryException" +
depth), twrVars),
syms.throwableType,
currentMethodSym);
twrVars.enter(primaryException);
JCVariableDecl primaryExceptionTreeDecl = make.VarDef(primaryException, makeNull());
stats.add(primaryExceptionTreeDecl);
// Create catch clause that saves exception and then rethrows it
VarSymbol param =
new VarSymbol(FINAL|SYNTHETIC,
names.fromString("t" +
target.syntheticNameChar()),
syms.throwableType,
currentMethodSym);
JCVariableDecl paramTree = make.VarDef(param, null);
JCStatement assign = make.Assignment(primaryException, make.Ident(param));
JCStatement rethrowStat = make.Throw(make.Ident(param));
JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(assign, rethrowStat));
JCCatch catchClause = make.Catch(paramTree, catchBlock);
int oldPos = make.pos;
make.at(TreeInfo.endPos(block));
JCBlock finallyClause = makeTwrFinallyClause(primaryException, expr);
make.at(oldPos);
JCTry outerTry = make.Try(makeTwrBlock(resources.tail, block, depth + 1),
List.<JCCatch>of(catchClause),
finallyClause);
stats.add(outerTry);
return make.Block(0L, stats.toList());
}
private JCBlock makeTwrFinallyClause(Symbol primaryException, JCExpression resource) {
// primaryException.addSuppressed(catchException);
VarSymbol catchException =
new VarSymbol(0, make.paramName(2),
syms.throwableType,
currentMethodSym);
JCStatement addSuppressionStatement =
make.Exec(makeCall(make.Ident(primaryException),
names.addSuppressed,
List.<JCExpression>of(make.Ident(catchException))));
// try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
JCBlock tryBlock =
make.Block(0L, List.<JCStatement>of(makeResourceCloseInvocation(resource)));
JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(addSuppressionStatement));
List<JCCatch> catchClauses = List.<JCCatch>of(make.Catch(catchExceptionDecl, catchBlock));
JCTry tryTree = make.Try(tryBlock, catchClauses, null);
// if (primaryException != null) {try...} else resourceClose;
JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
tryTree,
makeResourceCloseInvocation(resource));
// if (#resource != null) { if (primaryException ... }
return make.Block(0L,
List.<JCStatement>of(make.If(makeNonNullCheck(resource),
closeIfStatement,
null)));
}
private JCStatement makeResourceCloseInvocation(JCExpression resource) {
// create resource.close() method invocation
JCExpression resourceClose = makeCall(resource,
names.close,
List.<JCExpression>nil());
return make.Exec(resourceClose);
}
private JCExpression makeNonNullCheck(JCExpression expression) {
return makeBinary(JCTree.NE, expression, makeNull());
}
/** Construct a tree that represents the outer instance
* <C.this>. Never pick the current `this'.
* @param pos The source code position to be used for the tree.
* @param c The qualifier class.
*/
JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
List<VarSymbol> ots = outerThisStack;
if (ots.isEmpty()) {
log.error(pos, "no.encl.instance.of.type.in.scope", c);
Assert.error();
return makeNull();
}
VarSymbol ot = ots.head;
JCExpression tree = access(make.at(pos).Ident(ot));
TypeSymbol otc = ot.type.tsym;
while (otc != c) {
do {
ots = ots.tail;
if (ots.isEmpty()) {
log.error(pos,
"no.encl.instance.of.type.in.scope",
c);
Assert.error(); // should have been caught in Attr
return tree;
}
ot = ots.head;
} while (ot.owner != otc);
if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
chk.earlyRefError(pos, c);
Assert.error(); // should have been caught in Attr
return makeNull();
}
tree = access(make.at(pos).Select(tree, ot));
otc = ot.type.tsym;
}
return tree;
}
/** Construct a tree that represents the closest outer instance
* <C.this> such that the given symbol is a member of C.
* @param pos The source code position to be used for the tree.
* @param sym The accessed symbol.
* @param preciseMatch should we accept a type that is a subtype of
* sym's owner, even if it doesn't contain sym
* due to hiding, overriding, or non-inheritance
* due to protection?
*/
JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
Symbol c = sym.owner;
if (preciseMatch ? sym.isMemberOf(currentClass, types)
: currentClass.isSubClass(sym.owner, types)) {
// in this case, `this' works fine
return make.at(pos).This(c.erasure(types));
} else {
// need to go via this$n
return makeOwnerThisN(pos, sym, preciseMatch);
}
}
/**
* Similar to makeOwnerThis but will never pick "this".
*/
JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
Symbol c = sym.owner;
List<VarSymbol> ots = outerThisStack;
if (ots.isEmpty()) {
log.error(pos, "no.encl.instance.of.type.in.scope", c);
Assert.error();
return makeNull();
}
VarSymbol ot = ots.head;
JCExpression tree = access(make.at(pos).Ident(ot));
TypeSymbol otc = ot.type.tsym;
while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
do {
ots = ots.tail;
if (ots.isEmpty()) {
log.error(pos,
"no.encl.instance.of.type.in.scope",
c);
Assert.error();
return tree;
}
ot = ots.head;
} while (ot.owner != otc);
tree = access(make.at(pos).Select(tree, ot));
otc = ot.type.tsym;
}
return tree;
}
/** Return tree simulating the assignment <this.name = name>, where
* name is the name of a free variable.
*/
JCStatement initField(int pos, Name name) {
Scope.Entry e = proxies.lookup(name);
Symbol rhs = e.sym;
Assert.check(rhs.owner.kind == MTH);
Symbol lhs = e.next().sym;
Assert.check(rhs.owner.owner == lhs.owner);
make.at(pos);
return
make.Exec(
make.Assign(
make.Select(make.This(lhs.owner.erasure(types)), lhs),
make.Ident(rhs)).setType(lhs.erasure(types)));
}
/** Return tree simulating the assignment <this.this$n = this$n>.
*/
JCStatement initOuterThis(int pos) {
VarSymbol rhs = outerThisStack.head;
Assert.check(rhs.owner.kind == MTH);
VarSymbol lhs = outerThisStack.tail.head;
Assert.check(rhs.owner.owner == lhs.owner);
make.at(pos);
return
make.Exec(
make.Assign(
make.Select(make.This(lhs.owner.erasure(types)), lhs),
make.Ident(rhs)).setType(lhs.erasure(types)));
}
/**************************************************************************
* Code for .class
*************************************************************************/
/** Return the symbol of a class to contain a cache of
* compiler-generated statics such as class$ and the
* $assertionsDisabled flag. We create an anonymous nested class
* (unless one already exists) and return its symbol. However,
* for backward compatibility in 1.4 and earlier we use the
* top-level class itself.
*/
private ClassSymbol outerCacheClass() {
ClassSymbol clazz = outermostClassDef.sym;
if ((clazz.flags() & INTERFACE) == 0 &&
!target.useInnerCacheClass()) return clazz;
Scope s = clazz.members();
for (Scope.Entry e = s.elems; e != null; e = e.sibling)
if (e.sym.kind == TYP &&
e.sym.name == names.empty &&
(e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
return makeEmptyClass(STATIC | SYNTHETIC, clazz);
}
/** Return symbol for "class$" method. If there is no method definition
* for class$, construct one as follows:
*
* class class$(String x0) {
* try {
* return Class.forName(x0);
* } catch (ClassNotFoundException x1) {
* throw new NoClassDefFoundError(x1.getMessage());
* }
* }
*/
private MethodSymbol classDollarSym(DiagnosticPosition pos) {
ClassSymbol outerCacheClass = outerCacheClass();
MethodSymbol classDollarSym =
(MethodSymbol)lookupSynthetic(classDollar,
outerCacheClass.members());
if (classDollarSym == null) {
classDollarSym = new MethodSymbol(
STATIC | SYNTHETIC,
classDollar,
new MethodType(
List.of(syms.stringType),
types.erasure(syms.classType),
List.<Type>nil(),
syms.methodClass),
outerCacheClass);
enterSynthetic(pos, classDollarSym, outerCacheClass.members());
JCMethodDecl md = make.MethodDef(classDollarSym, null);
try {
md.body = classDollarSymBody(pos, md);
} catch (CompletionFailure ex) {
md.body = make.Block(0, List.<JCStatement>nil());
chk.completionError(pos, ex);
}
JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
}
return classDollarSym;
}
/** Generate code for class$(String name). */
JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
MethodSymbol classDollarSym = md.sym;
ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
JCBlock returnResult;
// in 1.4.2 and above, we use
// Class.forName(String name, boolean init, ClassLoader loader);
// which requires we cache the current loader in cl$
if (target.classLiteralsNoInit()) {
// clsym = "private static ClassLoader cl$"
VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
names.fromString("cl" + target.syntheticNameChar()),
syms.classLoaderType,
outerCacheClass);
enterSynthetic(pos, clsym, outerCacheClass.members());
// emit "private static ClassLoader cl$;"
JCVariableDecl cldef = make.VarDef(clsym, null);
JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
// newcache := "new cache$1[0]"
JCNewArray newcache = make.
NewArray(make.Type(outerCacheClass.type),
List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
null);
newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
syms.arrayClass);
// forNameSym := java.lang.Class.forName(
// String s,boolean init,ClassLoader loader)
Symbol forNameSym = lookupMethod(make_pos, names.forName,
types.erasure(syms.classType),
List.of(syms.stringType,
syms.booleanType,
syms.classLoaderType));
// clvalue := "(cl$ == null) ?
// $newcache.getClass().getComponentType().getClassLoader() : cl$"
JCExpression clvalue =
make.Conditional(
makeBinary(JCTree.EQ, make.Ident(clsym), makeNull()),
make.Assign(
make.Ident(clsym),
makeCall(
makeCall(makeCall(newcache,
names.getClass,
List.<JCExpression>nil()),
names.getComponentType,
List.<JCExpression>nil()),
names.getClassLoader,
List.<JCExpression>nil())).setType(syms.classLoaderType),
make.Ident(clsym)).setType(syms.classLoaderType);
// returnResult := "{ return Class.forName(param1, false, cl$); }"
List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
makeLit(syms.booleanType, 0),
clvalue);
returnResult = make.
Block(0, List.<JCStatement>of(make.
Call(make. // return
App(make.
Ident(forNameSym), args))));
} else {
// forNameSym := java.lang.Class.forName(String s)
Symbol forNameSym = lookupMethod(make_pos,
names.forName,
types.erasure(syms.classType),
List.of(syms.stringType));
// returnResult := "{ return Class.forName(param1); }"
returnResult = make.
Block(0, List.of(make.
Call(make. // return
App(make.
QualIdent(forNameSym),
List.<JCExpression>of(make.
Ident(md.params.
head.sym))))));
}
// catchParam := ClassNotFoundException e1
VarSymbol catchParam =
new VarSymbol(0, make.paramName(1),
syms.classNotFoundExceptionType,
classDollarSym);
JCStatement rethrow;
if (target.hasInitCause()) {
// rethrow = "throw new NoClassDefFoundError().initCause(e);
JCTree throwExpr =
makeCall(makeNewClass(syms.noClassDefFoundErrorType,
List.<JCExpression>nil()),
names.initCause,
List.<JCExpression>of(make.Ident(catchParam)));
rethrow = make.Throw(throwExpr);
} else {
// getMessageSym := ClassNotFoundException.getMessage()
Symbol getMessageSym = lookupMethod(make_pos,
names.getMessage,
syms.classNotFoundExceptionType,
List.<Type>nil());
// rethrow = "throw new NoClassDefFoundError(e.getMessage());"
rethrow = make.
Throw(makeNewClass(syms.noClassDefFoundErrorType,
List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
getMessageSym),
List.<JCExpression>nil()))));
}
// rethrowStmt := "( $rethrow )"
JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
// catchBlock := "catch ($catchParam) $rethrowStmt"
JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
rethrowStmt);
// tryCatch := "try $returnResult $catchBlock"
JCStatement tryCatch = make.Try(returnResult,
List.of(catchBlock), null);
return make.Block(0, List.of(tryCatch));
}
// where
/** Create an attributed tree of the form left.name(). */
private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
Assert.checkNonNull(left.type);
Symbol funcsym = lookupMethod(make_pos, name, left.type,
TreeInfo.types(args));
return make.App(make.Select(left, funcsym), args);
}
/** The Name Of The variable to cache T.class values.
* @param sig The signature of type T.
*/
private Name cacheName(String sig) {
StringBuffer buf = new StringBuffer();
if (sig.startsWith("[")) {
buf = buf.append("array");
while (sig.startsWith("[")) {
buf = buf.append(target.syntheticNameChar());
sig = sig.substring(1);
}
if (sig.startsWith("L")) {
sig = sig.substring(0, sig.length() - 1);
}
} else {
buf = buf.append("class" + target.syntheticNameChar());
}
buf = buf.append(sig.replace('.', target.syntheticNameChar()));
return names.fromString(buf.toString());
}
/** The variable symbol that caches T.class values.
* If none exists yet, create a definition.
* @param sig The signature of type T.
* @param pos The position to report diagnostics, if any.
*/
private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
ClassSymbol outerCacheClass = outerCacheClass();
Name cname = cacheName(sig);
VarSymbol cacheSym =
(VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
if (cacheSym == null) {
cacheSym = new VarSymbol(
STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
enterSynthetic(pos, cacheSym, outerCacheClass.members());
JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
}
return cacheSym;
}
/** The tree simulating a T.class expression.
* @param clazz The tree identifying type T.
*/
private JCExpression classOf(JCTree clazz) {
return classOfType(clazz.type, clazz.pos());
}
private JCExpression classOfType(Type type, DiagnosticPosition pos) {
switch (type.tag) {
case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
case DOUBLE: case BOOLEAN: case VOID:
// replace with <BoxedClass>.TYPE
ClassSymbol c = types.boxedClass(type);
Symbol typeSym =
rs.access(
rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
pos, c.type, names.TYPE, true);
if (typeSym.kind == VAR)
((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
return make.QualIdent(typeSym);
case CLASS: case ARRAY:
if (target.hasClassLiterals()) {
VarSymbol sym = new VarSymbol(
STATIC | PUBLIC | FINAL, names._class,
syms.classType, type.tsym);
return make_at(pos).Select(make.Type(type), sym);
}
// replace with <cache == null ? cache = class$(tsig) : cache>
// where
// - <tsig> is the type signature of T,
// - <cache> is the cache variable for tsig.
String sig =
writer.xClassName(type).toString().replace('/', '.');
Symbol cs = cacheSym(pos, sig);
return make_at(pos).Conditional(
makeBinary(JCTree.EQ, make.Ident(cs), makeNull()),
make.Assign(
make.Ident(cs),
make.App(
make.Ident(classDollarSym(pos)),
List.<JCExpression>of(make.Literal(CLASS, sig)
.setType(syms.stringType))))
.setType(types.erasure(syms.classType)),
make.Ident(cs)).setType(types.erasure(syms.classType));
default:
throw new AssertionError();
}
}
/**************************************************************************
* Code for enabling/disabling assertions.
*************************************************************************/
// This code is not particularly robust if the user has
// previously declared a member named '$assertionsDisabled'.
// The same faulty idiom also appears in the translation of
// class literals above. We should report an error if a
// previous declaration is not synthetic.
private JCExpression assertFlagTest(DiagnosticPosition pos) {
// Outermost class may be either true class or an interface.
ClassSymbol outermostClass = outermostClassDef.sym;
// note that this is a class, as an interface can't contain a statement.
ClassSymbol container = currentClass;
VarSymbol assertDisabledSym =
(VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
container.members());
if (assertDisabledSym == null) {
assertDisabledSym =
new VarSymbol(STATIC | FINAL | SYNTHETIC,
dollarAssertionsDisabled,
syms.booleanType,
container);
enterSynthetic(pos, assertDisabledSym, container.members());
Symbol desiredAssertionStatusSym = lookupMethod(pos,
names.desiredAssertionStatus,
types.erasure(syms.classType),
List.<Type>nil());
JCClassDecl containerDef = classDef(container);
make_at(containerDef.pos());
JCExpression notStatus = makeUnary(JCTree.NOT, make.App(make.Select(
classOfType(types.erasure(outermostClass.type),
containerDef.pos()),
desiredAssertionStatusSym)));
JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
notStatus);
containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
}
make_at(pos);
return makeUnary(JCTree.NOT, make.Ident(assertDisabledSym));
}
/**************************************************************************
* Building blocks for let expressions
*************************************************************************/
interface TreeBuilder {
JCTree build(JCTree arg);
}
/** Construct an expression using the builder, with the given rval
* expression as an argument to the builder. However, the rval
* expression must be computed only once, even if used multiple
* times in the result of the builder. We do that by
* constructing a "let" expression that saves the rvalue into a
* temporary variable and then uses the temporary variable in
* place of the expression built by the builder. The complete
* resulting expression is of the form
* <pre>
* (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
* in (<b>BUILDER</b>(<b>TEMP</b>)))
* </pre>
* where <code><b>TEMP</b></code> is a newly declared variable
* in the let expression.
*/
JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
rval = TreeInfo.skipParens(rval);
switch (rval.getTag()) {
case JCTree.LITERAL:
return builder.build(rval);
case JCTree.IDENT:
JCIdent id = (JCIdent) rval;
if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
return builder.build(rval);
}
VarSymbol var =
new VarSymbol(FINAL|SYNTHETIC,
names.fromString(
target.syntheticNameChar()
+ "" + rval.hashCode()),
type,
currentMethodSym);
rval = convert(rval,type);
JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
JCTree built = builder.build(make.Ident(var));
JCTree res = make.LetExpr(def, built);
res.type = built.type;
return res;
}
// same as above, with the type of the temporary variable computed
JCTree abstractRval(JCTree rval, TreeBuilder builder) {
return abstractRval(rval, rval.type, builder);
}
// same as above, but for an expression that may be used as either
// an rvalue or an lvalue. This requires special handling for
// Select expressions, where we place the left-hand-side of the
// select in a temporary, and for Indexed expressions, where we
// place both the indexed expression and the index value in temps.
JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
lval = TreeInfo.skipParens(lval);
switch (lval.getTag()) {
case JCTree.IDENT:
return builder.build(lval);
case JCTree.SELECT: {
final JCFieldAccess s = (JCFieldAccess)lval;
JCTree selected = TreeInfo.skipParens(s.selected);
Symbol lid = TreeInfo.symbol(s.selected);
if (lid != null && lid.kind == TYP) return builder.build(lval);
return abstractRval(s.selected, new TreeBuilder() {
public JCTree build(final JCTree selected) {
return builder.build(make.Select((JCExpression)selected, s.sym));
}
});
}
case JCTree.INDEXED: {
final JCArrayAccess i = (JCArrayAccess)lval;
return abstractRval(i.indexed, new TreeBuilder() {
public JCTree build(final JCTree indexed) {
return abstractRval(i.index, syms.intType, new TreeBuilder() {
public JCTree build(final JCTree index) {
JCTree newLval = make.Indexed((JCExpression)indexed,
(JCExpression)index);
newLval.setType(i.type);
return builder.build(newLval);
}
});
}
});
}
case JCTree.TYPECAST: {
return abstractLval(((JCTypeCast)lval).expr, builder);
}
}
throw new AssertionError(lval);
}
// evaluate and discard the first expression, then evaluate the second.
JCTree makeComma(final JCTree expr1, final JCTree expr2) {
return abstractRval(expr1, new TreeBuilder() {
public JCTree build(final JCTree discarded) {
return expr2;
}
});
}
/**************************************************************************
* Translation methods
*************************************************************************/
/** Visitor argument: enclosing operator node.
*/
private JCExpression enclOp;
/** Visitor method: Translate a single node.
* Attach the source position from the old tree to its replacement tree.
*/
public <T extends JCTree> T translate(T tree) {
if (tree == null) {
return null;
} else {
make_at(tree.pos());
T result = super.translate(tree);
if (endPositions != null && result != tree) {
Integer endPos = endPositions.remove(tree);
if (endPos != null) endPositions.put(result, endPos);
}
return result;
}
}
/** Visitor method: Translate a single node, boxing or unboxing if needed.
*/
public <T extends JCTree> T translate(T tree, Type type) {
return (tree == null) ? null : boxIfNeeded(translate(tree), type);
}
/** Visitor method: Translate tree.
*/
public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
JCExpression prevEnclOp = this.enclOp;
this.enclOp = enclOp;
T res = translate(tree);
this.enclOp = prevEnclOp;
return res;
}
/** Visitor method: Translate list of trees.
*/
public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
JCExpression prevEnclOp = this.enclOp;
this.enclOp = enclOp;
List<T> res = translate(trees);
this.enclOp = prevEnclOp;
return res;
}
/** Visitor method: Translate list of trees.
*/
public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
if (trees == null) return null;
for (List<T> l = trees; l.nonEmpty(); l = l.tail)
l.head = translate(l.head, type);
return trees;
}
public void visitTopLevel(JCCompilationUnit tree) {
if (needPackageInfoClass(tree)) {
Name name = names.package_info;
long flags = Flags.ABSTRACT | Flags.INTERFACE;
if (target.isPackageInfoSynthetic())
// package-info is marked SYNTHETIC in JDK 1.6 and later releases
flags = flags | Flags.SYNTHETIC;
JCClassDecl packageAnnotationsClass
= make.ClassDef(make.Modifiers(flags,
tree.packageAnnotations),
name, List.<JCTypeParameter>nil(),
null, List.<JCExpression>nil(), List.<JCTree>nil());
ClassSymbol c = tree.packge.package_info;
c.flags_field |= flags;
c.attributes_field = tree.packge.attributes_field;
ClassType ctype = (ClassType) c.type;
ctype.supertype_field = syms.objectType;
ctype.interfaces_field = List.nil();
packageAnnotationsClass.sym = c;
translated.append(packageAnnotationsClass);
}
}
// where
private boolean needPackageInfoClass(JCCompilationUnit tree) {
switch (pkginfoOpt) {
case ALWAYS:
return true;
case LEGACY:
return tree.packageAnnotations.nonEmpty();
case NONEMPTY:
for (Attribute.Compound a: tree.packge.attributes_field) {
Attribute.RetentionPolicy p = types.getRetention(a);
if (p != Attribute.RetentionPolicy.SOURCE)
return true;
}
return false;
}
throw new AssertionError();
}
public void visitClassDef(JCClassDecl tree) {
ClassSymbol currentClassPrev = currentClass;
MethodSymbol currentMethodSymPrev = currentMethodSym;
currentClass = tree.sym;
currentMethodSym = null;
classdefs.put(currentClass, tree);
proxies = proxies.dup(currentClass);
List<VarSymbol> prevOuterThisStack = outerThisStack;
// If this is an enum definition
if ((tree.mods.flags & ENUM) != 0 &&
(types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
visitEnumDef(tree);
// If this is a nested class, define a this$n field for
// it and add to proxies.
JCVariableDecl otdef = null;
if (currentClass.hasOuterInstance())
otdef = outerThisDef(tree.pos, currentClass);
// If this is a local class, define proxies for all its free variables.
List<JCVariableDecl> fvdefs = freevarDefs(
tree.pos, freevars(currentClass), currentClass);
// Recursively translate superclass, interfaces.
tree.extending = translate(tree.extending);
tree.implementing = translate(tree.implementing);
if (currentClass.isLocal()) {
ClassSymbol encl = currentClass.owner.enclClass();
if (encl.trans_local == null) {
encl.trans_local = List.nil();
}
encl.trans_local = encl.trans_local.prepend(currentClass);
}
// Recursively translate members, taking into account that new members
// might be created during the translation and prepended to the member
// list `tree.defs'.
List<JCTree> seen = List.nil();
while (tree.defs != seen) {
List<JCTree> unseen = tree.defs;
for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
JCTree outermostMemberDefPrev = outermostMemberDef;
if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
l.head = translate(l.head);
outermostMemberDef = outermostMemberDefPrev;
}
seen = unseen;
}
// Convert a protected modifier to public, mask static modifier.
if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
tree.mods.flags &= ClassFlags;
// Convert name to flat representation, replacing '.' by '$'.
tree.name = Convert.shortName(currentClass.flatName());
// Add this$n and free variables proxy definitions to class.
for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
tree.defs = tree.defs.prepend(l.head);
enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
}
if (currentClass.hasOuterInstance()) {
tree.defs = tree.defs.prepend(otdef);
enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
}
proxies = proxies.leave();
outerThisStack = prevOuterThisStack;
// Append translated tree to `translated' queue.
translated.append(tree);
currentClass = currentClassPrev;
currentMethodSym = currentMethodSymPrev;
// Return empty block {} as a placeholder for an inner class.
result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
}
/** Translate an enum class. */
private void visitEnumDef(JCClassDecl tree) {
make_at(tree.pos());
// add the supertype, if needed
if (tree.extending == null)
tree.extending = make.Type(types.supertype(tree.type));
// classOfType adds a cache field to tree.defs unless
// target.hasClassLiterals().
JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
setType(types.erasure(syms.classType));
// process each enumeration constant, adding implicit constructor parameters
int nextOrdinal = 0;
ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
for (List<JCTree> defs = tree.defs;
defs.nonEmpty();
defs=defs.tail) {
if (defs.head.getTag() == JCTree.VARDEF && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
JCVariableDecl var = (JCVariableDecl)defs.head;
visitEnumConstantDef(var, nextOrdinal++);
values.append(make.QualIdent(var.sym));
enumDefs.append(var);
} else {
otherDefs.append(defs.head);
}
}
// private static final T[] #VALUES = { a, b, c };
Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
valuesName,
arrayType,
tree.type.tsym);
JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
List.<JCExpression>nil(),
values.toList());
newArray.type = arrayType;
enumDefs.append(make.VarDef(valuesVar, newArray));
tree.sym.members().enter(valuesVar);
Symbol valuesSym = lookupMethod(tree.pos(), names.values,
tree.type, List.<Type>nil());
List<JCStatement> valuesBody;
if (useClone()) {
// return (T[]) $VALUES.clone();
JCTypeCast valuesResult =
make.TypeCast(valuesSym.type.getReturnType(),
make.App(make.Select(make.Ident(valuesVar),
syms.arrayCloneMethod)));
valuesBody = List.<JCStatement>of(make.Return(valuesResult));
} else {
// template: T[] $result = new T[$values.length];
Name resultName = names.fromString(target.syntheticNameChar() + "result");
while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
resultName = names.fromString(resultName + "" + target.syntheticNameChar());
VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
resultName,
arrayType,
valuesSym);
JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
null);
resultArray.type = arrayType;
JCVariableDecl decl = make.VarDef(resultVar, resultArray);
// template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
if (systemArraycopyMethod == null) {
systemArraycopyMethod =
new MethodSymbol(PUBLIC | STATIC,
names.fromString("arraycopy"),
new MethodType(List.<Type>of(syms.objectType,
syms.intType,
syms.objectType,
syms.intType,
syms.intType),
syms.voidType,
List.<Type>nil(),
syms.methodClass),
syms.systemType.tsym);
}
JCStatement copy =
make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
systemArraycopyMethod),
List.of(make.Ident(valuesVar), make.Literal(0),
make.Ident(resultVar), make.Literal(0),
make.Select(make.Ident(valuesVar), syms.lengthVar))));
// template: return $result;
JCStatement ret = make.Return(make.Ident(resultVar));
valuesBody = List.<JCStatement>of(decl, copy, ret);
}
JCMethodDecl valuesDef =
make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
enumDefs.append(valuesDef);
if (debugLower)
System.err.println(tree.sym + ".valuesDef = " + valuesDef);
/** The template for the following code is:
*
* public static E valueOf(String name) {
* return (E)Enum.valueOf(E.class, name);
* }
*
* where E is tree.sym
*/
MethodSymbol valueOfSym = lookupMethod(tree.pos(),
names.valueOf,
tree.sym.type,
List.of(syms.stringType));
Assert.check((valueOfSym.flags() & STATIC) != 0);
VarSymbol nameArgSym = valueOfSym.params.head;
JCIdent nameVal = make.Ident(nameArgSym);
JCStatement enum_ValueOf =
make.Return(make.TypeCast(tree.sym.type,
makeCall(make.Ident(syms.enumSym),
names.valueOf,
List.of(e_class, nameVal))));
JCMethodDecl valueOf = make.MethodDef(valueOfSym,
make.Block(0, List.of(enum_ValueOf)));
nameVal.sym = valueOf.params.head.sym;
if (debugLower)
System.err.println(tree.sym + ".valueOf = " + valueOf);
enumDefs.append(valueOf);
enumDefs.appendList(otherDefs.toList());
tree.defs = enumDefs.toList();
// Add the necessary members for the EnumCompatibleMode
if (target.compilerBootstrap(tree.sym)) {
addEnumCompatibleMembers(tree);
}
}
// where
private MethodSymbol systemArraycopyMethod;
private boolean useClone() {
try {
Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
return (e.sym != null);
}
catch (CompletionFailure e) {
return false;
}
}
/** Translate an enumeration constant and its initializer. */
private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
JCNewClass varDef = (JCNewClass)var.init;
varDef.args = varDef.args.
prepend(makeLit(syms.intType, ordinal)).
prepend(makeLit(syms.stringType, var.name.toString()));
}
public void visitMethodDef(JCMethodDecl tree) {
if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
// Add "String $enum$name, int $enum$ordinal" to the beginning of the
// argument list for each constructor of an enum.
JCVariableDecl nameParam = make_at(tree.pos()).
Param(names.fromString(target.syntheticNameChar() +
"enum" + target.syntheticNameChar() + "name"),
syms.stringType, tree.sym);
nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
JCVariableDecl ordParam = make.
Param(names.fromString(target.syntheticNameChar() +
"enum" + target.syntheticNameChar() +
"ordinal"),
syms.intType, tree.sym);
ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
tree.params = tree.params.prepend(ordParam).prepend(nameParam);
MethodSymbol m = tree.sym;
Type olderasure = m.erasure(types);
m.erasure_field = new MethodType(
olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
olderasure.getReturnType(),
olderasure.getThrownTypes(),
syms.methodClass);
if (target.compilerBootstrap(m.owner)) {
// Initialize synthetic name field
Symbol nameVarSym = lookupSynthetic(names.fromString("$name"),
tree.sym.owner.members());
JCIdent nameIdent = make.Ident(nameParam.sym);
JCIdent id1 = make.Ident(nameVarSym);
JCAssign newAssign = make.Assign(id1, nameIdent);
newAssign.type = id1.type;
JCExpressionStatement nameAssign = make.Exec(newAssign);
nameAssign.type = id1.type;
tree.body.stats = tree.body.stats.prepend(nameAssign);
// Initialize synthetic ordinal field
Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"),
tree.sym.owner.members());
JCIdent ordIdent = make.Ident(ordParam.sym);
id1 = make.Ident(ordinalVarSym);
newAssign = make.Assign(id1, ordIdent);
newAssign.type = id1.type;
JCExpressionStatement ordinalAssign = make.Exec(newAssign);
ordinalAssign.type = id1.type;
tree.body.stats = tree.body.stats.prepend(ordinalAssign);
}
}
JCMethodDecl prevMethodDef = currentMethodDef;
MethodSymbol prevMethodSym = currentMethodSym;
try {
currentMethodDef = tree;
currentMethodSym = tree.sym;
visitMethodDefInternal(tree);
} finally {
currentMethodDef = prevMethodDef;
currentMethodSym = prevMethodSym;
}
}
//where
private void visitMethodDefInternal(JCMethodDecl tree) {
if (tree.name == names.init &&
(currentClass.isInner() ||
(currentClass.owner.kind & (VAR | MTH)) != 0)) {
// We are seeing a constructor of an inner class.
MethodSymbol m = tree.sym;
// Push a new proxy scope for constructor parameters.
// and create definitions for any this$n and proxy parameters.
proxies = proxies.dup(m);
List<VarSymbol> prevOuterThisStack = outerThisStack;
List<VarSymbol> fvs = freevars(currentClass);
JCVariableDecl otdef = null;
if (currentClass.hasOuterInstance())
otdef = outerThisDef(tree.pos, m);
List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m);
// Recursively translate result type, parameters and thrown list.
tree.restype = translate(tree.restype);
tree.params = translateVarDefs(tree.params);
tree.thrown = translate(tree.thrown);
// when compiling stubs, don't process body
if (tree.body == null) {
result = tree;
return;
}
// Add this$n (if needed) in front of and free variables behind
// constructor parameter list.
tree.params = tree.params.appendList(fvdefs);
if (currentClass.hasOuterInstance())
tree.params = tree.params.prepend(otdef);
// If this is an initial constructor, i.e., it does not start with
// this(...), insert initializers for this$n and proxies
// before (pre-1.4, after) the call to superclass constructor.
JCStatement selfCall = translate(tree.body.stats.head);
List<JCStatement> added = List.nil();
if (fvs.nonEmpty()) {
List<Type> addedargtypes = List.nil();
for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
if (TreeInfo.isInitialConstructor(tree))
added = added.prepend(
initField(tree.body.pos, proxyName(l.head.name)));
addedargtypes = addedargtypes.prepend(l.head.erasure(types));
}
Type olderasure = m.erasure(types);
m.erasure_field = new MethodType(
olderasure.getParameterTypes().appendList(addedargtypes),
olderasure.getReturnType(),
olderasure.getThrownTypes(),
syms.methodClass);
}
if (currentClass.hasOuterInstance() &&
TreeInfo.isInitialConstructor(tree))
{
added = added.prepend(initOuterThis(tree.body.pos));
}
// pop local variables from proxy stack
proxies = proxies.leave();
// recursively translate following local statements and
// combine with this- or super-call
List<JCStatement> stats = translate(tree.body.stats.tail);
if (target.initializeFieldsBeforeSuper())
tree.body.stats = stats.prepend(selfCall).prependList(added);
else
tree.body.stats = stats.prependList(added).prepend(selfCall);
outerThisStack = prevOuterThisStack;
} else {
super.visitMethodDef(tree);
}
result = tree;
}
public void visitTypeCast(JCTypeCast tree) {
tree.clazz = translate(tree.clazz);
if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
tree.expr = translate(tree.expr, tree.type);
else
tree.expr = translate(tree.expr);
result = tree;
}
public void visitNewClass(JCNewClass tree) {
ClassSymbol c = (ClassSymbol)tree.constructor.owner;
// Box arguments, if necessary
boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
List<Type> argTypes = tree.constructor.type.getParameterTypes();
if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
tree.varargsElement = null;
// If created class is local, add free variables after
// explicit constructor arguments.
if ((c.owner.kind & (VAR | MTH)) != 0) {
tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
}
// If an access constructor is used, append null as a last argument.
Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
if (constructor != tree.constructor) {
tree.args = tree.args.append(makeNull());
tree.constructor = constructor;
}
// If created class has an outer instance, and new is qualified, pass
// qualifier as first argument. If new is not qualified, pass the
// correct outer instance as first argument.
if (c.hasOuterInstance()) {
JCExpression thisArg;
if (tree.encl != null) {
thisArg = attr.makeNullCheck(translate(tree.encl));
thisArg.type = tree.encl.type;
} else if ((c.owner.kind & (MTH | VAR)) != 0) {
// local class
thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
} else {
// nested class
thisArg = makeOwnerThis(tree.pos(), c, false);
}
tree.args = tree.args.prepend(thisArg);
}
tree.encl = null;
// If we have an anonymous class, create its flat version, rather
// than the class or interface following new.
if (tree.def != null) {
translate(tree.def);
tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
tree.def = null;
} else {
tree.clazz = access(c, tree.clazz, enclOp, false);
}
result = tree;
}
// Simplify conditionals with known constant controlling expressions.
// This allows us to avoid generating supporting declarations for
// the dead code, which will not be eliminated during code generation.
// Note that Flow.isFalse and Flow.isTrue only return true
// for constant expressions in the sense of JLS 15.27, which
// are guaranteed to have no side-effects. More aggressive
// constant propagation would require that we take care to
// preserve possible side-effects in the condition expression.
/** Visitor method for conditional expressions.
*/
public void visitConditional(JCConditional tree) {
JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
if (cond.type.isTrue()) {
result = convert(translate(tree.truepart, tree.type), tree.type);
} else if (cond.type.isFalse()) {
result = convert(translate(tree.falsepart, tree.type), tree.type);
} else {
// Condition is not a compile-time constant.
tree.truepart = translate(tree.truepart, tree.type);
tree.falsepart = translate(tree.falsepart, tree.type);
result = tree;
}
}
//where
private JCTree convert(JCTree tree, Type pt) {
if (tree.type == pt || tree.type.tag == TypeTags.BOT)
return tree;
JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
: pt;
return result;
}
/** Visitor method for if statements.
*/
public void visitIf(JCIf tree) {
JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
if (cond.type.isTrue()) {
result = translate(tree.thenpart);
} else if (cond.type.isFalse()) {
if (tree.elsepart != null) {
result = translate(tree.elsepart);
} else {
result = make.Skip();
}
} else {
// Condition is not a compile-time constant.
tree.thenpart = translate(tree.thenpart);
tree.elsepart = translate(tree.elsepart);
result = tree;
}
}
/** Visitor method for assert statements. Translate them away.
*/
public void visitAssert(JCAssert tree) {
DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
tree.cond = translate(tree.cond, syms.booleanType);
if (!tree.cond.type.isTrue()) {
JCExpression cond = assertFlagTest(tree.pos());
List<JCExpression> exnArgs = (tree.detail == null) ?
List.<JCExpression>nil() : List.of(translate(tree.detail));
if (!tree.cond.type.isFalse()) {
cond = makeBinary
(JCTree.AND,
cond,
makeUnary(JCTree.NOT, tree.cond));
}
result =
make.If(cond,
make_at(detailPos).
Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
null);
} else {
result = make.Skip();
}
}
public void visitApply(JCMethodInvocation tree) {
Symbol meth = TreeInfo.symbol(tree.meth);
List<Type> argtypes = meth.type.getParameterTypes();
if (allowEnums &&
meth.name==names.init &&
meth.owner == syms.enumSym)
argtypes = argtypes.tail.tail;
tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
tree.varargsElement = null;
Name methName = TreeInfo.name(tree.meth);
if (meth.name==names.init) {
// We are seeing a this(...) or super(...) constructor call.
// If an access constructor is used, append null as a last argument.
Symbol constructor = accessConstructor(tree.pos(), meth);
if (constructor != meth) {
tree.args = tree.args.append(makeNull());
TreeInfo.setSymbol(tree.meth, constructor);
}
// If we are calling a constructor of a local class, add
// free variables after explicit constructor arguments.
ClassSymbol c = (ClassSymbol)constructor.owner;
if ((c.owner.kind & (VAR | MTH)) != 0) {
tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
}
// If we are calling a constructor of an enum class, pass
// along the name and ordinal arguments
if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
List<JCVariableDecl> params = currentMethodDef.params;
if (currentMethodSym.owner.hasOuterInstance())
params = params.tail; // drop this$n
tree.args = tree.args
.prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
.prepend(make.Ident(params.head.sym)); // name
}
// If we are calling a constructor of a class with an outer
// instance, and the call
// is qualified, pass qualifier as first argument in front of
// the explicit constructor arguments. If the call
// is not qualified, pass the correct outer instance as
// first argument.
if (c.hasOuterInstance()) {
JCExpression thisArg;
if (tree.meth.getTag() == JCTree.SELECT) {
thisArg = attr.
makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
tree.meth = make.Ident(constructor);
((JCIdent) tree.meth).name = methName;
} else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
// local class or this() call
thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
} else {
// super() call of nested class - never pick 'this'
thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
}
tree.args = tree.args.prepend(thisArg);
}
} else {
// We are seeing a normal method invocation; translate this as usual.
tree.meth = translate(tree.meth);
// If the translated method itself is an Apply tree, we are
// seeing an access method invocation. In this case, append
// the method arguments to the arguments of the access method.
if (tree.meth.getTag() == JCTree.APPLY) {
JCMethodInvocation app = (JCMethodInvocation)tree.meth;
app.args = tree.args.prependList(app.args);
result = app;
return;
}
}
result = tree;
}
List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
List<JCExpression> args = _args;
if (parameters.isEmpty()) return args;
boolean anyChanges = false;
ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
while (parameters.tail.nonEmpty()) {
JCExpression arg = translate(args.head, parameters.head);
anyChanges |= (arg != args.head);
result.append(arg);
args = args.tail;
parameters = parameters.tail;
}
Type parameter = parameters.head;
if (varargsElement != null) {
anyChanges = true;
ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
while (args.nonEmpty()) {
JCExpression arg = translate(args.head, varargsElement);
elems.append(arg);
args = args.tail;
}
JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
List.<JCExpression>nil(),
elems.toList());
boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
result.append(boxedArgs);
} else {
if (args.length() != 1) throw new AssertionError(args);
JCExpression arg = translate(args.head, parameter);
anyChanges |= (arg != args.head);
result.append(arg);
if (!anyChanges) return _args;
}
return result.toList();
}
/** Expand a boxing or unboxing conversion if needed. */
@SuppressWarnings("unchecked") // XXX unchecked
<T extends JCTree> T boxIfNeeded(T tree, Type type) {
boolean havePrimitive = tree.type.isPrimitive();
if (havePrimitive == type.isPrimitive())
return tree;
if (havePrimitive) {
Type unboxedTarget = types.unboxedType(type);
if (unboxedTarget.tag != NONE) {
if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
tree.type = unboxedTarget.constType(tree.type.constValue());
return (T)boxPrimitive((JCExpression)tree, type);
} else {
tree = (T)boxPrimitive((JCExpression)tree);
}
} else {
tree = (T)unbox((JCExpression)tree, type);
}
return tree;
}
/** Box up a single primitive expression. */
JCExpression boxPrimitive(JCExpression tree) {
return boxPrimitive(tree, types.boxedClass(tree.type).type);
}
/** Box up a single primitive expression. */
JCExpression boxPrimitive(JCExpression tree, Type box) {
make_at(tree.pos());
if (target.boxWithConstructors()) {
Symbol ctor = lookupConstructor(tree.pos(),
box,
List.<Type>nil()
.prepend(tree.type));
return make.Create(ctor, List.of(tree));
} else {
Symbol valueOfSym = lookupMethod(tree.pos(),
names.valueOf,
box,
List.<Type>nil()
.prepend(tree.type));
return make.App(make.QualIdent(valueOfSym), List.of(tree));
}
}
/** Unbox an object to a primitive value. */
JCExpression unbox(JCExpression tree, Type primitive) {
Type unboxedType = types.unboxedType(tree.type);
if (unboxedType.tag == NONE) {
unboxedType = primitive;
if (!unboxedType.isPrimitive())
throw new AssertionError(unboxedType);
make_at(tree.pos());
tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
} else {
// There must be a conversion from unboxedType to primitive.
if (!types.isSubtype(unboxedType, primitive))
throw new AssertionError(tree);
}
make_at(tree.pos());
Symbol valueSym = lookupMethod(tree.pos(),
unboxedType.tsym.name.append(names.Value), // x.intValue()
tree.type,
List.<Type>nil());
return make.App(make.Select(tree, valueSym));
}
/** Visitor method for parenthesized expressions.
* If the subexpression has changed, omit the parens.
*/
public void visitParens(JCParens tree) {
JCTree expr = translate(tree.expr);
result = ((expr == tree.expr) ? tree : expr);
}
public void visitIndexed(JCArrayAccess tree) {
tree.indexed = translate(tree.indexed);
tree.index = translate(tree.index, syms.intType);
result = tree;
}
public void visitAssign(JCAssign tree) {
tree.lhs = translate(tree.lhs, tree);
tree.rhs = translate(tree.rhs, tree.lhs.type);
// If translated left hand side is an Apply, we are
// seeing an access method invocation. In this case, append
// right hand side as last argument of the access method.
if (tree.lhs.getTag() == JCTree.APPLY) {
JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
app.args = List.of(tree.rhs).prependList(app.args);
result = app;
} else {
result = tree;
}
}
public void visitAssignop(final JCAssignOp tree) {
if (!tree.lhs.type.isPrimitive() &&
tree.operator.type.getReturnType().isPrimitive()) {
// boxing required; need to rewrite as x = (unbox typeof x)(x op y);
// or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
// (but without recomputing x)
JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
public JCTree build(final JCTree lhs) {
int newTag = tree.getTag() - JCTree.ASGOffset;
// Erasure (TransTypes) can change the type of
// tree.lhs. However, we can still get the
// unerased type of tree.lhs as it is stored
// in tree.type in Attr.
Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
newTag,
attrEnv,
tree.type,
tree.rhs.type);
JCExpression expr = (JCExpression)lhs;
if (expr.type != tree.type)
expr = make.TypeCast(tree.type, expr);
JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
opResult.operator = newOperator;
opResult.type = newOperator.type.getReturnType();
JCTypeCast newRhs = make.TypeCast(types.unboxedType(tree.type),
opResult);
return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
}
});
result = translate(newTree);
return;
}
tree.lhs = translate(tree.lhs, tree);
tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
// If translated left hand side is an Apply, we are
// seeing an access method invocation. In this case, append
// right hand side as last argument of the access method.
if (tree.lhs.getTag() == JCTree.APPLY) {
JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
// if operation is a += on strings,
// make sure to convert argument to string
JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
? makeString(tree.rhs)
: tree.rhs;
app.args = List.of(rhs).prependList(app.args);
result = app;
} else {
result = tree;
}
}
/** Lower a tree of the form e++ or e-- where e is an object type */
JCTree lowerBoxedPostop(final JCUnary tree) {
// translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
// or
// translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
// where OP is += or -=
final boolean cast = TreeInfo.skipParens(tree.arg).getTag() == JCTree.TYPECAST;
return abstractLval(tree.arg, new TreeBuilder() {
public JCTree build(final JCTree tmp1) {
return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
public JCTree build(final JCTree tmp2) {
int opcode = (tree.getTag() == JCTree.POSTINC)
? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
JCTree lhs = cast
? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
: tmp1;
JCTree update = makeAssignop(opcode,
lhs,
make.Literal(1));
return makeComma(update, tmp2);
}
});
}
});
}
public void visitUnary(JCUnary tree) {
boolean isUpdateOperator =
JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC;
if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
switch(tree.getTag()) {
case JCTree.PREINC: // ++ e
// translate to e += 1
case JCTree.PREDEC: // -- e
// translate to e -= 1
{
int opcode = (tree.getTag() == JCTree.PREINC)
? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
JCAssignOp newTree = makeAssignop(opcode,
tree.arg,
make.Literal(1));
result = translate(newTree, tree.type);
return;
}
case JCTree.POSTINC: // e ++
case JCTree.POSTDEC: // e --
{
result = translate(lowerBoxedPostop(tree), tree.type);
return;
}
}
throw new AssertionError(tree);
}
tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
if (tree.getTag() == JCTree.NOT && tree.arg.type.constValue() != null) {
tree.type = cfolder.fold1(bool_not, tree.arg.type);
}
// If translated left hand side is an Apply, we are
// seeing an access method invocation. In this case, return
// that access method invocation as result.
if (isUpdateOperator && tree.arg.getTag() == JCTree.APPLY) {
result = tree.arg;
} else {
result = tree;
}
}
public void visitBinary(JCBinary tree) {
List<Type> formals = tree.operator.type.getParameterTypes();
JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
switch (tree.getTag()) {
case JCTree.OR:
if (lhs.type.isTrue()) {
result = lhs;
return;
}
if (lhs.type.isFalse()) {
result = translate(tree.rhs, formals.tail.head);
return;
}
break;
case JCTree.AND:
if (lhs.type.isFalse()) {
result = lhs;
return;
}
if (lhs.type.isTrue()) {
result = translate(tree.rhs, formals.tail.head);
return;
}
break;
}
tree.rhs = translate(tree.rhs, formals.tail.head);
result = tree;
}
public void visitIdent(JCIdent tree) {
result = access(tree.sym, tree, enclOp, false);
}
/** Translate away the foreach loop. */
public void visitForeachLoop(JCEnhancedForLoop tree) {
if (types.elemtype(tree.expr.type) == null)
visitIterableForeachLoop(tree);
else
visitArrayForeachLoop(tree);
}
// where
/**
* A statement of the form
*
* <pre>
* for ( T v : arrayexpr ) stmt;
* </pre>
*
* (where arrayexpr is of an array type) gets translated to
*
* <pre>
* for ( { arraytype #arr = arrayexpr;
* int #len = array.length;
* int #i = 0; };
* #i < #len; i$++ ) {
* T v = arr$[#i];
* stmt;
* }
* </pre>
*
* where #arr, #len, and #i are freshly named synthetic local variables.
*/
private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
make_at(tree.expr.pos());
VarSymbol arraycache = new VarSymbol(0,
names.fromString("arr" + target.syntheticNameChar()),
tree.expr.type,
currentMethodSym);
JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
VarSymbol lencache = new VarSymbol(0,
names.fromString("len" + target.syntheticNameChar()),
syms.intType,
currentMethodSym);
JCStatement lencachedef = make.
VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
VarSymbol index = new VarSymbol(0,
names.fromString("i" + target.syntheticNameChar()),
syms.intType,
currentMethodSym);
JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
indexdef.init.type = indexdef.type = syms.intType.constType(0);
List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
JCBinary cond = makeBinary(JCTree.LT, make.Ident(index), make.Ident(lencache));
JCExpressionStatement step = make.Exec(makeUnary(JCTree.PREINC, make.Ident(index)));
Type elemtype = types.elemtype(tree.expr.type);
JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
make.Ident(index)).setType(elemtype);
JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
tree.var.name,
tree.var.vartype,
loopvarinit).setType(tree.var.type);
loopvardef.sym = tree.var.sym;
JCBlock body = make.
Block(0, List.of(loopvardef, tree.body));
result = translate(make.
ForLoop(loopinit,
cond,
List.of(step),
body));
patchTargets(body, tree, result);
}
/** Patch up break and continue targets. */
private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
class Patcher extends TreeScanner {
public void visitBreak(JCBreak tree) {
if (tree.target == src)
tree.target = dest;
}
public void visitContinue(JCContinue tree) {
if (tree.target == src)
tree.target = dest;
}
public void visitClassDef(JCClassDecl tree) {}
}
new Patcher().scan(body);
}
/**
* A statement of the form
*
* <pre>
* for ( T v : coll ) stmt ;
* </pre>
*
* (where coll implements Iterable<? extends T>) gets translated to
*
* <pre>
* for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
* T v = (T) #i.next();
* stmt;
* }
* </pre>
*
* where #i is a freshly named synthetic local variable.
*/
private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
make_at(tree.expr.pos());
Type iteratorTarget = syms.objectType;
Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
syms.iterableType.tsym);
if (iterableType.getTypeArguments().nonEmpty())
iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
Type eType = tree.expr.type;
tree.expr.type = types.erasure(eType);
if (eType.tag == TYPEVAR && eType.getUpperBound().isCompound())
tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
Symbol iterator = lookupMethod(tree.expr.pos(),
names.iterator,
types.erasure(syms.iterableType),
List.<Type>nil());
VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
types.erasure(iterator.type.getReturnType()),
currentMethodSym);
JCStatement init = make.
VarDef(itvar,
make.App(make.Select(tree.expr, iterator)));
Symbol hasNext = lookupMethod(tree.expr.pos(),
names.hasNext,
itvar.type,
List.<Type>nil());
JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
Symbol next = lookupMethod(tree.expr.pos(),
names.next,
itvar.type,
List.<Type>nil());
JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
if (tree.var.type.isPrimitive())
vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
else
vardefinit = make.TypeCast(tree.var.type, vardefinit);
JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
tree.var.name,
tree.var.vartype,
vardefinit).setType(tree.var.type);
indexDef.sym = tree.var.sym;
JCBlock body = make.Block(0, List.of(indexDef, tree.body));
body.endpos = TreeInfo.endPos(tree.body);
result = translate(make.
ForLoop(List.of(init),
cond,
List.<JCExpressionStatement>nil(),
body));
patchTargets(body, tree, result);
}
public void visitVarDef(JCVariableDecl tree) {
MethodSymbol oldMethodSym = currentMethodSym;
tree.mods = translate(tree.mods);
tree.vartype = translate(tree.vartype);
if (currentMethodSym == null) {
// A class or instance field initializer.
currentMethodSym =
new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
names.empty, null,
currentClass);
}
if (tree.init != null) tree.init = translate(tree.init, tree.type);
result = tree;
currentMethodSym = oldMethodSym;
}
public void visitBlock(JCBlock tree) {
MethodSymbol oldMethodSym = currentMethodSym;
if (currentMethodSym == null) {
// Block is a static or instance initializer.
currentMethodSym =
new MethodSymbol(tree.flags | BLOCK,
names.empty, null,
currentClass);
}
super.visitBlock(tree);
currentMethodSym = oldMethodSym;
}
public void visitDoLoop(JCDoWhileLoop tree) {
tree.body = translate(tree.body);
tree.cond = translate(tree.cond, syms.booleanType);
result = tree;
}
public void visitWhileLoop(JCWhileLoop tree) {
tree.cond = translate(tree.cond, syms.booleanType);
tree.body = translate(tree.body);
result = tree;
}
public void visitForLoop(JCForLoop tree) {
tree.init = translate(tree.init);
if (tree.cond != null)
tree.cond = translate(tree.cond, syms.booleanType);
tree.step = translate(tree.step);
tree.body = translate(tree.body);
result = tree;
}
public void visitReturn(JCReturn tree) {
if (tree.expr != null)
tree.expr = translate(tree.expr,
types.erasure(currentMethodDef
.restype.type));
result = tree;
}
public void visitSwitch(JCSwitch tree) {
Type selsuper = types.supertype(tree.selector.type);
boolean enumSwitch = selsuper != null &&
(tree.selector.type.tsym.flags() & ENUM) != 0;
boolean stringSwitch = selsuper != null &&
types.isSameType(tree.selector.type, syms.stringType);
Type target = enumSwitch ? tree.selector.type :
(stringSwitch? syms.stringType : syms.intType);
tree.selector = translate(tree.selector, target);
tree.cases = translateCases(tree.cases);
if (enumSwitch) {
result = visitEnumSwitch(tree);
} else if (stringSwitch) {
result = visitStringSwitch(tree);
} else {
result = tree;
}
}
public JCTree visitEnumSwitch(JCSwitch tree) {
TypeSymbol enumSym = tree.selector.type.tsym;
EnumMapping map = mapForEnum(tree.pos(), enumSym);
make_at(tree.pos());
Symbol ordinalMethod = lookupMethod(tree.pos(),
names.ordinal,
tree.selector.type,
List.<Type>nil());
JCArrayAccess selector = make.Indexed(map.mapVar,
make.App(make.Select(tree.selector,
ordinalMethod)));
ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
for (JCCase c : tree.cases) {
if (c.pat != null) {
VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
JCLiteral pat = map.forConstant(label);
cases.append(make.Case(pat, c.stats));
} else {
cases.append(c);
}
}
JCSwitch enumSwitch = make.Switch(selector, cases.toList());
patchTargets(enumSwitch, tree, enumSwitch);
return enumSwitch;
}
public JCTree visitStringSwitch(JCSwitch tree) {
List<JCCase> caseList = tree.getCases();
int alternatives = caseList.size();
if (alternatives == 0) { // Strange but legal possibility
return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
} else {
/*
* The general approach used is to translate a single
* string switch statement into a series of two chained
* switch statements: the first a synthesized statement
* switching on the argument string's hash value and
* computing a string's position in the list of original
* case labels, if any, followed by a second switch on the
* computed integer value. The second switch has the same
* code structure as the original string switch statement
* except that the string case labels are replaced with
* positional integer constants starting at 0.
*
* The first switch statement can be thought of as an
* inlined map from strings to their position in the case
* label list. An alternate implementation would use an
* actual Map for this purpose, as done for enum switches.
*
* With some additional effort, it would be possible to
* use a single switch statement on the hash code of the
* argument, but care would need to be taken to preserve
* the proper control flow in the presence of hash
* collisions and other complications, such as
* fallthroughs. Switch statements with one or two
* alternatives could also be specially translated into
* if-then statements to omit the computation of the hash
* code.
*
* The generated code assumes that the hashing algorithm
* of String is the same in the compilation environment as
* in the environment the code will run in. The string
* hashing algorithm in the SE JDK has been unchanged
* since at least JDK 1.2. Since the algorithm has been
* specified since that release as well, it is very
* unlikely to be changed in the future.
*
* Different hashing algorithms, such as the length of the
* strings or a perfect hashing algorithm over the
* particular set of case labels, could potentially be
* used instead of String.hashCode.
*/
ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
// Map from String case labels to their original position in
// the list of case labels.
Map<String, Integer> caseLabelToPosition =
new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
// Map of hash codes to the string case labels having that hashCode.
Map<Integer, Set<String>> hashToString =
new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
int casePosition = 0;
for(JCCase oneCase : caseList) {
JCExpression expression = oneCase.getExpression();
if (expression != null) { // expression for a "default" case is null
expression = TreeInfo.skipParens(expression);
String labelExpr = (String) expression.type.constValue();
Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
Assert.checkNull(mapping);
int hashCode = labelExpr.hashCode();
Set<String> stringSet = hashToString.get(hashCode);
if (stringSet == null) {
stringSet = new LinkedHashSet<String>(1, 1.0f);
stringSet.add(labelExpr);
hashToString.put(hashCode, stringSet);
} else {
boolean added = stringSet.add(labelExpr);
Assert.check(added);
}
}
casePosition++;
}
// Synthesize a switch statement that has the effect of
// mapping from a string to the integer position of that
// string in the list of case labels. This is done by
// switching on the hashCode of the string followed by an
// if-then-else chain comparing the input for equality
// with all the case labels having that hash value.
/*
* s$ = top of stack;
* tmp$ = -1;
* switch($s.hashCode()) {
* case caseLabel.hashCode:
* if (s$.equals("caseLabel_1")
* tmp$ = caseLabelToPosition("caseLabel_1");
* else if (s$.equals("caseLabel_2"))
* tmp$ = caseLabelToPosition("caseLabel_2");
* ...
* break;
* ...
* }
*/
VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
names.fromString("s" + tree.pos + target.syntheticNameChar()),
syms.stringType,
currentMethodSym);
stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
syms.intType,
currentMethodSym);
JCVariableDecl dollar_tmp_def =
(JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
stmtList.append(dollar_tmp_def);
ListBuffer<JCCase> caseBuffer = ListBuffer.lb();
// hashCode will trigger nullcheck on original switch expression
JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
names.hashCode,
List.<JCExpression>nil()).setType(syms.intType);
JCSwitch switch1 = make.Switch(hashCodeCall,
caseBuffer.toList());
for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
int hashCode = entry.getKey();
Set<String> stringsWithHashCode = entry.getValue();
Assert.check(stringsWithHashCode.size() >= 1);
JCStatement elsepart = null;
for(String caseLabel : stringsWithHashCode ) {
JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
names.equals,
List.<JCExpression>of(make.Literal(caseLabel)));
elsepart = make.If(stringEqualsCall,
make.Exec(make.Assign(make.Ident(dollar_tmp),
make.Literal(caseLabelToPosition.get(caseLabel))).
setType(dollar_tmp.type)),
elsepart);
}
ListBuffer<JCStatement> lb = ListBuffer.lb();
JCBreak breakStmt = make.Break(null);
breakStmt.target = switch1;
lb.append(elsepart).append(breakStmt);
caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
}
switch1.cases = caseBuffer.toList();
stmtList.append(switch1);
// Make isomorphic switch tree replacing string labels
// with corresponding integer ones from the label to
// position map.
ListBuffer<JCCase> lb = ListBuffer.lb();
JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
for(JCCase oneCase : caseList ) {
// Rewire up old unlabeled break statements to the
// replacement switch being created.
patchTargets(oneCase, tree, switch2);
boolean isDefault = (oneCase.getExpression() == null);
JCExpression caseExpr;
if (isDefault)
caseExpr = null;
else {
caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
getExpression()).
type.constValue()));
}
lb.append(make.Case(caseExpr,
oneCase.getStatements()));
}
switch2.cases = lb.toList();
stmtList.append(switch2);
return make.Block(0L, stmtList.toList());
}
}
public void visitNewArray(JCNewArray tree) {
tree.elemtype = translate(tree.elemtype);
for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
if (t.head != null) t.head = translate(t.head, syms.intType);
tree.elems = translate(tree.elems, types.elemtype(tree.type));
result = tree;
}
public void visitSelect(JCFieldAccess tree) {
// need to special case-access of the form C.super.x
// these will always need an access method.
boolean qualifiedSuperAccess =
tree.selected.getTag() == JCTree.SELECT &&
TreeInfo.name(tree.selected) == names._super;
tree.selected = translate(tree.selected);
if (tree.name == names._class)
result = classOf(tree.selected);
else if (tree.name == names._this || tree.name == names._super)
result = makeThis(tree.pos(), tree.selected.type.tsym);
else
result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
}
public void visitLetExpr(LetExpr tree) {
tree.defs = translateVarDefs(tree.defs);
tree.expr = translate(tree.expr, tree.type);
result = tree;
}
// There ought to be nothing to rewrite here;
// we don't generate code.
public void visitAnnotation(JCAnnotation tree) {
result = tree;
}
@Override
public void visitTry(JCTry tree) {
if (tree.resources.isEmpty()) {
super.visitTry(tree);
} else {
result = makeTwrTry(tree);
}
}
/**************************************************************************
* main method
*************************************************************************/
/** Translate a toplevel class and return a list consisting of
* the translated class and translated versions of all inner classes.
* @param env The attribution environment current at the class definition.
* We need this for resolving some additional symbols.
* @param cdef The tree representing the class definition.
*/
public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
ListBuffer<JCTree> translated = null;
try {
attrEnv = env;
this.make = make;
endPositions = env.toplevel.endPositions;
currentClass = null;
currentMethodDef = null;
outermostClassDef = (cdef.getTag() == JCTree.CLASSDEF) ? (JCClassDecl)cdef : null;
outermostMemberDef = null;
this.translated = new ListBuffer<JCTree>();
classdefs = new HashMap<ClassSymbol,JCClassDecl>();
actualSymbols = new HashMap<Symbol,Symbol>();
freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
proxies = new Scope(syms.noSymbol);
twrVars = new Scope(syms.noSymbol);
outerThisStack = List.nil();
accessNums = new HashMap<Symbol,Integer>();
accessSyms = new HashMap<Symbol,MethodSymbol[]>();
accessConstrs = new HashMap<Symbol,MethodSymbol>();
accessConstrTags = List.nil();
accessed = new ListBuffer<Symbol>();
translate(cdef, (JCExpression)null);
for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
makeAccessible(l.head);
for (EnumMapping map : enumSwitchMap.values())
map.translate();
checkConflicts(this.translated.toList());
checkAccessConstructorTags();
translated = this.translated;
} finally {
// note that recursive invocations of this method fail hard
attrEnv = null;
this.make = null;
endPositions = null;
currentClass = null;
currentMethodDef = null;
outermostClassDef = null;
outermostMemberDef = null;
this.translated = null;
classdefs = null;
actualSymbols = null;
freevarCache = null;
proxies = null;
outerThisStack = null;
accessNums = null;
accessSyms = null;
accessConstrs = null;
accessConstrTags = null;
accessed = null;
enumSwitchMap.clear();
}
return translated.toList();
}
//////////////////////////////////////////////////////////////
// The following contributed by Borland for bootstrapping purposes
//////////////////////////////////////////////////////////////
private void addEnumCompatibleMembers(JCClassDecl cdef) {
make_at(null);
// Add the special enum fields
VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef);
VarSymbol nameFieldSym = addEnumNameField(cdef);
// Add the accessor methods for name and ordinal
MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym);
MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym);
// Add the toString method
addEnumToString(cdef, nameFieldSym);
// Add the compareTo method
addEnumCompareTo(cdef, ordinalFieldSym);
}
private VarSymbol addEnumOrdinalField(JCClassDecl cdef) {
VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
names.fromString("$ordinal"),
syms.intType,
cdef.sym);
cdef.sym.members().enter(ordinal);
cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null));
return ordinal;
}
private VarSymbol addEnumNameField(JCClassDecl cdef) {
VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
names.fromString("$name"),
syms.stringType,
cdef.sym);
cdef.sym.members().enter(name);
cdef.defs = cdef.defs.prepend(make.VarDef(name, null));
return name;
}
private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) {
// Add the accessor methods for ordinal
Symbol ordinalSym = lookupMethod(cdef.pos(),
names.ordinal,
cdef.type,
List.<Type>nil());
Assert.check(ordinalSym instanceof MethodSymbol);
JCStatement ret = make.Return(make.Ident(ordinalSymbol));
cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym,
make.Block(0L, List.of(ret))));
return (MethodSymbol)ordinalSym;
}
private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) {
// Add the accessor methods for name
Symbol nameSym = lookupMethod(cdef.pos(),
names._name,
cdef.type,
List.<Type>nil());
Assert.check(nameSym instanceof MethodSymbol);
JCStatement ret = make.Return(make.Ident(nameSymbol));
cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym,
make.Block(0L, List.of(ret))));
return (MethodSymbol)nameSym;
}
private MethodSymbol addEnumToString(JCClassDecl cdef,
VarSymbol nameSymbol) {
Symbol toStringSym = lookupMethod(cdef.pos(),
names.toString,
cdef.type,
List.<Type>nil());
JCTree toStringDecl = null;
if (toStringSym != null)
toStringDecl = TreeInfo.declarationFor(toStringSym, cdef);
if (toStringDecl != null)
return (MethodSymbol)toStringSym;
JCStatement ret = make.Return(make.Ident(nameSymbol));
JCTree resTypeTree = make.Type(syms.stringType);
MethodType toStringType = new MethodType(List.<Type>nil(),
syms.stringType,
List.<Type>nil(),
cdef.sym);
toStringSym = new MethodSymbol(PUBLIC,
names.toString,
toStringType,
cdef.type.tsym);
toStringDecl = make.MethodDef((MethodSymbol)toStringSym,
make.Block(0L, List.of(ret)));
cdef.defs = cdef.defs.prepend(toStringDecl);
cdef.sym.members().enter(toStringSym);
return (MethodSymbol)toStringSym;
}
private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) {
Symbol compareToSym = lookupMethod(cdef.pos(),
names.compareTo,
cdef.type,
List.of(cdef.sym.type));
Assert.check(compareToSym instanceof MethodSymbol);
JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef);
ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>();
JCModifiers mod1 = make.Modifiers(0L);
Name oName = names.fromString("o");
JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym);
JCIdent paramId1 = make.Ident(names.java_lang_Object);
paramId1.type = cdef.type;
paramId1.sym = par1.sym;
((MethodSymbol)compareToSym).params = List.of(par1.sym);
JCIdent par1UsageId = make.Ident(par1.sym);
JCIdent castTargetIdent = make.Ident(cdef.sym);
JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId);
cast.setType(castTargetIdent.type);
Name otherName = names.fromString("other");
VarSymbol otherVarSym = new VarSymbol(mod1.flags,
otherName,
cdef.type,
compareToSym);
JCVariableDecl otherVar = make.VarDef(otherVarSym, cast);
blockStatements.append(otherVar);
JCIdent id1 = make.Ident(ordinalSymbol);
JCIdent fLocUsageId = make.Ident(otherVarSym);
JCExpression sel = make.Select(fLocUsageId, ordinalSymbol);
JCBinary bin = makeBinary(JCTree.MINUS, id1, sel);
JCReturn ret = make.Return(bin);
blockStatements.append(ret);
JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym,
make.Block(0L,
blockStatements.toList()));
compareToMethod.params = List.of(par1);
cdef.defs = cdef.defs.append(compareToMethod);
return (MethodSymbol)compareToSym;
}
//////////////////////////////////////////////////////////////
// The above contributed by Borland for bootstrapping purposes
//////////////////////////////////////////////////////////////
}
| 164,727 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ConstFold.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/comp/ConstFold.java | /*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.comp;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.code.Type.*;
import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.jvm.ByteCodes.*;
/** Helper class for constant folding, used by the attribution phase.
* This class is marked strictfp as mandated by JLS 15.4.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
strictfp class ConstFold {
protected static final Context.Key<ConstFold> constFoldKey =
new Context.Key<ConstFold>();
private Symtab syms;
public static ConstFold instance(Context context) {
ConstFold instance = context.get(constFoldKey);
if (instance == null)
instance = new ConstFold(context);
return instance;
}
private ConstFold(Context context) {
context.put(constFoldKey, this);
syms = Symtab.instance(context);
}
static Integer minusOne = -1;
static Integer zero = 0;
static Integer one = 1;
/** Convert boolean to integer (true = 1, false = 0).
*/
private static Integer b2i(boolean b) {
return b ? one : zero;
}
private static int intValue(Object x) { return ((Number)x).intValue(); }
private static long longValue(Object x) { return ((Number)x).longValue(); }
private static float floatValue(Object x) { return ((Number)x).floatValue(); }
private static double doubleValue(Object x) { return ((Number)x).doubleValue(); }
/** Fold binary or unary operation, returning constant type reflecting the
* operations result. Return null if fold failed due to an
* arithmetic exception.
* @param opcode The operation's opcode instruction (usually a byte code),
* as entered by class Symtab.
* @param argtypes The operation's argument types (a list of length 1 or 2).
* Argument types are assumed to have non-null constValue's.
*/
Type fold(int opcode, List<Type> argtypes) {
int argCount = argtypes.length();
if (argCount == 1)
return fold1(opcode, argtypes.head);
else if (argCount == 2)
return fold2(opcode, argtypes.head, argtypes.tail.head);
else
throw new AssertionError();
}
/** Fold unary operation.
* @param opcode The operation's opcode instruction (usually a byte code),
* as entered by class Symtab.
* opcode's ifeq to ifge are for postprocessing
* xcmp; ifxx pairs of instructions.
* @param operand The operation's operand type.
* Argument types are assumed to have non-null constValue's.
*/
Type fold1(int opcode, Type operand) {
try {
Object od = operand.constValue();
switch (opcode) {
case nop:
return operand;
case ineg: // unary -
return syms.intType.constType(-intValue(od));
case ixor: // ~
return syms.intType.constType(~intValue(od));
case bool_not: // !
return syms.booleanType.constType(b2i(intValue(od) == 0));
case ifeq:
return syms.booleanType.constType(b2i(intValue(od) == 0));
case ifne:
return syms.booleanType.constType(b2i(intValue(od) != 0));
case iflt:
return syms.booleanType.constType(b2i(intValue(od) < 0));
case ifgt:
return syms.booleanType.constType(b2i(intValue(od) > 0));
case ifle:
return syms.booleanType.constType(b2i(intValue(od) <= 0));
case ifge:
return syms.booleanType.constType(b2i(intValue(od) >= 0));
case lneg: // unary -
return syms.longType.constType(new Long(-longValue(od)));
case lxor: // ~
return syms.longType.constType(new Long(~longValue(od)));
case fneg: // unary -
return syms.floatType.constType(new Float(-floatValue(od)));
case dneg: // ~
return syms.doubleType.constType(new Double(-doubleValue(od)));
default:
return null;
}
} catch (ArithmeticException e) {
return null;
}
}
/** Fold binary operation.
* @param opcode The operation's opcode instruction (usually a byte code),
* as entered by class Symtab.
* opcode's ifeq to ifge are for postprocessing
* xcmp; ifxx pairs of instructions.
* @param left The type of the operation's left operand.
* @param right The type of the operation's right operand.
*/
Type fold2(int opcode, Type left, Type right) {
try {
if (opcode > ByteCodes.preMask) {
// we are seeing a composite instruction of the form xcmp; ifxx.
// In this case fold both instructions separately.
Type t1 = fold2(opcode >> ByteCodes.preShift, left, right);
return (t1.constValue() == null) ? t1
: fold1(opcode & ByteCodes.preMask, t1);
} else {
Object l = left.constValue();
Object r = right.constValue();
switch (opcode) {
case iadd:
return syms.intType.constType(intValue(l) + intValue(r));
case isub:
return syms.intType.constType(intValue(l) - intValue(r));
case imul:
return syms.intType.constType(intValue(l) * intValue(r));
case idiv:
return syms.intType.constType(intValue(l) / intValue(r));
case imod:
return syms.intType.constType(intValue(l) % intValue(r));
case iand:
return (left.tag == BOOLEAN
? syms.booleanType : syms.intType)
.constType(intValue(l) & intValue(r));
case bool_and:
return syms.booleanType.constType(b2i((intValue(l) & intValue(r)) != 0));
case ior:
return (left.tag == BOOLEAN
? syms.booleanType : syms.intType)
.constType(intValue(l) | intValue(r));
case bool_or:
return syms.booleanType.constType(b2i((intValue(l) | intValue(r)) != 0));
case ixor:
return (left.tag == BOOLEAN
? syms.booleanType : syms.intType)
.constType(intValue(l) ^ intValue(r));
case ishl: case ishll:
return syms.intType.constType(intValue(l) << intValue(r));
case ishr: case ishrl:
return syms.intType.constType(intValue(l) >> intValue(r));
case iushr: case iushrl:
return syms.intType.constType(intValue(l) >>> intValue(r));
case if_icmpeq:
return syms.booleanType.constType(
b2i(intValue(l) == intValue(r)));
case if_icmpne:
return syms.booleanType.constType(
b2i(intValue(l) != intValue(r)));
case if_icmplt:
return syms.booleanType.constType(
b2i(intValue(l) < intValue(r)));
case if_icmpgt:
return syms.booleanType.constType(
b2i(intValue(l) > intValue(r)));
case if_icmple:
return syms.booleanType.constType(
b2i(intValue(l) <= intValue(r)));
case if_icmpge:
return syms.booleanType.constType(
b2i(intValue(l) >= intValue(r)));
case ladd:
return syms.longType.constType(
new Long(longValue(l) + longValue(r)));
case lsub:
return syms.longType.constType(
new Long(longValue(l) - longValue(r)));
case lmul:
return syms.longType.constType(
new Long(longValue(l) * longValue(r)));
case ldiv:
return syms.longType.constType(
new Long(longValue(l) / longValue(r)));
case lmod:
return syms.longType.constType(
new Long(longValue(l) % longValue(r)));
case land:
return syms.longType.constType(
new Long(longValue(l) & longValue(r)));
case lor:
return syms.longType.constType(
new Long(longValue(l) | longValue(r)));
case lxor:
return syms.longType.constType(
new Long(longValue(l) ^ longValue(r)));
case lshl: case lshll:
return syms.longType.constType(
new Long(longValue(l) << intValue(r)));
case lshr: case lshrl:
return syms.longType.constType(
new Long(longValue(l) >> intValue(r)));
case lushr:
return syms.longType.constType(
new Long(longValue(l) >>> intValue(r)));
case lcmp:
if (longValue(l) < longValue(r))
return syms.intType.constType(minusOne);
else if (longValue(l) > longValue(r))
return syms.intType.constType(one);
else
return syms.intType.constType(zero);
case fadd:
return syms.floatType.constType(
new Float(floatValue(l) + floatValue(r)));
case fsub:
return syms.floatType.constType(
new Float(floatValue(l) - floatValue(r)));
case fmul:
return syms.floatType.constType(
new Float(floatValue(l) * floatValue(r)));
case fdiv:
return syms.floatType.constType(
new Float(floatValue(l) / floatValue(r)));
case fmod:
return syms.floatType.constType(
new Float(floatValue(l) % floatValue(r)));
case fcmpg: case fcmpl:
if (floatValue(l) < floatValue(r))
return syms.intType.constType(minusOne);
else if (floatValue(l) > floatValue(r))
return syms.intType.constType(one);
else if (floatValue(l) == floatValue(r))
return syms.intType.constType(zero);
else if (opcode == fcmpg)
return syms.intType.constType(one);
else
return syms.intType.constType(minusOne);
case dadd:
return syms.doubleType.constType(
new Double(doubleValue(l) + doubleValue(r)));
case dsub:
return syms.doubleType.constType(
new Double(doubleValue(l) - doubleValue(r)));
case dmul:
return syms.doubleType.constType(
new Double(doubleValue(l) * doubleValue(r)));
case ddiv:
return syms.doubleType.constType(
new Double(doubleValue(l) / doubleValue(r)));
case dmod:
return syms.doubleType.constType(
new Double(doubleValue(l) % doubleValue(r)));
case dcmpg: case dcmpl:
if (doubleValue(l) < doubleValue(r))
return syms.intType.constType(minusOne);
else if (doubleValue(l) > doubleValue(r))
return syms.intType.constType(one);
else if (doubleValue(l) == doubleValue(r))
return syms.intType.constType(zero);
else if (opcode == dcmpg)
return syms.intType.constType(one);
else
return syms.intType.constType(minusOne);
case if_acmpeq:
return syms.booleanType.constType(b2i(l.equals(r)));
case if_acmpne:
return syms.booleanType.constType(b2i(!l.equals(r)));
case string_add:
return syms.stringType.constType(
left.stringValue() + right.stringValue());
default:
return null;
}
}
} catch (ArithmeticException e) {
return null;
}
}
/** Coerce constant type to target type.
* @param etype The source type of the coercion,
* which is assumed to be a constant type compatble with
* ttype.
* @param ttype The target type of the coercion.
*/
Type coerce(Type etype, Type ttype) {
// WAS if (etype.baseType() == ttype.baseType())
if (etype.tsym.type == ttype.tsym.type)
return etype;
if (etype.tag <= DOUBLE) {
Object n = etype.constValue();
switch (ttype.tag) {
case BYTE:
return syms.byteType.constType(0 + (byte)intValue(n));
case CHAR:
return syms.charType.constType(0 + (char)intValue(n));
case SHORT:
return syms.shortType.constType(0 + (short)intValue(n));
case INT:
return syms.intType.constType(intValue(n));
case LONG:
return syms.longType.constType(longValue(n));
case FLOAT:
return syms.floatType.constType(floatValue(n));
case DOUBLE:
return syms.doubleType.constType(doubleValue(n));
}
}
return ttype;
}
}
| 15,908 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
List.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/List.java | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.AbstractCollection;
import java.util.ListIterator;
import java.util.NoSuchElementException;
/** A class for generic linked lists. Links are supposed to be
* immutable, the only exception being the incremental construction of
* lists via ListBuffers. List is the main container class in
* GJC. Most data structures and algorthms in GJC use lists rather
* than arrays.
*
* <p>Lists are always trailed by a sentinel element, whose head and tail
* are both null.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class List<A> extends AbstractCollection<A> implements java.util.List<A> {
/** The first element of the list, supposed to be immutable.
*/
public A head;
/** The remainder of the list except for its first element, supposed
* to be immutable.
*/
//@Deprecated
public List<A> tail;
/** Construct a list given its head and tail.
*/
List(A head, List<A> tail) {
this.tail = tail;
this.head = head;
}
/** Construct an empty list.
*/
@SuppressWarnings("unchecked")
public static <A> List<A> nil() {
return (List<A>)EMPTY_LIST;
}
private static List<?> EMPTY_LIST = new List<Object>(null,null) {
public List<Object> setTail(List<Object> tail) {
throw new UnsupportedOperationException();
}
public boolean isEmpty() {
return true;
}
};
/** Construct a list consisting of given element.
*/
public static <A> List<A> of(A x1) {
return new List<A>(x1, List.<A>nil());
}
/** Construct a list consisting of given elements.
*/
public static <A> List<A> of(A x1, A x2) {
return new List<A>(x1, of(x2));
}
/** Construct a list consisting of given elements.
*/
public static <A> List<A> of(A x1, A x2, A x3) {
return new List<A>(x1, of(x2, x3));
}
/** Construct a list consisting of given elements.
*/
@SuppressWarnings({"varargs", "unchecked"})
public static <A> List<A> of(A x1, A x2, A x3, A... rest) {
return new List<A>(x1, new List<A>(x2, new List<A>(x3, from(rest))));
}
/**
* Construct a list consisting all elements of given array.
* @param array an array; if {@code null} return an empty list
*/
public static <A> List<A> from(A[] array) {
List<A> xs = nil();
if (array != null)
for (int i = array.length - 1; i >= 0; i--)
xs = new List<A>(array[i], xs);
return xs;
}
/** Construct a list consisting of a given number of identical elements.
* @param len The number of elements in the list.
* @param init The value of each element.
*/
@Deprecated
public static <A> List<A> fill(int len, A init) {
List<A> l = nil();
for (int i = 0; i < len; i++) l = new List<A>(init, l);
return l;
}
/** Does list have no elements?
*/
@Override
public boolean isEmpty() {
return tail == null;
}
/** Does list have elements?
*/
//@Deprecated
public boolean nonEmpty() {
return tail != null;
}
/** Return the number of elements in this list.
*/
//@Deprecated
public int length() {
List<A> l = this;
int len = 0;
while (l.tail != null) {
l = l.tail;
len++;
}
return len;
}
@Override
public int size() {
return length();
}
public List<A> setTail(List<A> tail) {
this.tail = tail;
return tail;
}
/** Prepend given element to front of list, forming and returning
* a new list.
*/
public List<A> prepend(A x) {
return new List<A>(x, this);
}
/** Prepend given list of elements to front of list, forming and returning
* a new list.
*/
public List<A> prependList(List<A> xs) {
if (this.isEmpty()) return xs;
if (xs.isEmpty()) return this;
if (xs.tail.isEmpty()) return prepend(xs.head);
// return this.prependList(xs.tail).prepend(xs.head);
List<A> result = this;
List<A> rev = xs.reverse();
Assert.check(rev != xs);
// since xs.reverse() returned a new list, we can reuse the
// individual List objects, instead of allocating new ones.
while (rev.nonEmpty()) {
List<A> h = rev;
rev = rev.tail;
h.setTail(result);
result = h;
}
return result;
}
/** Reverse list.
* If the list is empty or a singleton, then the same list is returned.
* Otherwise a new list is formed.
*/
public List<A> reverse() {
// if it is empty or a singleton, return itself
if (isEmpty() || tail.isEmpty())
return this;
List<A> rev = nil();
for (List<A> l = this; l.nonEmpty(); l = l.tail)
rev = new List<A>(l.head, rev);
return rev;
}
/** Append given element at length, forming and returning
* a new list.
*/
public List<A> append(A x) {
return of(x).prependList(this);
}
/** Append given list at length, forming and returning
* a new list.
*/
public List<A> appendList(List<A> x) {
return x.prependList(this);
}
/**
* Append given list buffer at length, forming and returning a new
* list.
*/
public List<A> appendList(ListBuffer<A> x) {
return appendList(x.toList());
}
/** Copy successive elements of this list into given vector until
* list is exhausted or end of vector is reached.
*/
@Override @SuppressWarnings("unchecked")
public <T> T[] toArray(T[] vec) {
int i = 0;
List<A> l = this;
Object[] dest = vec;
while (l.nonEmpty() && i < vec.length) {
dest[i] = l.head;
l = l.tail;
i++;
}
if (l.isEmpty()) {
if (i < vec.length)
vec[i] = null;
return vec;
}
vec = (T[])Array.newInstance(vec.getClass().getComponentType(), size());
return toArray(vec);
}
public Object[] toArray() {
return toArray(new Object[size()]);
}
/** Form a string listing all elements with given separator character.
*/
public String toString(String sep) {
if (isEmpty()) {
return "";
} else {
StringBuffer buf = new StringBuffer();
buf.append(head);
for (List<A> l = tail; l.nonEmpty(); l = l.tail) {
buf.append(sep);
buf.append(l.head);
}
return buf.toString();
}
}
/** Form a string listing all elements with comma as the separator character.
*/
@Override
public String toString() {
return toString(",");
}
/** Compute a hash code, overrides Object
* @see java.util.List#hashCode
*/
@Override
public int hashCode() {
List<A> l = this;
int h = 1;
while (l.tail != null) {
h = h * 31 + (l.head == null ? 0 : l.head.hashCode());
l = l.tail;
}
return h;
}
/** Is this list the same as other list?
* @see java.util.List#equals
*/
@Override
public boolean equals(Object other) {
if (other instanceof List<?>)
return equals(this, (List<?>)other);
if (other instanceof java.util.List<?>) {
List<A> t = this;
Iterator<?> oIter = ((java.util.List<?>) other).iterator();
while (t.tail != null && oIter.hasNext()) {
Object o = oIter.next();
if ( !(t.head == null ? o == null : t.head.equals(o)))
return false;
t = t.tail;
}
return (t.isEmpty() && !oIter.hasNext());
}
return false;
}
/** Are the two lists the same?
*/
public static boolean equals(List<?> xs, List<?> ys) {
while (xs.tail != null && ys.tail != null) {
if (xs.head == null) {
if (ys.head != null) return false;
} else {
if (!xs.head.equals(ys.head)) return false;
}
xs = xs.tail;
ys = ys.tail;
}
return xs.tail == null && ys.tail == null;
}
/** Does the list contain the specified element?
*/
@Override
public boolean contains(Object x) {
List<A> l = this;
while (l.tail != null) {
if (x == null) {
if (l.head == null) return true;
} else {
if (l.head.equals(x)) return true;
}
l = l.tail;
}
return false;
}
/** The last element in the list, if any, or null.
*/
public A last() {
A last = null;
List<A> t = this;
while (t.tail != null) {
last = t.head;
t = t.tail;
}
return last;
}
@SuppressWarnings("unchecked")
public static <T> List<T> convert(Class<T> klass, List<?> list) {
if (list == null)
return null;
for (Object o : list)
klass.cast(o);
return (List<T>)list;
}
private static Iterator<?> EMPTYITERATOR = new Iterator<Object>() {
public boolean hasNext() {
return false;
}
public Object next() {
throw new java.util.NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
@SuppressWarnings("unchecked")
private static <A> Iterator<A> emptyIterator() {
return (Iterator<A>)EMPTYITERATOR;
}
@Override
public Iterator<A> iterator() {
if (tail == null)
return emptyIterator();
return new Iterator<A>() {
List<A> elems = List.this;
public boolean hasNext() {
return elems.tail != null;
}
public A next() {
if (elems.tail == null)
throw new NoSuchElementException();
A result = elems.head;
elems = elems.tail;
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public A get(int index) {
if (index < 0)
throw new IndexOutOfBoundsException(String.valueOf(index));
List<A> l = this;
for (int i = index; i-- > 0 && !l.isEmpty(); l = l.tail)
;
if (l.isEmpty())
throw new IndexOutOfBoundsException("Index: " + index + ", " +
"Size: " + size());
return l.head;
}
public boolean addAll(int index, Collection<? extends A> c) {
if (c.isEmpty())
return false;
throw new UnsupportedOperationException();
}
public A set(int index, A element) {
throw new UnsupportedOperationException();
}
public void add(int index, A element) {
throw new UnsupportedOperationException();
}
public A remove(int index) {
throw new UnsupportedOperationException();
}
public int indexOf(Object o) {
int i = 0;
for (List<A> l = this; l.tail != null; l = l.tail, i++) {
if (l.head == null ? o == null : l.head.equals(o))
return i;
}
return -1;
}
public int lastIndexOf(Object o) {
int last = -1;
int i = 0;
for (List<A> l = this; l.tail != null; l = l.tail, i++) {
if (l.head == null ? o == null : l.head.equals(o))
last = i;
}
return last;
}
public ListIterator<A> listIterator() {
return Collections.unmodifiableList(new ArrayList<A>(this)).listIterator();
}
public ListIterator<A> listIterator(int index) {
return Collections.unmodifiableList(new ArrayList<A>(this)).listIterator(index);
}
public java.util.List<A> subList(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > size() || fromIndex > toIndex)
throw new IllegalArgumentException();
ArrayList<A> a = new ArrayList<A>(toIndex - fromIndex);
int i = 0;
for (List<A> l = this; l.tail != null; l = l.tail, i++) {
if (i == toIndex)
break;
if (i >= fromIndex)
a.add(l.head);
}
return Collections.unmodifiableList(a);
}
}
| 14,342 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Options.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Options.java | /*
* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.*;
import com.sun.tools.javac.main.OptionName;
import static com.sun.tools.javac.main.OptionName.*;
/** A table of all command-line options.
* If an option has an argument, the option name is mapped to the argument.
* If a set option has no argument, it is mapped to itself.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Options {
private static final long serialVersionUID = 0;
/** The context key for the options. */
public static final Context.Key<Options> optionsKey =
new Context.Key<Options>();
private LinkedHashMap<String,String> values;
/** Get the Options instance for this context. */
public static Options instance(Context context) {
Options instance = context.get(optionsKey);
if (instance == null)
instance = new Options(context);
return instance;
}
protected Options(Context context) {
// DEBUGGING -- Use LinkedHashMap for reproducability
values = new LinkedHashMap<String,String>();
context.put(optionsKey, this);
}
/**
* Get the value for an undocumented option.
*/
public String get(String name) {
return values.get(name);
}
/**
* Get the value for an option.
*/
public String get(OptionName name) {
return values.get(name.optionName);
}
/**
* Get the boolean value for an option, patterned after Boolean.getBoolean,
* essentially will return true, iff the value exists and is set to "true".
*/
public boolean getBoolean(String name) {
return getBoolean(name, false);
}
/**
* Get the boolean with a default value if the option is not set.
*/
public boolean getBoolean(String name, boolean defaultValue) {
String value = get(name);
return (value == null) ? defaultValue : Boolean.parseBoolean(value);
}
/**
* Check if the value for an undocumented option has been set.
*/
public boolean isSet(String name) {
return (values.get(name) != null);
}
/**
* Check if the value for an option has been set.
*/
public boolean isSet(OptionName name) {
return (values.get(name.optionName) != null);
}
/**
* Check if the value for a choice option has been set to a specific value.
*/
public boolean isSet(OptionName name, String value) {
return (values.get(name.optionName + value) != null);
}
/**
* Check if the value for an undocumented option has not been set.
*/
public boolean isUnset(String name) {
return (values.get(name) == null);
}
/**
* Check if the value for an option has not been set.
*/
public boolean isUnset(OptionName name) {
return (values.get(name.optionName) == null);
}
/**
* Check if the value for a choice option has not been set to a specific value.
*/
public boolean isUnset(OptionName name, String value) {
return (values.get(name.optionName + value) == null);
}
public void put(String name, String value) {
values.put(name, value);
}
public void put(OptionName name, String value) {
values.put(name.optionName, value);
}
public void putAll(Options options) {
values.putAll(options.values);
}
public void remove(String name) {
values.remove(name);
}
public Set<String> keySet() {
return values.keySet();
}
public int size() {
return values.size();
}
/** Check for a lint suboption. */
public boolean lint(String s) {
// return true if either the specific option is enabled, or
// they are all enabled without the specific one being
// disabled
return
isSet(XLINT_CUSTOM, s) ||
(isSet(XLINT) || isSet(XLINT_CUSTOM, "all")) &&
isUnset(XLINT_CUSTOM, "-" + s);
}
}
| 5,369 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AbstractDiagnosticFormatter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java | /*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.api.DiagnosticFormatter;
import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.DiagnosticPart;
import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.MultilineLimit;
import com.sun.tools.javac.api.DiagnosticFormatter.PositionKind;
import com.sun.tools.javac.api.Formattable;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.code.Printer;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.CapturedType;
import com.sun.tools.javac.file.BaseFileObject;
import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticType.*;
/**
* This abstract class provides a basic implementation of the functionalities that should be provided
* by any formatter used by javac. Among the main features provided by AbstractDiagnosticFormatter are:
*
* <ul>
* <li> Provides a standard implementation of the visitor-like methods defined in the interface DiagnisticFormatter.
* Those implementations are specifically targeting JCDiagnostic objects.
* <li> Provides basic support for i18n and a method for executing all locale-dependent conversions
* <li> Provides the formatting logic for rendering the arguments of a JCDiagnostic object.
* <ul>
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class AbstractDiagnosticFormatter implements DiagnosticFormatter<JCDiagnostic> {
/**
* JavacMessages object used by this formatter for i18n.
*/
protected JavacMessages messages;
/**
* Configuration object used by this formatter
*/
private SimpleConfiguration config;
/**
* Current depth level of the disgnostic being formatted
* (!= 0 for subdiagnostics)
*/
protected int depth = 0;
/**
* All captured types that have been encountered during diagnostic formatting.
* This info is used by the FormatterPrinter in order to print friendly unique
* ids for captured types
*/
private List<Type> allCaptured = List.nil();
/**
* Initialize an AbstractDiagnosticFormatter by setting its JavacMessages object.
* @param messages
*/
protected AbstractDiagnosticFormatter(JavacMessages messages, SimpleConfiguration config) {
this.messages = messages;
this.config = config;
}
public String formatKind(JCDiagnostic d, Locale l) {
switch (d.getType()) {
case FRAGMENT: return "";
case NOTE: return localize(l, "compiler.note.note");
case WARNING: return localize(l, "compiler.warn.warning");
case ERROR: return localize(l, "compiler.err.error");
default:
throw new AssertionError("Unknown diagnostic type: " + d.getType());
}
}
@Override
public String format(JCDiagnostic d, Locale locale) {
allCaptured = List.nil();
return formatDiagnostic(d, locale);
}
protected abstract String formatDiagnostic(JCDiagnostic d, Locale locale);
public String formatPosition(JCDiagnostic d, PositionKind pk,Locale l) {
Assert.check(d.getPosition() != Position.NOPOS);
return String.valueOf(getPosition(d, pk));
}
//where
private long getPosition(JCDiagnostic d, PositionKind pk) {
switch (pk) {
case START: return d.getIntStartPosition();
case END: return d.getIntEndPosition();
case LINE: return d.getLineNumber();
case COLUMN: return d.getColumnNumber();
case OFFSET: return d.getIntPosition();
default:
throw new AssertionError("Unknown diagnostic position: " + pk);
}
}
public String formatSource(JCDiagnostic d, boolean fullname, Locale l) {
JavaFileObject fo = d.getSource();
if (fo == null)
throw new IllegalArgumentException(); // d should have source set
if (fullname)
return fo.getName();
else if (fo instanceof BaseFileObject)
return ((BaseFileObject) fo).getShortName();
else
return BaseFileObject.getSimpleName(fo);
}
/**
* Format the arguments of a given diagnostic.
*
* @param d diagnostic whose arguments are to be formatted
* @param l locale object to be used for i18n
* @return a Collection whose elements are the formatted arguments of the diagnostic
*/
protected Collection<String> formatArguments(JCDiagnostic d, Locale l) {
ListBuffer<String> buf = new ListBuffer<String>();
for (Object o : d.getArgs()) {
buf.append(formatArgument(d, o, l));
}
return buf.toList();
}
/**
* Format a single argument of a given diagnostic.
*
* @param d diagnostic whose argument is to be formatted
* @param arg argument to be formatted
* @param l locale object to be used for i18n
* @return string representation of the diagnostic argument
*/
protected String formatArgument(JCDiagnostic d, Object arg, Locale l) {
if (arg instanceof JCDiagnostic) {
String s = null;
depth++;
try {
s = formatMessage((JCDiagnostic)arg, l);
}
finally {
depth--;
}
return s;
}
else if (arg instanceof Iterable<?>) {
return formatIterable(d, (Iterable<?>)arg, l);
}
else if (arg instanceof Type) {
return printer.visit((Type)arg, l);
}
else if (arg instanceof Symbol) {
return printer.visit((Symbol)arg, l);
}
else if (arg instanceof JavaFileObject) {
return ((JavaFileObject)arg).getName();
}
else if (arg instanceof Formattable) {
return ((Formattable)arg).toString(l, messages);
}
else {
return String.valueOf(arg);
}
}
/**
* Format an iterable argument of a given diagnostic.
*
* @param d diagnostic whose argument is to be formatted
* @param it iterable argument to be formatted
* @param l locale object to be used for i18n
* @return string representation of the diagnostic iterable argument
*/
protected String formatIterable(JCDiagnostic d, Iterable<?> it, Locale l) {
StringBuilder sbuf = new StringBuilder();
String sep = "";
for (Object o : it) {
sbuf.append(sep);
sbuf.append(formatArgument(d, o, l));
sep = ",";
}
return sbuf.toString();
}
/**
* Format all the subdiagnostics attached to a given diagnostic.
*
* @param d diagnostic whose subdiagnostics are to be formatted
* @param l locale object to be used for i18n
* @return list of all string representations of the subdiagnostics
*/
protected List<String> formatSubdiagnostics(JCDiagnostic d, Locale l) {
List<String> subdiagnostics = List.nil();
int maxDepth = config.getMultilineLimit(MultilineLimit.DEPTH);
if (maxDepth == -1 || depth < maxDepth) {
depth++;
try {
int maxCount = config.getMultilineLimit(MultilineLimit.LENGTH);
int count = 0;
for (JCDiagnostic d2 : d.getSubdiagnostics()) {
if (maxCount == -1 || count < maxCount) {
subdiagnostics = subdiagnostics.append(formatSubdiagnostic(d, d2, l));
count++;
}
else
break;
}
}
finally {
depth--;
}
}
return subdiagnostics;
}
/**
* Format a subdiagnostics attached to a given diagnostic.
*
* @param parent multiline diagnostic whose subdiagnostics is to be formatted
* @param sub subdiagnostic to be formatted
* @param l locale object to be used for i18n
* @return string representation of the subdiagnostics
*/
protected String formatSubdiagnostic(JCDiagnostic parent, JCDiagnostic sub, Locale l) {
return formatMessage(sub, l);
}
/** Format the faulty source code line and point to the error.
* @param d The diagnostic for which the error line should be printed
*/
protected String formatSourceLine(JCDiagnostic d, int nSpaces) {
StringBuilder buf = new StringBuilder();
DiagnosticSource source = d.getDiagnosticSource();
int pos = d.getIntPosition();
if (d.getIntPosition() == Position.NOPOS)
throw new AssertionError();
String line = (source == null ? null : source.getLine(pos));
if (line == null)
return "";
buf.append(indent(line, nSpaces));
int col = source.getColumnNumber(pos, false);
if (config.isCaretEnabled()) {
buf.append("\n");
for (int i = 0; i < col - 1; i++) {
buf.append((line.charAt(i) == '\t') ? "\t" : " ");
}
buf.append(indent("^", nSpaces));
}
return buf.toString();
}
protected String formatLintCategory(JCDiagnostic d, Locale l) {
LintCategory lc = d.getLintCategory();
if (lc == null)
return "";
return localize(l, "compiler.warn.lintOption", lc.option);
}
/**
* Converts a String into a locale-dependent representation accordingly to a given locale.
*
* @param l locale object to be used for i18n
* @param key locale-independent key used for looking up in a resource file
* @param args localization arguments
* @return a locale-dependent string
*/
protected String localize(Locale l, String key, Object... args) {
return messages.getLocalizedString(l, key, args);
}
public boolean displaySource(JCDiagnostic d) {
return config.getVisible().contains(DiagnosticPart.SOURCE) &&
d.getType() != FRAGMENT &&
d.getIntPosition() != Position.NOPOS;
}
public boolean isRaw() {
return false;
}
/**
* Creates a string with a given amount of empty spaces. Useful for
* indenting the text of a diagnostic message.
*
* @param nSpaces the amount of spaces to be added to the result string
* @return the indentation string
*/
protected String indentString(int nSpaces) {
String spaces = " ";
if (nSpaces <= spaces.length())
return spaces.substring(0, nSpaces);
else {
StringBuilder buf = new StringBuilder();
for (int i = 0 ; i < nSpaces ; i++)
buf.append(" ");
return buf.toString();
}
}
/**
* Indent a string by prepending a given amount of empty spaces to each line
* of the string.
*
* @param s the string to be indented
* @param nSpaces the amount of spaces that should be prepended to each line
* of the string
* @return an indented string
*/
protected String indent(String s, int nSpaces) {
String indent = indentString(nSpaces);
StringBuilder buf = new StringBuilder();
String nl = "";
for (String line : s.split("\n")) {
buf.append(nl);
buf.append(indent + line);
nl = "\n";
}
return buf.toString();
}
public SimpleConfiguration getConfiguration() {
return config;
}
static public class SimpleConfiguration implements Configuration {
protected Map<MultilineLimit, Integer> multilineLimits;
protected EnumSet<DiagnosticPart> visibleParts;
protected boolean caretEnabled;
public SimpleConfiguration(Set<DiagnosticPart> parts) {
multilineLimits = new HashMap<MultilineLimit, Integer>();
setVisible(parts);
setMultilineLimit(MultilineLimit.DEPTH, -1);
setMultilineLimit(MultilineLimit.LENGTH, -1);
setCaretEnabled(true);
}
@SuppressWarnings("fallthrough")
public SimpleConfiguration(Options options, Set<DiagnosticPart> parts) {
this(parts);
String showSource = null;
if ((showSource = options.get("showSource")) != null) {
if (showSource.equals("true"))
setVisiblePart(DiagnosticPart.SOURCE, true);
else if (showSource.equals("false"))
setVisiblePart(DiagnosticPart.SOURCE, false);
}
String diagOpts = options.get("diags");
if (diagOpts != null) {//override -XDshowSource
Collection<String> args = Arrays.asList(diagOpts.split(","));
if (args.contains("short")) {
setVisiblePart(DiagnosticPart.DETAILS, false);
setVisiblePart(DiagnosticPart.SUBDIAGNOSTICS, false);
}
if (args.contains("source"))
setVisiblePart(DiagnosticPart.SOURCE, true);
if (args.contains("-source"))
setVisiblePart(DiagnosticPart.SOURCE, false);
}
String multiPolicy = null;
if ((multiPolicy = options.get("multilinePolicy")) != null) {
if (multiPolicy.equals("disabled"))
setVisiblePart(DiagnosticPart.SUBDIAGNOSTICS, false);
else if (multiPolicy.startsWith("limit:")) {
String limitString = multiPolicy.substring("limit:".length());
String[] limits = limitString.split(":");
try {
switch (limits.length) {
case 2: {
if (!limits[1].equals("*"))
setMultilineLimit(MultilineLimit.DEPTH, Integer.parseInt(limits[1]));
}
case 1: {
if (!limits[0].equals("*"))
setMultilineLimit(MultilineLimit.LENGTH, Integer.parseInt(limits[0]));
}
}
}
catch(NumberFormatException ex) {
setMultilineLimit(MultilineLimit.DEPTH, -1);
setMultilineLimit(MultilineLimit.LENGTH, -1);
}
}
}
String showCaret = null;
if (((showCaret = options.get("showCaret")) != null) &&
showCaret.equals("false"))
setCaretEnabled(false);
else
setCaretEnabled(true);
}
public int getMultilineLimit(MultilineLimit limit) {
return multilineLimits.get(limit);
}
public EnumSet<DiagnosticPart> getVisible() {
return EnumSet.copyOf(visibleParts);
}
public void setMultilineLimit(MultilineLimit limit, int value) {
multilineLimits.put(limit, value < -1 ? -1 : value);
}
public void setVisible(Set<DiagnosticPart> diagParts) {
visibleParts = EnumSet.copyOf(diagParts);
}
public void setVisiblePart(DiagnosticPart diagParts, boolean enabled) {
if (enabled)
visibleParts.add(diagParts);
else
visibleParts.remove(diagParts);
}
/**
* Shows a '^' sign under the source line displayed by the formatter
* (if applicable).
*
* @param caretEnabled if true enables caret
*/
public void setCaretEnabled(boolean caretEnabled) {
this.caretEnabled = caretEnabled;
}
/**
* Tells whether the caret display is active or not.
*
* @param caretEnabled if true the caret is enabled
*/
public boolean isCaretEnabled() {
return caretEnabled;
}
}
public Printer getPrinter() {
return printer;
}
public void setPrinter(Printer printer) {
this.printer = printer;
}
/**
* An enhanced printer for formatting types/symbols used by
* AbstractDiagnosticFormatter. Provides alternate numbering of captured
* types (they are numbered starting from 1 on each new diagnostic, instead
* of relying on the underlying hashcode() method which generates unstable
* output). Also detects cycles in wildcard messages (e.g. if the wildcard
* type referred by a given captured type C contains C itself) which might
* lead to infinite loops.
*/
protected Printer printer = new Printer() {
@Override
protected String localize(Locale locale, String key, Object... args) {
return AbstractDiagnosticFormatter.this.localize(locale, key, args);
}
@Override
protected String capturedVarId(CapturedType t, Locale locale) {
return "" + (allCaptured.indexOf(t) + 1);
}
@Override
public String visitCapturedType(CapturedType t, Locale locale) {
if (!allCaptured.contains(t)) {
allCaptured = allCaptured.append(t);
}
return super.visitCapturedType(t, locale);
}
};
}
| 19,063 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
LayoutCharacters.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/LayoutCharacters.java | /*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/** An interface containing layout character constants used in Java
* programs.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public interface LayoutCharacters {
/** Tabulator column increment.
*/
final static int TabInc = 8;
/** Standard indentation for subdiagnostics
*/
final static int DiagInc = 4;
/** Standard indentation for additional diagnostic lines
*/
final static int DetailsInc = 2;
/** Tabulator character.
*/
final static byte TAB = 0x9;
/** Line feed character.
*/
final static byte LF = 0xA;
/** Form feed character.
*/
final static byte FF = 0xC;
/** Carriage return character.
*/
final static byte CR = 0xD;
/** End of input character. Used as a sentinel to denote the
* character one beyond the last defined character in a
* source file.
*/
final static byte EOI = 0x1A;
}
| 2,364 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DiagnosticSource.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/DiagnosticSource.java | /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.nio.CharBuffer;
import java.util.Map;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.tree.JCTree;
import static com.sun.tools.javac.util.LayoutCharacters.*;
/**
* A simple abstraction of a source file, as needed for use in a diagnostic message.
* Provides access to the line and position in a line for any given character offset.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class DiagnosticSource {
/* constant DiagnosticSource to be used when sourcefile is missing */
public static final DiagnosticSource NO_SOURCE = new DiagnosticSource() {
@Override
protected boolean findLine(int pos) {
return false;
}
};
public DiagnosticSource(JavaFileObject fo, AbstractLog log) {
this.fileObject = fo;
this.log = log;
}
private DiagnosticSource() {}
/** Return the underlying file object handled by this
* DiagnosticSource object.
*/
public JavaFileObject getFile() {
return fileObject;
}
/** Return the one-based line number associated with a given pos
* for the current source file. Zero is returned if no line exists
* for the given position.
*/
public int getLineNumber(int pos) {
try {
if (findLine(pos)) {
return line;
}
return 0;
} finally {
buf = null;
}
}
/** Return the one-based column number associated with a given pos
* for the current source file. Zero is returned if no column exists
* for the given position.
*/
public int getColumnNumber(int pos, boolean expandTabs) {
try {
if (findLine(pos)) {
int column = 0;
for (int bp = lineStart; bp < pos; bp++) {
if (bp >= bufLen) {
return 0;
}
if (buf[bp] == '\t' && expandTabs) {
column = (column / TabInc * TabInc) + TabInc;
} else {
column++;
}
}
return column + 1; // positions are one-based
}
return 0;
} finally {
buf = null;
}
}
/** Return the content of the line containing a given pos.
*/
public String getLine(int pos) {
try {
if (!findLine(pos))
return null;
int lineEnd = lineStart;
while (lineEnd < bufLen && buf[lineEnd] != CR && buf[lineEnd] != LF)
lineEnd++;
if (lineEnd - lineStart == 0)
return null;
return new String(buf, lineStart, lineEnd - lineStart);
} finally {
buf = null;
}
}
public Map<JCTree, Integer> getEndPosTable() {
return endPosTable;
}
public void setEndPosTable(Map<JCTree, Integer> t) {
if (endPosTable != null && endPosTable != t)
throw new IllegalStateException("endPosTable already set");
endPosTable = t;
}
/** Find the line in the buffer that contains the current position
* @param pos Character offset into the buffer
*/
protected boolean findLine(int pos) {
if (pos == Position.NOPOS)
return false;
try {
// try and recover buffer from soft reference cache
if (buf == null && refBuf != null)
buf = refBuf.get();
if (buf == null) {
buf = initBuf(fileObject);
lineStart = 0;
line = 1;
} else if (lineStart > pos) { // messages don't come in order
lineStart = 0;
line = 1;
}
int bp = lineStart;
while (bp < bufLen && bp < pos) {
switch (buf[bp++]) {
case CR:
if (bp < bufLen && buf[bp] == LF) bp++;
line++;
lineStart = bp;
break;
case LF:
line++;
lineStart = bp;
break;
}
}
return bp <= bufLen;
} catch (IOException e) {
log.directError("source.unavailable");
buf = new char[0];
return false;
}
}
protected char[] initBuf(JavaFileObject fileObject) throws IOException {
char[] buf;
CharSequence cs = fileObject.getCharContent(true);
if (cs instanceof CharBuffer) {
CharBuffer cb = (CharBuffer) cs;
buf = JavacFileManager.toArray(cb);
bufLen = cb.limit();
} else {
buf = cs.toString().toCharArray();
bufLen = buf.length;
}
refBuf = new SoftReference<char[]>(buf);
return buf;
}
/** The underlying file object. */
protected JavaFileObject fileObject;
protected Map<JCTree, Integer> endPosTable;
/** A soft reference to the content of the file object. */
protected SoftReference<char[]> refBuf;
/** A temporary hard reference to the content of the file object. */
protected char[] buf;
/** The length of the content. */
protected int bufLen;
/** The start of a line found by findLine. */
protected int lineStart;
/** The line number of a line found by findLine. */
protected int line;
/** A log for reporting errors, such as errors accessing the content. */
protected AbstractLog log;
}
| 7,158 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ByteBuffer.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/ByteBuffer.java | /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.io.*;
/** A byte buffer is a flexible array which grows when elements are
* appended. There are also methods to append names to byte buffers
* and to convert byte buffers to names.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ByteBuffer {
/** An array holding the bytes in this buffer; can be grown.
*/
public byte[] elems;
/** The current number of defined bytes in this buffer.
*/
public int length;
/** Create a new byte buffer.
*/
public ByteBuffer() {
this(64);
}
/** Create a new byte buffer with an initial elements array
* of given size.
*/
public ByteBuffer(int initialSize) {
elems = new byte[initialSize];
length = 0;
}
private void copy(int size) {
byte[] newelems = new byte[size];
System.arraycopy(elems, 0, newelems, 0, elems.length);
elems = newelems;
}
/** Append byte to this buffer.
*/
public void appendByte(int b) {
if (length >= elems.length) copy(elems.length * 2);
elems[length++] = (byte)b;
}
/** Append `len' bytes from byte array,
* starting at given `start' offset.
*/
public void appendBytes(byte[] bs, int start, int len) {
while (length + len > elems.length) copy(elems.length * 2);
System.arraycopy(bs, start, elems, length, len);
length += len;
}
/** Append all bytes from given byte array.
*/
public void appendBytes(byte[] bs) {
appendBytes(bs, 0, bs.length);
}
/** Append a character as a two byte number.
*/
public void appendChar(int x) {
while (length + 1 >= elems.length) copy(elems.length * 2);
elems[length ] = (byte)((x >> 8) & 0xFF);
elems[length+1] = (byte)((x ) & 0xFF);
length = length + 2;
}
/** Append an integer as a four byte number.
*/
public void appendInt(int x) {
while (length + 3 >= elems.length) copy(elems.length * 2);
elems[length ] = (byte)((x >> 24) & 0xFF);
elems[length+1] = (byte)((x >> 16) & 0xFF);
elems[length+2] = (byte)((x >> 8) & 0xFF);
elems[length+3] = (byte)((x ) & 0xFF);
length = length + 4;
}
/** Append a long as an eight byte number.
*/
public void appendLong(long x) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(8);
DataOutputStream bufout = new DataOutputStream(buffer);
try {
bufout.writeLong(x);
appendBytes(buffer.toByteArray(), 0, 8);
} catch (IOException e) {
throw new AssertionError("write");
}
}
/** Append a float as a four byte number.
*/
public void appendFloat(float x) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(4);
DataOutputStream bufout = new DataOutputStream(buffer);
try {
bufout.writeFloat(x);
appendBytes(buffer.toByteArray(), 0, 4);
} catch (IOException e) {
throw new AssertionError("write");
}
}
/** Append a double as a eight byte number.
*/
public void appendDouble(double x) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(8);
DataOutputStream bufout = new DataOutputStream(buffer);
try {
bufout.writeDouble(x);
appendBytes(buffer.toByteArray(), 0, 8);
} catch (IOException e) {
throw new AssertionError("write");
}
}
/** Append a name.
*/
public void appendName(Name name) {
appendBytes(name.getByteArray(), name.getByteOffset(), name.getByteLength());
}
/** Reset to zero length.
*/
public void reset() {
length = 0;
}
/** Convert contents to name.
*/
public Name toName(Names names) {
return names.fromUtf(elems, 0, length);
}
}
| 5,367 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Position.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Position.java | /*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.BitSet;
import static com.sun.tools.javac.util.LayoutCharacters.*;
/** A class that defines source code positions as simple character
* offsets from the beginning of the file. The first character
* is at position 0.
*
* Support is also provided for (line,column) coordinates, but tab
* expansion is optional and no Unicode excape translation is considered.
* The first character is at location (1,1).
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Position {
public static final int NOPOS = -1;
public static final int FIRSTPOS = 0;
public static final int FIRSTLINE = 1;
public static final int FIRSTCOLUMN = 1;
public static final int LINESHIFT = 10;
public static final int MAXCOLUMN = (1<<LINESHIFT) - 1;
public static final int MAXLINE = (1<<(Integer.SIZE-LINESHIFT)) - 1;
public static final int MAXPOS = Integer.MAX_VALUE;
/**
* This is class is not supposed to be instantiated.
*/
private Position() {}
/** A two-way map between line/column numbers and positions,
* derived from a scan done at creation time. Tab expansion is
* optionally supported via a character map. Text content
* is not retained.
*<p>
* Notes: The first character position FIRSTPOS is at
* (FIRSTLINE,FIRSTCOLUMN). No account is taken of Unicode escapes.
*
* @param src Source characters
* @param max Number of characters to read
* @param expandTabs If true, expand tabs when calculating columns
*/
public static LineMap makeLineMap(char[] src, int max, boolean expandTabs) {
LineMapImpl lineMap = expandTabs ?
new LineTabMapImpl(max) : new LineMapImpl();
lineMap.build(src, max);
return lineMap;
}
/** Encode line and column numbers in an integer as:
* line-number << LINESHIFT + column-number
* {@link Position.NOPOS represents an undefined position.
*
* @param line number of line (first is 1)
* @param col number of character on line (first is 1)
* @return an encoded position or {@link Position.NOPOS
* if the line or column number is too big to
* represent in the encoded format
* @throws IllegalArgumentException if line or col is less than 1
*/
public static int encodePosition(int line, int col) {
if (line < 1)
throw new IllegalArgumentException("line must be greater than 0");
if (col < 1)
throw new IllegalArgumentException("column must be greater than 0");
if (line > MAXLINE || col > MAXCOLUMN) {
return NOPOS;
}
return (line << LINESHIFT) + col;
}
public static interface LineMap extends com.sun.source.tree.LineMap {
/** Find the start position of a line.
*
* @param line number of line (first is 1)
* @return position of first character in line
* @throws ArrayIndexOutOfBoundsException
* if <tt>lineNumber < 1</tt>
* if <tt>lineNumber > no. of lines</tt>
*/
int getStartPosition(int line);
/** Find the position corresponding to a (line,column).
*
* @param line number of line (first is 1)
* @param column number of character on line (first is 1)
*
* @return position of character
* @throws ArrayIndexOutOfBoundsException
* if <tt>line < 1</tt>
* if <tt>line > no. of lines</tt>
*/
int getPosition(int line, int column);
/** Find the line containing a position; a line termination
* character is on the line it terminates.
*
* @param pos character offset of the position
* @return the line number on which pos occurs (first line is 1)
*/
int getLineNumber(int pos);
/** Find the column for a character position.
* Note: this method does not handle tab expansion.
* If tab expansion is needed, use a LineTabMap instead.
*
* @param pos character offset of the position
* @return the column number at which pos occurs
*/
int getColumnNumber(int pos);
}
static class LineMapImpl implements LineMap {
protected int[] startPosition; // start position of each line
protected LineMapImpl() {}
protected void build(char[] src, int max) {
int c = 0;
int i = 0;
int[] linebuf = new int[max];
while (i < max) {
linebuf[c++] = i;
do {
char ch = src[i];
if (ch == '\r' || ch == '\n') {
if (ch == '\r' && (i+1) < max && src[i+1] == '\n')
i += 2;
else
++i;
break;
}
else if (ch == '\t')
setTabPosition(i);
} while (++i < max);
}
this.startPosition = new int[c];
System.arraycopy(linebuf, 0, startPosition, 0, c);
}
public int getStartPosition(int line) {
return startPosition[line - FIRSTLINE];
}
public long getStartPosition(long line) {
return getStartPosition(longToInt(line));
}
public int getPosition(int line, int column) {
return startPosition[line - FIRSTLINE] + column - FIRSTCOLUMN;
}
public long getPosition(long line, long column) {
return getPosition(longToInt(line), longToInt(column));
}
// Cache of last line number lookup
private int lastPosition = Position.FIRSTPOS;
private int lastLine = Position.FIRSTLINE;
public int getLineNumber(int pos) {
if (pos == lastPosition) {
return lastLine;
}
lastPosition = pos;
int low = 0;
int high = startPosition.length-1;
while (low <= high) {
int mid = (low + high) >> 1;
int midVal = startPosition[mid];
if (midVal < pos)
low = mid + 1;
else if (midVal > pos)
high = mid - 1;
else {
lastLine = mid + 1; // pos is at beginning of this line
return lastLine;
}
}
lastLine = low;
return lastLine; // pos is on this line
}
public long getLineNumber(long pos) {
return getLineNumber(longToInt(pos));
}
public int getColumnNumber(int pos) {
return pos - startPosition[getLineNumber(pos) - FIRSTLINE] + FIRSTCOLUMN;
}
public long getColumnNumber(long pos) {
return getColumnNumber(longToInt(pos));
}
private static int longToInt(long longValue) {
int intValue = (int)longValue;
if (intValue != longValue)
throw new IndexOutOfBoundsException();
return intValue;
}
protected void setTabPosition(int offset) {}
}
/**
* A LineMap that handles tab expansion correctly. The cost is
* an additional bit per character in the source array.
*/
public static class LineTabMapImpl extends LineMapImpl {
private BitSet tabMap; // bits set for tab positions.
public LineTabMapImpl(int max) {
super();
tabMap = new BitSet(max);
}
protected void setTabPosition(int offset) {
tabMap.set(offset);
}
public int getColumnNumber(int pos) {
int lineStart = startPosition[getLineNumber(pos) - FIRSTLINE];
int column = 0;
for (int bp = lineStart; bp < pos; bp++) {
if (tabMap.get(bp))
column = (column / TabInc * TabInc) + TabInc;
else
column++;
}
return column + FIRSTCOLUMN;
}
public int getPosition(int line, int column) {
int pos = startPosition[line - FIRSTLINE];
column -= FIRSTCOLUMN;
int col = 0;
while (col < column) {
pos++;
if (tabMap.get(pos))
col = (col / TabInc * TabInc) + TabInc;
else
col++;
}
return pos;
}
}
}
| 10,171 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavacMessages.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/JavacMessages.java | /*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import com.sun.tools.javac.api.Messages;
import java.lang.ref.SoftReference;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* Support for formatted localized messages.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JavacMessages implements Messages {
/** The context key for the JavacMessages object. */
public static final Context.Key<JavacMessages> messagesKey =
new Context.Key<JavacMessages>();
/** Get the JavacMessages instance for this context. */
public static JavacMessages instance(Context context) {
JavacMessages instance = context.get(messagesKey);
if (instance == null)
instance = new JavacMessages(context);
return instance;
}
private Map<Locale, SoftReference<List<ResourceBundle>>> bundleCache;
private List<String> bundleNames;
private Locale currentLocale;
private List<ResourceBundle> currentBundles;
public Locale getCurrentLocale() {
return currentLocale;
}
public void setCurrentLocale(Locale locale) {
if (locale == null) {
locale = Locale.getDefault();
}
this.currentBundles = getBundles(locale);
this.currentLocale = locale;
}
/** Creates a JavacMessages object.
*/
public JavacMessages(Context context) {
this(defaultBundleName, context.get(Locale.class));
context.put(messagesKey, this);
}
/** Creates a JavacMessages object.
* @param bundleName the name to identify the resource buundle of localized messages.
*/
public JavacMessages(String bundleName) throws MissingResourceException {
this(bundleName, null);
}
/** Creates a JavacMessages object.
* @param bundleName the name to identify the resource buundle of localized messages.
*/
public JavacMessages(String bundleName, Locale locale) throws MissingResourceException {
bundleNames = List.nil();
bundleCache = new HashMap<Locale, SoftReference<List<ResourceBundle>>>();
add(bundleName);
setCurrentLocale(locale);
}
public JavacMessages() throws MissingResourceException {
this(defaultBundleName);
}
public void add(String bundleName) throws MissingResourceException {
bundleNames = bundleNames.prepend(bundleName);
if (!bundleCache.isEmpty())
bundleCache.clear();
currentBundles = null;
}
public List<ResourceBundle> getBundles(Locale locale) {
if (locale == currentLocale && currentBundles != null)
return currentBundles;
SoftReference<List<ResourceBundle>> bundles = bundleCache.get(locale);
List<ResourceBundle> bundleList = bundles == null ? null : bundles.get();
if (bundleList == null) {
bundleList = List.nil();
for (String bundleName : bundleNames) {
try {
ResourceBundle rb = ResourceBundle.getBundle(bundleName, locale);
bundleList = bundleList.prepend(rb);
} catch (MissingResourceException e) {
throw new InternalError("Cannot find javac resource bundle for locale " + locale);
}
}
bundleCache.put(locale, new SoftReference<List<ResourceBundle>>(bundleList));
}
return bundleList;
}
/** Gets the localized string corresponding to a key, formatted with a set of args.
*/
public String getLocalizedString(String key, Object... args) {
return getLocalizedString(currentLocale, key, args);
}
public String getLocalizedString(Locale l, String key, Object... args) {
if (l == null)
l = getCurrentLocale();
return getLocalizedString(getBundles(l), key, args);
}
/* Static access:
* javac has a firmly entrenched notion of a default message bundle
* which it can access from any static context. This is used to get
* easy access to simple localized strings.
*/
private static final String defaultBundleName =
"com.sun.tools.javac.resources.compiler";
private static ResourceBundle defaultBundle;
private static JavacMessages defaultMessages;
/**
* Gets a localized string from the compiler's default bundle.
*/
// used to support legacy Log.getLocalizedString
static String getDefaultLocalizedString(String key, Object... args) {
return getLocalizedString(List.of(getDefaultBundle()), key, args);
}
// used to support legacy static Diagnostic.fragment
@Deprecated
static JavacMessages getDefaultMessages() {
if (defaultMessages == null)
defaultMessages = new JavacMessages(defaultBundleName);
return defaultMessages;
}
public static ResourceBundle getDefaultBundle() {
try {
if (defaultBundle == null)
defaultBundle = ResourceBundle.getBundle(defaultBundleName);
return defaultBundle;
}
catch (MissingResourceException e) {
throw new Error("Fatal: Resource for compiler is missing", e);
}
}
private static String getLocalizedString(List<ResourceBundle> bundles,
String key,
Object... args) {
String msg = null;
for (List<ResourceBundle> l = bundles; l.nonEmpty() && msg == null; l = l.tail) {
ResourceBundle rb = l.head;
try {
msg = rb.getString(key);
}
catch (MissingResourceException e) {
// ignore, try other bundles in list
}
}
if (msg == null) {
msg = "compiler message file broken: key=" + key +
" arguments={0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}";
}
return MessageFormat.format(msg, args);
}
}
| 7,484 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Filter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Filter.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/**
* Simple filter acting as a boolean predicate. Method accepts return true if
* the supplied element matches against the filter.
*/
public interface Filter<T> {
/**
* Does this element match against the filter?
* @param t element to be checked
* @return true if the element satisfy constraints imposed by filter
*/
boolean accepts(T t);
}
| 1,616 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ListBuffer.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/ListBuffer.java | /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
/** A class for constructing lists by appending elements. Modelled after
* java.lang.StringBuffer.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ListBuffer<A> extends AbstractQueue<A> {
public static <T> ListBuffer<T> lb() {
return new ListBuffer<T>();
}
public static <T> ListBuffer<T> of(T x) {
ListBuffer<T> lb = new ListBuffer<T>();
lb.add(x);
return lb;
}
/** The list of elements of this buffer.
*/
public List<A> elems;
/** A pointer pointing to the last, sentinel element of `elems'.
*/
public List<A> last;
/** The number of element in this buffer.
*/
public int count;
/** Has a list been created from this buffer yet?
*/
public boolean shared;
/** Create a new initially empty list buffer.
*/
public ListBuffer() {
clear();
}
public final void clear() {
this.elems = new List<A>(null,null);
this.last = this.elems;
count = 0;
shared = false;
}
/** Return the number of elements in this buffer.
*/
public int length() {
return count;
}
public int size() {
return count;
}
/** Is buffer empty?
*/
public boolean isEmpty() {
return count == 0;
}
/** Is buffer not empty?
*/
public boolean nonEmpty() {
return count != 0;
}
/** Copy list and sets last.
*/
private void copy() {
List<A> p = elems = new List<A>(elems.head, elems.tail);
while (true) {
List<A> tail = p.tail;
if (tail == null) break;
tail = new List<A>(tail.head, tail.tail);
p.setTail(tail);
p = tail;
}
last = p;
shared = false;
}
/** Prepend an element to buffer.
*/
public ListBuffer<A> prepend(A x) {
elems = elems.prepend(x);
count++;
return this;
}
/** Append an element to buffer.
*/
public ListBuffer<A> append(A x) {
x.getClass(); // null check
if (shared) copy();
last.head = x;
last.setTail(new List<A>(null,null));
last = last.tail;
count++;
return this;
}
/** Append all elements in a list to buffer.
*/
public ListBuffer<A> appendList(List<A> xs) {
while (xs.nonEmpty()) {
append(xs.head);
xs = xs.tail;
}
return this;
}
/** Append all elements in a list to buffer.
*/
public ListBuffer<A> appendList(ListBuffer<A> xs) {
return appendList(xs.toList());
}
/** Append all elements in an array to buffer.
*/
public ListBuffer<A> appendArray(A[] xs) {
for (int i = 0; i < xs.length; i++) {
append(xs[i]);
}
return this;
}
/** Convert buffer to a list of all its elements.
*/
public List<A> toList() {
shared = true;
return elems;
}
/** Does the list contain the specified element?
*/
public boolean contains(Object x) {
return elems.contains(x);
}
/** Convert buffer to an array
*/
public <T> T[] toArray(T[] vec) {
return elems.toArray(vec);
}
public Object[] toArray() {
return toArray(new Object[size()]);
}
/** The first element in this buffer.
*/
public A first() {
return elems.head;
}
/** Return first element in this buffer and remove
*/
public A next() {
A x = elems.head;
if (elems != last) {
elems = elems.tail;
count--;
}
return x;
}
/** An enumeration of all elements in this buffer.
*/
public Iterator<A> iterator() {
return new Iterator<A>() {
List<A> elems = ListBuffer.this.elems;
public boolean hasNext() {
return elems != last;
}
public A next() {
if (elems == last)
throw new NoSuchElementException();
A elem = elems.head;
elems = elems.tail;
return elem;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public boolean add(A a) {
append(a);
return true;
}
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
public boolean containsAll(Collection<?> c) {
for (Object x: c) {
if (!contains(x))
return false;
}
return true;
}
public boolean addAll(Collection<? extends A> c) {
for (A a: c)
append(a);
return true;
}
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
public boolean offer(A a) {
append(a);
return true;
}
public A poll() {
return next();
}
public A peek() {
return first();
}
}
| 6,766 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
MandatoryWarningHandler.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/MandatoryWarningHandler.java | /*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.HashSet;
import java.util.Set;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
/**
* A handler to process mandatory warnings, setting up a deferred diagnostic
* to be printed at the end of the compilation if some warnings get suppressed
* because too many warnings have already been generated.
*
* Note that the SuppressWarnings annotation can be used to suppress warnings
* about conditions that would otherwise merit a warning. Such processing
* is done when the condition is detected, and in those cases, no call is
* made on any API to generate a warning at all. In consequence, this handler only
* gets to handle those warnings that JLS says must be generated.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class MandatoryWarningHandler {
/**
* The kinds of different deferred diagnostics that might be generated
* if a mandatory warning is suppressed because too many warnings have
* already been output.
*
* The parameter is a fragment used to build an I18N message key for Log.
*/
private enum DeferredDiagnosticKind {
/**
* This kind is used when a single specific file is found to have warnings
* and no similar warnings have already been given.
* It generates a message like:
* FILE has ISSUES
*/
IN_FILE(".filename"),
/**
* This kind is used when a single specific file is found to have warnings
* and when similar warnings have already been reported for the file.
* It generates a message like:
* FILE has additional ISSUES
*/
ADDITIONAL_IN_FILE(".filename.additional"),
/**
* This kind is used when multiple files have been found to have warnings,
* and none of them have had any similar warnings.
* It generates a message like:
* Some files have ISSUES
*/
IN_FILES(".plural"),
/**
* This kind is used when multiple files have been found to have warnings,
* and some of them have had already had specific similar warnings.
* It generates a message like:
* Some files have additional ISSUES
*/
ADDITIONAL_IN_FILES(".plural.additional");
DeferredDiagnosticKind(String v) { value = v; }
String getKey(String prefix) { return prefix + value; }
private String value;
}
/**
* Create a handler for mandatory warnings.
* @param log The log on which to generate any diagnostics
* @param verbose Specify whether or not detailed messages about
* individual instances should be given, or whether an aggregate
* message should be generated at the end of the compilation.
* Typically set via -Xlint:option.
* @param enforceMandatory
* True if mandatory warnings and notes are being enforced.
* @param prefix A common prefix for the set of message keys for
* the messages that may be generated.
* @param lc An associated lint category for the warnings, or null if none.
*/
public MandatoryWarningHandler(Log log, boolean verbose,
boolean enforceMandatory, String prefix,
LintCategory lc) {
this.log = log;
this.verbose = verbose;
this.prefix = prefix;
this.enforceMandatory = enforceMandatory;
this.lintCategory = lc;
}
/**
* Report a mandatory warning.
*/
public void report(DiagnosticPosition pos, String msg, Object... args) {
JavaFileObject currentSource = log.currentSourceFile();
if (verbose) {
if (sourcesWithReportedWarnings == null)
sourcesWithReportedWarnings = new HashSet<JavaFileObject>();
if (log.nwarnings < log.MaxWarnings) {
// generate message and remember the source file
logMandatoryWarning(pos, msg, args);
sourcesWithReportedWarnings.add(currentSource);
} else if (deferredDiagnosticKind == null) {
// set up deferred message
if (sourcesWithReportedWarnings.contains(currentSource)) {
// more errors in a file that already has reported warnings
deferredDiagnosticKind = DeferredDiagnosticKind.ADDITIONAL_IN_FILE;
} else {
// warnings in a new source file
deferredDiagnosticKind = DeferredDiagnosticKind.IN_FILE;
}
deferredDiagnosticSource = currentSource;
deferredDiagnosticArg = currentSource;
} else if ((deferredDiagnosticKind == DeferredDiagnosticKind.IN_FILE
|| deferredDiagnosticKind == DeferredDiagnosticKind.ADDITIONAL_IN_FILE)
&& !equal(deferredDiagnosticSource, currentSource)) {
// additional errors in more than one source file
deferredDiagnosticKind = DeferredDiagnosticKind.ADDITIONAL_IN_FILES;
deferredDiagnosticArg = null;
}
} else {
if (deferredDiagnosticKind == null) {
// warnings in a single source
deferredDiagnosticKind = DeferredDiagnosticKind.IN_FILE;
deferredDiagnosticSource = currentSource;
deferredDiagnosticArg = currentSource;
} else if (deferredDiagnosticKind == DeferredDiagnosticKind.IN_FILE &&
!equal(deferredDiagnosticSource, currentSource)) {
// warnings in multiple source files
deferredDiagnosticKind = DeferredDiagnosticKind.IN_FILES;
deferredDiagnosticArg = null;
}
}
}
/**
* Report any diagnostic that might have been deferred by previous calls of report().
*/
public void reportDeferredDiagnostic() {
if (deferredDiagnosticKind != null) {
if (deferredDiagnosticArg == null)
logMandatoryNote(deferredDiagnosticSource, deferredDiagnosticKind.getKey(prefix));
else
logMandatoryNote(deferredDiagnosticSource, deferredDiagnosticKind.getKey(prefix), deferredDiagnosticArg);
if (!verbose)
logMandatoryNote(deferredDiagnosticSource, prefix + ".recompile");
}
}
/**
* Check two objects, each possibly null, are either both null or are equal.
*/
private static boolean equal(Object o1, Object o2) {
return ((o1 == null || o2 == null) ? (o1 == o2) : o1.equals(o2));
}
/**
* The log to which to report warnings.
*/
private Log log;
/**
* Whether or not to report individual warnings, or simply to report a
* single aggregate warning at the end of the compilation.
*/
private boolean verbose;
/**
* The common prefix for all I18N message keys generated by this handler.
*/
private String prefix;
/**
* A set containing the names of the source files for which specific
* warnings have been generated -- i.e. in verbose mode. If a source name
* appears in this list, then deferred diagnostics will be phrased to
* include "additionally"...
*/
private Set<JavaFileObject> sourcesWithReportedWarnings;
/**
* A variable indicating the latest best guess at what the final
* deferred diagnostic will be. Initially as specific and helpful
* as possible, as more warnings are reported, the scope of the
* diagnostic will be broadened.
*/
private DeferredDiagnosticKind deferredDiagnosticKind;
/**
* If deferredDiagnosticKind is IN_FILE or ADDITIONAL_IN_FILE, this variable
* gives the value of log.currentSource() for the file in question.
*/
private JavaFileObject deferredDiagnosticSource;
/**
* An optional argument to be used when constructing the
* deferred diagnostic message, based on deferredDiagnosticKind.
* This variable should normally be set/updated whenever
* deferredDiagnosticKind is updated.
*/
private Object deferredDiagnosticArg;
/**
* True if mandatory warnings and notes are being enforced.
*/
private final boolean enforceMandatory;
/**
* A LintCategory to be included in point-of-use diagnostics to indicate
* how messages might be suppressed (i.e. with @SuppressWarnings).
*/
private final LintCategory lintCategory;
/**
* Reports a mandatory warning to the log. If mandatory warnings
* are not being enforced, treat this as an ordinary warning.
*/
private void logMandatoryWarning(DiagnosticPosition pos, String msg,
Object... args) {
// Note: the following log methods are safe if lintCategory is null.
if (enforceMandatory)
log.mandatoryWarning(lintCategory, pos, msg, args);
else
log.warning(lintCategory, pos, msg, args);
}
/**
* Reports a mandatory note to the log. If mandatory notes are
* not being enforced, treat this as an ordinary note.
*/
private void logMandatoryNote(JavaFileObject file, String msg, Object... args) {
if (enforceMandatory)
log.mandatoryNote(file, msg, args);
else
log.note(file, msg, args);
}
}
| 11,061 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Abort.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Abort.java | /*
* Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/** Throwing an instance of
* this class causes (silent) termination of the main compiler method.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Abort extends Error {
private static final long serialVersionUID = 0;
public Abort(Throwable cause) {
super(cause);
}
public Abort() {
super();
}
}
| 1,777 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Bits.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Bits.java | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/** A class for extensible, mutable bit sets.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Bits {
private final static int wordlen = 32;
private final static int wordshift = 5;
private final static int wordmask = wordlen - 1;
private int[] bits;
/** Construct an initially empty set.
*/
public Bits() {
this(new int[1]);
}
/** Construct a set consisting initially of given bit vector.
*/
public Bits(int[] bits) {
this.bits = bits;
}
/** Construct a set consisting initially of given range.
*/
public Bits(int start, int limit) {
this();
inclRange(start, limit);
}
private void sizeTo(int len) {
if (bits.length < len) {
int[] newbits = new int[len];
System.arraycopy(bits, 0, newbits, 0, bits.length);
bits = newbits;
}
}
/** This set = {}.
*/
public void clear() {
for (int i = 0; i < bits.length; i++) bits[i] = 0;
}
/** Return a copy of this set.
*/
public Bits dup() {
int[] newbits = new int[bits.length];
System.arraycopy(bits, 0, newbits, 0, bits.length);
return new Bits(newbits);
}
/** Include x in this set.
*/
public void incl(int x) {
Assert.check(x >= 0);
sizeTo((x >>> wordshift) + 1);
bits[x >>> wordshift] = bits[x >>> wordshift] |
(1 << (x & wordmask));
}
/** Include [start..limit) in this set.
*/
public void inclRange(int start, int limit) {
sizeTo((limit >>> wordshift) + 1);
for (int x = start; x < limit; x++)
bits[x >>> wordshift] = bits[x >>> wordshift] |
(1 << (x & wordmask));
}
/** Exclude [start...end] from this set.
*/
public void excludeFrom(int start) {
Bits temp = new Bits();
temp.sizeTo(bits.length);
temp.inclRange(0, start);
andSet(temp);
}
/** Exclude x from this set.
*/
public void excl(int x) {
Assert.check(x >= 0);
sizeTo((x >>> wordshift) + 1);
bits[x >>> wordshift] = bits[x >>> wordshift] &
~(1 << (x & wordmask));
}
/** Is x an element of this set?
*/
public boolean isMember(int x) {
return
0 <= x && x < (bits.length << wordshift) &&
(bits[x >>> wordshift] & (1 << (x & wordmask))) != 0;
}
/** this set = this set & xs.
*/
public Bits andSet(Bits xs) {
sizeTo(xs.bits.length);
for (int i = 0; i < xs.bits.length; i++)
bits[i] = bits[i] & xs.bits[i];
return this;
}
/** this set = this set | xs.
*/
public Bits orSet(Bits xs) {
sizeTo(xs.bits.length);
for (int i = 0; i < xs.bits.length; i++)
bits[i] = bits[i] | xs.bits[i];
return this;
}
/** this set = this set \ xs.
*/
public Bits diffSet(Bits xs) {
for (int i = 0; i < bits.length; i++) {
if (i < xs.bits.length) {
bits[i] = bits[i] & ~xs.bits[i];
}
}
return this;
}
/** this set = this set ^ xs.
*/
public Bits xorSet(Bits xs) {
sizeTo(xs.bits.length);
for (int i = 0; i < xs.bits.length; i++)
bits[i] = bits[i] ^ xs.bits[i];
return this;
}
/** Count trailing zero bits in an int. Algorithm from "Hacker's
* Delight" by Henry S. Warren Jr. (figure 5-13)
*/
private static int trailingZeroBits(int x) {
Assert.check(wordlen == 32);
if (x == 0) return 32;
int n = 1;
if ((x & 0xffff) == 0) { n += 16; x >>>= 16; }
if ((x & 0x00ff) == 0) { n += 8; x >>>= 8; }
if ((x & 0x000f) == 0) { n += 4; x >>>= 4; }
if ((x & 0x0003) == 0) { n += 2; x >>>= 2; }
return n - (x&1);
}
/** Return the index of the least bit position >= x that is set.
* If none are set, returns -1. This provides a nice way to iterate
* over the members of a bit set:
* <pre>
* for (int i = bits.nextBit(0); i>=0; i = bits.nextBit(i+1)) ...
* </pre>
*/
public int nextBit(int x) {
int windex = x >>> wordshift;
if (windex >= bits.length) return -1;
int word = bits[windex] & ~((1 << (x & wordmask))-1);
while (true) {
if (word != 0)
return (windex << wordshift) + trailingZeroBits(word);
windex++;
if (windex >= bits.length) return -1;
word = bits[windex];
}
}
/** a string representation of this set.
*/
public String toString() {
char[] digits = new char[bits.length * wordlen];
for (int i = 0; i < bits.length * wordlen; i++)
digits[i] = isMember(i) ? '1' : '0';
return new String(digits);
}
/** Test Bits.nextBit(int). */
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
Bits bits = new Bits();
int dupCount = 0;
for (int i=0; i<125; i++) {
int k;
do {
k = r.nextInt(250);
} while (bits.isMember(k));
System.out.println("adding " + k);
bits.incl(k);
}
int count = 0;
for (int i = bits.nextBit(0); i >= 0; i = bits.nextBit(i+1)) {
System.out.println("found " + i);
count ++;
}
if (count != 125) throw new Error();
}
}
| 7,008 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Pair.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Pair.java | /*
* Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/** A generic class for pairs.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Pair<A, B> {
public final A fst;
public final B snd;
public Pair(A fst, B snd) {
this.fst = fst;
this.snd = snd;
}
public String toString() {
return "Pair[" + fst + "," + snd + "]";
}
private static boolean equals(Object x, Object y) {
return (x == null && y == null) || (x != null && x.equals(y));
}
public boolean equals(Object other) {
return
other instanceof Pair<?,?> &&
equals(fst, ((Pair<?,?>)other).fst) &&
equals(snd, ((Pair<?,?>)other).snd);
}
public int hashCode() {
if (fst == null) return (snd == null) ? 0 : snd.hashCode() + 1;
else if (snd == null) return fst.hashCode() + 2;
else return fst.hashCode() * 17 + snd.hashCode();
}
public static <A,B> Pair<A,B> of(A a, B b) {
return new Pair<A,B>(a,b);
}
}
| 2,411 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
RichDiagnosticFormatter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/RichDiagnosticFormatter.java | /*
* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Printer;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.code.Types;
import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.util.LayoutCharacters.*;
import static com.sun.tools.javac.util.RichDiagnosticFormatter.RichConfiguration.*;
/**
* A rich diagnostic formatter is a formatter that provides better integration
* with javac's type system. A diagostic is first preprocessed in order to keep
* track of each types/symbols in it; after these informations are collected,
* the diagnostic is rendered using a standard formatter, whose type/symbol printer
* has been replaced by a more refined version provided by this rich formatter.
* The rich formatter currently enables three different features: (i) simple class
* names - that is class names are displayed used a non qualified name (thus
* omitting package info) whenever possible - (ii) where clause list - a list of
* additional subdiagnostics that provide specific info about type-variables,
* captured types, intersection types that occur in the diagnostic that is to be
* formatted and (iii) type-variable disambiguation - when the diagnostic refers
* to two different type-variables with the same name, their representation is
* disambiguated by appending an index to the type variable name.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class RichDiagnosticFormatter extends
ForwardingDiagnosticFormatter<JCDiagnostic, AbstractDiagnosticFormatter> {
final Symtab syms;
final Types types;
final JCDiagnostic.Factory diags;
final JavacMessages messages;
/* name simplifier used by this formatter */
protected ClassNameSimplifier nameSimplifier;
/* type/symbol printer used by this formatter */
private RichPrinter printer;
/* map for keeping track of a where clause associated to a given type */
Map<WhereClauseKind, Map<Type, JCDiagnostic>> whereClauses;
/** Get the DiagnosticFormatter instance for this context. */
public static RichDiagnosticFormatter instance(Context context) {
RichDiagnosticFormatter instance = context.get(RichDiagnosticFormatter.class);
if (instance == null)
instance = new RichDiagnosticFormatter(context);
return instance;
}
protected RichDiagnosticFormatter(Context context) {
super((AbstractDiagnosticFormatter)Log.instance(context).getDiagnosticFormatter());
setRichPrinter(new RichPrinter());
this.syms = Symtab.instance(context);
this.diags = JCDiagnostic.Factory.instance(context);
this.types = Types.instance(context);
this.messages = JavacMessages.instance(context);
whereClauses = new LinkedHashMap<WhereClauseKind, Map<Type, JCDiagnostic>>();
configuration = new RichConfiguration(Options.instance(context), formatter);
for (WhereClauseKind kind : WhereClauseKind.values())
whereClauses.put(kind, new LinkedHashMap<Type, JCDiagnostic>());
}
@Override
public String format(JCDiagnostic diag, Locale l) {
StringBuilder sb = new StringBuilder();
nameSimplifier = new ClassNameSimplifier();
for (WhereClauseKind kind : WhereClauseKind.values())
whereClauses.get(kind).clear();
preprocessDiagnostic(diag);
sb.append(formatter.format(diag, l));
if (getConfiguration().isEnabled(RichFormatterFeature.WHERE_CLAUSES)) {
List<JCDiagnostic> clauses = getWhereClauses();
String indent = formatter.isRaw() ? "" :
formatter.indentString(DetailsInc);
for (JCDiagnostic d : clauses) {
String whereClause = formatter.format(d, l);
if (whereClause.length() > 0) {
sb.append('\n' + indent + whereClause);
}
}
}
return sb.toString();
}
/**
* Sets the type/symbol printer used by this formatter.
* @param printer the rich printer to be set
*/
protected void setRichPrinter(RichPrinter printer) {
this.printer = printer;
formatter.setPrinter(printer);
}
/**
* Gets the type/symbol printer used by this formatter.
* @return type/symbol rich printer
*/
protected RichPrinter getRichPrinter() {
return printer;
}
/**
* Preprocess a given diagnostic by looking both into its arguments and into
* its subdiagnostics (if any). This preprocessing is responsible for
* generating info corresponding to features like where clauses, name
* simplification, etc.
*
* @param diag the diagnostic to be preprocessed
*/
protected void preprocessDiagnostic(JCDiagnostic diag) {
for (Object o : diag.getArgs()) {
if (o != null) {
preprocessArgument(o);
}
}
if (diag.isMultiline()) {
for (JCDiagnostic d : diag.getSubdiagnostics())
preprocessDiagnostic(d);
}
}
/**
* Preprocess a diagnostic argument. A type/symbol argument is
* preprocessed by specialized type/symbol preprocessors.
*
* @param arg the argument to be translated
*/
protected void preprocessArgument(Object arg) {
if (arg instanceof Type) {
preprocessType((Type)arg);
}
else if (arg instanceof Symbol) {
preprocessSymbol((Symbol)arg);
}
else if (arg instanceof JCDiagnostic) {
preprocessDiagnostic((JCDiagnostic)arg);
}
else if (arg instanceof Iterable<?>) {
for (Object o : (Iterable<?>)arg) {
preprocessArgument(o);
}
}
}
/**
* Build a list of multiline diagnostics containing detailed info about
* type-variables, captured types, and intersection types
*
* @return where clause list
*/
protected List<JCDiagnostic> getWhereClauses() {
List<JCDiagnostic> clauses = List.nil();
for (WhereClauseKind kind : WhereClauseKind.values()) {
List<JCDiagnostic> lines = List.nil();
for (Map.Entry<Type, JCDiagnostic> entry : whereClauses.get(kind).entrySet()) {
lines = lines.prepend(entry.getValue());
}
if (!lines.isEmpty()) {
String key = kind.key();
if (lines.size() > 1)
key += ".1";
JCDiagnostic d = diags.fragment(key, whereClauses.get(kind).keySet());
d = new JCDiagnostic.MultilineDiagnostic(d, lines.reverse());
clauses = clauses.prepend(d);
}
}
return clauses.reverse();
}
private int indexOf(Type type, WhereClauseKind kind) {
int index = 1;
for (Type t : whereClauses.get(kind).keySet()) {
if (t.tsym == type.tsym) {
return index;
}
if (kind != WhereClauseKind.TYPEVAR ||
t.toString().equals(type.toString())) {
index++;
}
}
return -1;
}
private boolean unique(TypeVar typevar) {
int found = 0;
for (Type t : whereClauses.get(WhereClauseKind.TYPEVAR).keySet()) {
if (t.toString().equals(typevar.toString())) {
found++;
}
}
if (found < 1)
throw new AssertionError("Missing type variable in where clause " + typevar);
return found == 1;
}
//where
/**
* This enum defines all posssible kinds of where clauses that can be
* attached by a rich diagnostic formatter to a given diagnostic
*/
enum WhereClauseKind {
/** where clause regarding a type variable */
TYPEVAR("where.description.typevar"),
/** where clause regarding a captured type */
CAPTURED("where.description.captured"),
/** where clause regarding an intersection type */
INTERSECTION("where.description.intersection");
/** resource key for this where clause kind */
private String key;
WhereClauseKind(String key) {
this.key = key;
}
String key() {
return key;
}
}
// <editor-fold defaultstate="collapsed" desc="name simplifier">
/**
* A name simplifier keeps track of class names usages in order to determine
* whether a class name can be compacted or not. Short names are not used
* if a conflict is detected, e.g. when two classes with the same simple
* name belong to different packages - in this case the formatter reverts
* to fullnames as compact names might lead to a confusing diagnostic.
*/
protected class ClassNameSimplifier {
/* table for keeping track of all short name usages */
Map<Name, List<Symbol>> nameClashes = new HashMap<Name, List<Symbol>>();
/**
* Add a name usage to the simplifier's internal cache
*/
protected void addUsage(Symbol sym) {
Name n = sym.getSimpleName();
List<Symbol> conflicts = nameClashes.get(n);
if (conflicts == null) {
conflicts = List.nil();
}
if (!conflicts.contains(sym))
nameClashes.put(n, conflicts.append(sym));
}
public String simplify(Symbol s) {
String name = s.getQualifiedName().toString();
if (!s.type.isCompound()) {
List<Symbol> conflicts = nameClashes.get(s.getSimpleName());
if (conflicts == null ||
(conflicts.size() == 1 &&
conflicts.contains(s))) {
List<Name> l = List.nil();
Symbol s2 = s;
while (s2.type.getEnclosingType().tag == CLASS
&& s2.owner.kind == Kinds.TYP) {
l = l.prepend(s2.getSimpleName());
s2 = s2.owner;
}
l = l.prepend(s2.getSimpleName());
StringBuilder buf = new StringBuilder();
String sep = "";
for (Name n2 : l) {
buf.append(sep);
buf.append(n2);
sep = ".";
}
name = buf.toString();
}
}
return name;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="rich printer">
/**
* Enhanced type/symbol printer that provides support for features like simple names
* and type variable disambiguation. This enriched printer exploits the info
* discovered during type/symbol preprocessing. This printer is set on the delegate
* formatter so that rich type/symbol info can be properly rendered.
*/
protected class RichPrinter extends Printer {
@Override
public String localize(Locale locale, String key, Object... args) {
return formatter.localize(locale, key, args);
}
@Override
public String capturedVarId(CapturedType t, Locale locale) {
return indexOf(t, WhereClauseKind.CAPTURED) + "";
}
@Override
public String visitType(Type t, Locale locale) {
String s = super.visitType(t, locale);
if (t == syms.botType)
s = localize(locale, "compiler.misc.type.null");
return s;
}
@Override
public String visitCapturedType(CapturedType t, Locale locale) {
if (getConfiguration().isEnabled(RichFormatterFeature.WHERE_CLAUSES)) {
return localize(locale,
"compiler.misc.captured.type",
indexOf(t, WhereClauseKind.CAPTURED));
}
else
return super.visitCapturedType(t, locale);
}
@Override
public String visitClassType(ClassType t, Locale locale) {
if (t.isCompound() &&
getConfiguration().isEnabled(RichFormatterFeature.WHERE_CLAUSES)) {
return localize(locale,
"compiler.misc.intersection.type",
indexOf(t, WhereClauseKind.INTERSECTION));
}
else
return super.visitClassType(t, locale);
}
@Override
protected String className(ClassType t, boolean longform, Locale locale) {
Symbol sym = t.tsym;
if (sym.name.length() == 0 ||
!getConfiguration().isEnabled(RichFormatterFeature.SIMPLE_NAMES)) {
return super.className(t, longform, locale);
}
else if (longform)
return nameSimplifier.simplify(sym).toString();
else
return sym.name.toString();
}
@Override
public String visitTypeVar(TypeVar t, Locale locale) {
if (unique(t) ||
!getConfiguration().isEnabled(RichFormatterFeature.UNIQUE_TYPEVAR_NAMES)) {
return t.toString();
}
else {
return localize(locale,
"compiler.misc.type.var",
t.toString(), indexOf(t, WhereClauseKind.TYPEVAR));
}
}
@Override
protected String printMethodArgs(List<Type> args, boolean varArgs, Locale locale) {
return super.printMethodArgs(args, varArgs, locale);
}
@Override
public String visitClassSymbol(ClassSymbol s, Locale locale) {
String name = nameSimplifier.simplify(s);
if (name.length() == 0 ||
!getConfiguration().isEnabled(RichFormatterFeature.SIMPLE_NAMES)) {
return super.visitClassSymbol(s, locale);
}
else {
return name;
}
}
@Override
public String visitMethodSymbol(MethodSymbol s, Locale locale) {
String ownerName = visit(s.owner, locale);
if (s.isStaticOrInstanceInit()) {
return ownerName;
} else {
String ms = (s.name == s.name.table.names.init)
? ownerName
: s.name.toString();
if (s.type != null) {
if (s.type.tag == FORALL) {
ms = "<" + visitTypes(s.type.getTypeArguments(), locale) + ">" + ms;
}
ms += "(" + printMethodArgs(
s.type.getParameterTypes(),
(s.flags() & VARARGS) != 0,
locale) + ")";
}
return ms;
}
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="type scanner">
/**
* Preprocess a given type looking for (i) additional info (where clauses) to be
* added to the main diagnostic (ii) names to be compacted.
*/
protected void preprocessType(Type t) {
typePreprocessor.visit(t);
}
//where
protected Types.UnaryVisitor<Void> typePreprocessor =
new Types.UnaryVisitor<Void>() {
public Void visit(List<Type> ts) {
for (Type t : ts)
visit(t);
return null;
}
@Override
public Void visitForAll(ForAll t, Void ignored) {
visit(t.tvars);
visit(t.qtype);
return null;
}
@Override
public Void visitMethodType(MethodType t, Void ignored) {
visit(t.argtypes);
visit(t.restype);
return null;
}
@Override
public Void visitErrorType(ErrorType t, Void ignored) {
Type ot = t.getOriginalType();
if (ot != null)
visit(ot);
return null;
}
@Override
public Void visitArrayType(ArrayType t, Void ignored) {
visit(t.elemtype);
return null;
}
@Override
public Void visitWildcardType(WildcardType t, Void ignored) {
visit(t.type);
return null;
}
public Void visitType(Type t, Void ignored) {
return null;
}
@Override
public Void visitCapturedType(CapturedType t, Void ignored) {
if (indexOf(t, WhereClauseKind.CAPTURED) == -1) {
String suffix = t.lower == syms.botType ? ".1" : "";
JCDiagnostic d = diags.fragment("where.captured"+ suffix, t, t.bound, t.lower, t.wildcard);
whereClauses.get(WhereClauseKind.CAPTURED).put(t, d);
visit(t.wildcard);
visit(t.lower);
visit(t.bound);
}
return null;
}
@Override
public Void visitClassType(ClassType t, Void ignored) {
if (t.isCompound()) {
if (indexOf(t, WhereClauseKind.INTERSECTION) == -1) {
Type supertype = types.supertype(t);
List<Type> interfaces = types.interfaces(t);
JCDiagnostic d = diags.fragment("where.intersection", t, interfaces.prepend(supertype));
whereClauses.get(WhereClauseKind.INTERSECTION).put(t, d);
visit(supertype);
visit(interfaces);
}
}
nameSimplifier.addUsage(t.tsym);
visit(t.getTypeArguments());
if (t.getEnclosingType() != Type.noType)
visit(t.getEnclosingType());
return null;
}
@Override
public Void visitTypeVar(TypeVar t, Void ignored) {
if (indexOf(t, WhereClauseKind.TYPEVAR) == -1) {
//access the bound type and skip error types
Type bound = t.bound;
while ((bound instanceof ErrorType))
bound = ((ErrorType)bound).getOriginalType();
//retrieve the bound list - if the type variable
//has not been attributed the bound is not set
List<Type> bounds = bound != null ?
types.getBounds(t) :
List.<Type>nil();
nameSimplifier.addUsage(t.tsym);
boolean boundErroneous = bounds.head == null ||
bounds.head.tag == NONE ||
bounds.head.tag == ERROR;
JCDiagnostic d = diags.fragment("where.typevar" +
(boundErroneous ? ".1" : ""), t, bounds,
Kinds.kindName(t.tsym.location()), t.tsym.location());
whereClauses.get(WhereClauseKind.TYPEVAR).put(t, d);
symbolPreprocessor.visit(t.tsym.location(), null);
visit(bounds);
}
return null;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="symbol scanner">
/**
* Preprocess a given symbol looking for (i) additional info (where clauses) to be
* asdded to the main diagnostic (ii) names to be compacted
*/
protected void preprocessSymbol(Symbol s) {
symbolPreprocessor.visit(s, null);
}
//where
protected Types.DefaultSymbolVisitor<Void, Void> symbolPreprocessor =
new Types.DefaultSymbolVisitor<Void, Void>() {
@Override
public Void visitClassSymbol(ClassSymbol s, Void ignored) {
nameSimplifier.addUsage(s);
return null;
}
@Override
public Void visitSymbol(Symbol s, Void ignored) {
return null;
}
@Override
public Void visitMethodSymbol(MethodSymbol s, Void ignored) {
visit(s.owner, null);
if (s.type != null)
typePreprocessor.visit(s.type);
return null;
}
};
// </editor-fold>
@Override
public RichConfiguration getConfiguration() {
//the following cast is always safe - see init
return (RichConfiguration)configuration;
}
/**
* Configuration object provided by the rich formatter.
*/
public static class RichConfiguration extends ForwardingDiagnosticFormatter.ForwardingConfiguration {
/** set of enabled rich formatter's features */
protected java.util.EnumSet<RichFormatterFeature> features;
@SuppressWarnings("fallthrough")
public RichConfiguration(Options options, AbstractDiagnosticFormatter formatter) {
super(formatter.getConfiguration());
features = formatter.isRaw() ? EnumSet.noneOf(RichFormatterFeature.class) :
EnumSet.of(RichFormatterFeature.SIMPLE_NAMES,
RichFormatterFeature.WHERE_CLAUSES,
RichFormatterFeature.UNIQUE_TYPEVAR_NAMES);
String diagOpts = options.get("diags");
if (diagOpts != null) {
for (String args: diagOpts.split(",")) {
if (args.equals("-where")) {
features.remove(RichFormatterFeature.WHERE_CLAUSES);
}
else if (args.equals("where")) {
features.add(RichFormatterFeature.WHERE_CLAUSES);
}
if (args.equals("-simpleNames")) {
features.remove(RichFormatterFeature.SIMPLE_NAMES);
}
else if (args.equals("simpleNames")) {
features.add(RichFormatterFeature.SIMPLE_NAMES);
}
if (args.equals("-disambiguateTvars")) {
features.remove(RichFormatterFeature.UNIQUE_TYPEVAR_NAMES);
}
else if (args.equals("disambiguateTvars")) {
features.add(RichFormatterFeature.UNIQUE_TYPEVAR_NAMES);
}
}
}
}
/**
* Returns a list of all the features supported by the rich formatter.
* @return list of supported features
*/
public RichFormatterFeature[] getAvailableFeatures() {
return RichFormatterFeature.values();
}
/**
* Enable a specific feature on this rich formatter.
* @param feature feature to be enabled
*/
public void enable(RichFormatterFeature feature) {
features.add(feature);
}
/**
* Disable a specific feature on this rich formatter.
* @param feature feature to be disabled
*/
public void disable(RichFormatterFeature feature) {
features.remove(feature);
}
/**
* Is a given feature enabled on this formatter?
* @param feature feature to be tested
*/
public boolean isEnabled(RichFormatterFeature feature) {
return features.contains(feature);
}
/**
* The advanced formatting features provided by the rich formatter
*/
public enum RichFormatterFeature {
/** a list of additional info regarding a given type/symbol */
WHERE_CLAUSES,
/** full class names simplification (where possible) */
SIMPLE_NAMES,
/** type-variable names disambiguation */
UNIQUE_TYPEVAR_NAMES;
}
}
}
| 25,515 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ClientCodeException.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/ClientCodeException.java | /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/**
* An exception used for propogating exceptions found in client code
* invoked from javac.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ClientCodeException extends RuntimeException {
static final long serialVersionUID = -5674494409392415163L;
public ClientCodeException(Throwable cause) {
super(cause);
}
}
| 1,779 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Names.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Names.java | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/**
* Access to the compiler's name table. STandard names are defined,
* as well as methods to create new names.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Names {
public static final Context.Key<Names> namesKey = new Context.Key<Names>();
public static Names instance(Context context) {
Names instance = context.get(namesKey);
if (instance == null) {
instance = new Names(context);
context.put(namesKey, instance);
}
return instance;
}
public final Name slash;
public final Name hyphen;
public final Name T;
public final Name slashequals;
public final Name deprecated;
public final Name init;
public final Name clinit;
public final Name error;
public final Name any;
public final Name empty;
public final Name one;
public final Name period;
public final Name comma;
public final Name semicolon;
public final Name asterisk;
public final Name _this;
public final Name _super;
public final Name _default;
public final Name _class;
public final Name java_lang;
public final Name java_lang_Object;
public final Name java_lang_Class;
public final Name java_lang_Cloneable;
public final Name java_io_Serializable;
public final Name serialVersionUID;
public final Name java_lang_Enum;
public final Name java_lang_invoke_MethodHandle;
public final Name package_info;
public final Name ConstantValue;
public final Name LineNumberTable;
public final Name LocalVariableTable;
public final Name LocalVariableTypeTable;
public final Name CharacterRangeTable;
public final Name StackMap;
public final Name StackMapTable;
public final Name SourceID;
public final Name CompilationID;
public final Name Code;
public final Name Exceptions;
public final Name SourceFile;
public final Name InnerClasses;
public final Name Synthetic;
public final Name Bridge;
public final Name Deprecated;
public final Name Enum;
public final Name _name;
public final Name Signature;
public final Name Varargs;
public final Name Annotation;
public final Name RuntimeVisibleAnnotations;
public final Name RuntimeInvisibleAnnotations;
public final Name RuntimeVisibleTypeAnnotations;
public final Name RuntimeInvisibleTypeAnnotations;
public final Name RuntimeVisibleParameterAnnotations;
public final Name RuntimeInvisibleParameterAnnotations;
public final Name Value;
public final Name EnclosingMethod;
public final Name desiredAssertionStatus;
public final Name append;
public final Name family;
public final Name forName;
public final Name toString;
public final Name length;
public final Name valueOf;
public final Name value;
public final Name getMessage;
public final Name getClass;
public final Name TYPE;
public final Name TYPE_USE;
public final Name TYPE_PARAMETER;
public final Name FIELD;
public final Name METHOD;
public final Name PARAMETER;
public final Name CONSTRUCTOR;
public final Name LOCAL_VARIABLE;
public final Name ANNOTATION_TYPE;
public final Name PACKAGE;
public final Name SOURCE;
public final Name CLASS;
public final Name RUNTIME;
public final Name Array;
public final Name Method;
public final Name Bound;
public final Name clone;
public final Name getComponentType;
public final Name getClassLoader;
public final Name initCause;
public final Name values;
public final Name iterator;
public final Name hasNext;
public final Name next;
public final Name AnnotationDefault;
public final Name ordinal;
public final Name equals;
public final Name hashCode;
public final Name compareTo;
public final Name getDeclaringClass;
public final Name ex;
public final Name finalize;
public final Name java_lang_AutoCloseable;
public final Name close;
public final Name addSuppressed;
public final Name.Table table;
public Names(Context context) {
Options options = Options.instance(context);
table = createTable(options);
slash = fromString("/");
hyphen = fromString("-");
T = fromString("T");
slashequals = fromString("/=");
deprecated = fromString("deprecated");
init = fromString("<init>");
clinit = fromString("<clinit>");
error = fromString("<error>");
any = fromString("<any>");
empty = fromString("");
one = fromString("1");
period = fromString(".");
comma = fromString(",");
semicolon = fromString(";");
asterisk = fromString("*");
_this = fromString("this");
_super = fromString("super");
_default = fromString("default");
_class = fromString("class");
java_lang = fromString("java.lang");
java_lang_Object = fromString("java.lang.Object");
java_lang_Class = fromString("java.lang.Class");
java_lang_Cloneable = fromString("java.lang.Cloneable");
java_io_Serializable = fromString("java.io.Serializable");
java_lang_Enum = fromString("java.lang.Enum");
java_lang_invoke_MethodHandle = fromString("java.lang.invoke.MethodHandle");
package_info = fromString("package-info");
serialVersionUID = fromString("serialVersionUID");
ConstantValue = fromString("ConstantValue");
LineNumberTable = fromString("LineNumberTable");
LocalVariableTable = fromString("LocalVariableTable");
LocalVariableTypeTable = fromString("LocalVariableTypeTable");
CharacterRangeTable = fromString("CharacterRangeTable");
StackMap = fromString("StackMap");
StackMapTable = fromString("StackMapTable");
SourceID = fromString("SourceID");
CompilationID = fromString("CompilationID");
Code = fromString("Code");
Exceptions = fromString("Exceptions");
SourceFile = fromString("SourceFile");
InnerClasses = fromString("InnerClasses");
Synthetic = fromString("Synthetic");
Bridge = fromString("Bridge");
Deprecated = fromString("Deprecated");
Enum = fromString("Enum");
_name = fromString("name");
Signature = fromString("Signature");
Varargs = fromString("Varargs");
Annotation = fromString("Annotation");
RuntimeVisibleAnnotations = fromString("RuntimeVisibleAnnotations");
RuntimeInvisibleAnnotations = fromString("RuntimeInvisibleAnnotations");
RuntimeVisibleTypeAnnotations = fromString("RuntimeVisibleTypeAnnotations");
RuntimeInvisibleTypeAnnotations = fromString("RuntimeInvisibleTypeAnnotations");
RuntimeVisibleParameterAnnotations = fromString("RuntimeVisibleParameterAnnotations");
RuntimeInvisibleParameterAnnotations = fromString("RuntimeInvisibleParameterAnnotations");
Value = fromString("Value");
EnclosingMethod = fromString("EnclosingMethod");
desiredAssertionStatus = fromString("desiredAssertionStatus");
append = fromString("append");
family = fromString("family");
forName = fromString("forName");
toString = fromString("toString");
length = fromString("length");
valueOf = fromString("valueOf");
value = fromString("value");
getMessage = fromString("getMessage");
getClass = fromString("getClass");
TYPE = fromString("TYPE");
TYPE_USE = fromString("TYPE_USE");
TYPE_PARAMETER = fromString("TYPE_PARAMETER");
FIELD = fromString("FIELD");
METHOD = fromString("METHOD");
PARAMETER = fromString("PARAMETER");
CONSTRUCTOR = fromString("CONSTRUCTOR");
LOCAL_VARIABLE = fromString("LOCAL_VARIABLE");
ANNOTATION_TYPE = fromString("ANNOTATION_TYPE");
PACKAGE = fromString("PACKAGE");
SOURCE = fromString("SOURCE");
CLASS = fromString("CLASS");
RUNTIME = fromString("RUNTIME");
Array = fromString("Array");
Method = fromString("Method");
Bound = fromString("Bound");
clone = fromString("clone");
getComponentType = fromString("getComponentType");
getClassLoader = fromString("getClassLoader");
initCause = fromString("initCause");
values = fromString("values");
iterator = fromString("iterator");
hasNext = fromString("hasNext");
next = fromString("next");
AnnotationDefault = fromString("AnnotationDefault");
ordinal = fromString("ordinal");
equals = fromString("equals");
hashCode = fromString("hashCode");
compareTo = fromString("compareTo");
getDeclaringClass = fromString("getDeclaringClass");
ex = fromString("ex");
finalize = fromString("finalize");
java_lang_AutoCloseable = fromString("java.lang.AutoCloseable");
close = fromString("close");
addSuppressed = fromString("addSuppressed");
}
protected Name.Table createTable(Options options) {
boolean useUnsharedTable = options.isSet("useUnsharedTable");
if (useUnsharedTable)
return new UnsharedNameTable(this);
else
return new SharedNameTable(this);
}
public void dispose() {
table.dispose();
}
public Name fromChars(char[] cs, int start, int len) {
return table.fromChars(cs, start, len);
}
public Name fromString(String s) {
return table.fromString(s);
}
public Name fromUtf(byte[] cs) {
return table.fromUtf(cs);
}
public Name fromUtf(byte[] cs, int start, int len) {
return table.fromUtf(cs, start, len);
}
}
| 11,264 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
BaseFileManager.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/BaseFileManager.java | /*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.main.JavacOption;
import com.sun.tools.javac.main.OptionName;
import com.sun.tools.javac.main.RecognizedOptions;
import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.lang.ref.SoftReference;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
/**
* Utility methods for building a filemanager.
* There are no references here to file-system specific objects such as
* java.io.File or java.nio.file.Path.
*/
public abstract class BaseFileManager {
protected BaseFileManager(Charset charset) {
this.charset = charset;
byteBufferCache = new ByteBufferCache();
}
/**
* Set the context for JavacPathFileManager.
*/
protected void setContext(Context context) {
log = Log.instance(context);
options = Options.instance(context);
classLoaderClass = options.get("procloader");
}
/**
* The log to be used for error reporting.
*/
public Log log;
/**
* User provided charset (through javax.tools).
*/
protected Charset charset;
protected Options options;
protected String classLoaderClass;
protected Source getSource() {
String sourceName = options.get(OptionName.SOURCE);
Source source = null;
if (sourceName != null)
source = Source.lookup(sourceName);
return (source != null ? source : Source.DEFAULT);
}
protected ClassLoader getClassLoader(URL[] urls) {
ClassLoader thisClassLoader = getClass().getClassLoader();
// Bug: 6558476
// Ideally, ClassLoader should be Closeable, but before JDK7 it is not.
// On older versions, try the following, to get a closeable classloader.
// 1: Allow client to specify the class to use via hidden option
if (classLoaderClass != null) {
try {
Class<? extends ClassLoader> loader =
Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
return constr.newInstance(new Object[] { urls, thisClassLoader });
} catch (Throwable t) {
// ignore errors loading user-provided class loader, fall through
}
}
// 2: If URLClassLoader implements Closeable, use that.
if (Closeable.class.isAssignableFrom(URLClassLoader.class))
return new URLClassLoader(urls, thisClassLoader);
// 3: Try using private reflection-based CloseableURLClassLoader
try {
return new CloseableURLClassLoader(urls, thisClassLoader);
} catch (Throwable t) {
// ignore errors loading workaround class loader, fall through
}
// 4: If all else fails, use plain old standard URLClassLoader
return new URLClassLoader(urls, thisClassLoader);
}
// <editor-fold defaultstate="collapsed" desc="Option handling">
public boolean handleOption(String current, Iterator<String> remaining) {
for (JavacOption o: javacFileManagerOptions) {
if (o.matches(current)) {
if (o.hasArg()) {
if (remaining.hasNext()) {
if (!o.process(options, current, remaining.next()))
return true;
}
} else {
if (!o.process(options, current))
return true;
}
// operand missing, or process returned false
throw new IllegalArgumentException(current);
}
}
return false;
}
// where
private static JavacOption[] javacFileManagerOptions =
RecognizedOptions.getJavacFileManagerOptions(
new RecognizedOptions.GrumpyHelper());
public int isSupportedOption(String option) {
for (JavacOption o : javacFileManagerOptions) {
if (o.matches(option))
return o.hasArg() ? 1 : 0;
}
return -1;
}
public abstract boolean isDefaultBootClassPath();
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Encoding">
private String defaultEncodingName;
private String getDefaultEncodingName() {
if (defaultEncodingName == null) {
defaultEncodingName =
new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
}
return defaultEncodingName;
}
public String getEncodingName() {
String encName = options.get(OptionName.ENCODING);
if (encName == null)
return getDefaultEncodingName();
else
return encName;
}
public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
String encodingName = getEncodingName();
CharsetDecoder decoder;
try {
decoder = getDecoder(encodingName, ignoreEncodingErrors);
} catch (IllegalCharsetNameException e) {
log.error("unsupported.encoding", encodingName);
return (CharBuffer)CharBuffer.allocate(1).flip();
} catch (UnsupportedCharsetException e) {
log.error("unsupported.encoding", encodingName);
return (CharBuffer)CharBuffer.allocate(1).flip();
}
// slightly overestimate the buffer size to avoid reallocation.
float factor =
decoder.averageCharsPerByte() * 0.8f +
decoder.maxCharsPerByte() * 0.2f;
CharBuffer dest = CharBuffer.
allocate(10 + (int)(inbuf.remaining()*factor));
while (true) {
CoderResult result = decoder.decode(inbuf, dest, true);
dest.flip();
if (result.isUnderflow()) { // done reading
// make sure there is at least one extra character
if (dest.limit() == dest.capacity()) {
dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
dest.flip();
}
return dest;
} else if (result.isOverflow()) { // buffer too small; expand
int newCapacity =
10 + dest.capacity() +
(int)(inbuf.remaining()*decoder.maxCharsPerByte());
dest = CharBuffer.allocate(newCapacity).put(dest);
} else if (result.isMalformed() || result.isUnmappable()) {
// bad character in input
// report coding error (warn only pre 1.5)
if (!getSource().allowEncodingErrors()) {
log.error(new SimpleDiagnosticPosition(dest.limit()),
"illegal.char.for.encoding",
charset == null ? encodingName : charset.name());
} else {
log.warning(new SimpleDiagnosticPosition(dest.limit()),
"illegal.char.for.encoding",
charset == null ? encodingName : charset.name());
}
// skip past the coding error
inbuf.position(inbuf.position() + result.length());
// undo the flip() to prepare the output buffer
// for more translation
dest.position(dest.limit());
dest.limit(dest.capacity());
dest.put((char)0xfffd); // backward compatible
} else {
throw new AssertionError(result);
}
}
// unreached
}
public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
Charset cs = (this.charset == null)
? Charset.forName(encodingName)
: this.charset;
CharsetDecoder decoder = cs.newDecoder();
CodingErrorAction action;
if (ignoreEncodingErrors)
action = CodingErrorAction.REPLACE;
else
action = CodingErrorAction.REPORT;
return decoder
.onMalformedInput(action)
.onUnmappableCharacter(action);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="ByteBuffers">
/**
* Make a byte buffer from an input stream.
*/
public ByteBuffer makeByteBuffer(InputStream in)
throws IOException {
int limit = in.available();
if (limit < 1024) limit = 1024;
ByteBuffer result = byteBufferCache.get(limit);
int position = 0;
while (in.available() != 0) {
if (position >= limit)
// expand buffer
result = ByteBuffer.
allocate(limit <<= 1).
put((ByteBuffer)result.flip());
int count = in.read(result.array(),
position,
limit - position);
if (count < 0) break;
result.position(position += count);
}
return (ByteBuffer)result.flip();
}
public void recycleByteBuffer(ByteBuffer bb) {
byteBufferCache.put(bb);
}
/**
* A single-element cache of direct byte buffers.
*/
private static class ByteBufferCache {
private ByteBuffer cached;
ByteBuffer get(int capacity) {
if (capacity < 20480) capacity = 20480;
ByteBuffer result =
(cached != null && cached.capacity() >= capacity)
? (ByteBuffer)cached.clear()
: ByteBuffer.allocate(capacity + capacity>>1);
cached = null;
return result;
}
void put(ByteBuffer x) {
cached = x;
}
}
private final ByteBufferCache byteBufferCache;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Content cache">
public CharBuffer getCachedContent(JavaFileObject file) {
ContentCacheEntry e = contentCache.get(file);
if (e == null)
return null;
if (!e.isValid(file)) {
contentCache.remove(file);
return null;
}
return e.getValue();
}
public void cache(JavaFileObject file, CharBuffer cb) {
contentCache.put(file, new ContentCacheEntry(file, cb));
}
public void flushCache(JavaFileObject file) {
contentCache.remove(file);
}
protected final Map<JavaFileObject, ContentCacheEntry> contentCache
= new HashMap<JavaFileObject, ContentCacheEntry>();
protected static class ContentCacheEntry {
final long timestamp;
final SoftReference<CharBuffer> ref;
ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
this.timestamp = file.getLastModified();
this.ref = new SoftReference<CharBuffer>(cb);
}
boolean isValid(JavaFileObject file) {
return timestamp == file.getLastModified();
}
CharBuffer getValue() {
return ref.get();
}
}
// </editor-fold>
public static Kind getKind(String name) {
if (name.endsWith(Kind.CLASS.extension))
return Kind.CLASS;
else if (name.endsWith(Kind.SOURCE.extension))
return Kind.SOURCE;
else if (name.endsWith(Kind.HTML.extension))
return Kind.HTML;
else
return Kind.OTHER;
}
protected static <T> T nullCheck(T o) {
o.getClass(); // null check
return o;
}
protected static <T> Collection<T> nullCheck(Collection<T> it) {
for (T t : it)
t.getClass(); // null check
return it;
}
}
| 13,713 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
CloseableURLClassLoader.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/CloseableURLClassLoader.java | /*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.jar.JarFile;
/**
* A URLClassLoader that also implements Closeable.
* Reflection is used to access internal data structures in the URLClassLoader,
* since no public API exists for this purpose. Therefore this code is somewhat
* fragile. Caveat emptor.
* @throws Error if the internal data structures are not as expected.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class CloseableURLClassLoader
extends URLClassLoader implements Closeable {
public CloseableURLClassLoader(URL[] urls, ClassLoader parent) throws Error {
super(urls, parent);
try {
getLoaders(); //proactive check that URLClassLoader is as expected
} catch (Throwable t) {
throw new Error("cannot create CloseableURLClassLoader", t);
}
}
/**
* Close any jar files that may have been opened by the class loader.
* Reflection is used to access the jar files in the URLClassLoader's
* internal data structures.
* @throws java.io.IOException if the jar files cannot be found for any
* reson, or if closing the jar file itself causes an IOException.
*/
@Override
public void close() throws IOException {
try {
for (Object l: getLoaders()) {
if (l.getClass().getName().equals("sun.misc.URLClassPath$JarLoader")) {
Field jarField = l.getClass().getDeclaredField("jar");
JarFile jar = (JarFile) getField(l, jarField);
if (jar != null) {
//System.err.println("CloseableURLClassLoader: closing " + jar);
jar.close();
}
}
}
} catch (Throwable t) {
IOException e = new IOException("cannot close class loader");
e.initCause(t);
throw e;
}
}
private ArrayList<?> getLoaders()
throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException
{
Field ucpField = URLClassLoader.class.getDeclaredField("ucp");
Object urlClassPath = getField(this, ucpField);
if (urlClassPath == null)
throw new AssertionError("urlClassPath not set in URLClassLoader");
Field loadersField = urlClassPath.getClass().getDeclaredField("loaders");
return (ArrayList<?>) getField(urlClassPath, loadersField);
}
private Object getField(Object o, Field f)
throws IllegalArgumentException, IllegalAccessException {
boolean prev = f.isAccessible();
try {
f.setAccessible(true);
return f.get(o);
} finally {
f.setAccessible(prev);
}
}
}
| 4,322 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AbstractLog.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/AbstractLog.java | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.HashMap;
import java.util.Map;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
/**
* A base class for error logs. Reports errors and warnings, and
* keeps track of error numbers and positions.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class AbstractLog {
AbstractLog(JCDiagnostic.Factory diags) {
this.diags = diags;
sourceMap = new HashMap<JavaFileObject, DiagnosticSource>();
}
/** Re-assign source, returning previous setting.
*/
public JavaFileObject useSource(JavaFileObject file) {
JavaFileObject prev = (source == null ? null : source.getFile());
source = getSource(file);
return prev;
}
protected DiagnosticSource getSource(JavaFileObject file) {
if (file == null)
return DiagnosticSource.NO_SOURCE;
DiagnosticSource s = sourceMap.get(file);
if (s == null) {
s = new DiagnosticSource(file, this);
sourceMap.put(file, s);
}
return s;
}
/** Return the underlying diagnostic source
*/
public DiagnosticSource currentSource() {
return source;
}
/** Report an error, unless another error was already reported at same
* source position.
* @param key The key for the localized error message.
* @param args Fields of the error message.
*/
public void error(String key, Object ... args) {
report(diags.error(source, null, key, args));
}
/** Report an error, unless another error was already reported at same
* source position.
* @param pos The source position at which to report the error.
* @param key The key for the localized error message.
* @param args Fields of the error message.
*/
public void error(DiagnosticPosition pos, String key, Object ... args) {
report(diags.error(source, pos, key, args));
}
/** Report an error, unless another error was already reported at same
* source position.
* @param flag A flag to set on the diagnostic
* @param pos The source position at which to report the error.
* @param key The key for the localized error message.
* @param args Fields of the error message.
*/
public void error(DiagnosticFlag flag, DiagnosticPosition pos, String key, Object ... args) {
JCDiagnostic d = diags.error(source, pos, key, args);
d.setFlag(flag);
report(d);
}
/** Report an error, unless another error was already reported at same
* source position.
* @param pos The source position at which to report the error.
* @param key The key for the localized error message.
* @param args Fields of the error message.
*/
public void error(int pos, String key, Object ... args) {
report(diags.error(source, wrap(pos), key, args));
}
/** Report an error, unless another error was already reported at same
* source position.
* @param flag A flag to set on the diagnostic
* @param pos The source position at which to report the error.
* @param key The key for the localized error message.
* @param args Fields of the error message.
*/
public void error(DiagnosticFlag flag, int pos, String key, Object ... args) {
JCDiagnostic d = diags.error(source, wrap(pos), key, args);
d.setFlag(flag);
report(d);
}
/** Report a warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public void warning(String key, Object ... args) {
report(diags.warning(source, null, key, args));
}
/** Report a lint warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
* @param lc The lint category for the diagnostic
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public void warning(LintCategory lc, String key, Object ... args) {
report(diags.warning(lc, key, args));
}
/** Report a warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public void warning(DiagnosticPosition pos, String key, Object ... args) {
report(diags.warning(source, pos, key, args));
}
/** Report a lint warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
* @param lc The lint category for the diagnostic
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public void warning(LintCategory lc, DiagnosticPosition pos, String key, Object ... args) {
report(diags.warning(lc, source, pos, key, args));
}
/** Report a warning, unless suppressed by the -nowarn option or the
* maximum number of warnings has been reached.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public void warning(int pos, String key, Object ... args) {
report(diags.warning(source, wrap(pos), key, args));
}
/** Report a warning.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public void mandatoryWarning(DiagnosticPosition pos, String key, Object ... args) {
report(diags.mandatoryWarning(source, pos, key, args));
}
/** Report a warning.
* @param lc The lint category for the diagnostic
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public void mandatoryWarning(LintCategory lc, DiagnosticPosition pos, String key, Object ... args) {
report(diags.mandatoryWarning(lc, source, pos, key, args));
}
/** Provide a non-fatal notification, unless suppressed by the -nowarn option.
* @param key The key for the localized notification message.
* @param args Fields of the notint an error or warning message:
*/
public void note(String key, Object ... args) {
report(diags.note(source, null, key, args));
}
/** Provide a non-fatal notification, unless suppressed by the -nowarn option.
* @param key The key for the localized notification message.
* @param args Fields of the notification message.
*/
public void note(DiagnosticPosition pos, String key, Object ... args) {
report(diags.note(source, pos, key, args));
}
/** Provide a non-fatal notification, unless suppressed by the -nowarn option.
* @param key The key for the localized notification message.
* @param args Fields of the notification message.
*/
public void note(int pos, String key, Object ... args) {
report(diags.note(source, wrap(pos), key, args));
}
/** Provide a non-fatal notification, unless suppressed by the -nowarn option.
* @param key The key for the localized notification message.
* @param args Fields of the notification message.
*/
public void note(JavaFileObject file, String key, Object ... args) {
report(diags.note(getSource(file), null, key, args));
}
/** Provide a non-fatal notification, unless suppressed by the -nowarn option.
* @param key The key for the localized notification message.
* @param args Fields of the notification message.
*/
public void mandatoryNote(final JavaFileObject file, String key, Object ... args) {
report(diags.mandatoryNote(getSource(file), key, args));
}
protected abstract void report(JCDiagnostic diagnostic);
protected abstract void directError(String key, Object... args);
private DiagnosticPosition wrap(int pos) {
return (pos == Position.NOPOS ? null : new SimpleDiagnosticPosition(pos));
}
/** Factory for diagnostics
*/
protected JCDiagnostic.Factory diags;
/** The file that's currently being translated.
*/
protected DiagnosticSource source;
/** A cache of lightweight DiagnosticSource objects.
*/
protected Map<JavaFileObject, DiagnosticSource> sourceMap;
}
| 10,718 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PropagatedException.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/PropagatedException.java | /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/**
* Used to propagate exceptions through to the user.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Peter von der Ah\u00e9
*/
public class PropagatedException extends RuntimeException {
static final long serialVersionUID = -6065309339888775367L;
public PropagatedException(RuntimeException cause) {
super(cause);
}
@Override
public RuntimeException getCause() {
return (RuntimeException)super.getCause();
}
}
| 1,892 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ForwardingDiagnosticFormatter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/ForwardingDiagnosticFormatter.java | /*
* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.Set;
import java.util.Locale;
import javax.tools.Diagnostic;
import com.sun.tools.javac.api.DiagnosticFormatter;
import com.sun.tools.javac.api.DiagnosticFormatter.Configuration;
import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.DiagnosticPart;
import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.MultilineLimit;
import com.sun.tools.javac.api.DiagnosticFormatter.PositionKind;
/**
* A delegated diagnostic formatter delegates all formatting
* actions to an underlying formatter (aka the delegated formatter).
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ForwardingDiagnosticFormatter<D extends Diagnostic<?>, F extends DiagnosticFormatter<D>>
implements DiagnosticFormatter<D> {
/**
* The delegated formatter
*/
protected F formatter;
/*
* configuration object used by this formatter
*/
protected ForwardingConfiguration configuration;
public ForwardingDiagnosticFormatter(F formatter) {
this.formatter = formatter;
this.configuration = new ForwardingConfiguration(formatter.getConfiguration());
}
/**
* Returns the underlying delegated formatter
* @return delegate formatter
*/
public F getDelegatedFormatter() {
return formatter;
}
public Configuration getConfiguration() {
return configuration;
}
public boolean displaySource(D diag) {
return formatter.displaySource(diag);
}
public String format(D diag, Locale l) {
return formatter.format(diag, l);
}
public String formatKind(D diag, Locale l) {
return formatter.formatKind(diag, l);
}
public String formatMessage(D diag, Locale l) {
return formatter.formatMessage(diag, l);
}
public String formatPosition(D diag, PositionKind pk, Locale l) {
return formatter.formatPosition(diag, pk, l);
}
public String formatSource(D diag, boolean fullname, Locale l) {
return formatter.formatSource(diag, fullname, l);
}
/**
* A delegated formatter configuration delegates all configurations settings
* to an underlying configuration object (aka the delegated configuration).
*/
public static class ForwardingConfiguration implements DiagnosticFormatter.Configuration {
/** The configurationr object to which the forwarding configuration delegates some settings */
protected Configuration configuration;
public ForwardingConfiguration(Configuration configuration) {
this.configuration = configuration;
}
/**
* Returns the underlying delegated configuration.
* @return delegated configuration
*/
public Configuration getDelegatedConfiguration() {
return configuration;
}
public int getMultilineLimit(MultilineLimit limit) {
return configuration.getMultilineLimit(limit);
}
public Set<DiagnosticPart> getVisible() {
return configuration.getVisible();
}
public void setMultilineLimit(MultilineLimit limit, int value) {
configuration.setMultilineLimit(limit, value);
}
public void setVisible(Set<DiagnosticPart> diagParts) {
configuration.setVisible(diagParts);
}
}
}
| 4,770 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
BasicDiagnosticFormatter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/BasicDiagnosticFormatter.java | /*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.util.AbstractDiagnosticFormatter.SimpleConfiguration;
import com.sun.tools.javac.util.BasicDiagnosticFormatter.BasicConfiguration;
import static com.sun.tools.javac.api.DiagnosticFormatter.PositionKind.*;
import static com.sun.tools.javac.util.BasicDiagnosticFormatter.BasicConfiguration.*;
import static com.sun.tools.javac.util.LayoutCharacters.*;
/**
* A basic formatter for diagnostic messages.
* The basic formatter will format a diagnostic according to one of three format patterns, depending on whether
* or not the source name and position are set. The formatter supports a printf-like string for patterns
* with the following special characters:
* <ul>
* <li>%b: the base of the source name
* <li>%f: the source name (full absolute path)
* <li>%l: the line number of the diagnostic, derived from the character offset
* <li>%c: the column number of the diagnostic, derived from the character offset
* <li>%o: the character offset of the diagnostic if set
* <li>%p: the prefix for the diagnostic, derived from the diagnostic type
* <li>%t: the prefix as it normally appears in standard diagnostics. In this case, no prefix is
* shown if the type is ERROR and if a source name is set
* <li>%m: the text or the diagnostic, including any appropriate arguments
* <li>%_: space delimiter, useful for formatting purposes
* </ul>
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
/**
* Create a basic formatter based on the supplied options.
*
* @param opts list of command-line options
* @param msgs JavacMessages object used for i18n
*/
public BasicDiagnosticFormatter(Options options, JavacMessages msgs) {
super(msgs, new BasicConfiguration(options));
}
/**
* Create a standard basic formatter
*
* @param msgs JavacMessages object used for i18n
*/
public BasicDiagnosticFormatter(JavacMessages msgs) {
super(msgs, new BasicConfiguration());
}
public String formatDiagnostic(JCDiagnostic d, Locale l) {
if (l == null)
l = messages.getCurrentLocale();
String format = selectFormat(d);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < format.length(); i++) {
char c = format.charAt(i);
boolean meta = false;
if (c == '%' && i < format.length() - 1) {
meta = true;
c = format.charAt(++i);
}
buf.append(meta ? formatMeta(c, d, l) : String.valueOf(c));
}
if (depth == 0)
return addSourceLineIfNeeded(d, buf.toString());
else
return buf.toString();
}
public String formatMessage(JCDiagnostic d, Locale l) {
int currentIndentation = 0;
StringBuilder buf = new StringBuilder();
Collection<String> args = formatArguments(d, l);
String msg = localize(l, d.getCode(), args.toArray());
String[] lines = msg.split("\n");
if (getConfiguration().getVisible().contains(DiagnosticPart.SUMMARY)) {
currentIndentation += getConfiguration().getIndentation(DiagnosticPart.SUMMARY);
buf.append(indent(lines[0], currentIndentation)); //summary
}
if (lines.length > 1 && getConfiguration().getVisible().contains(DiagnosticPart.DETAILS)) {
currentIndentation += getConfiguration().getIndentation(DiagnosticPart.DETAILS);
for (int i = 1;i < lines.length; i++) {
buf.append("\n" + indent(lines[i], currentIndentation));
}
}
if (d.isMultiline() && getConfiguration().getVisible().contains(DiagnosticPart.SUBDIAGNOSTICS)) {
currentIndentation += getConfiguration().getIndentation(DiagnosticPart.SUBDIAGNOSTICS);
for (String sub : formatSubdiagnostics(d, l)) {
buf.append("\n" + indent(sub, currentIndentation));
}
}
return buf.toString();
}
protected String addSourceLineIfNeeded(JCDiagnostic d, String msg) {
if (!displaySource(d))
return msg;
else {
BasicConfiguration conf = getConfiguration();
int indentSource = conf.getIndentation(DiagnosticPart.SOURCE);
String sourceLine = "\n" + formatSourceLine(d, indentSource);
boolean singleLine = msg.indexOf("\n") == -1;
if (singleLine || getConfiguration().getSourcePosition() == SourcePosition.BOTTOM)
return msg + sourceLine;
else
return msg.replaceFirst("\n", Matcher.quoteReplacement(sourceLine) + "\n");
}
}
protected String formatMeta(char c, JCDiagnostic d, Locale l) {
switch (c) {
case 'b':
return formatSource(d, false, l);
case 'e':
return formatPosition(d, END, l);
case 'f':
return formatSource(d, true, l);
case 'l':
return formatPosition(d, LINE, l);
case 'c':
return formatPosition(d, COLUMN, l);
case 'o':
return formatPosition(d, OFFSET, l);
case 'p':
return formatKind(d, l);
case 's':
return formatPosition(d, START, l);
case 't': {
boolean usePrefix;
switch (d.getType()) {
case FRAGMENT:
usePrefix = false;
break;
case ERROR:
usePrefix = (d.getIntPosition() == Position.NOPOS);
break;
default:
usePrefix = true;
}
if (usePrefix)
return formatKind(d, l);
else
return "";
}
case 'm':
return formatMessage(d, l);
case 'L':
return formatLintCategory(d, l);
case '_':
return " ";
case '%':
return "%";
default:
return String.valueOf(c);
}
}
private String selectFormat(JCDiagnostic d) {
DiagnosticSource source = d.getDiagnosticSource();
String format = getConfiguration().getFormat(BasicFormatKind.DEFAULT_NO_POS_FORMAT);
if (source != null && source != DiagnosticSource.NO_SOURCE) {
if (d.getIntPosition() != Position.NOPOS) {
format = getConfiguration().getFormat(BasicFormatKind.DEFAULT_POS_FORMAT);
} else if (source.getFile() != null &&
source.getFile().getKind() == JavaFileObject.Kind.CLASS) {
format = getConfiguration().getFormat(BasicFormatKind.DEFAULT_CLASS_FORMAT);
}
}
return format;
}
@Override
public BasicConfiguration getConfiguration() {
//the following cast is always safe - see init
return (BasicConfiguration)super.getConfiguration();
}
static public class BasicConfiguration extends SimpleConfiguration {
protected Map<DiagnosticPart, Integer> indentationLevels;
protected Map<BasicFormatKind, String> availableFormats;
protected SourcePosition sourcePosition;
@SuppressWarnings("fallthrough")
public BasicConfiguration(Options options) {
super(options, EnumSet.of(DiagnosticPart.SUMMARY,
DiagnosticPart.DETAILS,
DiagnosticPart.SUBDIAGNOSTICS,
DiagnosticPart.SOURCE));
initFormat();
initIndentation();
if (options.isSet("oldDiags"))
initOldFormat();
String fmt = options.get("diagsFormat");
if (fmt != null) {
if (fmt.equals("OLD"))
initOldFormat();
else
initFormats(fmt);
}
String srcPos = null;
if ((((srcPos = options.get("sourcePosition")) != null)) &&
srcPos.equals("bottom"))
setSourcePosition(SourcePosition.BOTTOM);
else
setSourcePosition(SourcePosition.AFTER_SUMMARY);
String indent = options.get("diagsIndentation");
if (indent != null) {
String[] levels = indent.split("\\|");
try {
switch (levels.length) {
case 5:
setIndentation(DiagnosticPart.JLS,
Integer.parseInt(levels[4]));
case 4:
setIndentation(DiagnosticPart.SUBDIAGNOSTICS,
Integer.parseInt(levels[3]));
case 3:
setIndentation(DiagnosticPart.SOURCE,
Integer.parseInt(levels[2]));
case 2:
setIndentation(DiagnosticPart.DETAILS,
Integer.parseInt(levels[1]));
default:
setIndentation(DiagnosticPart.SUMMARY,
Integer.parseInt(levels[0]));
}
}
catch (NumberFormatException ex) {
initIndentation();
}
}
}
public BasicConfiguration() {
super(EnumSet.of(DiagnosticPart.SUMMARY,
DiagnosticPart.DETAILS,
DiagnosticPart.SUBDIAGNOSTICS,
DiagnosticPart.SOURCE));
initFormat();
initIndentation();
}
private void initFormat() {
initFormats("%f:%l:%_%p%L%m", "%p%L%m", "%f:%_%p%L%m");
}
private void initOldFormat() {
initFormats("%f:%l:%_%t%L%m", "%p%L%m", "%f:%_%t%L%m");
}
private void initFormats(String pos, String nopos, String clazz) {
availableFormats = new EnumMap<BasicFormatKind, String>(BasicFormatKind.class);
setFormat(BasicFormatKind.DEFAULT_POS_FORMAT, pos);
setFormat(BasicFormatKind.DEFAULT_NO_POS_FORMAT, nopos);
setFormat(BasicFormatKind.DEFAULT_CLASS_FORMAT, clazz);
}
@SuppressWarnings("fallthrough")
private void initFormats(String fmt) {
String[] formats = fmt.split("\\|");
switch (formats.length) {
case 3:
setFormat(BasicFormatKind.DEFAULT_CLASS_FORMAT, formats[2]);
case 2:
setFormat(BasicFormatKind.DEFAULT_NO_POS_FORMAT, formats[1]);
default:
setFormat(BasicFormatKind.DEFAULT_POS_FORMAT, formats[0]);
}
}
private void initIndentation() {
indentationLevels = new HashMap<DiagnosticPart, Integer>();
setIndentation(DiagnosticPart.SUMMARY, 0);
setIndentation(DiagnosticPart.DETAILS, DetailsInc);
setIndentation(DiagnosticPart.SUBDIAGNOSTICS, DiagInc);
setIndentation(DiagnosticPart.SOURCE, 0);
}
/**
* Get the amount of spaces for a given indentation kind
* @param diagPart the diagnostic part for which the indentation is
* to be retrieved
* @return the amount of spaces used for the specified indentation kind
*/
public int getIndentation(DiagnosticPart diagPart) {
return indentationLevels.get(diagPart);
}
/**
* Set the indentation level for various element of a given diagnostic -
* this might lead to more readable diagnostics
*
* @param indentationKind kind of indentation to be set
* @param nSpaces amount of spaces for the specified diagnostic part
*/
public void setIndentation(DiagnosticPart diagPart, int nSpaces) {
indentationLevels.put(diagPart, nSpaces);
}
/**
* Set the source line positioning used by this formatter
*
* @param sourcePos a positioning value for source line
*/
public void setSourcePosition(SourcePosition sourcePos) {
sourcePosition = sourcePos;
}
/**
* Get the source line positioning used by this formatter
*
* @return the positioning value used by this formatter
*/
public SourcePosition getSourcePosition() {
return sourcePosition;
}
//where
/**
* A source positioning value controls the position (within a given
* diagnostic message) in which the source line the diagnostic refers to
* should be displayed (if applicable)
*/
public enum SourcePosition {
/**
* Source line is displayed after the diagnostic message
*/
BOTTOM,
/**
* Source line is displayed after the first line of the diagnostic
* message
*/
AFTER_SUMMARY;
}
/**
* Set a metachar string for a specific format
*
* @param kind the format kind to be set
* @param s the metachar string specifying the format
*/
public void setFormat(BasicFormatKind kind, String s) {
availableFormats.put(kind, s);
}
/**
* Get a metachar string for a specific format
*
* @param sourcePos a positioning value for source line
*/
public String getFormat(BasicFormatKind kind) {
return availableFormats.get(kind);
}
//where
/**
* This enum contains all the kinds of formatting patterns supported
* by a basic diagnostic formatter.
*/
public enum BasicFormatKind {
/**
* A format string to be used for diagnostics with a given position.
*/
DEFAULT_POS_FORMAT,
/**
* A format string to be used for diagnostics without a given position.
*/
DEFAULT_NO_POS_FORMAT,
/**
* A format string to be used for diagnostics regarding classfiles
*/
DEFAULT_CLASS_FORMAT;
}
}
}
| 16,253 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Assert.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Assert.java | /*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/**
* Simple facility for unconditional assertions.
* The methods in this class are described in terms of equivalent assert
* statements, assuming that assertions have been enabled.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Assert {
/** Equivalent to
* assert cond;
*/
public static void check(boolean cond) {
if (!cond)
error();
}
/** Equivalent to
* assert (o == null);
*/
public static void checkNull(Object o) {
if (o != null)
error();
}
/** Equivalent to
* assert (t != null); return t;
*/
public static <T> T checkNonNull(T t) {
if (t == null)
error();
return t;
}
/** Equivalent to
* assert cond : value;
*/
public static void check(boolean cond, int value) {
if (!cond)
error(String.valueOf(value));
}
/** Equivalent to
* assert cond : value;
*/
public static void check(boolean cond, long value) {
if (!cond)
error(String.valueOf(value));
}
/** Equivalent to
* assert cond : value;
*/
public static void check(boolean cond, Object value) {
if (!cond)
error(String.valueOf(value));
}
/** Equivalent to
* assert cond : value;
*/
public static void check(boolean cond, String msg) {
if (!cond)
error(msg);
}
/** Equivalent to
* assert (o == null) : value;
*/
public static void checkNull(Object o, Object value) {
if (o != null)
error(String.valueOf(value));
}
/** Equivalent to
* assert (o == null) : value;
*/
public static void checkNull(Object o, String msg) {
if (o != null)
error(msg);
}
/** Equivalent to
* assert (o != null) : value;
*/
public static <T> T checkNonNull(T t, String msg) {
if (t == null)
error(msg);
return t;
}
/** Equivalent to
* assert false;
*/
public static void error() {
throw new AssertionError();
}
/** Equivalent to
* assert false : msg;
*/
public static void error(String msg) {
throw new AssertionError(msg);
}
/** Prevent instantiation. */
private Assert() { }
}
| 3,792 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
RawDiagnosticFormatter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/RawDiagnosticFormatter.java | /*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Locale;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.*;
import com.sun.tools.javac.api.Formattable;
import com.sun.tools.javac.file.BaseFileObject;
import com.sun.tools.javac.util.AbstractDiagnosticFormatter.SimpleConfiguration;
import static com.sun.tools.javac.api.DiagnosticFormatter.PositionKind.*;
/**
* A raw formatter for diagnostic messages.
* The raw formatter will format a diagnostic according to one of two format patterns, depending on whether
* or not the source name and position are set. This formatter provides a standardized, localize-independent
* implementation of a diagnostic formatter; as such, this formatter is best suited for testing purposes.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public final class RawDiagnosticFormatter extends AbstractDiagnosticFormatter {
/**
* Create a formatter based on the supplied options.
* @param msgs
*/
public RawDiagnosticFormatter(Options options) {
super(null, new SimpleConfiguration(options,
EnumSet.of(DiagnosticPart.SUMMARY,
DiagnosticPart.DETAILS,
DiagnosticPart.SUBDIAGNOSTICS)));
}
//provide common default formats
public String formatDiagnostic(JCDiagnostic d, Locale l) {
try {
StringBuilder buf = new StringBuilder();
if (d.getPosition() != Position.NOPOS) {
buf.append(formatSource(d, false, null));
buf.append(':');
buf.append(formatPosition(d, LINE, null));
buf.append(':');
buf.append(formatPosition(d, COLUMN, null));
buf.append(':');
}
else if (d.getSource() != null && d.getSource().getKind() == JavaFileObject.Kind.CLASS) {
buf.append(formatSource(d, false, null));
buf.append(":-:-:");
}
else
buf.append('-');
buf.append(' ');
buf.append(formatMessage(d, null));
if (displaySource(d)) {
buf.append("\n");
buf.append(formatSourceLine(d, 0));
}
return buf.toString();
}
catch (Exception e) {
//e.printStackTrace();
return null;
}
}
public String formatMessage(JCDiagnostic d, Locale l) {
StringBuilder buf = new StringBuilder();
Collection<String> args = formatArguments(d, l);
buf.append(localize(null, d.getCode(), args.toArray()));
if (d.isMultiline() && getConfiguration().getVisible().contains(DiagnosticPart.SUBDIAGNOSTICS)) {
List<String> subDiags = formatSubdiagnostics(d, null);
if (subDiags.nonEmpty()) {
String sep = "";
buf.append(",{");
for (String sub : formatSubdiagnostics(d, null)) {
buf.append(sep);
buf.append("(");
buf.append(sub);
buf.append(")");
sep = ",";
}
buf.append('}');
}
}
return buf.toString();
}
@Override
protected String formatArgument(JCDiagnostic diag, Object arg, Locale l) {
String s;
if (arg instanceof Formattable)
s = arg.toString();
else if (arg instanceof BaseFileObject)
s = ((BaseFileObject) arg).getShortName();
else
s = super.formatArgument(diag, arg, null);
if (arg instanceof JCDiagnostic)
return "(" + s + ")";
else
return s;
}
@Override
protected String localize(Locale l, String key, Object... args) {
StringBuilder buf = new StringBuilder();
buf.append(key);
String sep = ": ";
for (Object o : args) {
buf.append(sep);
buf.append(o);
sep = ", ";
}
return buf.toString();
}
@Override
public boolean isRaw() {
return true;
}
}
| 5,613 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Constants.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Constants.java | /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import com.sun.tools.javac.code.Type;
import static com.sun.tools.javac.code.TypeTags.*;
/**
* Utilities for operating on constant values.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Constants {
/**
* Converts a constant in internal representation (in which
* boolean, char, byte, short, and int are each represented by an
* Integer) into standard representation. Other values (including
* null) are returned unchanged.
*/
public static Object decode(Object value, Type type) {
if (value instanceof Integer) {
int i = (Integer) value;
switch (type.tag) {
case BOOLEAN: return i != 0;
case CHAR: return (char) i;
case BYTE: return (byte) i;
case SHORT: return (short) i;
}
}
return value;
}
/**
* Returns a string representation of a constant value (given in
* internal representation), quoted and formatted as in Java source.
*/
public static String format(Object value, Type type) {
value = decode(value, type);
switch (type.tag) {
case BYTE: return formatByte((Byte) value);
case LONG: return formatLong((Long) value);
case FLOAT: return formatFloat((Float) value);
case DOUBLE: return formatDouble((Double) value);
case CHAR: return formatChar((Character) value);
}
if (value instanceof String)
return formatString((String) value);
return value + "";
}
/**
* Returns a string representation of a constant value (given in
* standard wrapped representation), quoted and formatted as in
* Java source.
*/
public static String format(Object value) {
if (value instanceof Byte) return formatByte((Byte) value);
if (value instanceof Short) return formatShort((Short) value);
if (value instanceof Long) return formatLong((Long) value);
if (value instanceof Float) return formatFloat((Float) value);
if (value instanceof Double) return formatDouble((Double) value);
if (value instanceof Character) return formatChar((Character) value);
if (value instanceof String) return formatString((String) value);
if (value instanceof Integer ||
value instanceof Boolean) return value.toString();
else
throw new IllegalArgumentException("Argument is not a primitive type or a string; it " +
((value == null) ?
"is a null value." :
"has class " +
value.getClass().getName()) + "." );
}
private static String formatByte(byte b) {
return String.format("(byte)0x%02x", b);
}
private static String formatShort(short s) {
return String.format("(short)%d", s);
}
private static String formatLong(long lng) {
return lng + "L";
}
private static String formatFloat(float f) {
if (Float.isNaN(f))
return "0.0f/0.0f";
else if (Float.isInfinite(f))
return (f < 0) ? "-1.0f/0.0f" : "1.0f/0.0f";
else
return f + "f";
}
private static String formatDouble(double d) {
if (Double.isNaN(d))
return "0.0/0.0";
else if (Double.isInfinite(d))
return (d < 0) ? "-1.0/0.0" : "1.0/0.0";
else
return d + "";
}
private static String formatChar(char c) {
return '\'' + Convert.quote(c) + '\'';
}
private static String formatString(String s) {
return '"' + Convert.quote(s) + '"';
}
}
| 5,248 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Name.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Name.java | /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/** An abstraction for internal compiler strings. They are stored in
* Utf8 format. Names are stored in a Name.Table, and are unique within
* that table.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class Name implements javax.lang.model.element.Name {
public final Table table;
protected Name(Table table) {
this.table = table;
}
/**
* @inheritDoc
*/
public boolean contentEquals(CharSequence cs) {
return toString().equals(cs.toString());
}
/**
* @inheritDoc
*/
public int length() {
return toString().length();
}
/**
* @inheritDoc
*/
public char charAt(int index) {
return toString().charAt(index);
}
/**
* @inheritDoc
*/
public CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
/** Return the concatenation of this name and name `n'.
*/
public Name append(Name n) {
int len = getByteLength();
byte[] bs = new byte[len + n.getByteLength()];
getBytes(bs, 0);
n.getBytes(bs, len);
return table.fromUtf(bs, 0, bs.length);
}
/** Return the concatenation of this name, the given ASCII
* character, and name `n'.
*/
public Name append(char c, Name n) {
int len = getByteLength();
byte[] bs = new byte[len + 1 + n.getByteLength()];
getBytes(bs, 0);
bs[len] = (byte) c;
n.getBytes(bs, len+1);
return table.fromUtf(bs, 0, bs.length);
}
/** An arbitrary but consistent complete order among all Names.
*/
public int compareTo(Name other) {
return other.getIndex() - this.getIndex();
}
/** Return true if this is the empty name.
*/
public boolean isEmpty() {
return getByteLength() == 0;
}
/** Returns last occurrence of byte b in this name, -1 if not found.
*/
public int lastIndexOf(byte b) {
byte[] bytes = getByteArray();
int offset = getByteOffset();
int i = getByteLength() - 1;
while (i >= 0 && bytes[offset + i] != b) i--;
return i;
}
/** Does this name start with prefix?
*/
public boolean startsWith(Name prefix) {
byte[] thisBytes = this.getByteArray();
int thisOffset = this.getByteOffset();
int thisLength = this.getByteLength();
byte[] prefixBytes = prefix.getByteArray();
int prefixOffset = prefix.getByteOffset();
int prefixLength = prefix.getByteLength();
int i = 0;
while (i < prefixLength &&
i < thisLength &&
thisBytes[thisOffset + i] == prefixBytes[prefixOffset + i])
i++;
return i == prefixLength;
}
/** Returns the sub-name starting at position start, up to and
* excluding position end.
*/
public Name subName(int start, int end) {
if (end < start) end = start;
return table.fromUtf(getByteArray(), getByteOffset() + start, end - start);
}
/** Return the string representation of this name.
*/
public String toString() {
return Convert.utf2string(getByteArray(), getByteOffset(), getByteLength());
}
/** Return the Utf8 representation of this name.
*/
public byte[] toUtf() {
byte[] bs = new byte[getByteLength()];
getBytes(bs, 0);
return bs;
}
/* Get a "reasonably small" value that uniquely identifies this name
* within its name table.
*/
public abstract int getIndex();
/** Get the length (in bytes) of this name.
*/
public abstract int getByteLength();
/** Returns i'th byte of this name.
*/
public abstract byte getByteAt(int i);
/** Copy all bytes of this name to buffer cs, starting at start.
*/
public void getBytes(byte cs[], int start) {
System.arraycopy(getByteArray(), getByteOffset(), cs, start, getByteLength());
}
/** Get the underlying byte array for this name. The contents of the
* array must not be modified.
*/
public abstract byte[] getByteArray();
/** Get the start offset of this name within its byte array.
*/
public abstract int getByteOffset();
/** An abstraction for the hash table used to create unique Name instances.
*/
public static abstract class Table {
/** Standard name table.
*/
public final Names names;
Table(Names names) {
this.names = names;
}
/** Get the name from the characters in cs[start..start+len-1].
*/
public abstract Name fromChars(char[] cs, int start, int len);
/** Get the name for the characters in string s.
*/
public Name fromString(String s) {
char[] cs = s.toCharArray();
return fromChars(cs, 0, cs.length);
}
/** Get the name for the bytes in array cs.
* Assume that bytes are in utf8 format.
*/
public Name fromUtf(byte[] cs) {
return fromUtf(cs, 0, cs.length);
}
/** get the name for the bytes in cs[start..start+len-1].
* Assume that bytes are in utf8 format.
*/
public abstract Name fromUtf(byte[] cs, int start, int len);
/** Release any resources used by this table.
*/
public abstract void dispose();
/** The hashcode of a name.
*/
protected static int hashValue(byte bytes[], int offset, int length) {
int h = 0;
int off = offset;
for (int i = 0; i < length; i++) {
h = (h << 5) - h + bytes[off++];
}
return h;
}
/** Compare two subarrays
*/
protected static boolean equals(byte[] bytes1, int offset1,
byte[] bytes2, int offset2, int length) {
int i = 0;
while (i < length && bytes1[offset1 + i] == bytes2[offset2 + i]) {
i++;
}
return i == length;
}
}
}
| 7,572 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JCDiagnostic.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/JCDiagnostic.java | /*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.api.DiagnosticFormatter;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.tree.JCTree;
import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticType.*;
/** An abstraction of a diagnostic message generated by the compiler.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JCDiagnostic implements Diagnostic<JavaFileObject> {
/** A factory for creating diagnostic objects. */
public static class Factory {
/** The context key for the diagnostic factory. */
protected static final Context.Key<JCDiagnostic.Factory> diagnosticFactoryKey =
new Context.Key<JCDiagnostic.Factory>();
/** Get the Factory instance for this context. */
public static Factory instance(Context context) {
Factory instance = context.get(diagnosticFactoryKey);
if (instance == null)
instance = new Factory(context);
return instance;
}
DiagnosticFormatter<JCDiagnostic> formatter;
final String prefix;
final Set<DiagnosticFlag> defaultErrorFlags;
/** Create a new diagnostic factory. */
protected Factory(Context context) {
this(JavacMessages.instance(context), "compiler");
context.put(diagnosticFactoryKey, this);
Options options = Options.instance(context);
if (options.isSet("onlySyntaxErrorsUnrecoverable"))
defaultErrorFlags.add(DiagnosticFlag.RECOVERABLE);
}
/** Create a new diagnostic factory. */
public Factory(JavacMessages messages, String prefix) {
this.prefix = prefix;
this.formatter = new BasicDiagnosticFormatter(messages);
defaultErrorFlags = EnumSet.of(DiagnosticFlag.MANDATORY);
}
/**
* Create an error diagnostic.
* @param source The source of the compilation unit, if any, in which to report the error.
* @param pos The source position at which to report the error.
* @param key The key for the localized error message.
* @param args Fields of the error message.
*/
public JCDiagnostic error(
DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(ERROR, null, defaultErrorFlags, source, pos, key, args);
}
/**
* Create a warning diagnostic that will not be hidden by the -nowarn or -Xlint:none options.
* @param source The source of the compilation unit, if any, in which to report the warning.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
* @see MandatoryWarningHandler
*/
public JCDiagnostic mandatoryWarning(
DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(WARNING, null, EnumSet.of(DiagnosticFlag.MANDATORY), source, pos, key, args);
}
/**
* Create a warning diagnostic that will not be hidden by the -nowarn or -Xlint:none options.
* @param lc The lint category for the diagnostic
* @param source The source of the compilation unit, if any, in which to report the warning.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
* @see MandatoryWarningHandler
*/
public JCDiagnostic mandatoryWarning(
LintCategory lc,
DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(WARNING, lc, EnumSet.of(DiagnosticFlag.MANDATORY), source, pos, key, args);
}
/**
* Create a warning diagnostic.
* @param lc The lint category for the diagnostic
* @param key The key for the localized error message.
* @param args Fields of the warning message.
* @see MandatoryWarningHandler
*/
public JCDiagnostic warning(
LintCategory lc, String key, Object... args) {
return create(WARNING, lc, EnumSet.noneOf(DiagnosticFlag.class), null, null, key, args);
}
/**
* Create a warning diagnostic.
* @param source The source of the compilation unit, if any, in which to report the warning.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public JCDiagnostic warning(
DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(WARNING, null, EnumSet.noneOf(DiagnosticFlag.class), source, pos, key, args);
}
/**
* Create a warning diagnostic.
* @param lc The lint category for the diagnostic
* @param source The source of the compilation unit, if any, in which to report the warning.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
* @see MandatoryWarningHandler
*/
public JCDiagnostic warning(
LintCategory lc, DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(WARNING, lc, EnumSet.noneOf(DiagnosticFlag.class), source, pos, key, args);
}
/**
* Create a note diagnostic that will not be hidden by the -nowarn or -Xlint:none options.
* @param key The key for the localized message.
* @param args Fields of the message.
* @see MandatoryWarningHandler
*/
public JCDiagnostic mandatoryNote(DiagnosticSource source, String key, Object... args) {
return create(NOTE, null, EnumSet.of(DiagnosticFlag.MANDATORY), source, null, key, args);
}
/**
* Create a note diagnostic.
* @param key The key for the localized error message.
* @param args Fields of the message.
*/
public JCDiagnostic note(String key, Object... args) {
return create(NOTE, null, EnumSet.noneOf(DiagnosticFlag.class), null, null, key, args);
}
/**
* Create a note diagnostic.
* @param source The source of the compilation unit, if any, in which to report the note.
* @param pos The source position at which to report the note.
* @param key The key for the localized message.
* @param args Fields of the message.
*/
public JCDiagnostic note(
DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(NOTE, null, EnumSet.noneOf(DiagnosticFlag.class), source, pos, key, args);
}
/**
* Create a fragment diagnostic, for use as an argument in other diagnostics
* @param key The key for the localized message.
* @param args Fields of the message.
*/
public JCDiagnostic fragment(String key, Object... args) {
return create(FRAGMENT, null, EnumSet.noneOf(DiagnosticFlag.class), null, null, key, args);
}
/**
* Create a new diagnostic of the given kind, which is not mandatory and which has
* no lint category.
* @param kind The diagnostic kind
* @param ls The lint category, if applicable, or null
* @param source The source of the compilation unit, if any, in which to report the message.
* @param pos The source position at which to report the message.
* @param key The key for the localized message.
* @param args Fields of the message.
*/
public JCDiagnostic create(
DiagnosticType kind, DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return create(kind, null, EnumSet.noneOf(DiagnosticFlag.class), source, pos, key, args);
}
/**
* Create a new diagnostic of the given kind.
* @param kind The diagnostic kind
* @param lc The lint category, if applicable, or null
* @param isMandatory is diagnostic mandatory?
* @param source The source of the compilation unit, if any, in which to report the message.
* @param pos The source position at which to report the message.
* @param key The key for the localized message.
* @param args Fields of the message.
*/
public JCDiagnostic create(
DiagnosticType kind, LintCategory lc, Set<DiagnosticFlag> flags, DiagnosticSource source, DiagnosticPosition pos, String key, Object... args) {
return new JCDiagnostic(formatter, kind, lc, flags, source, pos, qualify(kind, key), args);
}
protected String qualify(DiagnosticType t, String key) {
return prefix + "." + t.key + "." + key;
}
}
/**
* Create a fragment diagnostic, for use as an argument in other diagnostics
* @param key The key for the localized error message.
* @param args Fields of the error message.
*
*/
@Deprecated
public static JCDiagnostic fragment(String key, Object... args) {
return new JCDiagnostic(getFragmentFormatter(),
FRAGMENT,
null,
EnumSet.noneOf(DiagnosticFlag.class),
null,
null,
"compiler." + FRAGMENT.key + "." + key,
args);
}
//where
@Deprecated
public static DiagnosticFormatter<JCDiagnostic> getFragmentFormatter() {
if (fragmentFormatter == null) {
fragmentFormatter = new BasicDiagnosticFormatter(JavacMessages.getDefaultMessages());
}
return fragmentFormatter;
}
/**
* A DiagnosticType defines the type of the diagnostic.
**/
public enum DiagnosticType {
/** A fragment of an enclosing diagnostic. */
FRAGMENT("misc"),
/** A note: similar to, but less serious than, a warning. */
NOTE("note"),
/** A warning. */
WARNING("warn"),
/** An error. */
ERROR("err");
final String key;
/** Create a DiagnosticType.
* @param key A string used to create the resource key for the diagnostic.
*/
DiagnosticType(String key) {
this.key = key;
}
};
/**
* A DiagnosticPosition provides information about the positions in a file
* that gave rise to a diagnostic. It always defines a "preferred" position
* that most accurately defines the location of the diagnostic, it may also
* provide a related tree node that spans that location.
*/
public static interface DiagnosticPosition {
/** Gets the tree node, if any, to which the diagnostic applies. */
JCTree getTree();
/** If there is a tree node, get the start position of the tree node.
* Otherwise, just returns the same as getPreferredPosition(). */
int getStartPosition();
/** Get the position within the file that most accurately defines the
* location for the diagnostic. */
int getPreferredPosition();
/** If there is a tree node, and if endPositions are available, get
* the end position of the tree node. Otherwise, just returns the
* same as getPreferredPosition(). */
int getEndPosition(Map<JCTree, Integer> endPosTable);
}
/**
* A DiagnosticPosition that simply identifies a position, but no related
* tree node, as the location for a diagnostic. Used for scanner and parser
* diagnostics. */
public static class SimpleDiagnosticPosition implements DiagnosticPosition {
public SimpleDiagnosticPosition(int pos) {
this.pos = pos;
}
public JCTree getTree() {
return null;
}
public int getStartPosition() {
return pos;
}
public int getPreferredPosition() {
return pos;
}
public int getEndPosition(Map<JCTree, Integer> endPosTable) {
return pos;
}
private final int pos;
}
public enum DiagnosticFlag {
MANDATORY,
RESOLVE_ERROR,
SYNTAX,
RECOVERABLE
}
private final DiagnosticType type;
private final DiagnosticSource source;
private final DiagnosticPosition position;
private final int line;
private final int column;
private final String key;
protected final Object[] args;
private final Set<DiagnosticFlag> flags;
private final LintCategory lintCategory;
/**
* Create a diagnostic object.
* @param fomatter the formatter to use for the diagnostic
* @param dt the type of diagnostic
* @param lc the lint category for the diagnostic
* @param source the name of the source file, or null if none.
* @param pos the character offset within the source file, if given.
* @param key a resource key to identify the text of the diagnostic
* @param args arguments to be included in the text of the diagnostic
*/
protected JCDiagnostic(DiagnosticFormatter<JCDiagnostic> formatter,
DiagnosticType dt,
LintCategory lc,
Set<DiagnosticFlag> flags,
DiagnosticSource source,
DiagnosticPosition pos,
String key,
Object... args) {
if (source == null && pos != null && pos.getPreferredPosition() != Position.NOPOS)
throw new IllegalArgumentException();
this.defaultFormatter = formatter;
this.type = dt;
this.lintCategory = lc;
this.flags = flags;
this.source = source;
this.position = pos;
this.key = key;
this.args = args;
int n = (pos == null ? Position.NOPOS : pos.getPreferredPosition());
if (n == Position.NOPOS || source == null)
line = column = -1;
else {
line = source.getLineNumber(n);
column = source.getColumnNumber(n, true);
}
}
/**
* Get the type of this diagnostic.
* @return the type of this diagnostic
*/
public DiagnosticType getType() {
return type;
}
/**
* Get the subdiagnostic list
* @return subdiagnostic list
*/
public List<JCDiagnostic> getSubdiagnostics() {
return List.nil();
}
public boolean isMultiline() {
return false;
}
/**
* Check whether or not this diagnostic is required to be shown.
* @return true if this diagnostic is required to be shown.
*/
public boolean isMandatory() {
return flags.contains(DiagnosticFlag.MANDATORY);
}
/**
* Check whether this diagnostic has an associated lint category.
*/
public boolean hasLintCategory() {
return (lintCategory != null);
}
/**
* Get the associated lint category, or null if none.
*/
public LintCategory getLintCategory() {
return lintCategory;
}
/**
* Get the name of the source file referred to by this diagnostic.
* @return the name of the source referred to with this diagnostic, or null if none
*/
public JavaFileObject getSource() {
if (source == null)
return null;
else
return source.getFile();
}
/**
* Get the source referred to by this diagnostic.
* @return the source referred to with this diagnostic, or null if none
*/
public DiagnosticSource getDiagnosticSource() {
return source;
}
protected int getIntStartPosition() {
return (position == null ? Position.NOPOS : position.getStartPosition());
}
protected int getIntPosition() {
return (position == null ? Position.NOPOS : position.getPreferredPosition());
}
protected int getIntEndPosition() {
return (position == null ? Position.NOPOS : position.getEndPosition(source.getEndPosTable()));
}
public long getStartPosition() {
return getIntStartPosition();
}
public long getPosition() {
return getIntPosition();
}
public long getEndPosition() {
return getIntEndPosition();
}
/**
* Get the line number within the source referred to by this diagnostic.
* @return the line number within the source referred to by this diagnostic
*/
public long getLineNumber() {
return line;
}
/**
* Get the column number within the line of source referred to by this diagnostic.
* @return the column number within the line of source referred to by this diagnostic
*/
public long getColumnNumber() {
return column;
}
/**
* Get the arguments to be included in the text of the diagnostic.
* @return the arguments to be included in the text of the diagnostic
*/
public Object[] getArgs() {
return args;
}
/**
* Get the prefix string associated with this type of diagnostic.
* @return the prefix string associated with this type of diagnostic
*/
public String getPrefix() {
return getPrefix(type);
}
/**
* Get the prefix string associated with a particular type of diagnostic.
* @return the prefix string associated with a particular type of diagnostic
*/
public String getPrefix(DiagnosticType dt) {
return defaultFormatter.formatKind(this, Locale.getDefault());
}
/**
* Return the standard presentation of this diagnostic.
*/
@Override
public String toString() {
return defaultFormatter.format(this,Locale.getDefault());
}
private DiagnosticFormatter<JCDiagnostic> defaultFormatter;
@Deprecated
private static DiagnosticFormatter<JCDiagnostic> fragmentFormatter;
// Methods for javax.tools.Diagnostic
public Diagnostic.Kind getKind() {
switch (type) {
case NOTE:
return Diagnostic.Kind.NOTE;
case WARNING:
return flags.contains(DiagnosticFlag.MANDATORY)
? Diagnostic.Kind.MANDATORY_WARNING
: Diagnostic.Kind.WARNING;
case ERROR:
return Diagnostic.Kind.ERROR;
default:
return Diagnostic.Kind.OTHER;
}
}
public String getCode() {
return key;
}
public String getMessage(Locale locale) {
return defaultFormatter.formatMessage(this, locale);
}
public void setFlag(DiagnosticFlag flag) {
flags.add(flag);
if (type == DiagnosticType.ERROR) {
switch (flag) {
case SYNTAX:
flags.remove(DiagnosticFlag.RECOVERABLE);
break;
case RESOLVE_ERROR:
flags.add(DiagnosticFlag.RECOVERABLE);
break;
}
}
}
public boolean isFlagSet(DiagnosticFlag flag) {
return flags.contains(flag);
}
public static class MultilineDiagnostic extends JCDiagnostic {
private final List<JCDiagnostic> subdiagnostics;
public MultilineDiagnostic(JCDiagnostic other, List<JCDiagnostic> subdiagnostics) {
super(other.defaultFormatter,
other.getType(),
other.getLintCategory(),
other.flags,
other.getDiagnosticSource(),
other.position,
other.getCode(),
other.getArgs());
this.subdiagnostics = subdiagnostics;
}
@Override
public List<JCDiagnostic> getSubdiagnostics() {
return subdiagnostics;
}
@Override
public boolean isMultiline() {
return true;
}
}
}
| 22,258 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Log.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Log.java | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.io.*;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.api.DiagnosticFormatter;
import com.sun.tools.javac.main.OptionName;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
import static com.sun.tools.javac.main.OptionName.*;
/** A class for error logs. Reports errors and warnings, and
* keeps track of error numbers and positions.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Log extends AbstractLog {
/** The context key for the log. */
public static final Context.Key<Log> logKey
= new Context.Key<Log>();
/** The context key for the output PrintWriter. */
public static final Context.Key<PrintWriter> outKey =
new Context.Key<PrintWriter>();
//@Deprecated
public final PrintWriter errWriter;
//@Deprecated
public final PrintWriter warnWriter;
//@Deprecated
public final PrintWriter noticeWriter;
/** The maximum number of errors/warnings that are reported.
*/
public final int MaxErrors;
public final int MaxWarnings;
/** Switch: prompt user on each error.
*/
public boolean promptOnError;
/** Switch: emit warning messages.
*/
public boolean emitWarnings;
/** Switch: suppress note messages.
*/
public boolean suppressNotes;
/** Print stack trace on errors?
*/
public boolean dumpOnError;
/** Print multiple errors for same source locations.
*/
public boolean multipleErrors;
/**
* Diagnostic listener, if provided through programmatic
* interface to javac (JSR 199).
*/
protected DiagnosticListener<? super JavaFileObject> diagListener;
/**
* Formatter for diagnostics.
*/
private DiagnosticFormatter<JCDiagnostic> diagFormatter;
/**
* Keys for expected diagnostics.
*/
public Set<String> expectDiagKeys;
/**
* JavacMessages object used for localization.
*/
private JavacMessages messages;
/**
* Deferred diagnostics
*/
public boolean deferDiagnostics;
public Queue<JCDiagnostic> deferredDiagnostics = new ListBuffer<JCDiagnostic>();
/** Construct a log with given I/O redirections.
*/
@Deprecated
protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
super(JCDiagnostic.Factory.instance(context));
context.put(logKey, this);
this.errWriter = errWriter;
this.warnWriter = warnWriter;
this.noticeWriter = noticeWriter;
Options options = Options.instance(context);
this.dumpOnError = options.isSet(DOE);
this.promptOnError = options.isSet(PROMPT);
this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
this.suppressNotes = options.isSet("suppressNotes");
this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
boolean rawDiagnostics = options.isSet("rawDiagnostics");
messages = JavacMessages.instance(context);
this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
new BasicDiagnosticFormatter(options, messages);
@SuppressWarnings("unchecked") // FIXME
DiagnosticListener<? super JavaFileObject> dl =
context.get(DiagnosticListener.class);
this.diagListener = dl;
String ek = options.get("expectKeys");
if (ek != null)
expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
}
// where
private int getIntOption(Options options, OptionName optionName, int defaultValue) {
String s = options.get(optionName);
try {
if (s != null) {
int n = Integer.parseInt(s);
return (n <= 0 ? Integer.MAX_VALUE : n);
}
} catch (NumberFormatException e) {
// silently ignore ill-formed numbers
}
return defaultValue;
}
/** Default value for -Xmaxerrs.
*/
protected int getDefaultMaxErrors() {
return 100;
}
/** Default value for -Xmaxwarns.
*/
protected int getDefaultMaxWarnings() {
return 100;
}
/** The default writer for diagnostics
*/
static final PrintWriter defaultWriter(Context context) {
PrintWriter result = context.get(outKey);
if (result == null)
context.put(outKey, result = new PrintWriter(System.err));
return result;
}
/** Construct a log with default settings.
*/
protected Log(Context context) {
this(context, defaultWriter(context));
}
/** Construct a log with all output redirected.
*/
protected Log(Context context, PrintWriter defaultWriter) {
this(context, defaultWriter, defaultWriter, defaultWriter);
}
/** Get the Log instance for this context. */
public static Log instance(Context context) {
Log instance = context.get(logKey);
if (instance == null)
instance = new Log(context);
return instance;
}
/** The number of errors encountered so far.
*/
public int nerrors = 0;
/** The number of warnings encountered so far.
*/
public int nwarnings = 0;
/** A set of all errors generated so far. This is used to avoid printing an
* error message more than once. For each error, a pair consisting of the
* source file name and source code position of the error is added to the set.
*/
private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
public boolean hasDiagnosticListener() {
return diagListener != null;
}
public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
name.getClass(); // null check
getSource(name).setEndPosTable(table);
}
/** Return current sourcefile.
*/
public JavaFileObject currentSourceFile() {
return source == null ? null : source.getFile();
}
/** Get the current diagnostic formatter.
*/
public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
return diagFormatter;
}
/** Set the current diagnostic formatter.
*/
public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
this.diagFormatter = diagFormatter;
}
/** Flush the logs
*/
public void flush() {
errWriter.flush();
warnWriter.flush();
noticeWriter.flush();
}
/** Returns true if an error needs to be reported for a given
* source name and pos.
*/
protected boolean shouldReport(JavaFileObject file, int pos) {
if (multipleErrors || file == null)
return true;
Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
boolean shouldReport = !recorded.contains(coords);
if (shouldReport)
recorded.add(coords);
return shouldReport;
}
/** Prompt user after an error.
*/
public void prompt() {
if (promptOnError) {
System.err.println(localize("resume.abort"));
char ch;
try {
while (true) {
switch (System.in.read()) {
case 'a': case 'A':
System.exit(-1);
return;
case 'r': case 'R':
return;
case 'x': case 'X':
throw new AssertionError("user abort");
default:
}
}
} catch (IOException e) {}
}
}
/** Print the faulty source code line and point to the error.
* @param pos Buffer index of the error position, must be on current line
*/
private void printErrLine(int pos, PrintWriter writer) {
String line = (source == null ? null : source.getLine(pos));
if (line == null)
return;
int col = source.getColumnNumber(pos, false);
printLines(writer, line);
for (int i = 0; i < col - 1; i++) {
writer.print((line.charAt(i) == '\t') ? "\t" : " ");
}
writer.println("^");
writer.flush();
}
/** Print the text of a message, translating newlines appropriately
* for the platform.
*/
public static void printLines(PrintWriter writer, String msg) {
int nl;
while ((nl = msg.indexOf('\n')) != -1) {
writer.println(msg.substring(0, nl));
msg = msg.substring(nl+1);
}
if (msg.length() != 0) writer.println(msg);
}
/** Print the text of a message to the errWriter stream,
* translating newlines appropriately for the platform.
*/
public void printErrLines(String key, Object... args) {
printLines(errWriter, localize(key, args));
}
/** Print the text of a message to the noticeWriter stream,
* translating newlines appropriately for the platform.
*/
public void printNoteLines(String key, Object... args) {
printLines(noticeWriter, localize(key, args));
}
/**
* Print the localized text of a "verbose" message to the
* noticeWriter stream.
*/
public void printVerbose(String key, Object... args) {
printLines(noticeWriter, localize("verbose." + key, args));
}
protected void directError(String key, Object... args) {
printErrLines(key, args);
errWriter.flush();
}
/** Report a warning that cannot be suppressed.
* @param pos The source position at which to report the warning.
* @param key The key for the localized warning message.
* @param args Fields of the warning message.
*/
public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
writeDiagnostic(diags.warning(source, pos, key, args));
nwarnings++;
}
/** Report all deferred diagnostics, and clear the deferDiagnostics flag. */
public void reportDeferredDiagnostics() {
reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
}
/** Report selected deferred diagnostics, and clear the deferDiagnostics flag. */
public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
deferDiagnostics = false;
JCDiagnostic d;
while ((d = deferredDiagnostics.poll()) != null) {
if (kinds.contains(d.getKind()))
report(d);
}
}
/**
* Common diagnostic handling.
* The diagnostic is counted, and depending on the options and how many diagnostics have been
* reported so far, the diagnostic may be handed off to writeDiagnostic.
*/
public void report(JCDiagnostic diagnostic) {
if (deferDiagnostics) {
deferredDiagnostics.add(diagnostic);
return;
}
if (expectDiagKeys != null)
expectDiagKeys.remove(diagnostic.getCode());
switch (diagnostic.getType()) {
case FRAGMENT:
throw new IllegalArgumentException();
case NOTE:
// Print out notes only when we are permitted to report warnings
// Notes are only generated at the end of a compilation, so should be small
// in number.
if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
writeDiagnostic(diagnostic);
}
break;
case WARNING:
if (emitWarnings || diagnostic.isMandatory()) {
if (nwarnings < MaxWarnings) {
writeDiagnostic(diagnostic);
nwarnings++;
}
}
break;
case ERROR:
if (nerrors < MaxErrors
&& shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
writeDiagnostic(diagnostic);
nerrors++;
}
break;
}
}
/**
* Write out a diagnostic.
*/
protected void writeDiagnostic(JCDiagnostic diag) {
if (diagListener != null) {
diagListener.report(diag);
return;
}
PrintWriter writer = getWriterForDiagnosticType(diag.getType());
printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
if (promptOnError) {
switch (diag.getType()) {
case ERROR:
case WARNING:
prompt();
}
}
if (dumpOnError)
new RuntimeException().printStackTrace(writer);
writer.flush();
}
@Deprecated
protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
switch (dt) {
case FRAGMENT:
throw new IllegalArgumentException();
case NOTE:
return noticeWriter;
case WARNING:
return warnWriter;
case ERROR:
return errWriter;
default:
throw new Error();
}
}
/** Find a localized string in the resource bundle.
* Because this method is static, it ignores the locale.
* Use localize(key, args) when possible.
* @param key The key for the localized string.
* @param args Fields to substitute into the string.
*/
public static String getLocalizedString(String key, Object ... args) {
return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
}
/** Find a localized string in the resource bundle.
* @param key The key for the localized string.
* @param args Fields to substitute into the string.
*/
public String localize(String key, Object... args) {
return messages.getLocalizedString("compiler.misc." + key, args);
}
/***************************************************************************
* raw error messages without internationalization; used for experimentation
* and quick prototyping
***************************************************************************/
/** print an error or warning message:
*/
private void printRawError(int pos, String msg) {
if (source == null || pos == Position.NOPOS) {
printLines(errWriter, "error: " + msg);
} else {
int line = source.getLineNumber(pos);
JavaFileObject file = source.getFile();
if (file != null)
printLines(errWriter,
file.getName() + ":" +
line + ": " + msg);
printErrLine(pos, errWriter);
}
errWriter.flush();
}
/** report an error:
*/
public void rawError(int pos, String msg) {
if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
printRawError(pos, msg);
prompt();
nerrors++;
}
errWriter.flush();
}
/** report a warning:
*/
public void rawWarning(int pos, String msg) {
if (nwarnings < MaxWarnings && emitWarnings) {
printRawError(pos, "warning: " + msg);
}
prompt();
nwarnings++;
errWriter.flush();
}
public static String format(String fmt, Object... args) {
return String.format((java.util.Locale)null, fmt, args);
}
}
| 17,375 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
UnsharedNameTable.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/UnsharedNameTable.java | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.lang.ref.WeakReference;
/**
* Implementation of Name.Table that stores names in individual arrays
* using weak references. It is recommended for use when a single shared
* byte array is unsuitable.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class UnsharedNameTable extends Name.Table {
static public Name.Table create(Names names) {
return new UnsharedNameTable(names);
}
static class HashEntry extends WeakReference<NameImpl> {
HashEntry next;
HashEntry(NameImpl referent) {
super(referent);
}
}
/** The hash table for names.
*/
private HashEntry[] hashes = null;
/** The mask to be used for hashing
*/
private int hashMask;
/** Index counter for names in this table.
*/
public int index;
/** Allocator
* @param names The main name table
* @param hashSize the (constant) size to be used for the hash table
* needs to be a power of two.
*/
public UnsharedNameTable(Names names, int hashSize) {
super(names);
hashMask = hashSize - 1;
hashes = new HashEntry[hashSize];
}
public UnsharedNameTable(Names names) {
this(names, 0x8000);
}
@Override
public Name fromChars(char[] cs, int start, int len) {
byte[] name = new byte[len * 3];
int nbytes = Convert.chars2utf(cs, start, name, 0, len);
return fromUtf(name, 0, nbytes);
}
@Override
public Name fromUtf(byte[] cs, int start, int len) {
int h = hashValue(cs, start, len) & hashMask;
HashEntry element = hashes[h];
NameImpl n = null;
HashEntry previousNonNullTableEntry = null;
HashEntry firstTableEntry = element;
while (element != null) {
if (element == null) {
break;
}
n = element.get();
if (n == null) {
if (firstTableEntry == element) {
hashes[h] = firstTableEntry = element.next;
}
else {
Assert.checkNonNull(previousNonNullTableEntry, "previousNonNullTableEntry cannot be null here.");
previousNonNullTableEntry.next = element.next;
}
}
else {
if (n.getByteLength() == len && equals(n.bytes, 0, cs, start, len)) {
return n;
}
previousNonNullTableEntry = element;
}
element = element.next;
}
byte[] bytes = new byte[len];
System.arraycopy(cs, start, bytes, 0, len);
n = new NameImpl(this, bytes, index++);
System.arraycopy(cs, start, n.bytes, 0, len);
HashEntry newEntry = new HashEntry(n);
if (previousNonNullTableEntry == null) { // We are not the first name with that hashCode.
hashes[h] = newEntry;
}
else {
Assert.checkNull(previousNonNullTableEntry.next, "previousNonNullTableEntry.next must be null.");
previousNonNullTableEntry.next = newEntry;
}
return n;
}
@Override
public void dispose() {
hashes = null;
}
static class NameImpl extends Name {
NameImpl(UnsharedNameTable table, byte[] bytes, int index) {
super(table);
this.bytes = bytes;
this.index = index;
}
final byte[] bytes;
final int index;
@Override
public int getIndex() {
return index;
}
@Override
public int getByteLength() {
return bytes.length;
}
@Override
public byte getByteAt(int i) {
return bytes[i];
}
@Override
public byte[] getByteArray() {
return bytes;
}
@Override
public int getByteOffset() {
return 0;
}
}
}
| 5,425 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Convert.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Convert.java | /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/** Utility class for static conversion methods between numbers
* and strings in various formats.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Convert {
/** Convert string to integer.
*/
public static int string2int(String s, int radix)
throws NumberFormatException {
if (radix == 10) {
return Integer.parseInt(s, radix);
} else {
char[] cs = s.toCharArray();
int limit = Integer.MAX_VALUE / (radix/2);
int n = 0;
for (int i = 0; i < cs.length; i++) {
int d = Character.digit(cs[i], radix);
if (n < 0 ||
n > limit ||
n * radix > Integer.MAX_VALUE - d)
throw new NumberFormatException();
n = n * radix + d;
}
return n;
}
}
/** Convert string to long integer.
*/
public static long string2long(String s, int radix)
throws NumberFormatException {
if (radix == 10) {
return Long.parseLong(s, radix);
} else {
char[] cs = s.toCharArray();
long limit = Long.MAX_VALUE / (radix/2);
long n = 0;
for (int i = 0; i < cs.length; i++) {
int d = Character.digit(cs[i], radix);
if (n < 0 ||
n > limit ||
n * radix > Long.MAX_VALUE - d)
throw new NumberFormatException();
n = n * radix + d;
}
return n;
}
}
/* Conversion routines between names, strings, and byte arrays in Utf8 format
*/
/** Convert `len' bytes from utf8 to characters.
* Parameters are as in System.arraycopy
* Return first index in `dst' past the last copied char.
* @param src The array holding the bytes to convert.
* @param sindex The start index from which bytes are converted.
* @param dst The array holding the converted characters..
* @param dindex The start index from which converted characters
* are written.
* @param len The maximum number of bytes to convert.
*/
public static int utf2chars(byte[] src, int sindex,
char[] dst, int dindex,
int len) {
int i = sindex;
int j = dindex;
int limit = sindex + len;
while (i < limit) {
int b = src[i++] & 0xFF;
if (b >= 0xE0) {
b = (b & 0x0F) << 12;
b = b | (src[i++] & 0x3F) << 6;
b = b | (src[i++] & 0x3F);
} else if (b >= 0xC0) {
b = (b & 0x1F) << 6;
b = b | (src[i++] & 0x3F);
}
dst[j++] = (char)b;
}
return j;
}
/** Return bytes in Utf8 representation as an array of characters.
* @param src The array holding the bytes.
* @param sindex The start index from which bytes are converted.
* @param len The maximum number of bytes to convert.
*/
public static char[] utf2chars(byte[] src, int sindex, int len) {
char[] dst = new char[len];
int len1 = utf2chars(src, sindex, dst, 0, len);
char[] result = new char[len1];
System.arraycopy(dst, 0, result, 0, len1);
return result;
}
/** Return all bytes of a given array in Utf8 representation
* as an array of characters.
* @param src The array holding the bytes.
*/
public static char[] utf2chars(byte[] src) {
return utf2chars(src, 0, src.length);
}
/** Return bytes in Utf8 representation as a string.
* @param src The array holding the bytes.
* @param sindex The start index from which bytes are converted.
* @param len The maximum number of bytes to convert.
*/
public static String utf2string(byte[] src, int sindex, int len) {
char dst[] = new char[len];
int len1 = utf2chars(src, sindex, dst, 0, len);
return new String(dst, 0, len1);
}
/** Return all bytes of a given array in Utf8 representation
* as a string.
* @param src The array holding the bytes.
*/
public static String utf2string(byte[] src) {
return utf2string(src, 0, src.length);
}
/** Copy characters in source array to bytes in target array,
* converting them to Utf8 representation.
* The target array must be large enough to hold the result.
* returns first index in `dst' past the last copied byte.
* @param src The array holding the characters to convert.
* @param sindex The start index from which characters are converted.
* @param dst The array holding the converted characters..
* @param dindex The start index from which converted bytes
* are written.
* @param len The maximum number of characters to convert.
*/
public static int chars2utf(char[] src, int sindex,
byte[] dst, int dindex,
int len) {
int j = dindex;
int limit = sindex + len;
for (int i = sindex; i < limit; i++) {
char ch = src[i];
if (1 <= ch && ch <= 0x7F) {
dst[j++] = (byte)ch;
} else if (ch <= 0x7FF) {
dst[j++] = (byte)(0xC0 | (ch >> 6));
dst[j++] = (byte)(0x80 | (ch & 0x3F));
} else {
dst[j++] = (byte)(0xE0 | (ch >> 12));
dst[j++] = (byte)(0x80 | ((ch >> 6) & 0x3F));
dst[j++] = (byte)(0x80 | (ch & 0x3F));
}
}
return j;
}
/** Return characters as an array of bytes in Utf8 representation.
* @param src The array holding the characters.
* @param sindex The start index from which characters are converted.
* @param len The maximum number of characters to convert.
*/
public static byte[] chars2utf(char[] src, int sindex, int len) {
byte[] dst = new byte[len * 3];
int len1 = chars2utf(src, sindex, dst, 0, len);
byte[] result = new byte[len1];
System.arraycopy(dst, 0, result, 0, len1);
return result;
}
/** Return all characters in given array as an array of bytes
* in Utf8 representation.
* @param src The array holding the characters.
*/
public static byte[] chars2utf(char[] src) {
return chars2utf(src, 0, src.length);
}
/** Return string as an array of bytes in in Utf8 representation.
*/
public static byte[] string2utf(String s) {
return chars2utf(s.toCharArray());
}
/**
* Escapes each character in a string that has an escape sequence or
* is non-printable ASCII. Leaves non-ASCII characters alone.
*/
public static String quote(String s) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
buf.append(quote(s.charAt(i)));
}
return buf.toString();
}
/**
* Escapes a character if it has an escape sequence or is
* non-printable ASCII. Leaves non-ASCII characters alone.
*/
public static String quote(char ch) {
switch (ch) {
case '\b': return "\\b";
case '\f': return "\\f";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
case '\'': return "\\'";
case '\"': return "\\\"";
case '\\': return "\\\\";
default:
return (isPrintableAscii(ch))
? String.valueOf(ch)
: String.format("\\u%04x", (int) ch);
}
}
/**
* Is a character printable ASCII?
*/
private static boolean isPrintableAscii(char ch) {
return ch >= ' ' && ch <= '~';
}
/** Escape all unicode characters in string.
*/
public static String escapeUnicode(String s) {
int len = s.length();
int i = 0;
while (i < len) {
char ch = s.charAt(i);
if (ch > 255) {
StringBuffer buf = new StringBuffer();
buf.append(s.substring(0, i));
while (i < len) {
ch = s.charAt(i);
if (ch > 255) {
buf.append("\\u");
buf.append(Character.forDigit((ch >> 12) % 16, 16));
buf.append(Character.forDigit((ch >> 8) % 16, 16));
buf.append(Character.forDigit((ch >> 4) % 16, 16));
buf.append(Character.forDigit((ch ) % 16, 16));
} else {
buf.append(ch);
}
i++;
}
s = buf.toString();
} else {
i++;
}
}
return s;
}
/* Conversion routines for qualified name splitting
*/
/** Return the last part of a class name.
*/
public static Name shortName(Name classname) {
return classname.subName(
classname.lastIndexOf((byte)'.') + 1, classname.getByteLength());
}
public static String shortName(String classname) {
return classname.substring(classname.lastIndexOf('.') + 1);
}
/** Return the package name of a class name, excluding the trailing '.',
* "" if not existent.
*/
public static Name packagePart(Name classname) {
return classname.subName(0, classname.lastIndexOf((byte)'.'));
}
public static String packagePart(String classname) {
int lastDot = classname.lastIndexOf('.');
return (lastDot < 0 ? "" : classname.substring(0, lastDot));
}
public static List<Name> enclosingCandidates(Name name) {
List<Name> names = List.nil();
int index;
while ((index = name.lastIndexOf((byte)'$')) > 0) {
name = name.subName(0, index);
names = names.prepend(name);
}
return names;
}
}
| 11,696 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SharedNameTable.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/SharedNameTable.java | /*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.lang.ref.SoftReference;
/**
* Implementation of Name.Table that stores all names in a single shared
* byte array, expanding it as needed. This avoids the overhead incurred
* by using an array of bytes for each name.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class SharedNameTable extends Name.Table {
// maintain a freelist of recently used name tables for reuse.
private static List<SoftReference<SharedNameTable>> freelist = List.nil();
static public synchronized SharedNameTable create(Names names) {
while (freelist.nonEmpty()) {
SharedNameTable t = freelist.head.get();
freelist = freelist.tail;
if (t != null) {
return t;
}
}
return new SharedNameTable(names);
}
static private synchronized void dispose(SharedNameTable t) {
freelist = freelist.prepend(new SoftReference<SharedNameTable>(t));
}
/** The hash table for names.
*/
private NameImpl[] hashes;
/** The shared byte array holding all encountered names.
*/
public byte[] bytes;
/** The mask to be used for hashing
*/
private int hashMask;
/** The number of filled bytes in `names'.
*/
private int nc = 0;
/** Allocator
* @param names The main name table
* @param hashSize the (constant) size to be used for the hash table
* needs to be a power of two.
* @param nameSize the initial size of the name table.
*/
public SharedNameTable(Names names, int hashSize, int nameSize) {
super(names);
hashMask = hashSize - 1;
hashes = new NameImpl[hashSize];
bytes = new byte[nameSize];
}
public SharedNameTable(Names names) {
this(names, 0x8000, 0x20000);
}
@Override
public Name fromChars(char[] cs, int start, int len) {
int nc = this.nc;
byte[] bytes = this.bytes;
while (nc + len * 3 >= bytes.length) {
// System.err.println("doubling name buffer of length " + names.length + " to fit " + len + " chars");//DEBUG
byte[] newnames = new byte[bytes.length * 2];
System.arraycopy(bytes, 0, newnames, 0, bytes.length);
bytes = this.bytes = newnames;
}
int nbytes = Convert.chars2utf(cs, start, bytes, nc, len) - nc;
int h = hashValue(bytes, nc, nbytes) & hashMask;
NameImpl n = hashes[h];
while (n != null &&
(n.getByteLength() != nbytes ||
!equals(bytes, n.index, bytes, nc, nbytes))) {
n = n.next;
}
if (n == null) {
n = new NameImpl(this);
n.index = nc;
n.length = nbytes;
n.next = hashes[h];
hashes[h] = n;
this.nc = nc + nbytes;
if (nbytes == 0) {
this.nc++;
}
}
return n;
}
@Override
public Name fromUtf(byte[] cs, int start, int len) {
int h = hashValue(cs, start, len) & hashMask;
NameImpl n = hashes[h];
byte[] names = this.bytes;
while (n != null &&
(n.getByteLength() != len || !equals(names, n.index, cs, start, len))) {
n = n.next;
}
if (n == null) {
int nc = this.nc;
while (nc + len > names.length) {
// System.err.println("doubling name buffer of length + " + names.length + " to fit " + len + " bytes");//DEBUG
byte[] newnames = new byte[names.length * 2];
System.arraycopy(names, 0, newnames, 0, names.length);
names = this.bytes = newnames;
}
System.arraycopy(cs, start, names, nc, len);
n = new NameImpl(this);
n.index = nc;
n.length = len;
n.next = hashes[h];
hashes[h] = n;
this.nc = nc + len;
if (len == 0) {
this.nc++;
}
}
return n;
}
@Override
public void dispose() {
dispose(this);
}
static class NameImpl extends Name {
/** The next name occupying the same hash bucket.
*/
NameImpl next;
/** The index where the bytes of this name are stored in the global name
* buffer `byte'.
*/
int index;
/** The number of bytes in this name.
*/
int length;
NameImpl(SharedNameTable table) {
super(table);
}
@Override
public int getIndex() {
return index;
}
@Override
public int getByteLength() {
return length;
}
@Override
public byte getByteAt(int i) {
return getByteArray()[index + i];
}
@Override
public byte[] getByteArray() {
return ((SharedNameTable) table).bytes;
}
@Override
public int getByteOffset() {
return index;
}
/** Return the hash value of this name.
*/
public int hashCode() {
return index;
}
/** Is this name equal to other?
*/
public boolean equals(Object other) {
if (other instanceof Name)
return
table == ((Name)other).table && index == ((Name) other).getIndex();
else return false;
}
}
}
| 6,960 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Context.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Context.java | /*
* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import java.util.*;
/**
* Support for an abstract context, modelled loosely after ThreadLocal
* but using a user-provided context instead of the current thread.
*
* <p>Within the compiler, a single Context is used for each
* invocation of the compiler. The context is then used to ensure a
* single copy of each compiler phase exists per compiler invocation.
*
* <p>The context can be used to assist in extending the compiler by
* extending its components. To do that, the extended component must
* be registered before the base component. We break initialization
* cycles by (1) registering a factory for the component rather than
* the component itself, and (2) a convention for a pattern of usage
* in which each base component registers itself by calling an
* instance method that is overridden in extended components. A base
* phase supporting extension would look something like this:
*
* <p><pre>
* public class Phase {
* protected static final Context.Key<Phase> phaseKey =
* new Context.Key<Phase>();
*
* public static Phase instance(Context context) {
* Phase instance = context.get(phaseKey);
* if (instance == null)
* // the phase has not been overridden
* instance = new Phase(context);
* return instance;
* }
*
* protected Phase(Context context) {
* context.put(phaseKey, this);
* // other intitialization follows...
* }
* }
* </pre>
*
* <p>In the compiler, we simply use Phase.instance(context) to get
* the reference to the phase. But in extensions of the compiler, we
* must register extensions of the phases to replace the base phase,
* and this must be done before any reference to the phase is accessed
* using Phase.instance(). An extended phase might be declared thus:
*
* <p><pre>
* public class NewPhase extends Phase {
* protected NewPhase(Context context) {
* super(context);
* }
* public static void preRegister(final Context context) {
* context.put(phaseKey, new Context.Factory<Phase>() {
* public Phase make() {
* return new NewPhase(context);
* }
* });
* }
* }
* </pre>
*
* <p>And is registered early in the extended compiler like this
*
* <p><pre>
* NewPhase.preRegister(context);
* </pre>
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Context {
/** The client creates an instance of this class for each key.
*/
public static class Key<T> {
// note: we inherit identity equality from Object.
}
/**
* The client can register a factory for lazy creation of the
* instance.
*/
public static interface Factory<T> {
T make(Context c);
};
/**
* The underlying map storing the data.
* We maintain the invariant that this table contains only
* mappings of the form
* Key<T> -> T or Key<T> -> Factory<T> */
private Map<Key<?>,Object> ht = new HashMap<Key<?>,Object>();
/** Set the factory for the key in this context. */
public <T> void put(Key<T> key, Factory<T> fac) {
checkState(ht);
Object old = ht.put(key, fac);
if (old != null)
throw new AssertionError("duplicate context value");
checkState(ft);
ft.put(key, fac); // cannot be duplicate if unique in ht
}
/** Set the value for the key in this context. */
public <T> void put(Key<T> key, T data) {
if (data instanceof Factory<?>)
throw new AssertionError("T extends Context.Factory");
checkState(ht);
Object old = ht.put(key, data);
if (old != null && !(old instanceof Factory<?>) && old != data && data != null)
throw new AssertionError("duplicate context value");
}
/** Get the value for the key in this context. */
public <T> T get(Key<T> key) {
checkState(ht);
Object o = ht.get(key);
if (o instanceof Factory<?>) {
Factory<?> fac = (Factory<?>)o;
o = fac.make(this);
if (o instanceof Factory<?>)
throw new AssertionError("T extends Context.Factory");
Assert.check(ht.get(key) == o);
}
/* The following cast can't fail unless there was
* cheating elsewhere, because of the invariant on ht.
* Since we found a key of type Key<T>, the value must
* be of type T.
*/
return Context.<T>uncheckedCast(o);
}
public Context() {}
/**
* The table of preregistered factories.
*/
private Map<Key<?>,Factory<?>> ft = new HashMap<Key<?>,Factory<?>>();
public Context(Context prev) {
kt.putAll(prev.kt); // retain all implicit keys
ft.putAll(prev.ft); // retain all factory objects
ht.putAll(prev.ft); // init main table with factories
}
/*
* The key table, providing a unique Key<T> for each Class<T>.
*/
private Map<Class<?>, Key<?>> kt = new HashMap<Class<?>, Key<?>>();
private <T> Key<T> key(Class<T> clss) {
checkState(kt);
Key<T> k = uncheckedCast(kt.get(clss));
if (k == null) {
k = new Key<T>();
kt.put(clss, k);
}
return k;
}
public <T> T get(Class<T> clazz) {
return get(key(clazz));
}
public <T> void put(Class<T> clazz, T data) {
put(key(clazz), data);
}
public <T> void put(Class<T> clazz, Factory<T> fac) {
put(key(clazz), fac);
}
/**
* TODO: This method should be removed and Context should be made type safe.
* This can be accomplished by using class literals as type tokens.
*/
@SuppressWarnings("unchecked")
private static <T> T uncheckedCast(Object o) {
return (T)o;
}
public void dump() {
for (Object value : ht.values())
System.err.println(value == null ? null : value.getClass());
}
public void clear() {
ht = null;
kt = null;
ft = null;
}
private static void checkState(Map<?,?> t) {
if (t == null)
throw new IllegalStateException();
}
}
| 7,649 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Warner.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/Warner.java | /*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import java.util.EnumSet;
/**
* An interface to support optional warnings, needed for support of
* unchecked conversions and unchecked casts.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Warner {
public static final Warner noWarnings = new Warner();
private DiagnosticPosition pos = null;
protected boolean warned = false;
private EnumSet<LintCategory> nonSilentLintSet = EnumSet.noneOf(LintCategory.class);
private EnumSet<LintCategory> silentLintSet = EnumSet.noneOf(LintCategory.class);
public DiagnosticPosition pos() {
return pos;
}
public void warn(LintCategory lint) {
nonSilentLintSet.add(lint);
}
public void silentWarn(LintCategory lint) {
silentLintSet.add(lint);
}
public Warner(DiagnosticPosition pos) {
this.pos = pos;
}
public boolean hasSilentLint(LintCategory lint) {
return silentLintSet.contains(lint);
}
public boolean hasNonSilentLint(LintCategory lint) {
return nonSilentLintSet.contains(lint);
}
public boolean hasLint(LintCategory lint) {
return hasSilentLint(lint) ||
hasNonSilentLint(lint);
}
public void clear() {
nonSilentLintSet.clear();
silentLintSet.clear();
this.warned = false;
}
public Warner() {
this(null);
}
}
| 2,913 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
FatalError.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/util/FatalError.java | /*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.util;
/** Throwing an instance of this class causes immediate termination
* of the main compiler method. It is used when some non-recoverable
* error has been detected in the compiler environment at runtime.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class FatalError extends Error {
private static final long serialVersionUID = 0;
/** Construct a <code>FatalError</code> with the specified detail message.
* @param d A diagnostic containing the reason for failure.
*/
public FatalError(JCDiagnostic d) {
super(d.toString());
}
/** Construct a <code>FatalError</code> with the specified detail message
* and cause.
* @param d A diagnostic containing the reason for failure.
* @param t An exception causing the error
*/
public FatalError(JCDiagnostic d, Throwable t) {
super(d.toString(), t);
}
/** Construct a <code>FatalError</code> with the specified detail message.
* @param s An English(!) string describing the failure, typically because
* the diagnostic resources are missing.
*/
public FatalError(String s) {
super(s);
}
}
| 2,596 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PathFileManager.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/nio/PathFileManager.java | /*
* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.nio;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
/**
* File manager based on {@linkplain File java.nio.file.Path}.
*
* Eventually, this should be moved to javax.tools.
* Also, JavaCompiler might reasonably provide a method getPathFileManager,
* similar to {@link javax.tools.JavaCompiler#getStandardFileManager
* getStandardFileManager}. However, would need to be handled carefully
* as another forward reference from langtools to jdk.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public interface PathFileManager extends JavaFileManager {
/**
* Get the default file system used to create paths. If no value has been
* set, the default file system is {@link FileSystems#getDefault}.
*/
FileSystem getDefaultFileSystem();
/**
* Set the default file system used to create paths.
* @param fs the default file system used to create any new paths.
*/
void setDefaultFileSystem(FileSystem fs);
/**
* Get file objects representing the given files.
*
* @param paths a list of paths
* @return a list of file objects
* @throws IllegalArgumentException if the list of paths includes
* a directory
*/
Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths(
Iterable<? extends Path> paths);
/**
* Get file objects representing the given paths.
* Convenience method equivalent to:
*
* <pre>
* getJavaFileObjectsFromPaths({@linkplain java.util.Arrays#asList Arrays.asList}(paths))
* </pre>
*
* @param paths an array of paths
* @return a list of file objects
* @throws IllegalArgumentException if the array of files includes
* a directory
* @throws NullPointerException if the given array contains null
* elements
*/
Iterable<? extends JavaFileObject> getJavaFileObjects(Path... paths);
/**
* Return the Path for a file object that has been obtained from this
* file manager.
*
* @param fo A file object that has been obtained from this file manager.
* @return The underlying Path object.
* @throws IllegalArgumentException is the file object was not obtained from
* from this file manager.
*/
Path getPath(FileObject fo);
/**
* Get the search path associated with the given location.
*
* @param location a location
* @return a list of paths or {@code null} if this location has no
* associated search path
* @see #setLocation
*/
Iterable<? extends Path> getLocation(Location location);
/**
* Associate the given search path with the given location. Any
* previous value will be discarded.
*
* @param location a location
* @param searchPath a list of files, if {@code null} use the default
* search path for this location
* @see #getLocation
* @throws IllegalArgumentException if location is an output
* location and searchpath does not contain exactly one element
* @throws IOException if location is an output location and searchpath
* does not represent an existing directory
*/
void setLocation(Location location, Iterable<? extends Path> searchPath) throws IOException;
}
| 4,794 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavacPathFileManager.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/nio/JavacPathFileManager.java | /*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.nio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.lang.model.SourceVersion;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardLocation;
import static java.nio.file.FileVisitOption.*;
import static javax.tools.StandardLocation.*;
import com.sun.tools.javac.file.Paths;
import com.sun.tools.javac.util.BaseFileManager;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import static com.sun.tools.javac.main.OptionName.*;
// NOTE the imports carefully for this compilation unit.
//
// Path: java.nio.file.Path -- the new NIO type for which this file manager exists
//
// Paths: com.sun.tools.javac.file.Paths -- legacy javac type for handling path options
// The other Paths (java.nio.file.Paths) is not used
// NOTE this and related classes depend on new API in JDK 7.
// This requires special handling while bootstrapping the JDK build,
// when these classes might not yet have been compiled. To workaround
// this, the build arranges to make stubs of these classes available
// when compiling this and related classes. The set of stub files
// is specified in make/build.properties.
/**
* Implementation of PathFileManager: a JavaFileManager based on the use
* of java.nio.file.Path.
*
* <p>Just as a Path is somewhat analagous to a File, so too is this
* JavacPathFileManager analogous to JavacFileManager, as it relates to the
* support of FileObjects based on File objects (i.e. just RegularFileObject,
* not ZipFileObject and its variants.)
*
* <p>The default values for the standard locations supported by this file
* manager are the same as the default values provided by JavacFileManager --
* i.e. as determined by the javac.file.Paths class. To override these values,
* call {@link #setLocation}.
*
* <p>To reduce confusion with Path objects, the locations such as "class path",
* "source path", etc, are generically referred to here as "search paths".
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JavacPathFileManager extends BaseFileManager implements PathFileManager {
protected FileSystem defaultFileSystem;
/**
* Create a JavacPathFileManager using a given context, optionally registering
* it as the JavaFileManager for that context.
*/
public JavacPathFileManager(Context context, boolean register, Charset charset) {
super(charset);
if (register)
context.put(JavaFileManager.class, this);
pathsForLocation = new HashMap<Location, PathsForLocation>();
fileSystems = new HashMap<Path,FileSystem>();
setContext(context);
}
/**
* Set the context for JavacPathFileManager.
*/
@Override
protected void setContext(Context context) {
super.setContext(context);
searchPaths = Paths.instance(context);
}
@Override
public FileSystem getDefaultFileSystem() {
if (defaultFileSystem == null)
defaultFileSystem = FileSystems.getDefault();
return defaultFileSystem;
}
@Override
public void setDefaultFileSystem(FileSystem fs) {
defaultFileSystem = fs;
}
@Override
public void flush() throws IOException {
contentCache.clear();
}
@Override
public void close() throws IOException {
for (FileSystem fs: fileSystems.values())
fs.close();
}
@Override
public ClassLoader getClassLoader(Location location) {
nullCheck(location);
Iterable<? extends Path> path = getLocation(location);
if (path == null)
return null;
ListBuffer<URL> lb = new ListBuffer<URL>();
for (Path p: path) {
try {
lb.append(p.toUri().toURL());
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
}
return getClassLoader(lb.toArray(new URL[lb.size()]));
}
@Override
public boolean isDefaultBootClassPath() {
return searchPaths.isDefaultBootClassPath();
}
// <editor-fold defaultstate="collapsed" desc="Location handling">
public boolean hasLocation(Location location) {
return (getLocation(location) != null);
}
public Iterable<? extends Path> getLocation(Location location) {
nullCheck(location);
lazyInitSearchPaths();
PathsForLocation path = pathsForLocation.get(location);
if (path == null && !pathsForLocation.containsKey(location)) {
setDefaultForLocation(location);
path = pathsForLocation.get(location);
}
return path;
}
private Path getOutputLocation(Location location) {
Iterable<? extends Path> paths = getLocation(location);
return (paths == null ? null : paths.iterator().next());
}
public void setLocation(Location location, Iterable<? extends Path> searchPath)
throws IOException
{
nullCheck(location);
lazyInitSearchPaths();
if (searchPath == null) {
setDefaultForLocation(location);
} else {
if (location.isOutputLocation())
checkOutputPath(searchPath);
PathsForLocation pl = new PathsForLocation();
for (Path p: searchPath)
pl.add(p); // TODO -Xlint:path warn if path not found
pathsForLocation.put(location, pl);
}
}
private void checkOutputPath(Iterable<? extends Path> searchPath) throws IOException {
Iterator<? extends Path> pathIter = searchPath.iterator();
if (!pathIter.hasNext())
throw new IllegalArgumentException("empty path for directory");
Path path = pathIter.next();
if (pathIter.hasNext())
throw new IllegalArgumentException("path too long for directory");
if (!isDirectory(path))
throw new IOException(path + ": not a directory");
}
private void setDefaultForLocation(Location locn) {
Collection<File> files = null;
if (locn instanceof StandardLocation) {
switch ((StandardLocation) locn) {
case CLASS_PATH:
files = searchPaths.userClassPath();
break;
case PLATFORM_CLASS_PATH:
files = searchPaths.bootClassPath();
break;
case SOURCE_PATH:
files = searchPaths.sourcePath();
break;
case CLASS_OUTPUT: {
String arg = options.get(D);
files = (arg == null ? null : Collections.singleton(new File(arg)));
break;
}
case SOURCE_OUTPUT: {
String arg = options.get(S);
files = (arg == null ? null : Collections.singleton(new File(arg)));
break;
}
}
}
PathsForLocation pl = new PathsForLocation();
if (files != null) {
for (File f: files)
pl.add(f.toPath());
}
pathsForLocation.put(locn, pl);
}
private void lazyInitSearchPaths() {
if (!inited) {
setDefaultForLocation(PLATFORM_CLASS_PATH);
setDefaultForLocation(CLASS_PATH);
setDefaultForLocation(SOURCE_PATH);
inited = true;
}
}
// where
private boolean inited = false;
private Map<Location, PathsForLocation> pathsForLocation;
private Paths searchPaths;
private static class PathsForLocation extends LinkedHashSet<Path> {
private static final long serialVersionUID = 6788510222394486733L;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="FileObject handling">
@Override
public Path getPath(FileObject fo) {
nullCheck(fo);
if (!(fo instanceof PathFileObject))
throw new IllegalArgumentException();
return ((PathFileObject) fo).getPath();
}
@Override
public boolean isSameFile(FileObject a, FileObject b) {
nullCheck(a);
nullCheck(b);
if (!(a instanceof PathFileObject))
throw new IllegalArgumentException("Not supported: " + a);
if (!(b instanceof PathFileObject))
throw new IllegalArgumentException("Not supported: " + b);
return ((PathFileObject) a).isSameFile((PathFileObject) b);
}
@Override
public Iterable<JavaFileObject> list(Location location,
String packageName, Set<Kind> kinds, boolean recurse)
throws IOException {
// validatePackageName(packageName);
nullCheck(packageName);
nullCheck(kinds);
Iterable<? extends Path> paths = getLocation(location);
if (paths == null)
return List.nil();
ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
for (Path path : paths)
list(path, packageName, kinds, recurse, results);
return results.toList();
}
private void list(Path path, String packageName, final Set<Kind> kinds,
boolean recurse, final ListBuffer<JavaFileObject> results)
throws IOException {
if (!Files.exists(path))
return;
final Path pathDir;
if (isDirectory(path))
pathDir = path;
else {
FileSystem fs = getFileSystem(path);
if (fs == null)
return;
pathDir = fs.getRootDirectories().iterator().next();
}
String sep = path.getFileSystem().getSeparator();
Path packageDir = packageName.isEmpty() ? pathDir
: pathDir.resolve(packageName.replace(".", sep));
if (!Files.exists(packageDir))
return;
/* Alternate impl of list, superceded by use of Files.walkFileTree */
// Deque<Path> queue = new LinkedList<Path>();
// queue.add(packageDir);
//
// Path dir;
// while ((dir = queue.poll()) != null) {
// DirectoryStream<Path> ds = dir.newDirectoryStream();
// try {
// for (Path p: ds) {
// String name = p.getFileName().toString();
// if (isDirectory(p)) {
// if (recurse && SourceVersion.isIdentifier(name)) {
// queue.add(p);
// }
// } else {
// if (kinds.contains(getKind(name))) {
// JavaFileObject fe =
// PathFileObject.createDirectoryPathFileObject(this, p, pathDir);
// results.append(fe);
// }
// }
// }
// } finally {
// ds.close();
// }
// }
int maxDepth = (recurse ? Integer.MAX_VALUE : 1);
Set<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS);
Files.walkFileTree(packageDir, opts, maxDepth,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
Path name = dir.getFileName();
if (name == null || SourceVersion.isIdentifier(name.toString())) // JSR 292?
return FileVisitResult.CONTINUE;
else
return FileVisitResult.SKIP_SUBTREE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isRegularFile() && kinds.contains(getKind(file.getFileName().toString()))) {
JavaFileObject fe =
PathFileObject.createDirectoryPathFileObject(
JavacPathFileManager.this, file, pathDir);
results.append(fe);
}
return FileVisitResult.CONTINUE;
}
});
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths(
Iterable<? extends Path> paths) {
ArrayList<PathFileObject> result;
if (paths instanceof Collection<?>)
result = new ArrayList<PathFileObject>(((Collection<?>)paths).size());
else
result = new ArrayList<PathFileObject>();
for (Path p: paths)
result.add(PathFileObject.createSimplePathFileObject(this, nullCheck(p)));
return result;
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjects(Path... paths) {
return getJavaFileObjectsFromPaths(Arrays.asList(nullCheck(paths)));
}
@Override
public JavaFileObject getJavaFileForInput(Location location,
String className, Kind kind) throws IOException {
return getFileForInput(location, getRelativePath(className, kind));
}
@Override
public FileObject getFileForInput(Location location,
String packageName, String relativeName) throws IOException {
return getFileForInput(location, getRelativePath(packageName, relativeName));
}
private JavaFileObject getFileForInput(Location location, String relativePath)
throws IOException {
for (Path p: getLocation(location)) {
if (isDirectory(p)) {
Path f = resolve(p, relativePath);
if (Files.exists(f))
return PathFileObject.createDirectoryPathFileObject(this, f, p);
} else {
FileSystem fs = getFileSystem(p);
if (fs != null) {
Path file = getPath(fs, relativePath);
if (Files.exists(file))
return PathFileObject.createJarPathFileObject(this, file);
}
}
}
return null;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location,
String className, Kind kind, FileObject sibling) throws IOException {
return getFileForOutput(location, getRelativePath(className, kind), sibling);
}
@Override
public FileObject getFileForOutput(Location location, String packageName,
String relativeName, FileObject sibling)
throws IOException {
return getFileForOutput(location, getRelativePath(packageName, relativeName), sibling);
}
private JavaFileObject getFileForOutput(Location location,
String relativePath, FileObject sibling) {
Path dir = getOutputLocation(location);
if (dir == null) {
if (location == CLASS_OUTPUT) {
Path siblingDir = null;
if (sibling != null && sibling instanceof PathFileObject) {
siblingDir = ((PathFileObject) sibling).getPath().getParent();
}
return PathFileObject.createSiblingPathFileObject(this,
siblingDir.resolve(getBaseName(relativePath)),
relativePath);
} else if (location == SOURCE_OUTPUT) {
dir = getOutputLocation(CLASS_OUTPUT);
}
}
Path file;
if (dir != null) {
file = resolve(dir, relativePath);
return PathFileObject.createDirectoryPathFileObject(this, file, dir);
} else {
file = getPath(getDefaultFileSystem(), relativePath);
return PathFileObject.createSimplePathFileObject(this, file);
}
}
@Override
public String inferBinaryName(Location location, JavaFileObject fo) {
nullCheck(fo);
// Need to match the path semantics of list(location, ...)
Iterable<? extends Path> paths = getLocation(location);
if (paths == null) {
return null;
}
if (!(fo instanceof PathFileObject))
throw new IllegalArgumentException(fo.getClass().getName());
return ((PathFileObject) fo).inferBinaryName(paths);
}
private FileSystem getFileSystem(Path p) throws IOException {
FileSystem fs = fileSystems.get(p);
if (fs == null) {
fs = FileSystems.newFileSystem(p, null);
fileSystems.put(p, fs);
}
return fs;
}
private Map<Path,FileSystem> fileSystems;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Utility methods">
private static String getRelativePath(String className, Kind kind) {
return className.replace(".", "/") + kind.extension;
}
private static String getRelativePath(String packageName, String relativeName) {
return packageName.replace(".", "/") + relativeName;
}
private static String getBaseName(String relativePath) {
int lastSep = relativePath.lastIndexOf("/");
return relativePath.substring(lastSep + 1); // safe if "/" not found
}
private static boolean isDirectory(Path path) throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return attrs.isDirectory();
}
private static Path getPath(FileSystem fs, String relativePath) {
return fs.getPath(relativePath.replace("/", fs.getSeparator()));
}
private static Path resolve(Path base, String relativePath) {
FileSystem fs = base.getFileSystem();
Path rp = fs.getPath(relativePath.replace("/", fs.getSeparator()));
return base.resolve(rp);
}
// </editor-fold>
}
| 19,854 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PathFileObject.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/nio/PathFileObject.java | /*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.nio;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.util.BaseFileManager;
/**
* Implementation of JavaFileObject using java.nio.file API.
*
* <p>PathFileObjects are, for the most part, straightforward wrappers around
* Path objects. The primary complexity is the support for "inferBinaryName".
* This is left as an abstract method, implemented by each of a number of
* different factory methods, which compute the binary name based on
* information available at the time the file object is created.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
abstract class PathFileObject implements JavaFileObject {
private JavacPathFileManager fileManager;
private Path path;
/**
* Create a PathFileObject within a directory, such that the binary name
* can be inferred from the relationship to the parent directory.
*/
static PathFileObject createDirectoryPathFileObject(JavacPathFileManager fileManager,
final Path path, final Path dir) {
return new PathFileObject(fileManager, path) {
@Override
String inferBinaryName(Iterable<? extends Path> paths) {
return toBinaryName(dir.relativize(path));
}
};
}
/**
* Create a PathFileObject in a file system such as a jar file, such that
* the binary name can be inferred from its position within the filesystem.
*/
static PathFileObject createJarPathFileObject(JavacPathFileManager fileManager,
final Path path) {
return new PathFileObject(fileManager, path) {
@Override
String inferBinaryName(Iterable<? extends Path> paths) {
return toBinaryName(path);
}
};
}
/**
* Create a PathFileObject whose binary name can be inferred from the
* relative path to a sibling.
*/
static PathFileObject createSiblingPathFileObject(JavacPathFileManager fileManager,
final Path path, final String relativePath) {
return new PathFileObject(fileManager, path) {
@Override
String inferBinaryName(Iterable<? extends Path> paths) {
return toBinaryName(relativePath, "/");
}
};
}
/**
* Create a PathFileObject whose binary name might be inferred from its
* position on a search path.
*/
static PathFileObject createSimplePathFileObject(JavacPathFileManager fileManager,
final Path path) {
return new PathFileObject(fileManager, path) {
@Override
String inferBinaryName(Iterable<? extends Path> paths) {
Path absPath = path.toAbsolutePath();
for (Path p: paths) {
Path ap = p.toAbsolutePath();
if (absPath.startsWith(ap)) {
try {
Path rp = ap.relativize(absPath);
if (rp != null) // maybe null if absPath same as ap
return toBinaryName(rp);
} catch (IllegalArgumentException e) {
// ignore this p if cannot relativize path to p
}
}
}
return null;
}
};
}
protected PathFileObject(JavacPathFileManager fileManager, Path path) {
fileManager.getClass(); // null check
path.getClass(); // null check
this.fileManager = fileManager;
this.path = path;
}
abstract String inferBinaryName(Iterable<? extends Path> paths);
/**
* Return the Path for this object.
* @return the Path for this object.
*/
Path getPath() {
return path;
}
@Override
public Kind getKind() {
return BaseFileManager.getKind(path.getFileName().toString());
}
@Override
public boolean isNameCompatible(String simpleName, Kind kind) {
simpleName.getClass();
// null check
if (kind == Kind.OTHER && getKind() != kind) {
return false;
}
String sn = simpleName + kind.extension;
String pn = path.getFileName().toString();
if (pn.equals(sn)) {
return true;
}
if (pn.equalsIgnoreCase(sn)) {
try {
// allow for Windows
return path.toRealPath(LinkOption.NOFOLLOW_LINKS).getFileName().toString().equals(sn);
} catch (IOException e) {
}
}
return false;
}
@Override
public NestingKind getNestingKind() {
return null;
}
@Override
public Modifier getAccessLevel() {
return null;
}
@Override
public URI toUri() {
return path.toUri();
}
@Override
public String getName() {
return path.toString();
}
@Override
public InputStream openInputStream() throws IOException {
return Files.newInputStream(path);
}
@Override
public OutputStream openOutputStream() throws IOException {
fileManager.flushCache(this);
ensureParentDirectoriesExist();
return Files.newOutputStream(path);
}
@Override
public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
CharsetDecoder decoder = fileManager.getDecoder(fileManager.getEncodingName(), ignoreEncodingErrors);
return new InputStreamReader(openInputStream(), decoder);
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
CharBuffer cb = fileManager.getCachedContent(this);
if (cb == null) {
InputStream in = openInputStream();
try {
ByteBuffer bb = fileManager.makeByteBuffer(in);
JavaFileObject prev = fileManager.log.useSource(this);
try {
cb = fileManager.decode(bb, ignoreEncodingErrors);
} finally {
fileManager.log.useSource(prev);
}
fileManager.recycleByteBuffer(bb);
if (!ignoreEncodingErrors) {
fileManager.cache(this, cb);
}
} finally {
in.close();
}
}
return cb;
}
@Override
public Writer openWriter() throws IOException {
fileManager.flushCache(this);
ensureParentDirectoriesExist();
return new OutputStreamWriter(Files.newOutputStream(path), fileManager.getEncodingName());
}
@Override
public long getLastModified() {
try {
return Files.getLastModifiedTime(path).toMillis();
} catch (IOException e) {
return -1;
}
}
@Override
public boolean delete() {
try {
Files.delete(path);
return true;
} catch (IOException e) {
return false;
}
}
public boolean isSameFile(PathFileObject other) {
try {
return Files.isSameFile(path, other.path);
} catch (IOException e) {
return false;
}
}
@Override
public boolean equals(Object other) {
return (other instanceof PathFileObject && path.equals(((PathFileObject) other).path));
}
@Override
public int hashCode() {
return path.hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + path + "]";
}
private void ensureParentDirectoriesExist() throws IOException {
Path parent = path.getParent();
if (parent != null)
Files.createDirectories(parent);
}
private long size() {
try {
return Files.size(path);
} catch (IOException e) {
return -1;
}
}
protected static String toBinaryName(Path relativePath) {
return toBinaryName(relativePath.toString(),
relativePath.getFileSystem().getSeparator());
}
protected static String toBinaryName(String relativePath, String sep) {
return removeExtension(relativePath).replace(sep, ".");
}
protected static String removeExtension(String fileName) {
int lastDot = fileName.lastIndexOf(".");
return (lastDot == -1 ? fileName : fileName.substring(0, lastDot));
}
}
| 10,402 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavacTypes.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/model/JavacTypes.java | /*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.model;
import java.util.List;
import java.util.Set;
import java.util.EnumSet;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.util.*;
/**
* Utility methods for operating on types.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
public class JavacTypes implements javax.lang.model.util.Types {
private Symtab syms;
private Types types;
public static JavacTypes instance(Context context) {
JavacTypes instance = context.get(JavacTypes.class);
if (instance == null)
instance = new JavacTypes(context);
return instance;
}
/**
* Public for use only by JavacProcessingEnvironment
*/
protected JavacTypes(Context context) {
setContext(context);
}
/**
* Use a new context. May be called from outside to update
* internal state for a new annotation-processing round.
*/
public void setContext(Context context) {
context.put(JavacTypes.class, this);
syms = Symtab.instance(context);
types = Types.instance(context);
}
public Element asElement(TypeMirror t) {
switch (t.getKind()) {
case DECLARED:
case ERROR:
case TYPEVAR:
Type type = cast(Type.class, t);
return type.asElement();
default:
return null;
}
}
public boolean isSameType(TypeMirror t1, TypeMirror t2) {
return types.isSameType((Type) t1, (Type) t2);
}
public boolean isSubtype(TypeMirror t1, TypeMirror t2) {
validateTypeNotIn(t1, EXEC_OR_PKG);
validateTypeNotIn(t2, EXEC_OR_PKG);
return types.isSubtype((Type) t1, (Type) t2);
}
public boolean isAssignable(TypeMirror t1, TypeMirror t2) {
validateTypeNotIn(t1, EXEC_OR_PKG);
validateTypeNotIn(t2, EXEC_OR_PKG);
return types.isAssignable((Type) t1, (Type) t2);
}
public boolean contains(TypeMirror t1, TypeMirror t2) {
validateTypeNotIn(t1, EXEC_OR_PKG);
validateTypeNotIn(t2, EXEC_OR_PKG);
return types.containsType((Type) t1, (Type) t2);
}
public boolean isSubsignature(ExecutableType m1, ExecutableType m2) {
return types.isSubSignature((Type) m1, (Type) m2);
}
public List<Type> directSupertypes(TypeMirror t) {
validateTypeNotIn(t, EXEC_OR_PKG);
Type type = (Type) t;
Type sup = types.supertype(type);
return (sup == Type.noType || sup == type || sup == null)
? types.interfaces(type)
: types.interfaces(type).prepend(sup);
}
public TypeMirror erasure(TypeMirror t) {
if (t.getKind() == TypeKind.PACKAGE)
throw new IllegalArgumentException(t.toString());
return types.erasure((Type) t);
}
public TypeElement boxedClass(PrimitiveType p) {
return types.boxedClass((Type) p);
}
public PrimitiveType unboxedType(TypeMirror t) {
if (t.getKind() != TypeKind.DECLARED)
throw new IllegalArgumentException(t.toString());
Type unboxed = types.unboxedType((Type) t);
if (! unboxed.isPrimitive()) // only true primitives, not void
throw new IllegalArgumentException(t.toString());
return unboxed;
}
public TypeMirror capture(TypeMirror t) {
validateTypeNotIn(t, EXEC_OR_PKG);
return types.capture((Type) t);
}
public PrimitiveType getPrimitiveType(TypeKind kind) {
switch (kind) {
case BOOLEAN: return syms.booleanType;
case BYTE: return syms.byteType;
case SHORT: return syms.shortType;
case INT: return syms.intType;
case LONG: return syms.longType;
case CHAR: return syms.charType;
case FLOAT: return syms.floatType;
case DOUBLE: return syms.doubleType;
default:
throw new IllegalArgumentException("Not a primitive type: " + kind);
}
}
public NullType getNullType() {
return (NullType) syms.botType;
}
public NoType getNoType(TypeKind kind) {
switch (kind) {
case VOID: return syms.voidType;
case NONE: return Type.noType;
default:
throw new IllegalArgumentException(kind.toString());
}
}
public ArrayType getArrayType(TypeMirror componentType) {
switch (componentType.getKind()) {
case VOID:
case EXECUTABLE:
case WILDCARD: // heh!
case PACKAGE:
throw new IllegalArgumentException(componentType.toString());
}
return new Type.ArrayType((Type) componentType, syms.arrayClass);
}
public WildcardType getWildcardType(TypeMirror extendsBound,
TypeMirror superBound) {
BoundKind bkind;
Type bound;
if (extendsBound == null && superBound == null) {
bkind = BoundKind.UNBOUND;
bound = syms.objectType;
} else if (superBound == null) {
bkind = BoundKind.EXTENDS;
bound = (Type) extendsBound;
} else if (extendsBound == null) {
bkind = BoundKind.SUPER;
bound = (Type) superBound;
} else {
throw new IllegalArgumentException(
"Extends and super bounds cannot both be provided");
}
switch (bound.getKind()) {
case ARRAY:
case DECLARED:
case ERROR:
case TYPEVAR:
return new Type.WildcardType(bound, bkind, syms.boundClass);
default:
throw new IllegalArgumentException(bound.toString());
}
}
public DeclaredType getDeclaredType(TypeElement typeElem,
TypeMirror... typeArgs) {
ClassSymbol sym = (ClassSymbol) typeElem;
if (typeArgs.length == 0)
return (DeclaredType) sym.erasure(types);
if (sym.type.getEnclosingType().isParameterized())
throw new IllegalArgumentException(sym.toString());
return getDeclaredType0(sym.type.getEnclosingType(), sym, typeArgs);
}
public DeclaredType getDeclaredType(DeclaredType enclosing,
TypeElement typeElem,
TypeMirror... typeArgs) {
if (enclosing == null)
return getDeclaredType(typeElem, typeArgs);
ClassSymbol sym = (ClassSymbol) typeElem;
Type outer = (Type) enclosing;
if (outer.tsym != sym.owner.enclClass())
throw new IllegalArgumentException(enclosing.toString());
if (!outer.isParameterized())
return getDeclaredType(typeElem, typeArgs);
return getDeclaredType0(outer, sym, typeArgs);
}
// where
private DeclaredType getDeclaredType0(Type outer,
ClassSymbol sym,
TypeMirror... typeArgs) {
if (typeArgs.length != sym.type.getTypeArguments().length())
throw new IllegalArgumentException(
"Incorrect number of type arguments");
ListBuffer<Type> targs = new ListBuffer<Type>();
for (TypeMirror t : typeArgs) {
if (!(t instanceof ReferenceType || t instanceof WildcardType))
throw new IllegalArgumentException(t.toString());
targs.append((Type) t);
}
// TODO: Would like a way to check that type args match formals.
return (DeclaredType) new Type.ClassType(outer, targs.toList(), sym);
}
/**
* Returns the type of an element when that element is viewed as
* a member of, or otherwise directly contained by, a given type.
* For example,
* when viewed as a member of the parameterized type {@code Set<String>},
* the {@code Set.add} method is an {@code ExecutableType}
* whose parameter is of type {@code String}.
*
* @param containing the containing type
* @param element the element
* @return the type of the element as viewed from the containing type
* @throws IllegalArgumentException if the element is not a valid one
* for the given type
*/
public TypeMirror asMemberOf(DeclaredType containing, Element element) {
Type site = (Type)containing;
Symbol sym = (Symbol)element;
if (types.asSuper(site, sym.getEnclosingElement()) == null)
throw new IllegalArgumentException(sym + "@" + site);
return types.memberType(site, sym);
}
private static final Set<TypeKind> EXEC_OR_PKG =
EnumSet.of(TypeKind.EXECUTABLE, TypeKind.PACKAGE);
/**
* Throws an IllegalArgumentException if a type's kind is one of a set.
*/
private void validateTypeNotIn(TypeMirror t, Set<TypeKind> invalidKinds) {
if (invalidKinds.contains(t.getKind()))
throw new IllegalArgumentException(t.toString());
}
/**
* Returns an object cast to the specified type.
* @throws NullPointerException if the object is {@code null}
* @throws IllegalArgumentException if the object is of the wrong type
*/
private static <T> T cast(Class<T> clazz, Object o) {
if (! clazz.isInstance(o))
throw new IllegalArgumentException(o.toString());
return clazz.cast(o);
}
}
| 11,007 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
FilteredMemberList.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/model/FilteredMemberList.java | /*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.model;
import java.util.AbstractList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol;
import static com.sun.tools.javac.code.Flags.*;
/**
* Utility to construct a view of a symbol's members,
* filtering out unwanted elements such as synthetic ones.
* This view is most efficiently accessed through its iterator() method.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class FilteredMemberList extends AbstractList<Symbol> {
private final Scope scope;
public FilteredMemberList(Scope scope) {
this.scope = scope;
}
public int size() {
int cnt = 0;
for (Scope.Entry e = scope.elems; e != null; e = e.sibling) {
if (!unwanted(e.sym))
cnt++;
}
return cnt;
}
public Symbol get(int index) {
for (Scope.Entry e = scope.elems; e != null; e = e.sibling) {
if (!unwanted(e.sym) && (index-- == 0))
return e.sym;
}
throw new IndexOutOfBoundsException();
}
// A more efficient implementation than AbstractList's.
public Iterator<Symbol> iterator() {
return new Iterator<Symbol>() {
/** The next entry to examine, or null if none. */
private Scope.Entry nextEntry = scope.elems;
private boolean hasNextForSure = false;
public boolean hasNext() {
if (hasNextForSure) {
return true;
}
while (nextEntry != null && unwanted(nextEntry.sym)) {
nextEntry = nextEntry.sibling;
}
hasNextForSure = (nextEntry != null);
return hasNextForSure;
}
public Symbol next() {
if (hasNext()) {
Symbol result = nextEntry.sym;
nextEntry = nextEntry.sibling;
hasNextForSure = false;
return result;
} else {
throw new NoSuchElementException();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Tests whether this is a symbol that should never be seen by
* clients, such as a synthetic class. Returns true for null.
*/
private static boolean unwanted(Symbol s) {
return s == null || (s.flags() & SYNTHETIC) != 0;
}
}
| 3,975 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationProxyMaker.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/model/AnnotationProxyMaker.java | /*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.model;
import com.sun.tools.javac.util.*;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.lang.annotation.*;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import sun.reflect.annotation.*;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.MirroredTypesException;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type.ArrayType;
/**
* A generator of dynamic proxy implementations of
* java.lang.annotation.Annotation.
*
* <p> The "dynamic proxy return form" of an annotation element value is
* the form used by sun.reflect.annotation.AnnotationInvocationHandler.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class AnnotationProxyMaker {
private final Attribute.Compound anno;
private final Class<? extends Annotation> annoType;
private AnnotationProxyMaker(Attribute.Compound anno,
Class<? extends Annotation> annoType) {
this.anno = anno;
this.annoType = annoType;
}
/**
* Returns a dynamic proxy for an annotation mirror.
*/
public static <A extends Annotation> A generateAnnotation(
Attribute.Compound anno, Class<A> annoType) {
AnnotationProxyMaker apm = new AnnotationProxyMaker(anno, annoType);
return annoType.cast(apm.generateAnnotation());
}
/**
* Returns a dynamic proxy for an annotation mirror.
*/
private Annotation generateAnnotation() {
return AnnotationParser.annotationForMap(annoType,
getAllReflectedValues());
}
/**
* Returns a map from element names to their values in "dynamic
* proxy return form". Includes all elements, whether explicit or
* defaulted.
*/
private Map<String, Object> getAllReflectedValues() {
Map<String, Object> res = new LinkedHashMap<String, Object>();
for (Map.Entry<MethodSymbol, Attribute> entry :
getAllValues().entrySet()) {
MethodSymbol meth = entry.getKey();
Object value = generateValue(meth, entry.getValue());
if (value != null) {
res.put(meth.name.toString(), value);
} else {
// Ignore this element. May (properly) lead to
// IncompleteAnnotationException somewhere down the line.
}
}
return res;
}
/**
* Returns a map from element symbols to their values.
* Includes all elements, whether explicit or defaulted.
*/
private Map<MethodSymbol, Attribute> getAllValues() {
Map<MethodSymbol, Attribute> res =
new LinkedHashMap<MethodSymbol, Attribute>();
// First find the default values.
ClassSymbol sym = (ClassSymbol) anno.type.tsym;
for (Scope.Entry e = sym.members().elems; e != null; e = e.sibling) {
if (e.sym.kind == Kinds.MTH) {
MethodSymbol m = (MethodSymbol) e.sym;
Attribute def = m.getDefaultValue();
if (def != null)
res.put(m, def);
}
}
// Next find the explicit values, possibly overriding defaults.
for (Pair<MethodSymbol, Attribute> p : anno.values)
res.put(p.fst, p.snd);
return res;
}
/**
* Converts an element value to its "dynamic proxy return form".
* Returns an exception proxy on some errors, but may return null if
* a useful exception cannot or should not be generated at this point.
*/
private Object generateValue(MethodSymbol meth, Attribute attr) {
ValueVisitor vv = new ValueVisitor(meth);
return vv.getValue(attr);
}
private class ValueVisitor implements Attribute.Visitor {
private MethodSymbol meth; // annotation element being visited
private Class<?> returnClass; // return type of annotation element
private Object value; // value in "dynamic proxy return form"
ValueVisitor(MethodSymbol meth) {
this.meth = meth;
}
Object getValue(Attribute attr) {
Method method; // runtime method of annotation element
try {
method = annoType.getMethod(meth.name.toString());
} catch (NoSuchMethodException e) {
return null;
}
returnClass = method.getReturnType();
attr.accept(this);
if (!(value instanceof ExceptionProxy) &&
!AnnotationType.invocationHandlerReturnType(returnClass)
.isInstance(value)) {
typeMismatch(method, attr);
}
return value;
}
public void visitConstant(Attribute.Constant c) {
value = c.getValue();
}
public void visitClass(Attribute.Class c) {
value = new MirroredTypeExceptionProxy(c.type);
}
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<TypeMirror>();
for (Attribute value : a.values) {
Type elem = ((Attribute.Class) value).type;
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;
}
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void visitEnum(Attribute.Enum e) {
if (returnClass.isEnum()) {
String constName = e.value.toString();
try {
value = Enum.valueOf((Class)returnClass, constName);
} catch (IllegalArgumentException ex) {
value = new EnumConstantNotPresentExceptionProxy(
(Class<Enum<?>>) returnClass, constName);
}
} else {
value = null; // indicates a type mismatch
}
}
public void visitCompound(Attribute.Compound c) {
try {
Class<? extends Annotation> nested =
returnClass.asSubclass(Annotation.class);
value = generateAnnotation(c, nested);
} catch (ClassCastException ex) {
value = null; // indicates a type mismatch
}
}
public void visitError(Attribute.Error e) {
value = null; // indicates a type mismatch
}
/**
* Sets "value" to an ExceptionProxy indicating a type mismatch.
*/
private void typeMismatch(Method method, final Attribute attr) {
class AnnotationTypeMismatchExceptionProxy extends ExceptionProxy {
static final long serialVersionUID = 269;
transient final Method method;
AnnotationTypeMismatchExceptionProxy(Method method) {
this.method = method;
}
public String toString() {
return "<error>"; // eg: @Anno(value=<error>)
}
protected RuntimeException generateException() {
return new AnnotationTypeMismatchException(method,
attr.type.toString());
}
}
value = new AnnotationTypeMismatchExceptionProxy(method);
}
}
/**
* ExceptionProxy for MirroredTypeException.
* The toString, hashCode, and equals methods foward to the underlying
* type.
*/
private static final class MirroredTypeExceptionProxy extends ExceptionProxy {
static final long serialVersionUID = 269;
private transient TypeMirror type;
private final String typeString;
MirroredTypeExceptionProxy(TypeMirror t) {
type = t;
typeString = t.toString();
}
public String toString() {
return typeString;
}
public int hashCode() {
return (type != null ? type : typeString).hashCode();
}
public boolean equals(Object obj) {
return type != null &&
obj instanceof MirroredTypeExceptionProxy &&
type.equals(((MirroredTypeExceptionProxy) obj).type);
}
protected RuntimeException generateException() {
return new MirroredTypeException(type);
}
// Explicitly set all transient fields.
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
type = null;
}
}
/**
* ExceptionProxy for MirroredTypesException.
* The toString, hashCode, and equals methods foward to the underlying
* types.
*/
private static final class MirroredTypesExceptionProxy extends ExceptionProxy {
static final long serialVersionUID = 269;
private transient List<TypeMirror> types;
private final String typeStrings;
MirroredTypesExceptionProxy(List<TypeMirror> ts) {
types = ts;
typeStrings = ts.toString();
}
public String toString() {
return typeStrings;
}
public int hashCode() {
return (types != null ? types : typeStrings).hashCode();
}
public boolean equals(Object obj) {
return types != null &&
obj instanceof MirroredTypesExceptionProxy &&
types.equals(
((MirroredTypesExceptionProxy) obj).types);
}
protected RuntimeException generateException() {
return new MirroredTypesException(types);
}
// Explicitly set all transient fields.
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
types = null;
}
}
}
| 12,877 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavacSourcePosition.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/model/JavacSourcePosition.java | /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.model;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.util.Position;
/**
* Implementation of model API SourcePosition based on javac internal state.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
class JavacSourcePosition {
final JavaFileObject sourcefile;
final int pos;
final Position.LineMap lineMap;
JavacSourcePosition(JavaFileObject sourcefile,
int pos,
Position.LineMap lineMap) {
this.sourcefile = sourcefile;
this.pos = pos;
this.lineMap = (pos != Position.NOPOS) ? lineMap : null;
}
public JavaFileObject getFile() {
return sourcefile;
}
public int getOffset() {
return pos; // makes use of fact that Position.NOPOS == -1
}
public int getLine() {
return (lineMap != null) ? lineMap.getLineNumber(pos) : -1;
}
public int getColumn() {
return (lineMap != null) ? lineMap.getColumnNumber(pos) : -1;
}
public String toString() {
int line = getLine();
return (line > 0)
? sourcefile + ":" + line
: sourcefile.toString();
}
}
| 2,585 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavacElements.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javac/model/JavacElements.java | /*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.model;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.util.Map;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.util.Elements;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.processing.PrintingProcessor;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.Name;
import static javax.lang.model.util.ElementFilter.methodsIn;
/**
* Utility methods for operating on program elements.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
public class JavacElements implements Elements {
private JavaCompiler javaCompiler;
private Symtab syms;
private Names names;
private Types types;
private Enter enter;
public static JavacElements instance(Context context) {
JavacElements instance = context.get(JavacElements.class);
if (instance == null)
instance = new JavacElements(context);
return instance;
}
/**
* Public for use only by JavacProcessingEnvironment
*/
protected JavacElements(Context context) {
setContext(context);
}
/**
* Use a new context. May be called from outside to update
* internal state for a new annotation-processing round.
*/
public void setContext(Context context) {
context.put(JavacElements.class, this);
javaCompiler = JavaCompiler.instance(context);
syms = Symtab.instance(context);
names = Names.instance(context);
types = Types.instance(context);
enter = Enter.instance(context);
}
/**
* An internal-use utility that creates a reified annotation.
*/
public static <A extends Annotation> A getAnnotation(Symbol annotated,
Class<A> annoType) {
if (!annoType.isAnnotation())
throw new IllegalArgumentException("Not an annotation type: "
+ annoType);
String name = annoType.getName();
for (Attribute.Compound anno : annotated.getAnnotationMirrors())
if (name.equals(anno.type.tsym.flatName().toString()))
return AnnotationProxyMaker.generateAnnotation(anno, annoType);
return null;
}
/**
* An internal-use utility that creates a reified annotation.
* This overloaded version take annotation inheritance into account.
*/
public static <A extends Annotation> A getAnnotation(ClassSymbol annotated,
Class<A> annoType) {
boolean inherited = annoType.isAnnotationPresent(Inherited.class);
A result = null;
while (annotated.name != annotated.name.table.names.java_lang_Object) {
result = getAnnotation((Symbol)annotated, annoType);
if (result != null || !inherited)
break;
Type sup = annotated.getSuperclass();
if (sup.tag != TypeTags.CLASS || sup.isErroneous())
break;
annotated = (ClassSymbol) sup.tsym;
}
return result;
}
public PackageSymbol getPackageElement(CharSequence name) {
String strName = name.toString();
if (strName.equals(""))
return syms.unnamedPackage;
return SourceVersion.isName(strName)
? nameToSymbol(strName, PackageSymbol.class)
: null;
}
public ClassSymbol getTypeElement(CharSequence name) {
String strName = name.toString();
return SourceVersion.isName(strName)
? nameToSymbol(strName, ClassSymbol.class)
: null;
}
/**
* Returns a symbol given the type's or packages's canonical name,
* or null if the name isn't found.
*/
private <S extends Symbol> S nameToSymbol(String nameStr, Class<S> clazz) {
Name name = names.fromString(nameStr);
// First check cache.
Symbol sym = (clazz == ClassSymbol.class)
? syms.classes.get(name)
: syms.packages.get(name);
try {
if (sym == null)
sym = javaCompiler.resolveIdent(nameStr);
sym.complete();
return (sym.kind != Kinds.ERR &&
sym.exists() &&
clazz.isInstance(sym) &&
name.equals(sym.getQualifiedName()))
? clazz.cast(sym)
: null;
} catch (CompletionFailure e) {
return null;
}
}
public JavacSourcePosition getSourcePosition(Element e) {
Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e);
if (treeTop == null)
return null;
JCTree tree = treeTop.fst;
JCCompilationUnit toplevel = treeTop.snd;
JavaFileObject sourcefile = toplevel.sourcefile;
if (sourcefile == null)
return null;
return new JavacSourcePosition(sourcefile, tree.pos, toplevel.lineMap);
}
public JavacSourcePosition getSourcePosition(Element e, AnnotationMirror a) {
Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e);
if (treeTop == null)
return null;
JCTree tree = treeTop.fst;
JCCompilationUnit toplevel = treeTop.snd;
JavaFileObject sourcefile = toplevel.sourcefile;
if (sourcefile == null)
return null;
JCTree annoTree = matchAnnoToTree(a, e, tree);
if (annoTree == null)
return null;
return new JavacSourcePosition(sourcefile, annoTree.pos,
toplevel.lineMap);
}
public JavacSourcePosition getSourcePosition(Element e, AnnotationMirror a,
AnnotationValue v) {
// TODO: better accuracy in getSourcePosition(... AnnotationValue)
return getSourcePosition(e, a);
}
/**
* Returns the tree for an annotation given the annotated element
* and the element's own tree. Returns null if the tree cannot be found.
*/
private JCTree matchAnnoToTree(AnnotationMirror findme,
Element e, JCTree tree) {
Symbol sym = cast(Symbol.class, e);
class Vis extends JCTree.Visitor {
List<JCAnnotation> result = null;
public void visitTopLevel(JCCompilationUnit tree) {
result = tree.packageAnnotations;
}
public void visitClassDef(JCClassDecl tree) {
result = tree.mods.annotations;
}
public void visitMethodDef(JCMethodDecl tree) {
result = tree.mods.annotations;
}
public void visitVarDef(JCVariableDecl tree) {
result = tree.mods.annotations;
}
}
Vis vis = new Vis();
tree.accept(vis);
if (vis.result == null)
return null;
return matchAnnoToTree(cast(Attribute.Compound.class, findme),
sym.getAnnotationMirrors(),
vis.result);
}
/**
* Returns the tree for an annotation given a list of annotations
* in which to search (recursively) and their corresponding trees.
* Returns null if the tree cannot be found.
*/
private JCTree matchAnnoToTree(Attribute.Compound findme,
List<Attribute.Compound> annos,
List<JCAnnotation> trees) {
for (Attribute.Compound anno : annos) {
for (JCAnnotation tree : trees) {
JCTree match = matchAnnoToTree(findme, anno, tree);
if (match != null)
return match;
}
}
return null;
}
/**
* Returns the tree for an annotation given an Attribute to
* search (recursively) and its corresponding tree.
* Returns null if the tree cannot be found.
*/
private JCTree matchAnnoToTree(final Attribute.Compound findme,
final Attribute attr,
final JCTree tree) {
if (attr == findme)
return (tree.type.tsym == findme.type.tsym) ? tree : null;
class Vis implements Attribute.Visitor {
JCTree result = null;
public void visitConstant(Attribute.Constant value) {
}
public void visitClass(Attribute.Class clazz) {
}
public void visitCompound(Attribute.Compound anno) {
for (Pair<MethodSymbol, Attribute> pair : anno.values) {
JCExpression expr = scanForAssign(pair.fst, tree);
if (expr != null) {
JCTree match = matchAnnoToTree(findme, pair.snd, expr);
if (match != null) {
result = match;
return;
}
}
}
}
public void visitArray(Attribute.Array array) {
if (tree.getTag() == JCTree.NEWARRAY &&
types.elemtype(array.type).tsym == findme.type.tsym) {
List<JCExpression> elems = ((JCNewArray) tree).elems;
for (Attribute value : array.values) {
if (value == findme) {
result = elems.head;
return;
}
elems = elems.tail;
}
}
}
public void visitEnum(Attribute.Enum e) {
}
public void visitError(Attribute.Error e) {
}
}
Vis vis = new Vis();
attr.accept(vis);
return vis.result;
}
/**
* Scans for a JCAssign node with a LHS matching a given
* symbol, and returns its RHS. Does not scan nested JCAnnotations.
*/
private JCExpression scanForAssign(final MethodSymbol sym,
final JCTree tree) {
class TS extends TreeScanner {
JCExpression result = null;
public void scan(JCTree t) {
if (t != null && result == null)
t.accept(this);
}
public void visitAnnotation(JCAnnotation t) {
if (t == tree)
scan(t.args);
}
public void visitAssign(JCAssign t) {
if (t.lhs.getTag() == JCTree.IDENT) {
JCIdent ident = (JCIdent) t.lhs;
if (ident.sym == sym)
result = t.rhs;
}
}
}
TS scanner = new TS();
tree.accept(scanner);
return scanner.result;
}
/**
* Returns the tree node corresponding to this element, or null
* if none can be found.
*/
public JCTree getTree(Element e) {
Pair<JCTree, ?> treeTop = getTreeAndTopLevel(e);
return (treeTop != null) ? treeTop.fst : null;
}
public String getDocComment(Element e) {
// Our doc comment is contained in a map in our toplevel,
// indexed by our tree. Find our enter environment, which gives
// us our toplevel. It also gives us a tree that contains our
// tree: walk it to find our tree. This is painful.
Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e);
if (treeTop == null)
return null;
JCTree tree = treeTop.fst;
JCCompilationUnit toplevel = treeTop.snd;
if (toplevel.docComments == null)
return null;
return toplevel.docComments.get(tree);
}
public PackageElement getPackageOf(Element e) {
return cast(Symbol.class, e).packge();
}
public boolean isDeprecated(Element e) {
Symbol sym = cast(Symbol.class, e);
return (sym.flags() & Flags.DEPRECATED) != 0;
}
public Name getBinaryName(TypeElement type) {
return cast(TypeSymbol.class, type).flatName();
}
public Map<MethodSymbol, Attribute> getElementValuesWithDefaults(
AnnotationMirror a) {
Attribute.Compound anno = cast(Attribute.Compound.class, a);
DeclaredType annotype = a.getAnnotationType();
Map<MethodSymbol, Attribute> valmap = anno.getElementValues();
for (ExecutableElement ex :
methodsIn(annotype.asElement().getEnclosedElements())) {
MethodSymbol meth = (MethodSymbol) ex;
Attribute defaultValue = meth.getDefaultValue();
if (defaultValue != null && !valmap.containsKey(meth)) {
valmap.put(meth, defaultValue);
}
}
return valmap;
}
/**
* {@inheritDoc}
*/
public FilteredMemberList getAllMembers(TypeElement element) {
Symbol sym = cast(Symbol.class, element);
Scope scope = sym.members().dupUnshared();
List<Type> closure = types.closure(sym.asType());
for (Type t : closure)
addMembers(scope, t);
return new FilteredMemberList(scope);
}
// where
private void addMembers(Scope scope, Type type) {
members:
for (Scope.Entry e = type.asElement().members().elems; e != null; e = e.sibling) {
Scope.Entry overrider = scope.lookup(e.sym.getSimpleName());
while (overrider.scope != null) {
if (overrider.sym.kind == e.sym.kind
&& (overrider.sym.flags() & Flags.SYNTHETIC) == 0)
{
if (overrider.sym.getKind() == ElementKind.METHOD
&& overrides((ExecutableElement)overrider.sym, (ExecutableElement)e.sym, (TypeElement)type.asElement())) {
continue members;
}
}
overrider = overrider.next();
}
boolean derived = e.sym.getEnclosingElement() != scope.owner;
ElementKind kind = e.sym.getKind();
boolean initializer = kind == ElementKind.CONSTRUCTOR
|| kind == ElementKind.INSTANCE_INIT
|| kind == ElementKind.STATIC_INIT;
if (!derived || (!initializer && e.sym.isInheritedIn(scope.owner, types)))
scope.enter(e.sym);
}
}
/**
* Returns all annotations of an element, whether
* inherited or directly present.
*
* @param e the element being examined
* @return all annotations of the element
*/
public List<Attribute.Compound> getAllAnnotationMirrors(Element e) {
Symbol sym = cast(Symbol.class, e);
List<Attribute.Compound> annos = sym.getAnnotationMirrors();
while (sym.getKind() == ElementKind.CLASS) {
Type sup = ((ClassSymbol) sym).getSuperclass();
if (sup.tag != TypeTags.CLASS || sup.isErroneous() ||
sup.tsym == syms.objectType.tsym) {
break;
}
sym = sup.tsym;
List<Attribute.Compound> oldAnnos = annos;
for (Attribute.Compound anno : sym.getAnnotationMirrors()) {
if (isInherited(anno.type) &&
!containsAnnoOfType(oldAnnos, anno.type)) {
annos = annos.prepend(anno);
}
}
}
return annos;
}
/**
* Tests whether an annotation type is @Inherited.
*/
private boolean isInherited(Type annotype) {
for (Attribute.Compound anno : annotype.tsym.getAnnotationMirrors()) {
if (anno.type.tsym == syms.inheritedType.tsym)
return true;
}
return false;
}
/**
* Tests whether a list of annotations contains an annotation
* of a given type.
*/
private static boolean containsAnnoOfType(List<Attribute.Compound> annos,
Type type) {
for (Attribute.Compound anno : annos) {
if (anno.type.tsym == type.tsym)
return true;
}
return false;
}
public boolean hides(Element hiderEl, Element hideeEl) {
Symbol hider = cast(Symbol.class, hiderEl);
Symbol hidee = cast(Symbol.class, hideeEl);
// Fields only hide fields; methods only methods; types only types.
// Names must match. Nothing hides itself (just try it).
if (hider == hidee ||
hider.kind != hidee.kind ||
hider.name != hidee.name) {
return false;
}
// Only static methods can hide other methods.
// Methods only hide methods with matching signatures.
if (hider.kind == Kinds.MTH) {
if (!hider.isStatic() ||
!types.isSubSignature(hider.type, hidee.type)) {
return false;
}
}
// Hider must be in a subclass of hidee's class.
// Note that if M1 hides M2, and M2 hides M3, and M3 is accessible
// in M1's class, then M1 and M2 both hide M3.
ClassSymbol hiderClass = hider.owner.enclClass();
ClassSymbol hideeClass = hidee.owner.enclClass();
if (hiderClass == null || hideeClass == null ||
!hiderClass.isSubClass(hideeClass, types)) {
return false;
}
// Hidee must be accessible in hider's class.
// The method isInheritedIn is poorly named: it checks only access.
return hidee.isInheritedIn(hiderClass, types);
}
public boolean overrides(ExecutableElement riderEl,
ExecutableElement rideeEl, TypeElement typeEl) {
MethodSymbol rider = cast(MethodSymbol.class, riderEl);
MethodSymbol ridee = cast(MethodSymbol.class, rideeEl);
ClassSymbol origin = cast(ClassSymbol.class, typeEl);
return rider.name == ridee.name &&
// not reflexive as per JLS
rider != ridee &&
// we don't care if ridee is static, though that wouldn't
// compile
!rider.isStatic() &&
// Symbol.overrides assumes the following
ridee.isMemberOf(origin, types) &&
// check access and signatures; don't check return types
rider.overrides(ridee, origin, types, false);
}
public String getConstantExpression(Object value) {
return Constants.format(value);
}
/**
* Print a representation of the elements to the given writer in
* the specified order. The main purpose of this method is for
* diagnostics. The exact format of the output is <em>not</em>
* specified and is subject to change.
*
* @param w the writer to print the output to
* @param elements the elements to print
*/
public void printElements(java.io.Writer w, Element... elements) {
for (Element element : elements)
(new PrintingProcessor.PrintingElementVisitor(w, this)).visit(element).flush();
}
public Name getName(CharSequence cs) {
return names.fromString(cs.toString());
}
/**
* Returns the tree node and compilation unit corresponding to this
* element, or null if they can't be found.
*/
private Pair<JCTree, JCCompilationUnit> getTreeAndTopLevel(Element e) {
Symbol sym = cast(Symbol.class, e);
Env<AttrContext> enterEnv = getEnterEnv(sym);
if (enterEnv == null)
return null;
JCTree tree = TreeInfo.declarationFor(sym, enterEnv.tree);
if (tree == null || enterEnv.toplevel == null)
return null;
return new Pair<JCTree,JCCompilationUnit>(tree, enterEnv.toplevel);
}
/**
* Returns the best approximation for the tree node and compilation unit
* corresponding to the given element, annotation and value.
* If the element is null, null is returned.
* If the annotation is null or cannot be found, the tree node and
* compilation unit for the element is returned.
* If the annotation value is null or cannot be found, the tree node and
* compilation unit for the annotation is returned.
*/
public Pair<JCTree, JCCompilationUnit> getTreeAndTopLevel(
Element e, AnnotationMirror a, AnnotationValue v) {
if (e == null)
return null;
Pair<JCTree, JCCompilationUnit> elemTreeTop = getTreeAndTopLevel(e);
if (elemTreeTop == null)
return null;
if (a == null)
return elemTreeTop;
JCTree annoTree = matchAnnoToTree(a, e, elemTreeTop.fst);
if (annoTree == null)
return elemTreeTop;
// 6388543: if v != null, we should search within annoTree to find
// the tree matching v. For now, we ignore v and return the tree of
// the annotation.
return new Pair<JCTree, JCCompilationUnit>(annoTree, elemTreeTop.snd);
}
/**
* Returns a symbol's enter environment, or null if it has none.
*/
private Env<AttrContext> getEnterEnv(Symbol sym) {
// Get enclosing class of sym, or sym itself if it is a class
// or package.
TypeSymbol ts = (sym.kind != Kinds.PCK)
? sym.enclClass()
: (PackageSymbol) sym;
return (ts != null)
? enter.getEnv(ts)
: null;
}
/**
* Returns an object cast to the specified type.
* @throws NullPointerException if the object is {@code null}
* @throws IllegalArgumentException if the object is of the wrong type
*/
private static <T> T cast(Class<T> clazz, Object o) {
if (! clazz.isInstance(o))
throw new IllegalArgumentException(o.toString());
return clazz.cast(o);
}
}
| 24,076 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavadocMemberEnter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/JavadocMemberEnter.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.comp.MemberEnter;
import com.sun.tools.javac.tree.JCTree.*;
/**
* Javadoc's own memberEnter phase does a few things above and beyond that
* done by javac.
* @author Neal Gafter
*/
public class JavadocMemberEnter extends MemberEnter {
public static JavadocMemberEnter instance0(Context context) {
MemberEnter instance = context.get(memberEnterKey);
if (instance == null)
instance = new JavadocMemberEnter(context);
return (JavadocMemberEnter)instance;
}
public static void preRegister(Context context) {
context.put(memberEnterKey, new Context.Factory<MemberEnter>() {
public MemberEnter make(Context c) {
return new JavadocMemberEnter(c);
}
});
}
final DocEnv docenv;
protected JavadocMemberEnter(Context context) {
super(context);
docenv = DocEnv.instance(context);
}
public void visitMethodDef(JCMethodDecl tree) {
super.visitMethodDef(tree);
MethodSymbol meth = tree.sym;
if (meth == null || meth.kind != Kinds.MTH) return;
String docComment = env.toplevel.docComments.get(tree);
Position.LineMap lineMap = env.toplevel.lineMap;
if (meth.isConstructor())
docenv.makeConstructorDoc(meth, docComment, tree, lineMap);
else if (isAnnotationTypeElement(meth))
docenv.makeAnnotationTypeElementDoc(meth, docComment, tree, lineMap);
else
docenv.makeMethodDoc(meth, docComment, tree, lineMap);
}
public void visitVarDef(JCVariableDecl tree) {
super.visitVarDef(tree);
if (tree.sym != null &&
tree.sym.kind == Kinds.VAR &&
!isParameter(tree.sym)) {
String docComment = env.toplevel.docComments.get(tree);
Position.LineMap lineMap = env.toplevel.lineMap;
docenv.makeFieldDoc(tree.sym, docComment, tree, lineMap);
}
}
private static boolean isAnnotationTypeElement(MethodSymbol meth) {
return ClassDocImpl.isAnnotationType(meth.enclClass());
}
private static boolean isParameter(VarSymbol var) {
return (var.flags() & Flags.PARAMETER) != 0;
}
}
| 3,712 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypeMaker.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/TypeMaker.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import com.sun.tools.javac.code.Type.TypeVar;
import com.sun.tools.javac.code.Type.ArrayType;
import com.sun.tools.javac.util.List;
import static com.sun.tools.javac.code.TypeTags.*;
public class TypeMaker {
public static com.sun.javadoc.Type getType(DocEnv env, Type t) {
return getType(env, t, true);
}
/**
* @param errToClassDoc if true, ERROR type results in a ClassDoc;
* false preserves legacy behavior
*/
@SuppressWarnings("fallthrough")
public static com.sun.javadoc.Type getType(DocEnv env, Type t,
boolean errToClassDoc) {
if (env.legacyDoclet) {
t = env.types.erasure(t);
}
switch (t.tag) {
case CLASS:
if (ClassDocImpl.isGeneric((ClassSymbol)t.tsym)) {
return env.getParameterizedType((ClassType)t);
} else {
return env.getClassDoc((ClassSymbol)t.tsym);
}
case WILDCARD:
Type.WildcardType a = (Type.WildcardType)t;
return new WildcardTypeImpl(env, a);
case TYPEVAR: return new TypeVariableImpl(env, (TypeVar)t);
case ARRAY: return new ArrayTypeImpl(env, t);
case BYTE: return PrimitiveType.byteType;
case CHAR: return PrimitiveType.charType;
case SHORT: return PrimitiveType.shortType;
case INT: return PrimitiveType.intType;
case LONG: return PrimitiveType.longType;
case FLOAT: return PrimitiveType.floatType;
case DOUBLE: return PrimitiveType.doubleType;
case BOOLEAN: return PrimitiveType.booleanType;
case VOID: return PrimitiveType.voidType;
case ERROR:
if (errToClassDoc)
return env.getClassDoc((ClassSymbol)t.tsym);
// FALLTHRU
default:
return new PrimitiveType(t.tsym.getQualifiedName().toString());
}
}
/**
* Convert a list of javac types into an array of javadoc types.
*/
public static com.sun.javadoc.Type[] getTypes(DocEnv env, List<Type> ts) {
return getTypes(env, ts, new com.sun.javadoc.Type[ts.length()]);
}
/**
* Like the above version, but use and return the array given.
*/
public static com.sun.javadoc.Type[] getTypes(DocEnv env, List<Type> ts,
com.sun.javadoc.Type res[]) {
int i = 0;
for (Type t : ts) {
res[i++] = getType(env, t);
}
return res;
}
public static String getTypeName(Type t, boolean full) {
switch (t.tag) {
case ARRAY:
StringBuilder s = new StringBuilder();
while (t.tag == ARRAY) {
s.append("[]");
t = ((ArrayType)t).elemtype;
}
s.insert(0, getTypeName(t, full));
return s.toString();
case CLASS:
return ClassDocImpl.getClassName((ClassSymbol)t.tsym, full);
default:
return t.tsym.getQualifiedName().toString();
}
}
/**
* Return the string representation of a type use. Bounds of type
* variables are not included; bounds of wildcard types are.
* Class names are qualified if "full" is true.
*/
static String getTypeString(DocEnv env, Type t, boolean full) {
switch (t.tag) {
case ARRAY:
StringBuilder s = new StringBuilder();
while (t.tag == ARRAY) {
s.append("[]");
t = env.types.elemtype(t);
}
s.insert(0, getTypeString(env, t, full));
return s.toString();
case CLASS:
return ParameterizedTypeImpl.
parameterizedTypeToString(env, (ClassType)t, full);
case WILDCARD:
Type.WildcardType a = (Type.WildcardType)t;
return WildcardTypeImpl.wildcardTypeToString(env, a, full);
default:
return t.tsym.getQualifiedName().toString();
}
}
/**
* Return the formal type parameters of a class or method as an
* angle-bracketed string. Each parameter is a type variable with
* optional bounds. Class names are qualified if "full" is true.
* Return "" if there are no type parameters or we're hiding generics.
*/
static String typeParametersString(DocEnv env, Symbol sym, boolean full) {
if (env.legacyDoclet || sym.type.getTypeArguments().isEmpty()) {
return "";
}
StringBuilder s = new StringBuilder();
for (Type t : sym.type.getTypeArguments()) {
s.append(s.length() == 0 ? "<" : ", ");
s.append(TypeVariableImpl.typeVarToString(env, (TypeVar)t, full));
}
s.append(">");
return s.toString();
}
/**
* Return the actual type arguments of a parameterized type as an
* angle-bracketed string. Class name are qualified if "full" is true.
* Return "" if there are no type arguments or we're hiding generics.
*/
static String typeArgumentsString(DocEnv env, ClassType cl, boolean full) {
if (env.legacyDoclet || cl.getTypeArguments().isEmpty()) {
return "";
}
StringBuilder s = new StringBuilder();
for (Type t : cl.getTypeArguments()) {
s.append(s.length() == 0 ? "<" : ", ");
s.append(getTypeString(env, t, full));
}
s.append(">");
return s.toString();
}
private static class ArrayTypeImpl implements com.sun.javadoc.Type {
Type arrayType;
DocEnv env;
ArrayTypeImpl(DocEnv env, Type arrayType) {
this.env = env;
this.arrayType = arrayType;
}
private com.sun.javadoc.Type skipArraysCache = null;
private com.sun.javadoc.Type skipArrays() {
if (skipArraysCache == null) {
Type t;
for (t = arrayType; t.tag == ARRAY; t = env.types.elemtype(t)) { }
skipArraysCache = TypeMaker.getType(env, t);
}
return skipArraysCache;
}
/**
* Return the type's dimension information, as a string.
* <p>
* For example, a two dimensional array of String returns '[][]'.
*/
public String dimension() {
StringBuilder dimension = new StringBuilder();
for (Type t = arrayType; t.tag == ARRAY; t = env.types.elemtype(t)) {
dimension.append("[]");
}
return dimension.toString();
}
/**
* Return unqualified name of type excluding any dimension information.
* <p>
* For example, a two dimensional array of String returns 'String'.
*/
public String typeName() {
return skipArrays().typeName();
}
/**
* Return qualified name of type excluding any dimension information.
*<p>
* For example, a two dimensional array of String
* returns 'java.lang.String'.
*/
public String qualifiedTypeName() {
return skipArrays().qualifiedTypeName();
}
/**
* Return the simple name of this type excluding any dimension information.
*/
public String simpleTypeName() {
return skipArrays().simpleTypeName();
}
/**
* Return this type as a class. Array dimensions are ignored.
*
* @return a ClassDocImpl if the type is a Class.
* Return null if it is a primitive type..
*/
public ClassDoc asClassDoc() {
return skipArrays().asClassDoc();
}
/**
* Return this type as a <code>ParameterizedType</code> if it
* represents a parameterized type. Array dimensions are ignored.
*/
public ParameterizedType asParameterizedType() {
return skipArrays().asParameterizedType();
}
/**
* Return this type as a <code>TypeVariable</code> if it represents
* a type variable. Array dimensions are ignored.
*/
public TypeVariable asTypeVariable() {
return skipArrays().asTypeVariable();
}
/**
* Return null, as there are no arrays of wildcard types.
*/
public WildcardType asWildcardType() {
return null;
}
/**
* Return this type as an <code>AnnotationTypeDoc</code> if it
* represents an annotation type. Array dimensions are ignored.
*/
public AnnotationTypeDoc asAnnotationTypeDoc() {
return skipArrays().asAnnotationTypeDoc();
}
/**
* Return true if this is an array of a primitive type.
*/
public boolean isPrimitive() {
return skipArrays().isPrimitive();
}
/**
* Return a string representation of the type.
*
* Return name of type including any dimension information.
* <p>
* For example, a two dimensional array of String returns
* <code>String[][]</code>.
*
* @return name of type including any dimension information.
*/
@Override
public String toString() {
return qualifiedTypeName() + dimension();
}
}
}
| 10,893 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationDescImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/AnnotationDescImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Pair;
/**
* Represents an annotation.
* An annotation associates a value with each element of an annotation type.
* Sure it ought to be called "Annotation", but that clashes with
* java.lang.annotation.Annotation.
*
* @author Scott Seligman
* @since 1.5
*/
public class AnnotationDescImpl implements AnnotationDesc {
private final DocEnv env;
private final Attribute.Compound annotation;
AnnotationDescImpl(DocEnv env, Attribute.Compound annotation) {
this.env = env;
this.annotation = annotation;
}
/**
* Returns the annotation type of this annotation.
*/
public AnnotationTypeDoc annotationType() {
ClassSymbol atsym = (ClassSymbol)annotation.type.tsym;
if (annotation.type.isErroneous()) {
env.warning(null, "javadoc.class_not_found", annotation.type.toString());
return new AnnotationTypeDocImpl(env, atsym);
} else {
return (AnnotationTypeDoc)env.getClassDoc(atsym);
}
}
/**
* Returns this annotation's elements and their values.
* Only those explicitly present in the annotation are
* included, not those assuming their default values.
* Returns an empty array if there are none.
*/
public ElementValuePair[] elementValues() {
List<Pair<MethodSymbol,Attribute>> vals = annotation.values;
ElementValuePair res[] = new ElementValuePair[vals.length()];
int i = 0;
for (Pair<MethodSymbol,Attribute> val : vals) {
res[i++] = new ElementValuePairImpl(env, val.fst, val.snd);
}
return res;
}
/**
* 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.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("@");
sb.append(annotation.type.tsym);
ElementValuePair vals[] = elementValues();
if (vals.length > 0) { // omit parens for marker annotation
sb.append('(');
boolean first = true;
for (ElementValuePair val : vals) {
if (!first) {
sb.append(", ");
}
first = false;
String name = val.element().name();
if (vals.length == 1 && name.equals("value")) {
sb.append(val.value());
} else {
sb.append(val);
}
}
sb.append(')');
}
return sb.toString();
}
/**
* Represents an association between an annotation type element
* and one of its values.
*/
public static class ElementValuePairImpl implements ElementValuePair {
private final DocEnv env;
private final MethodSymbol meth;
private final Attribute value;
ElementValuePairImpl(DocEnv env, MethodSymbol meth, Attribute value) {
this.env = env;
this.meth = meth;
this.value = value;
}
/**
* Returns the annotation type element.
*/
public AnnotationTypeElementDoc element() {
return env.getAnnotationTypeElementDoc(meth);
}
/**
* Returns the value associated with the annotation type element.
*/
public AnnotationValue value() {
return new AnnotationValueImpl(env, value);
}
/**
* Returns a string representation of this pair
* of the form "name=value".
*/
@Override
public String toString() {
return meth.name + "=" + value();
}
}
}
| 5,297 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ProgramElementDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ProgramElementDocImpl.java | /*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Position;
import java.lang.reflect.Modifier;
import java.text.CollationKey;
/**
* Represents a java program element: class, interface, field,
* constructor, or method.
* This is an abstract class dealing with information common to
* these elements.
*
* @see MemberDocImpl
* @see ClassDocImpl
*
* @author Robert Field
* @author Neal Gafter (rewrite)
* @author Scott Seligman (generics, enums, annotations)
*/
public abstract class ProgramElementDocImpl
extends DocImpl implements ProgramElementDoc {
private final Symbol sym;
// For source position information.
JCTree tree = null;
Position.LineMap lineMap = null;
// Cache for getModifiers().
private int modifiers = -1;
protected ProgramElementDocImpl(DocEnv env, Symbol sym,
String doc, JCTree tree, Position.LineMap lineMap) {
super(env, doc);
this.sym = sym;
this.tree = tree;
this.lineMap = lineMap;
}
void setTree(JCTree tree) {
this.tree = tree;
}
/**
* Subclasses override to identify the containing class
*/
protected abstract ClassSymbol getContainingClass();
/**
* Returns the flags in terms of javac's flags
*/
abstract protected long getFlags();
/**
* Returns the modifier flags in terms of java.lang.reflect.Modifier.
*/
protected int getModifiers() {
if (modifiers == -1) {
modifiers = DocEnv.translateModifiers(getFlags());
}
return modifiers;
}
/**
* Get the containing class of this program element.
*
* @return a ClassDocImpl for this element's containing class.
* If this is a class with no outer class, return null.
*/
public ClassDoc containingClass() {
if (getContainingClass() == null) {
return null;
}
return env.getClassDoc(getContainingClass());
}
/**
* Return the package that this member is contained in.
* Return "" if in unnamed package.
*/
public PackageDoc containingPackage() {
return env.getPackageDoc(getContainingClass().packge());
}
/**
* Get the modifier specifier integer.
*
* @see java.lang.reflect.Modifier
*/
public int modifierSpecifier() {
int modifiers = getModifiers();
if (isMethod() && containingClass().isInterface())
// Remove the implicit abstract modifier.
return modifiers & ~Modifier.ABSTRACT;
return modifiers;
}
/**
* Get modifiers string.
* <pre>
* Example, for:
* public abstract int foo() { ... }
* modifiers() would return:
* 'public abstract'
* </pre>
* Annotations are not included.
*/
public String modifiers() {
int modifiers = getModifiers();
if (isAnnotationTypeElement() ||
(isMethod() && containingClass().isInterface())) {
// Remove the implicit abstract modifier.
return Modifier.toString(modifiers & ~Modifier.ABSTRACT);
} else {
return Modifier.toString(modifiers);
}
}
/**
* Get the annotations of this program element.
* Return an empty array if there are none.
*/
public AnnotationDesc[] annotations() {
AnnotationDesc res[] = new AnnotationDesc[sym.getAnnotationMirrors().length()];
int i = 0;
for (Attribute.Compound a : sym.getAnnotationMirrors()) {
res[i++] = new AnnotationDescImpl(env, a);
}
return res;
}
/**
* Return true if this program element is public
*/
public boolean isPublic() {
int modifiers = getModifiers();
return Modifier.isPublic(modifiers);
}
/**
* Return true if this program element is protected
*/
public boolean isProtected() {
int modifiers = getModifiers();
return Modifier.isProtected(modifiers);
}
/**
* Return true if this program element is private
*/
public boolean isPrivate() {
int modifiers = getModifiers();
return Modifier.isPrivate(modifiers);
}
/**
* Return true if this program element is package private
*/
public boolean isPackagePrivate() {
return !(isPublic() || isPrivate() || isProtected());
}
/**
* Return true if this program element is static
*/
public boolean isStatic() {
int modifiers = getModifiers();
return Modifier.isStatic(modifiers);
}
/**
* Return true if this program element is final
*/
public boolean isFinal() {
int modifiers = getModifiers();
return Modifier.isFinal(modifiers);
}
/**
* Generate a key for sorting.
*/
CollationKey generateKey() {
String k = name();
// System.out.println("COLLATION KEY FOR " + this + " is \"" + k + "\"");
return env.doclocale.collator.getCollationKey(k);
}
}
| 6,539 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AbstractTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/AbstractTypeImpl.java | /*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Type;
/**
* Abstract implementation of <code>Type</code>, with useful
* defaults for the methods in <code>Type</code> (and a couple from
* <code>ProgramElementDoc</code>).
*
* @author Scott Seligman
* @since 1.5
*/
abstract class AbstractTypeImpl implements com.sun.javadoc.Type {
protected final DocEnv env;
protected final Type type;
protected AbstractTypeImpl(DocEnv env, Type type) {
this.env = env;
this.type = type;
}
public String typeName() {
return type.tsym.name.toString();
}
public String qualifiedTypeName() {
return type.tsym.getQualifiedName().toString();
}
public String simpleTypeName() {
return type.tsym.name.toString();
}
public String name() {
return typeName();
}
public String qualifiedName() {
return qualifiedTypeName();
}
public String toString() {
return qualifiedTypeName();
}
public String dimension() {
return "";
}
public boolean isPrimitive() {
return false;
}
public ClassDoc asClassDoc() {
return null;
}
public TypeVariable asTypeVariable() {
return null;
}
public WildcardType asWildcardType() {
return null;
}
public ParameterizedType asParameterizedType() {
return null;
}
public AnnotationTypeDoc asAnnotationTypeDoc() {
return null;
}
}
| 2,747 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
FieldDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/FieldDocImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.lang.reflect.Modifier;
import com.sun.javadoc.*;
import static com.sun.javadoc.LanguageVersion.*;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.Position;
/**
* Represents a field in a java class.
*
* @see MemberDocImpl
*
* @since 1.2
* @author Robert Field
* @author Neal Gafter (rewrite)
* @author Scott Seligman (generics, enums, annotations)
*/
public class FieldDocImpl extends MemberDocImpl implements FieldDoc {
protected final VarSymbol sym;
/**
* Constructor.
*/
public FieldDocImpl(DocEnv env, VarSymbol sym,
String rawDocs, JCVariableDecl tree, Position.LineMap lineMap) {
super(env, sym, rawDocs, tree, lineMap);
this.sym = sym;
}
/**
* Constructor.
*/
public FieldDocImpl(DocEnv env, VarSymbol sym) {
this(env, sym, null, null, null);
}
/**
* Returns the flags in terms of javac's flags
*/
protected long getFlags() {
return sym.flags();
}
/**
* Identify the containing class
*/
protected ClassSymbol getContainingClass() {
return sym.enclClass();
}
/**
* Get type of this field.
*/
public com.sun.javadoc.Type type() {
return TypeMaker.getType(env, sym.type, false);
}
/**
* Get the value of a constant field.
*
* @return the value of a constant field. The value is
* automatically wrapped in an object if it has a primitive type.
* If the field is not constant, returns null.
*/
public Object constantValue() {
Object result = sym.getConstValue();
if (result != null && sym.type.tag == TypeTags.BOOLEAN)
// javac represents false and true as Integers 0 and 1
result = Boolean.valueOf(((Integer)result).intValue() != 0);
return result;
}
/**
* Get the value of a constant field.
*
* @return the text of a Java language expression whose value
* is the value of the constant. The expression uses no identifiers
* other than primitive literals. If the field is
* not constant, returns null.
*/
public String constantValueExpression() {
return constantValueExpression(constantValue());
}
/**
* A static version of the above.
*/
static String constantValueExpression(Object cb) {
if (cb == null) return null;
if (cb instanceof Character) return sourceForm(((Character)cb).charValue());
if (cb instanceof Byte) return sourceForm(((Byte)cb).byteValue());
if (cb instanceof String) return sourceForm((String)cb);
if (cb instanceof Double) return sourceForm(((Double)cb).doubleValue(), 'd');
if (cb instanceof Float) return sourceForm(((Float)cb).doubleValue(), 'f');
if (cb instanceof Long) return cb + "L";
return cb.toString(); // covers int, short
}
// where
private static String sourceForm(double v, char suffix) {
if (Double.isNaN(v))
return "0" + suffix + "/0" + suffix;
if (v == Double.POSITIVE_INFINITY)
return "1" + suffix + "/0" + suffix;
if (v == Double.NEGATIVE_INFINITY)
return "-1" + suffix + "/0" + suffix;
return v + (suffix == 'f' || suffix == 'F' ? "" + suffix : "");
}
private static String sourceForm(char c) {
StringBuilder buf = new StringBuilder(8);
buf.append('\'');
sourceChar(c, buf);
buf.append('\'');
return buf.toString();
}
private static String sourceForm(byte c) {
return "0x" + Integer.toString(c & 0xff, 16);
}
private static String sourceForm(String s) {
StringBuilder buf = new StringBuilder(s.length() + 5);
buf.append('\"');
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
sourceChar(c, buf);
}
buf.append('\"');
return buf.toString();
}
private static void sourceChar(char c, StringBuilder buf) {
switch (c) {
case '\b': buf.append("\\b"); return;
case '\t': buf.append("\\t"); return;
case '\n': buf.append("\\n"); return;
case '\f': buf.append("\\f"); return;
case '\r': buf.append("\\r"); return;
case '\"': buf.append("\\\""); return;
case '\'': buf.append("\\\'"); return;
case '\\': buf.append("\\\\"); return;
default:
if (isPrintableAscii(c)) {
buf.append(c); return;
}
unicodeEscape(c, buf);
return;
}
}
private static void unicodeEscape(char c, StringBuilder buf) {
final String chars = "0123456789abcdef";
buf.append("\\u");
buf.append(chars.charAt(15 & (c>>12)));
buf.append(chars.charAt(15 & (c>>8)));
buf.append(chars.charAt(15 & (c>>4)));
buf.append(chars.charAt(15 & (c>>0)));
}
private static boolean isPrintableAscii(char c) {
return c >= ' ' && c <= '~';
}
/**
* Return true if this field is included in the active set.
*/
public boolean isIncluded() {
return containingClass().isIncluded() && env.shouldDocument(sym);
}
/**
* Is this Doc item a field (but not an enum constant?
*/
@Override
public boolean isField() {
return !isEnumConstant();
}
/**
* Is this Doc item an enum constant?
* (For legacy doclets, return false.)
*/
@Override
public boolean isEnumConstant() {
return (getFlags() & Flags.ENUM) != 0 &&
!env.legacyDoclet;
}
/**
* Return true if this field is transient
*/
public boolean isTransient() {
return Modifier.isTransient(getModifiers());
}
/**
* Return true if this field is volatile
*/
public boolean isVolatile() {
return Modifier.isVolatile(getModifiers());
}
/**
* Returns true if this field was synthesized by the compiler.
*/
public boolean isSynthetic() {
return (getFlags() & Flags.SYNTHETIC) != 0;
}
/**
* Return the serialField tags in this FieldDocImpl item.
*
* @return an array of <tt>SerialFieldTagImpl</tt> containing all
* <code>@serialField</code> tags.
*/
public SerialFieldTag[] serialFieldTags() {
return comment().serialFieldTags();
}
public String name() {
return sym.name.toString();
}
public String qualifiedName() {
return sym.enclClass().getQualifiedName() + "." + name();
}
/**
* Return the source position of the entity, or null if
* no position is available.
*/
@Override
public SourcePosition position() {
if (sym.enclClass().sourcefile == null) return null;
return SourcePositionImpl.make(sym.enclClass().sourcefile,
(tree==null) ? 0 : tree.pos,
lineMap);
}
}
| 8,731 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
WildcardTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/WildcardTypeImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.util.List;
/**
* Implementation of <code>WildcardType</code>, which
* represents a wildcard type.
*
* @author Scott Seligman
* @since 1.5
*/
public class WildcardTypeImpl extends AbstractTypeImpl implements WildcardType {
WildcardTypeImpl(DocEnv env, Type.WildcardType type) {
super(env, type);
}
/**
* Return the upper bounds of this wildcard type argument
* as given by the <i>extends</i> clause.
* Return an empty array if no such bounds are explicitly given.
*/
public com.sun.javadoc.Type[] extendsBounds() {
return TypeMaker.getTypes(env, getExtendsBounds((Type.WildcardType)type));
}
/**
* Return the lower bounds of this wildcard type argument
* as given by the <i>super</i> clause.
* Return an empty array if no such bounds are explicitly given.
*/
public com.sun.javadoc.Type[] superBounds() {
return TypeMaker.getTypes(env, getSuperBounds((Type.WildcardType)type));
}
/**
* Return the ClassDoc of the erasure of this wildcard type.
*/
@Override
public ClassDoc asClassDoc() {
return env.getClassDoc((ClassSymbol)env.types.erasure(type).tsym);
}
@Override
public WildcardType asWildcardType() {
return this;
}
@Override
public String typeName() { return "?"; }
@Override
public String qualifiedTypeName() { return "?"; }
@Override
public String simpleTypeName() { return "?"; }
@Override
public String toString() {
return wildcardTypeToString(env, (Type.WildcardType)type, true);
}
/**
* Return the string form of a wildcard type ("?") along with any
* "extends" or "super" clause. Delimiting brackets are not
* included. Class names are qualified if "full" is true.
*/
static String wildcardTypeToString(DocEnv env,
Type.WildcardType wildThing, boolean full) {
if (env.legacyDoclet) {
return TypeMaker.getTypeName(env.types.erasure(wildThing), full);
}
StringBuilder s = new StringBuilder("?");
List<Type> bounds = getExtendsBounds(wildThing);
if (bounds.nonEmpty()) {
s.append(" extends ");
} else {
bounds = getSuperBounds(wildThing);
if (bounds.nonEmpty()) {
s.append(" super ");
}
}
boolean first = true; // currently only one bound is allowed
for (Type b : bounds) {
if (!first) {
s.append(" & ");
}
s.append(TypeMaker.getTypeString(env, b, full));
first = false;
}
return s.toString();
}
private static List<Type> getExtendsBounds(Type.WildcardType wild) {
return wild.isSuperBound()
? List.<Type>nil()
: List.of(wild.type);
}
private static List<Type> getSuperBounds(Type.WildcardType wild) {
return wild.isExtendsBound()
? List.<Type>nil()
: List.of(wild.type);
}
}
| 4,506 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ClassDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ClassDocImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import javax.tools.FileObject;
import javax.tools.JavaFileManager.Location;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import com.sun.javadoc.*;
import static com.sun.javadoc.LanguageVersion.*;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Position;
import static com.sun.tools.javac.code.Kinds.*;
/**
* Represents a java class and provides access to information
* about the class, the class' comment and tags, and the
* members of the class. A ClassDocImpl only exists if it was
* processed in this run of javadoc. References to classes
* which may or may not have been processed in this run are
* referred to using Type (which can be converted to ClassDocImpl,
* if possible).
*
* @see Type
*
* @since 1.2
* @author Robert Field
* @author Neal Gafter (rewrite)
* @author Scott Seligman (generics, enums, annotations)
*/
public class ClassDocImpl extends ProgramElementDocImpl implements ClassDoc {
public final ClassType type; // protected->public for debugging
protected final ClassSymbol tsym;
boolean isIncluded = false; // Set in RootDocImpl
private SerializedForm serializedForm;
/**
* Constructor
*/
public ClassDocImpl(DocEnv env, ClassSymbol sym) {
this(env, sym, null, null, null);
}
/**
* Constructor
*/
public ClassDocImpl(DocEnv env, ClassSymbol sym, String documentation,
JCClassDecl tree, Position.LineMap lineMap) {
super(env, sym, documentation, tree, lineMap);
this.type = (ClassType)sym.type;
this.tsym = sym;
}
/**
* Returns the flags in terms of javac's flags
*/
protected long getFlags() {
return getFlags(tsym);
}
/**
* Returns the flags of a ClassSymbol in terms of javac's flags
*/
static long getFlags(ClassSymbol clazz) {
while (true) {
try {
return clazz.flags();
} catch (CompletionFailure ex) {
// quietly ignore completion failures
}
}
}
/**
* Is a ClassSymbol an annotation type?
*/
static boolean isAnnotationType(ClassSymbol clazz) {
return (getFlags(clazz) & Flags.ANNOTATION) != 0;
}
/**
* Identify the containing class
*/
protected ClassSymbol getContainingClass() {
return tsym.owner.enclClass();
}
/**
* Return true if this is a class, not an interface.
*/
@Override
public boolean isClass() {
return !Modifier.isInterface(getModifiers());
}
/**
* Return true if this is a ordinary class,
* not an enumeration, exception, an error, or an interface.
*/
@Override
public boolean isOrdinaryClass() {
if (isEnum() || isInterface() || isAnnotationType()) {
return false;
}
for (Type t = type; t.tag == TypeTags.CLASS; t = env.types.supertype(t)) {
if (t.tsym == env.syms.errorType.tsym ||
t.tsym == env.syms.exceptionType.tsym) {
return false;
}
}
return true;
}
/**
* Return true if this is an enumeration.
* (For legacy doclets, return false.)
*/
@Override
public boolean isEnum() {
return (getFlags() & Flags.ENUM) != 0
&&
!env.legacyDoclet;
}
/**
* Return true if this is an interface, but not an annotation type.
* Overridden by AnnotationTypeDocImpl.
*/
@Override
public boolean isInterface() {
return Modifier.isInterface(getModifiers());
}
/**
* Return true if this is an exception class
*/
@Override
public boolean isException() {
if (isEnum() || isInterface() || isAnnotationType()) {
return false;
}
for (Type t = type; t.tag == TypeTags.CLASS; t = env.types.supertype(t)) {
if (t.tsym == env.syms.exceptionType.tsym) {
return true;
}
}
return false;
}
/**
* Return true if this is an error class
*/
@Override
public boolean isError() {
if (isEnum() || isInterface() || isAnnotationType()) {
return false;
}
for (Type t = type; t.tag == TypeTags.CLASS; t = env.types.supertype(t)) {
if (t.tsym == env.syms.errorType.tsym) {
return true;
}
}
return false;
}
/**
* Return true if this is a throwable class
*/
public boolean isThrowable() {
if (isEnum() || isInterface() || isAnnotationType()) {
return false;
}
for (Type t = type; t.tag == TypeTags.CLASS; t = env.types.supertype(t)) {
if (t.tsym == env.syms.throwableType.tsym) {
return true;
}
}
return false;
}
/**
* Return true if this class is abstract
*/
public boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
/**
* Returns true if this class was synthesized by the compiler.
*/
public boolean isSynthetic() {
return (getFlags() & Flags.SYNTHETIC) != 0;
}
/**
* Return true if this class is included in the active set.
* A ClassDoc is included iff either it is specified on the
* commandline, or if it's containing package is specified
* on the command line, or if it is a member class of an
* included class.
*/
public boolean isIncluded() {
if (isIncluded) {
return true;
}
if (env.shouldDocument(tsym)) {
// Class is nameable from top-level and
// the class and all enclosing classes
// pass the modifier filter.
if (containingPackage().isIncluded()) {
return isIncluded=true;
}
ClassDoc outer = containingClass();
if (outer != null && outer.isIncluded()) {
return isIncluded=true;
}
}
return false;
}
/**
* Return the package that this class is contained in.
*/
@Override
public PackageDoc containingPackage() {
PackageDocImpl p = env.getPackageDoc(tsym.packge());
if (p.setDocPath == false) {
FileObject docPath;
try {
Location location = env.fileManager.hasLocation(StandardLocation.SOURCE_PATH)
? StandardLocation.SOURCE_PATH : StandardLocation.CLASS_PATH;
docPath = env.fileManager.getFileForInput(
location, p.qualifiedName(), "package.html");
} catch (IOException e) {
docPath = null;
}
if (docPath == null) {
// fall back on older semantics of looking in same directory as
// source file for this class
SourcePosition po = position();
if (env.fileManager instanceof StandardJavaFileManager &&
po instanceof SourcePositionImpl) {
URI uri = ((SourcePositionImpl) po).filename.toUri();
if ("file".equals(uri.getScheme())) {
File f = new File(uri);
File dir = f.getParentFile();
if (dir != null) {
File pf = new File(dir, "package.html");
if (pf.exists()) {
StandardJavaFileManager sfm = (StandardJavaFileManager) env.fileManager;
docPath = sfm.getJavaFileObjects(pf).iterator().next();
}
}
}
}
}
p.setDocPath(docPath);
}
return p;
}
/**
* Return the class name without package qualifier - but with
* enclosing class qualifier - as a String.
* <pre>
* Examples:
* for java.util.Hashtable
* return Hashtable
* for java.util.Map.Entry
* return Map.Entry
* </pre>
*/
public String name() {
return getClassName(tsym, false);
}
/**
* Return the qualified class name as a String.
* <pre>
* Example:
* for java.util.Hashtable
* return java.util.Hashtable
* if no qualifier, just return flat name
* </pre>
*/
public String qualifiedName() {
return getClassName(tsym, true);
}
/**
* Return unqualified name of type excluding any dimension information.
* <p>
* For example, a two dimensional array of String returns 'String'.
*/
public String typeName() {
return name();
}
/**
* Return qualified name of type excluding any dimension information.
*<p>
* For example, a two dimensional array of String
* returns 'java.lang.String'.
*/
public String qualifiedTypeName() {
return qualifiedName();
}
/**
* Return the simple name of this type.
*/
public String simpleTypeName() {
return tsym.name.toString();
}
/**
* Return the qualified name and any type parameters.
* Each parameter is a type variable with optional bounds.
*/
@Override
public String toString() {
return classToString(env, tsym, true);
}
/**
* Return the class name as a string. If "full" is true the name is
* qualified, otherwise it is qualified by its enclosing class(es) only.
*/
static String getClassName(ClassSymbol c, boolean full) {
if (full) {
return c.getQualifiedName().toString();
} else {
String n = "";
for ( ; c != null; c = c.owner.enclClass()) {
n = c.name + (n.equals("") ? "" : ".") + n;
}
return n;
}
}
/**
* Return the class name with any type parameters as a string.
* Each parameter is a type variable with optional bounds.
* If "full" is true all names are qualified, otherwise they are
* qualified by their enclosing class(es) only.
*/
static String classToString(DocEnv env, ClassSymbol c, boolean full) {
StringBuilder s = new StringBuilder();
if (!c.isInner()) { // if c is not an inner class
s.append(getClassName(c, full));
} else {
// c is an inner class, so include type params of outer.
ClassSymbol encl = c.owner.enclClass();
s.append(classToString(env, encl, full))
.append('.')
.append(c.name);
}
s.append(TypeMaker.typeParametersString(env, c, full));
return s.toString();
}
/**
* Is this class (or any enclosing class) generic? That is, does
* it have type parameters?
*/
static boolean isGeneric(ClassSymbol c) {
return c.type.allparams().nonEmpty();
}
/**
* Return the formal type parameters of this class or interface.
* Return an empty array if there are none.
*/
public TypeVariable[] typeParameters() {
if (env.legacyDoclet) {
return new TypeVariable[0];
}
TypeVariable res[] = new TypeVariable[type.getTypeArguments().length()];
TypeMaker.getTypes(env, type.getTypeArguments(), res);
return res;
}
/**
* Return the type parameter tags of this class or interface.
*/
public ParamTag[] typeParamTags() {
return (env.legacyDoclet)
? new ParamTag[0]
: comment().typeParamTags();
}
/**
* Return the modifier string for this class. If it's an interface
* exclude 'abstract' keyword from the modifier string
*/
@Override
public String modifiers() {
return Modifier.toString(modifierSpecifier());
}
@Override
public int modifierSpecifier() {
int modifiers = getModifiers();
return (isInterface() || isAnnotationType())
? modifiers & ~Modifier.ABSTRACT
: modifiers;
}
/**
* Return the superclass of this class
*
* @return the ClassDocImpl for the superclass of this class, null
* if there is no superclass.
*/
public ClassDoc superclass() {
if (isInterface() || isAnnotationType()) return null;
if (tsym == env.syms.objectType.tsym) return null;
ClassSymbol c = (ClassSymbol)env.types.supertype(type).tsym;
if (c == null || c == tsym) c = (ClassSymbol)env.syms.objectType.tsym;
return env.getClassDoc(c);
}
/**
* Return the superclass of this class. Return null if this is an
* interface. A superclass is represented by either a
* <code>ClassDoc</code> or a <code>ParameterizedType</code>.
*/
public com.sun.javadoc.Type superclassType() {
if (isInterface() || isAnnotationType() ||
(tsym == env.syms.objectType.tsym))
return null;
Type sup = env.types.supertype(type);
return TypeMaker.getType(env,
(sup != type) ? sup : env.syms.objectType);
}
/**
* Test whether this class is a subclass of the specified class.
*
* @param cd the candidate superclass.
* @return true if cd is a superclass of this class.
*/
public boolean subclassOf(ClassDoc cd) {
return tsym.isSubClass(((ClassDocImpl)cd).tsym, env.types);
}
/**
* Return interfaces implemented by this class or interfaces
* extended by this interface.
*
* @return An array of ClassDocImpl representing the interfaces.
* Return an empty array if there are no interfaces.
*/
public ClassDoc[] interfaces() {
ListBuffer<ClassDocImpl> ta = new ListBuffer<ClassDocImpl>();
for (Type t : env.types.interfaces(type)) {
ta.append(env.getClassDoc((ClassSymbol)t.tsym));
}
//### Cache ta here?
return ta.toArray(new ClassDocImpl[ta.length()]);
}
/**
* Return interfaces implemented by this class or interfaces extended
* by this interface. Includes only directly-declared interfaces, not
* inherited interfaces.
* Return an empty array if there are no interfaces.
*/
public com.sun.javadoc.Type[] interfaceTypes() {
//### Cache result here?
return TypeMaker.getTypes(env, env.types.interfaces(type));
}
/**
* Return fields in class.
* @param filter include only the included fields if filter==true
*/
public FieldDoc[] fields(boolean filter) {
return fields(filter, false);
}
/**
* Return included fields in class.
*/
public FieldDoc[] fields() {
return fields(true, false);
}
/**
* Return the enum constants if this is an enum type.
*/
public FieldDoc[] enumConstants() {
return fields(false, true);
}
/**
* Return fields in class.
* @param filter if true, return only the included fields
* @param enumConstants if true, return the enum constants instead
*/
private FieldDoc[] fields(boolean filter, boolean enumConstants) {
List<FieldDocImpl> fields = List.nil();
for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
if (e.sym != null && e.sym.kind == VAR) {
VarSymbol s = (VarSymbol)e.sym;
boolean isEnum = ((s.flags() & Flags.ENUM) != 0) &&
!env.legacyDoclet;
if (isEnum == enumConstants &&
(!filter || env.shouldDocument(s))) {
fields = fields.prepend(env.getFieldDoc(s));
}
}
}
return fields.toArray(new FieldDocImpl[fields.length()]);
}
/**
* Return methods in class.
* This method is overridden by AnnotationTypeDocImpl.
*
* @param filter include only the included methods if filter==true
* @return an array of MethodDocImpl for representing the visible
* methods in this class. Does not include constructors.
*/
public MethodDoc[] methods(boolean filter) {
Names names = tsym.name.table.names;
List<MethodDocImpl> methods = List.nil();
for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
if (e.sym != null &&
e.sym.kind == Kinds.MTH && e.sym.name != names.init) {
MethodSymbol s = (MethodSymbol)e.sym;
if (!filter || env.shouldDocument(s)) {
methods = methods.prepend(env.getMethodDoc(s));
}
}
}
//### Cache methods here?
return methods.toArray(new MethodDocImpl[methods.length()]);
}
/**
* Return included methods in class.
*
* @return an array of MethodDocImpl for representing the visible
* methods in this class. Does not include constructors.
*/
public MethodDoc[] methods() {
return methods(true);
}
/**
* Return constructors in class.
*
* @param filter include only the included constructors if filter==true
* @return an array of ConstructorDocImpl for representing the visible
* constructors in this class.
*/
public ConstructorDoc[] constructors(boolean filter) {
Names names = tsym.name.table.names;
List<ConstructorDocImpl> constructors = List.nil();
for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
if (e.sym != null &&
e.sym.kind == Kinds.MTH && e.sym.name == names.init) {
MethodSymbol s = (MethodSymbol)e.sym;
if (!filter || env.shouldDocument(s)) {
constructors = constructors.prepend(env.getConstructorDoc(s));
}
}
}
//### Cache constructors here?
return constructors.toArray(new ConstructorDocImpl[constructors.length()]);
}
/**
* Return included constructors in class.
*
* @return an array of ConstructorDocImpl for representing the visible
* constructors in this class.
*/
public ConstructorDoc[] constructors() {
return constructors(true);
}
/**
* Adds all inner classes of this class, and their
* inner classes recursively, to the list l.
*/
void addAllClasses(ListBuffer<ClassDocImpl> l, boolean filtered) {
try {
if (isSynthetic()) return;
// sometimes synthetic classes are not marked synthetic
if (!JavadocTool.isValidClassName(tsym.name.toString())) return;
if (filtered && !env.shouldDocument(tsym)) return;
if (l.contains(this)) return;
l.append(this);
List<ClassDocImpl> more = List.nil();
for (Scope.Entry e = tsym.members().elems; e != null;
e = e.sibling) {
if (e.sym != null && e.sym.kind == Kinds.TYP) {
ClassSymbol s = (ClassSymbol)e.sym;
ClassDocImpl c = env.getClassDoc(s);
if (c.isSynthetic()) continue;
if (c != null) more = more.prepend(c);
}
}
// this extra step preserves the ordering from oldjavadoc
for (; more.nonEmpty(); more=more.tail) {
more.head.addAllClasses(l, filtered);
}
} catch (CompletionFailure e) {
// quietly ignore completion failures
}
}
/**
* Return inner classes within this class.
*
* @param filter include only the included inner classes if filter==true.
* @return an array of ClassDocImpl for representing the visible
* classes defined in this class. Anonymous and local classes
* are not included.
*/
public ClassDoc[] innerClasses(boolean filter) {
ListBuffer<ClassDocImpl> innerClasses = new ListBuffer<ClassDocImpl>();
for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
if (e.sym != null && e.sym.kind == Kinds.TYP) {
ClassSymbol s = (ClassSymbol)e.sym;
if ((s.flags_field & Flags.SYNTHETIC) != 0) continue;
if (!filter || env.isVisible(s)) {
innerClasses.prepend(env.getClassDoc(s));
}
}
}
//### Cache classes here?
return innerClasses.toArray(new ClassDocImpl[innerClasses.length()]);
}
/**
* Return included inner classes within this class.
*
* @return an array of ClassDocImpl for representing the visible
* classes defined in this class. Anonymous and local classes
* are not included.
*/
public ClassDoc[] innerClasses() {
return innerClasses(true);
}
/**
* Find a class within the context of this class.
* Search order: qualified name, in this class (inner),
* in this package, in the class imports, in the package
* imports.
* Return the ClassDocImpl if found, null if not found.
*/
//### The specified search order is not the normal rule the
//### compiler would use. Leave as specified or change it?
public ClassDoc findClass(String className) {
ClassDoc searchResult = searchClass(className);
if (searchResult == null) {
ClassDocImpl enclosingClass = (ClassDocImpl)containingClass();
//Expand search space to include enclosing class.
while (enclosingClass != null && enclosingClass.containingClass() != null) {
enclosingClass = (ClassDocImpl)enclosingClass.containingClass();
}
searchResult = enclosingClass == null ?
null : enclosingClass.searchClass(className);
}
return searchResult;
}
private ClassDoc searchClass(String className) {
Names names = tsym.name.table.names;
// search by qualified name first
ClassDoc cd = env.lookupClass(className);
if (cd != null) {
return cd;
}
// search inner classes
//### Add private entry point to avoid creating array?
//### Replicate code in innerClasses here to avoid consing?
for (ClassDoc icd : innerClasses()) {
if (icd.name().equals(className) ||
//### This is from original javadoc but it looks suspicious to me...
//### I believe it is attempting to compensate for the confused
//### convention of including the nested class qualifiers in the
//### 'name' of the inner class, rather than the true simple name.
icd.name().endsWith("." + className)) {
return icd;
} else {
ClassDoc innercd = ((ClassDocImpl) icd).searchClass(className);
if (innercd != null) {
return innercd;
}
}
}
// check in this package
cd = containingPackage().findClass(className);
if (cd != null) {
return cd;
}
// make sure that this symbol has been completed
if (tsym.completer != null) {
tsym.complete();
}
// search imports
if (tsym.sourcefile != null) {
//### This information is available only for source classes.
Env<AttrContext> compenv = env.enter.getEnv(tsym);
if (compenv == null) return null;
Scope s = compenv.toplevel.namedImportScope;
for (Scope.Entry e = s.lookup(names.fromString(className)); e.scope != null; e = e.next()) {
if (e.sym.kind == Kinds.TYP) {
ClassDoc c = env.getClassDoc((ClassSymbol)e.sym);
return c;
}
}
s = compenv.toplevel.starImportScope;
for (Scope.Entry e = s.lookup(names.fromString(className)); e.scope != null; e = e.next()) {
if (e.sym.kind == Kinds.TYP) {
ClassDoc c = env.getClassDoc((ClassSymbol)e.sym);
return c;
}
}
}
return null; // not found
}
private boolean hasParameterTypes(MethodSymbol method, String[] argTypes) {
if (argTypes == null) {
// wildcard
return true;
}
int i = 0;
List<Type> types = method.type.getParameterTypes();
if (argTypes.length != types.length()) {
return false;
}
for (Type t : types) {
String argType = argTypes[i++];
// For vararg method, "T..." matches type T[].
if (i == argTypes.length) {
argType = argType.replace("...", "[]");
}
if (!hasTypeName(env.types.erasure(t), argType)) { //###(gj)
return false;
}
}
return true;
}
// where
private boolean hasTypeName(Type t, String name) {
return
name.equals(TypeMaker.getTypeName(t, true))
||
name.equals(TypeMaker.getTypeName(t, false))
||
(qualifiedName() + "." + name).equals(TypeMaker.getTypeName(t, true));
}
/**
* Find a method in this class scope.
* Search order: this class, interfaces, superclasses, outerclasses.
* Note that this is not necessarily what the compiler would do!
*
* @param methodName the unqualified name to search for.
* @param paramTypeArray the array of Strings for method parameter types.
* @return the first MethodDocImpl which matches, null if not found.
*/
public MethodDocImpl findMethod(String methodName, String[] paramTypes) {
// Use hash table 'searched' to avoid searching same class twice.
//### It is not clear how this could happen.
return searchMethod(methodName, paramTypes, new HashSet<ClassDocImpl>());
}
private MethodDocImpl searchMethod(String methodName,
String[] paramTypes, Set<ClassDocImpl> searched) {
//### Note that this search is not necessarily what the compiler would do!
Names names = tsym.name.table.names;
// do not match constructors
if (names.init.contentEquals(methodName)) {
return null;
}
ClassDocImpl cdi;
MethodDocImpl mdi;
if (searched.contains(this)) {
return null;
}
searched.add(this);
//DEBUG
/*---------------------------------*
System.out.print("searching " + this + " for " + methodName);
if (paramTypes == null) {
System.out.println("()");
} else {
System.out.print("(");
for (int k=0; k < paramTypes.length; k++) {
System.out.print(paramTypes[k]);
if ((k + 1) < paramTypes.length) {
System.out.print(", ");
}
}
System.out.println(")");
}
*---------------------------------*/
// search current class
Scope.Entry e = tsym.members().lookup(names.fromString(methodName));
//### Using modifier filter here isn't really correct,
//### but emulates the old behavior. Instead, we should
//### apply the normal rules of visibility and inheritance.
if (paramTypes == null) {
// If no parameters specified, we are allowed to return
// any method with a matching name. In practice, the old
// code returned the first method, which is now the last!
// In order to provide textually identical results, we
// attempt to emulate the old behavior.
MethodSymbol lastFound = null;
for (; e.scope != null; e = e.next()) {
if (e.sym.kind == Kinds.MTH) {
//### Should intern methodName as Name.
if (e.sym.name.toString().equals(methodName)) {
lastFound = (MethodSymbol)e.sym;
}
}
}
if (lastFound != null) {
return env.getMethodDoc(lastFound);
}
} else {
for (; e.scope != null; e = e.next()) {
if (e.sym != null &&
e.sym.kind == Kinds.MTH) {
//### Should intern methodName as Name.
if (hasParameterTypes((MethodSymbol)e.sym, paramTypes)) {
return env.getMethodDoc((MethodSymbol)e.sym);
}
}
}
}
//### If we found a MethodDoc above, but which did not pass
//### the modifier filter, we should return failure here!
// search superclass
cdi = (ClassDocImpl)superclass();
if (cdi != null) {
mdi = cdi.searchMethod(methodName, paramTypes, searched);
if (mdi != null) {
return mdi;
}
}
// search interfaces
ClassDoc intf[] = interfaces();
for (int i = 0; i < intf.length; i++) {
cdi = (ClassDocImpl)intf[i];
mdi = cdi.searchMethod(methodName, paramTypes, searched);
if (mdi != null) {
return mdi;
}
}
// search enclosing class
cdi = (ClassDocImpl)containingClass();
if (cdi != null) {
mdi = cdi.searchMethod(methodName, paramTypes, searched);
if (mdi != null) {
return mdi;
}
}
//###(gj) As a temporary measure until type variables are better
//### handled, try again without the parameter types.
//### This should most often find the right method, and occassionally
//### find the wrong one.
//if (paramTypes != null) {
// return findMethod(methodName, null);
//}
return null;
}
/**
* Find constructor in this class.
*
* @param constrName the unqualified name to search for.
* @param paramTypeArray the array of Strings for constructor parameters.
* @return the first ConstructorDocImpl which matches, null if not found.
*/
public ConstructorDoc findConstructor(String constrName,
String[] paramTypes) {
Names names = tsym.name.table.names;
for (Scope.Entry e = tsym.members().lookup(names.fromString("<init>")); e.scope != null; e = e.next()) {
if (e.sym.kind == Kinds.MTH) {
if (hasParameterTypes((MethodSymbol)e.sym, paramTypes)) {
return env.getConstructorDoc((MethodSymbol)e.sym);
}
}
}
//###(gj) As a temporary measure until type variables are better
//### handled, try again without the parameter types.
//### This will often find the right constructor, and occassionally
//### find the wrong one.
//if (paramTypes != null) {
// return findConstructor(constrName, null);
//}
return null;
}
/**
* Find a field in this class scope.
* Search order: this class, outerclasses, interfaces,
* superclasses. IMP: If see tag is defined in an inner class,
* which extends a super class and if outerclass and the super
* class have a visible field in common then Java compiler cribs
* about the ambiguity, but the following code will search in the
* above given search order.
*
* @param fieldName the unqualified name to search for.
* @return the first FieldDocImpl which matches, null if not found.
*/
public FieldDoc findField(String fieldName) {
return searchField(fieldName, new HashSet<ClassDocImpl>());
}
private FieldDocImpl searchField(String fieldName, Set<ClassDocImpl> searched) {
Names names = tsym.name.table.names;
if (searched.contains(this)) {
return null;
}
searched.add(this);
for (Scope.Entry e = tsym.members().lookup(names.fromString(fieldName)); e.scope != null; e = e.next()) {
if (e.sym.kind == Kinds.VAR) {
//### Should intern fieldName as Name.
return env.getFieldDoc((VarSymbol)e.sym);
}
}
//### If we found a FieldDoc above, but which did not pass
//### the modifier filter, we should return failure here!
ClassDocImpl cdi = (ClassDocImpl)containingClass();
if (cdi != null) {
FieldDocImpl fdi = cdi.searchField(fieldName, searched);
if (fdi != null) {
return fdi;
}
}
// search superclass
cdi = (ClassDocImpl)superclass();
if (cdi != null) {
FieldDocImpl fdi = cdi.searchField(fieldName, searched);
if (fdi != null) {
return fdi;
}
}
// search interfaces
ClassDoc intf[] = interfaces();
for (int i = 0; i < intf.length; i++) {
cdi = (ClassDocImpl)intf[i];
FieldDocImpl fdi = cdi.searchField(fieldName, searched);
if (fdi != null) {
return fdi;
}
}
return null;
}
/**
* Get the list of classes declared as imported.
* These are called "single-type-import declarations" in the JLS.
* This method is deprecated in the ClassDoc interface.
*
* @return an array of ClassDocImpl representing the imported classes.
*
* @deprecated Import declarations are implementation details that
* should not be exposed here. In addition, not all imported
* classes are imported through single-type-import declarations.
*/
@Deprecated
public ClassDoc[] importedClasses() {
// information is not available for binary classfiles
if (tsym.sourcefile == null) return new ClassDoc[0];
ListBuffer<ClassDocImpl> importedClasses = new ListBuffer<ClassDocImpl>();
Env<AttrContext> compenv = env.enter.getEnv(tsym);
if (compenv == null) return new ClassDocImpl[0];
Name asterisk = tsym.name.table.names.asterisk;
for (JCTree t : compenv.toplevel.defs) {
if (t.getTag() == JCTree.IMPORT) {
JCTree imp = ((JCImport) t).qualid;
if ((TreeInfo.name(imp) != asterisk) &&
(imp.type.tsym.kind & Kinds.TYP) != 0) {
importedClasses.append(
env.getClassDoc((ClassSymbol)imp.type.tsym));
}
}
}
return importedClasses.toArray(new ClassDocImpl[importedClasses.length()]);
}
/**
* Get the list of packages declared as imported.
* These are called "type-import-on-demand declarations" in the JLS.
* This method is deprecated in the ClassDoc interface.
*
* @return an array of PackageDocImpl representing the imported packages.
*
* ###NOTE: the syntax supports importing all inner classes from a class as well.
* @deprecated Import declarations are implementation details that
* should not be exposed here. In addition, this method's
* return type does not allow for all type-import-on-demand
* declarations to be returned.
*/
@Deprecated
public PackageDoc[] importedPackages() {
// information is not available for binary classfiles
if (tsym.sourcefile == null) return new PackageDoc[0];
ListBuffer<PackageDocImpl> importedPackages = new ListBuffer<PackageDocImpl>();
//### Add the implicit "import java.lang.*" to the result
Names names = tsym.name.table.names;
importedPackages.append(env.getPackageDoc(env.reader.enterPackage(names.java_lang)));
Env<AttrContext> compenv = env.enter.getEnv(tsym);
if (compenv == null) return new PackageDocImpl[0];
for (JCTree t : compenv.toplevel.defs) {
if (t.getTag() == JCTree.IMPORT) {
JCTree imp = ((JCImport) t).qualid;
if (TreeInfo.name(imp) == names.asterisk) {
JCFieldAccess sel = (JCFieldAccess)imp;
Symbol s = sel.selected.type.tsym;
PackageDocImpl pdoc = env.getPackageDoc(s.packge());
if (!importedPackages.contains(pdoc))
importedPackages.append(pdoc);
}
}
}
return importedPackages.toArray(new PackageDocImpl[importedPackages.length()]);
}
/**
* Return the type's dimension information.
* Always return "", as this is not an array type.
*/
public String dimension() {
return "";
}
/**
* Return this type as a class, which it already is.
*/
public ClassDoc asClassDoc() {
return this;
}
/**
* Return null (unless overridden), as this is not an annotation type.
*/
public AnnotationTypeDoc asAnnotationTypeDoc() {
return null;
}
/**
* Return null, as this is not a class instantiation.
*/
public ParameterizedType asParameterizedType() {
return null;
}
/**
* Return null, as this is not a type variable.
*/
public TypeVariable asTypeVariable() {
return null;
}
/**
* Return null, as this is not a wildcard type.
*/
public WildcardType asWildcardType() {
return null;
}
/**
* Return false, as this is not a primitive type.
*/
public boolean isPrimitive() {
return false;
}
//--- Serialization ---
//### These methods ignore modifier filter.
/**
* Return true if this class implements <code>java.io.Serializable</code>.
*
* Since <code>java.io.Externalizable</code> extends
* <code>java.io.Serializable</code>,
* Externalizable objects are also Serializable.
*/
public boolean isSerializable() {
try {
return env.types.isSubtype(type, env.syms.serializableType);
} catch (CompletionFailure ex) {
// quietly ignore completion failures
return false;
}
}
/**
* Return true if this class implements
* <code>java.io.Externalizable</code>.
*/
public boolean isExternalizable() {
try {
return env.types.isSubtype(type, env.externalizableSym.type);
} catch (CompletionFailure ex) {
// quietly ignore completion failures
return false;
}
}
/**
* Return the serialization methods for this class.
*
* @return an array of <code>MethodDocImpl</code> that represents
* the serialization methods for this class.
*/
public MethodDoc[] serializationMethods() {
if (serializedForm == null) {
serializedForm = new SerializedForm(env, tsym, this);
}
//### Clone this?
return serializedForm.methods();
}
/**
* Return the Serializable fields of class.<p>
*
* Return either a list of default fields documented by
* <code>serial</code> tag<br>
* or return a single <code>FieldDoc</code> for
* <code>serialPersistentField</code> member.
* There should be a <code>serialField</code> tag for
* each Serializable field defined by an <code>ObjectStreamField</code>
* array component of <code>serialPersistentField</code>.
*
* @returns an array of <code>FieldDoc</code> for the Serializable fields
* of this class.
*
* @see #definesSerializableFields()
* @see SerialFieldTagImpl
*/
public FieldDoc[] serializableFields() {
if (serializedForm == null) {
serializedForm = new SerializedForm(env, tsym, this);
}
//### Clone this?
return serializedForm.fields();
}
/**
* Return true if Serializable fields are explicitly defined with
* the special class member <code>serialPersistentFields</code>.
*
* @see #serializableFields()
* @see SerialFieldTagImpl
*/
public boolean definesSerializableFields() {
if (!isSerializable() || isExternalizable()) {
return false;
} else {
if (serializedForm == null) {
serializedForm = new SerializedForm(env, tsym, this);
}
//### Clone this?
return serializedForm.definesSerializableFields();
}
}
/**
* Determine if a class is a RuntimeException.
* <p>
* Used only by ThrowsTagImpl.
*/
boolean isRuntimeException() {
return tsym.isSubClass(env.syms.runtimeExceptionType.tsym, env.types);
}
/**
* Return the source position of the entity, or null if
* no position is available.
*/
@Override
public SourcePosition position() {
if (tsym.sourcefile == null) return null;
return SourcePositionImpl.make(tsym.sourcefile,
(tree==null) ? Position.NOPOS : tree.pos,
lineMap);
}
}
| 43,745 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DocEnv.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/DocEnv.java | /*
* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.lang.reflect.Modifier;
import java.util.*;
import javax.tools.JavaFileManager;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type.ClassType;
import com.sun.tools.javac.comp.Check;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Position;
/**
* Holds the environment for a run of javadoc.
* Holds only the information needed throughout the
* run and not the compiler info that could be GC'ed
* or ported.
*
* @since 1.4
* @author Robert Field
* @author Neal Gafter (rewrite)
* @author Scott Seligman (generics)
*/
public class DocEnv {
protected static final Context.Key<DocEnv> docEnvKey =
new Context.Key<DocEnv>();
public static DocEnv instance(Context context) {
DocEnv instance = context.get(docEnvKey);
if (instance == null)
instance = new DocEnv(context);
return instance;
}
private Messager messager;
DocLocale doclocale;
/** Predefined symbols known to the compiler. */
Symtab syms;
/** Referenced directly in RootDocImpl. */
JavadocClassReader reader;
/** Javadoc's own version of the compiler's enter phase. */
JavadocEnter enter;
/** The name table. */
Names names;
/** The encoding name. */
private String encoding;
final Symbol externalizableSym;
/** Access filter (public, protected, ...). */
protected ModifierFilter showAccess;
/** True if we are using a sentence BreakIterator. */
boolean breakiterator;
/**
* True if we do not want to print any notifications at all.
*/
boolean quiet = false;
Check chk;
Types types;
JavaFileManager fileManager;
/** Allow documenting from class files? */
boolean docClasses = false;
/** Does the doclet only expect pre-1.5 doclet API? */
protected boolean legacyDoclet = true;
/**
* Set this to true if you would like to not emit any errors, warnings and
* notices.
*/
private boolean silent = false;
/**
* Constructor
*
* @param context Context for this javadoc instance.
*/
protected DocEnv(Context context) {
context.put(docEnvKey, this);
messager = Messager.instance0(context);
syms = Symtab.instance(context);
reader = JavadocClassReader.instance0(context);
enter = JavadocEnter.instance0(context);
names = Names.instance(context);
externalizableSym = reader.enterClass(names.fromString("java.io.Externalizable"));
chk = Check.instance(context);
types = Types.instance(context);
fileManager = context.get(JavaFileManager.class);
// Default. Should normally be reset with setLocale.
this.doclocale = new DocLocale(this, "", breakiterator);
}
public void setSilent(boolean silent) {
this.silent = silent;
}
/**
* Look up ClassDoc by qualified name.
*/
public ClassDocImpl lookupClass(String name) {
ClassSymbol c = getClassSymbol(name);
if (c != null) {
return getClassDoc(c);
} else {
return null;
}
}
/**
* Load ClassDoc by qualified name.
*/
public ClassDocImpl loadClass(String name) {
try {
ClassSymbol c = reader.loadClass(names.fromString(name));
return getClassDoc(c);
} catch (CompletionFailure ex) {
chk.completionError(null, ex);
return null;
}
}
/**
* Look up PackageDoc by qualified name.
*/
public PackageDocImpl lookupPackage(String name) {
//### Jing alleges that class check is needed
//### to avoid a compiler bug. Most likely
//### instead a dummy created for error recovery.
//### Should investigate this.
PackageSymbol p = syms.packages.get(names.fromString(name));
ClassSymbol c = getClassSymbol(name);
if (p != null && c == null) {
return getPackageDoc(p);
} else {
return null;
}
}
// where
/** Retrieve class symbol by fully-qualified name.
*/
ClassSymbol getClassSymbol(String name) {
// Name may contain nested class qualification.
// Generate candidate flatnames with successively shorter
// package qualifiers and longer nested class qualifiers.
int nameLen = name.length();
char[] nameChars = name.toCharArray();
int idx = name.length();
for (;;) {
ClassSymbol s = syms.classes.get(names.fromChars(nameChars, 0, nameLen));
if (s != null)
return s; // found it!
idx = name.substring(0, idx).lastIndexOf('.');
if (idx < 0) break;
nameChars[idx] = '$';
}
return null;
}
/**
* Set the locale.
*/
public void setLocale(String localeName) {
// create locale specifics
doclocale = new DocLocale(this, localeName, breakiterator);
// reset Messager if locale has changed.
messager.reset();
}
/** Check whether this member should be documented. */
public boolean shouldDocument(VarSymbol sym) {
long mod = sym.flags();
if ((mod & Flags.SYNTHETIC) != 0) {
return false;
}
return showAccess.checkModifier(translateModifiers(mod));
}
/** Check whether this member should be documented. */
public boolean shouldDocument(MethodSymbol sym) {
long mod = sym.flags();
if ((mod & Flags.SYNTHETIC) != 0) {
return false;
}
return showAccess.checkModifier(translateModifiers(mod));
}
/** check whether this class should be documented. */
public boolean shouldDocument(ClassSymbol sym) {
return
(sym.flags_field&Flags.SYNTHETIC) == 0 && // no synthetics
(docClasses || getClassDoc(sym).tree != null) &&
isVisible(sym);
}
//### Comment below is inaccurate wrt modifier filter testing
/**
* Check the visibility if this is an nested class.
* if this is not a nested class, return true.
* if this is an static visible nested class,
* return true.
* if this is an visible nested class
* if the outer class is visible return true.
* else return false.
* IMPORTANT: This also allows, static nested classes
* to be defined inside an nested class, which is not
* allowed by the compiler. So such an test case will
* not reach upto this method itself, but if compiler
* allows it, then that will go through.
*/
protected boolean isVisible(ClassSymbol sym) {
long mod = sym.flags_field;
if (!showAccess.checkModifier(translateModifiers(mod))) {
return false;
}
ClassSymbol encl = sym.owner.enclClass();
return (encl == null || (mod & Flags.STATIC) != 0 || isVisible(encl));
}
//---------------- print forwarders ----------------//
/**
* Print error message, increment error count.
*
* @param msg message to print.
*/
public void printError(String msg) {
if (silent)
return;
messager.printError(msg);
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
*/
public void error(DocImpl doc, String key) {
if (silent)
return;
messager.error(doc==null ? null : doc.position(), key);
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
*/
public void error(SourcePosition pos, String key) {
if (silent)
return;
messager.error(pos, key);
}
/**
* Print error message, increment error count.
*
* @param msg message to print.
*/
public void printError(SourcePosition pos, String msg) {
if (silent)
return;
messager.printError(pos, msg);
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
* @param a1 first argument
*/
public void error(DocImpl doc, String key, String a1) {
if (silent)
return;
messager.error(doc==null ? null : doc.position(), key, a1);
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
*/
public void error(DocImpl doc, String key, String a1, String a2) {
if (silent)
return;
messager.error(doc==null ? null : doc.position(), key, a1, a2);
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
public void error(DocImpl doc, String key, String a1, String a2, String a3) {
if (silent)
return;
messager.error(doc==null ? null : doc.position(), key, a1, a2, a3);
}
/**
* Print warning message, increment warning count.
*
* @param msg message to print.
*/
public void printWarning(String msg) {
if (silent)
return;
messager.printWarning(msg);
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
*/
public void warning(DocImpl doc, String key) {
if (silent)
return;
messager.warning(doc==null ? null : doc.position(), key);
}
/**
* Print warning message, increment warning count.
*
* @param msg message to print.
*/
public void printWarning(SourcePosition pos, String msg) {
if (silent)
return;
messager.printWarning(pos, msg);
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
* @param a1 first argument
*/
public void warning(DocImpl doc, String key, String a1) {
if (silent)
return;
messager.warning(doc==null ? null : doc.position(), key, a1);
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
*/
public void warning(DocImpl doc, String key, String a1, String a2) {
if (silent)
return;
messager.warning(doc==null ? null : doc.position(), key, a1, a2);
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
public void warning(DocImpl doc, String key, String a1, String a2, String a3) {
if (silent)
return;
messager.warning(doc==null ? null : doc.position(), key, a1, a2, a3);
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
public void warning(DocImpl doc, String key, String a1, String a2, String a3,
String a4) {
if (silent)
return;
messager.warning(doc==null ? null : doc.position(), key, a1, a2, a3, a4);
}
/**
* Print a message.
*
* @param msg message to print.
*/
public void printNotice(String msg) {
if (silent || quiet)
return;
messager.printNotice(msg);
}
/**
* Print a message.
*
* @param key selects message from resource
*/
public void notice(String key) {
if (silent || quiet)
return;
messager.notice(key);
}
/**
* Print a message.
*
* @param msg message to print.
*/
public void printNotice(SourcePosition pos, String msg) {
if (silent || quiet)
return;
messager.printNotice(pos, msg);
}
/**
* Print a message.
*
* @param key selects message from resource
* @param a1 first argument
*/
public void notice(String key, String a1) {
if (silent || quiet)
return;
messager.notice(key, a1);
}
/**
* Print a message.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
*/
public void notice(String key, String a1, String a2) {
if (silent || quiet)
return;
messager.notice(key, a1, a2);
}
/**
* Print a message.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
public void notice(String key, String a1, String a2, String a3) {
if (silent || quiet)
return;
messager.notice(key, a1, a2, a3);
}
/**
* Exit, reporting errors and warnings.
*/
public void exit() {
// Messager should be replaced by a more general
// compilation environment. This can probably
// subsume DocEnv as well.
messager.exit();
}
protected Map<PackageSymbol, PackageDocImpl> packageMap =
new HashMap<PackageSymbol, PackageDocImpl>();
/**
* Return the PackageDoc of this package symbol.
*/
public PackageDocImpl getPackageDoc(PackageSymbol pack) {
PackageDocImpl result = packageMap.get(pack);
if (result != null) return result;
result = new PackageDocImpl(this, pack);
packageMap.put(pack, result);
return result;
}
/**
* Create the PackageDoc (or a subtype) for a package symbol.
*/
void makePackageDoc(PackageSymbol pack, String docComment, JCCompilationUnit tree) {
PackageDocImpl result = packageMap.get(pack);
if (result != null) {
if (docComment != null) result.setRawCommentText(docComment);
if (tree != null) result.setTree(tree);
} else {
result = new PackageDocImpl(this, pack, docComment, tree);
packageMap.put(pack, result);
}
}
protected Map<ClassSymbol, ClassDocImpl> classMap =
new HashMap<ClassSymbol, ClassDocImpl>();
/**
* Return the ClassDoc (or a subtype) of this class symbol.
*/
public ClassDocImpl getClassDoc(ClassSymbol clazz) {
ClassDocImpl result = classMap.get(clazz);
if (result != null) return result;
if (isAnnotationType(clazz)) {
result = new AnnotationTypeDocImpl(this, clazz);
} else {
result = new ClassDocImpl(this, clazz);
}
classMap.put(clazz, result);
return result;
}
/**
* Create the ClassDoc (or a subtype) for a class symbol.
*/
protected void makeClassDoc(ClassSymbol clazz, String docComment, JCClassDecl tree, Position.LineMap lineMap) {
ClassDocImpl result = classMap.get(clazz);
if (result != null) {
if (docComment != null) result.setRawCommentText(docComment);
if (tree != null) result.setTree(tree);
return;
}
if (isAnnotationType(tree)) { // flags of clazz may not yet be set
result = new AnnotationTypeDocImpl(this, clazz, docComment, tree, lineMap);
} else {
result = new ClassDocImpl(this, clazz, docComment, tree, lineMap);
}
classMap.put(clazz, result);
}
protected static boolean isAnnotationType(ClassSymbol clazz) {
return ClassDocImpl.isAnnotationType(clazz);
}
protected static boolean isAnnotationType(JCClassDecl tree) {
return (tree.mods.flags & Flags.ANNOTATION) != 0;
}
protected Map<VarSymbol, FieldDocImpl> fieldMap =
new HashMap<VarSymbol, FieldDocImpl>();
/**
* Return the FieldDoc of this var symbol.
*/
public FieldDocImpl getFieldDoc(VarSymbol var) {
FieldDocImpl result = fieldMap.get(var);
if (result != null) return result;
result = new FieldDocImpl(this, var);
fieldMap.put(var, result);
return result;
}
/**
* Create a FieldDoc for a var symbol.
*/
protected void makeFieldDoc(VarSymbol var, String docComment, JCVariableDecl tree, Position.LineMap lineMap) {
FieldDocImpl result = fieldMap.get(var);
if (result != null) {
if (docComment != null) result.setRawCommentText(docComment);
if (tree != null) result.setTree(tree);
} else {
result = new FieldDocImpl(this, var, docComment, tree, lineMap);
fieldMap.put(var, result);
}
}
protected Map<MethodSymbol, ExecutableMemberDocImpl> methodMap =
new HashMap<MethodSymbol, ExecutableMemberDocImpl>();
/**
* Create a MethodDoc for this MethodSymbol.
* Should be called only on symbols representing methods.
*/
protected void makeMethodDoc(MethodSymbol meth, String docComment,
JCMethodDecl tree, Position.LineMap lineMap) {
MethodDocImpl result = (MethodDocImpl)methodMap.get(meth);
if (result != null) {
if (docComment != null) result.setRawCommentText(docComment);
if (tree != null) result.setTree(tree);
} else {
result = new MethodDocImpl(this, meth, docComment, tree, lineMap);
methodMap.put(meth, result);
}
}
/**
* Return the MethodDoc for a MethodSymbol.
* Should be called only on symbols representing methods.
*/
public MethodDocImpl getMethodDoc(MethodSymbol meth) {
assert !meth.isConstructor() : "not expecting a constructor symbol";
MethodDocImpl result = (MethodDocImpl)methodMap.get(meth);
if (result != null) return result;
result = new MethodDocImpl(this, meth);
methodMap.put(meth, result);
return result;
}
/**
* Create the ConstructorDoc for a MethodSymbol.
* Should be called only on symbols representing constructors.
*/
protected void makeConstructorDoc(MethodSymbol meth, String docComment,
JCMethodDecl tree, Position.LineMap lineMap) {
ConstructorDocImpl result = (ConstructorDocImpl)methodMap.get(meth);
if (result != null) {
if (docComment != null) result.setRawCommentText(docComment);
if (tree != null) result.setTree(tree);
} else {
result = new ConstructorDocImpl(this, meth, docComment, tree, lineMap);
methodMap.put(meth, result);
}
}
/**
* Return the ConstructorDoc for a MethodSymbol.
* Should be called only on symbols representing constructors.
*/
public ConstructorDocImpl getConstructorDoc(MethodSymbol meth) {
assert meth.isConstructor() : "expecting a constructor symbol";
ConstructorDocImpl result = (ConstructorDocImpl)methodMap.get(meth);
if (result != null) return result;
result = new ConstructorDocImpl(this, meth);
methodMap.put(meth, result);
return result;
}
/**
* Create the AnnotationTypeElementDoc for a MethodSymbol.
* Should be called only on symbols representing annotation type elements.
*/
protected void makeAnnotationTypeElementDoc(MethodSymbol meth,
String docComment, JCMethodDecl tree, Position.LineMap lineMap) {
AnnotationTypeElementDocImpl result =
(AnnotationTypeElementDocImpl)methodMap.get(meth);
if (result != null) {
if (docComment != null) result.setRawCommentText(docComment);
if (tree != null) result.setTree(tree);
} else {
result =
new AnnotationTypeElementDocImpl(this, meth, docComment, tree, lineMap);
methodMap.put(meth, result);
}
}
/**
* Return the AnnotationTypeElementDoc for a MethodSymbol.
* Should be called only on symbols representing annotation type elements.
*/
public AnnotationTypeElementDocImpl getAnnotationTypeElementDoc(
MethodSymbol meth) {
AnnotationTypeElementDocImpl result =
(AnnotationTypeElementDocImpl)methodMap.get(meth);
if (result != null) return result;
result = new AnnotationTypeElementDocImpl(this, meth);
methodMap.put(meth, result);
return result;
}
// private Map<ClassType, ParameterizedTypeImpl> parameterizedTypeMap =
// new HashMap<ClassType, ParameterizedTypeImpl>();
/**
* Return the ParameterizedType of this instantiation.
// * ### Could use Type.sameTypeAs() instead of equality matching in hashmap
// * ### to avoid some duplication.
*/
ParameterizedTypeImpl getParameterizedType(ClassType t) {
return new ParameterizedTypeImpl(this, t);
// ParameterizedTypeImpl result = parameterizedTypeMap.get(t);
// if (result != null) return result;
// result = new ParameterizedTypeImpl(this, t);
// parameterizedTypeMap.put(t, result);
// return result;
}
/**
* Set the encoding.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Get the encoding.
*/
public String getEncoding() {
return encoding;
}
/**
* Convert modifier bits from private coding used by
* the compiler to that of java.lang.reflect.Modifier.
*/
static int translateModifiers(long flags) {
int result = 0;
if ((flags & Flags.ABSTRACT) != 0)
result |= Modifier.ABSTRACT;
if ((flags & Flags.FINAL) != 0)
result |= Modifier.FINAL;
if ((flags & Flags.INTERFACE) != 0)
result |= Modifier.INTERFACE;
if ((flags & Flags.NATIVE) != 0)
result |= Modifier.NATIVE;
if ((flags & Flags.PRIVATE) != 0)
result |= Modifier.PRIVATE;
if ((flags & Flags.PROTECTED) != 0)
result |= Modifier.PROTECTED;
if ((flags & Flags.PUBLIC) != 0)
result |= Modifier.PUBLIC;
if ((flags & Flags.STATIC) != 0)
result |= Modifier.STATIC;
if ((flags & Flags.SYNCHRONIZED) != 0)
result |= Modifier.SYNCHRONIZED;
if ((flags & Flags.TRANSIENT) != 0)
result |= Modifier.TRANSIENT;
if ((flags & Flags.VOLATILE) != 0)
result |= Modifier.VOLATILE;
return result;
}
}
| 24,383 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavadocClassReader.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassReader.java | /*
* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.util.EnumSet;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.jvm.ClassReader;
import com.sun.tools.javac.util.Context;
/** Javadoc uses an extended class reader that records package.html entries
* @author Neal Gafter
*/
public class JavadocClassReader extends ClassReader {
public static JavadocClassReader instance0(Context context) {
ClassReader instance = context.get(classReaderKey);
if (instance == null)
instance = new JavadocClassReader(context);
return (JavadocClassReader)instance;
}
public static void preRegister(Context context) {
context.put(classReaderKey, new Context.Factory<ClassReader>() {
public ClassReader make(Context c) {
return new JavadocClassReader(c);
}
});
}
private DocEnv docenv;
private EnumSet<JavaFileObject.Kind> all = EnumSet.of(JavaFileObject.Kind.CLASS,
JavaFileObject.Kind.SOURCE,
JavaFileObject.Kind.HTML);
private EnumSet<JavaFileObject.Kind> noSource = EnumSet.of(JavaFileObject.Kind.CLASS,
JavaFileObject.Kind.HTML);
public JavadocClassReader(Context context) {
super(context, true);
docenv = DocEnv.instance(context);
preferSource = true;
}
/**
* Override getPackageFileKinds to include search for package.html
*/
@Override
protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
return docenv.docClasses ? noSource : all;
}
/**
* Override extraFileActions to check for package documentation
*/
@Override
protected void extraFileActions(PackageSymbol pack, JavaFileObject fo) {
if (fo.isNameCompatible("package", JavaFileObject.Kind.HTML))
docenv.getPackageDoc(pack).setDocPath(fo);
}
}
| 3,286 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SerialFieldTagImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/SerialFieldTagImpl.java | /*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
/**
* Documents a Serializable field defined by an ObjectStreamField.
* <pre>
* The class parses and stores the three serialField tag parameters:
*
* - field name
* - field type name
* (fully-qualified or visible from the current import context)
* - description of the valid values for the field
* </pre>
* This tag is only allowed in the javadoc for the special member
* serialPersistentFields.
*
* @author Joe Fialli
* @author Neal Gafter
*
* @see java.io.ObjectStreamField
*/
class SerialFieldTagImpl
extends TagImpl
implements SerialFieldTag, Comparable<Object>
{
//### These could be final, except that the constructor
//### does not set them directly.
private String fieldName; // Required Argument 1 of serialField
private String fieldType; // Required Argument 2 of serialField
private String description; // Optional Remaining Arguments of serialField
private ClassDoc containingClass; // Class containing serialPersistentField member
private ClassDoc fieldTypeDoc; // ClassDocImpl of fieldType
private FieldDocImpl matchingField; // FieldDocImpl with same name as fieldName
/* Constructor. */
SerialFieldTagImpl(DocImpl holder, String name, String text) {
super(holder, name, text);
parseSerialFieldString();
if (holder instanceof MemberDoc) {
containingClass = ((MemberDocImpl)holder).containingClass();
}
}
/*
* The serialField tag is composed of three entities.
*
* serialField serializableFieldName serisliableFieldType
* description of field.
*
* The fieldName and fieldType must be legal Java Identifiers.
*/
private void parseSerialFieldString() {
int len = text.length();
if (len == 0) {
return;
}
// if no white space found
/* Skip white space. */
int inx = 0;
int cp;
for (; inx < len; inx += Character.charCount(cp)) {
cp = text.codePointAt(inx);
if (!Character.isWhitespace(cp)) {
break;
}
}
/* find first word. */
int first = inx;
int last = inx;
cp = text.codePointAt(inx);
if (! Character.isJavaIdentifierStart(cp)) {
docenv().warning(holder,
"tag.serialField.illegal_character",
new String(Character.toChars(cp)), text);
return;
}
for (inx += Character.charCount(cp); inx < len; inx += Character.charCount(cp)) {
cp = text.codePointAt(inx);
if (!Character.isJavaIdentifierPart(cp)) {
break;
}
}
if (inx < len && ! Character.isWhitespace(cp = text.codePointAt(inx))) {
docenv().warning(holder,
"tag.serialField.illegal_character",
new String(Character.toChars(cp)), text);
return;
}
last = inx;
fieldName = text.substring(first, last);
/* Skip white space. */
for (; inx < len; inx += Character.charCount(cp)) {
cp = text.codePointAt(inx);
if (!Character.isWhitespace(cp)) {
break;
}
}
/* find second word. */
first = inx;
last = inx;
for (; inx < len; inx += Character.charCount(cp)) {
cp = text.codePointAt(inx);
if (Character.isWhitespace(cp)) {
break;
}
}
if (inx < len && ! Character.isWhitespace(cp = text.codePointAt(inx))) {
docenv().warning(holder,
"tag.serialField.illegal_character",
new String(Character.toChars(cp)), text);
return;
}
last = inx;
fieldType = text.substring(first, last);
/* Skip leading white space. Rest of string is description for serialField.*/
for (; inx < len; inx += Character.charCount(cp)) {
cp = text.codePointAt(inx);
if (!Character.isWhitespace(cp)) {
break;
}
}
description = text.substring(inx);
}
/**
* return a key for sorting.
*/
String key() {
return fieldName;
}
/*
* Optional. Link this serialField tag to its corrsponding
* field in the class. Note: there is no requirement that
* there be a field in the class that matches serialField tag.
*/
void mapToFieldDocImpl(FieldDocImpl fd) {
matchingField = fd;
}
/**
* Return the serialziable field name.
*/
public String fieldName() {
return fieldName;
}
/**
* Return the field type string.
*/
public String fieldType() {
return fieldType;
}
/**
* Return the ClassDocImpl for field type.
*
* @returns null if no ClassDocImpl for field type is visible from
* containingClass context.
*/
public ClassDoc fieldTypeDoc() {
if (fieldTypeDoc == null && containingClass != null) {
fieldTypeDoc = containingClass.findClass(fieldType);
}
return fieldTypeDoc;
}
/**
* Return the corresponding FieldDocImpl for this SerialFieldTagImpl.
*
* @returns null if no matching FieldDocImpl.
*/
FieldDocImpl getMatchingField() {
return matchingField;
}
/**
* Return the field comment. If there is no serialField comment, return
* javadoc comment of corresponding FieldDocImpl.
*/
public String description() {
if (description.length() == 0 && matchingField != null) {
//check for javadoc comment of corresponding field.
Comment comment = matchingField.comment();
if (comment != null) {
return comment.commentText();
}
}
return description;
}
/**
* Return the kind of this tag.
*/
public String kind() {
return "@serialField";
}
/**
* Convert this object to a string.
*/
public String toString() {
return name + ":" + text;
}
/**
* Compares this Object with the specified Object for order. Returns a
* negative integer, zero, or a positive integer as this Object is less
* than, equal to, or greater than the given Object.
* <p>
* Included to make SerialFieldTagImpl items java.lang.Comparable.
*
* @param obj the <code>Object</code> to be compared.
* @return a negative integer, zero, or a positive integer as this Object
* is less than, equal to, or greater than the given Object.
* @exception ClassCastException the specified Object's type prevents it
* from being compared to this Object.
* @since 1.2
*/
public int compareTo(Object obj) {
return key().compareTo(((SerialFieldTagImpl)obj).key());
}
}
| 8,369 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ModifierFilter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ModifierFilter.java | /*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import static com.sun.tools.javac.code.Flags.*;
/**
* A class whose instances are filters over Modifier bits.
* Filtering is done by returning boolean values.
* Classes, methods and fields can be filtered, or filtering
* can be done directly on modifier bits.
* @see com.sun.tools.javac.code.Flags;
* @author Robert Field
*/
public class ModifierFilter {
/**
* Package private access.
* A "pseudo-" modifier bit that can be used in the
* constructors of this class to specify package private
* access. This is needed since there is no Modifier.PACKAGE.
*/
public static final long PACKAGE = 0x8000000000000000L;
/**
* All access modifiers.
* A short-hand set of modifier bits that can be used in the
* constructors of this class to specify all access modifiers,
* Same as PRIVATE | PROTECTED | PUBLIC | PACKAGE.
*/
public static final long ALL_ACCESS =
PRIVATE | PROTECTED | PUBLIC | PACKAGE;
private long oneOf;
private long must;
private long cannot;
private static final int ACCESS_BITS = PRIVATE | PROTECTED | PUBLIC;
/**
* Constructor - Specify a filter.
*
* @param oneOf If zero, everything passes the filter.
* If non-zero, at least one of the specified
* bits must be on in the modifier bits to
* pass the filter.
*/
public ModifierFilter(long oneOf) {
this(oneOf, 0, 0);
}
/**
* Constructor - Specify a filter.
* For example, the filter below will only pass synchronized
* methods that are private or package private access and are
* not native or static.
* <pre>
* ModifierFilter( Modifier.PRIVATE | ModifierFilter.PACKAGE,
* Modifier.SYNCHRONIZED,
* Modifier.NATIVE | Modifier.STATIC)
* </pre><p>
* Each of the three arguments must either be
* zero or the or'ed combination of the bits specified in the
* class Modifier or this class. During filtering, these values
* are compared against the modifier bits as follows:
*
* @param oneOf If zero, ignore this argument.
* If non-zero, at least one of the bits must be on.
* @param must All bits specified must be on.
* @param cannot None of the bits specified can be on.
*/
public ModifierFilter(long oneOf, long must, long cannot) {
this.oneOf = oneOf;
this.must = must;
this.cannot = cannot;
}
/**
* Filter on modifier bits.
*
* @param modifierBits Bits as specified in the Modifier class
*
* @return Whether the modifierBits pass this filter.
*/
public boolean checkModifier(int modifierBits) {
// Add in the "pseudo-" modifier bit PACKAGE, if needed
long fmod = ((modifierBits & ACCESS_BITS) == 0) ?
modifierBits | PACKAGE :
modifierBits;
return ((oneOf == 0) || ((oneOf & fmod) != 0)) &&
((must & fmod) == must) &&
((cannot & fmod) == 0);
}
} // end ModifierFilter
| 4,465 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypeVariableImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/TypeVariableImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.TypeVar;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
/**
* Implementation of <code>TypeVariable</code>, which
* represents a type variable.
*
* @author Scott Seligman
* @since 1.5
*/
public class TypeVariableImpl extends AbstractTypeImpl implements TypeVariable {
TypeVariableImpl(DocEnv env, TypeVar type) {
super(env, type);
}
/**
* Return the bounds of this type variable.
*/
public com.sun.javadoc.Type[] bounds() {
return TypeMaker.getTypes(env, getBounds((TypeVar)type, env));
}
/**
* Return the class, interface, method, or constructor within
* which this type variable is declared.
*/
public ProgramElementDoc owner() {
Symbol osym = type.tsym.owner;
if ((osym.kind & Kinds.TYP) != 0) {
return env.getClassDoc((ClassSymbol)osym);
}
Names names = osym.name.table.names;
if (osym.name == names.init) {
return env.getConstructorDoc((MethodSymbol)osym);
} else {
return env.getMethodDoc((MethodSymbol)osym);
}
}
/**
* Return the ClassDoc of the erasure of this type variable.
*/
@Override
public ClassDoc asClassDoc() {
return env.getClassDoc((ClassSymbol)env.types.erasure(type).tsym);
}
@Override
public TypeVariable asTypeVariable() {
return this;
}
@Override
public String toString() {
return typeVarToString(env, (TypeVar)type, true);
}
/**
* Return the string form of a type variable along with any
* "extends" clause. Class names are qualified if "full" is true.
*/
static String typeVarToString(DocEnv env, TypeVar v, boolean full) {
StringBuilder s = new StringBuilder(v.toString());
List<Type> bounds = getBounds(v, env);
if (bounds.nonEmpty()) {
boolean first = true;
for (Type b : bounds) {
s.append(first ? " extends " : " & ");
s.append(TypeMaker.getTypeString(env, b, full));
first = false;
}
}
return s.toString();
}
/**
* Get the bounds of a type variable as listed in the "extends" clause.
*/
private static List<Type> getBounds(TypeVar v, DocEnv env) {
Name boundname = v.getUpperBound().tsym.getQualifiedName();
if (boundname == boundname.table.names.java_lang_Object) {
return List.nil();
} else {
return env.types.getBounds(v);
}
}
}
| 4,149 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationTypeDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/AnnotationTypeDocImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Position;
/**
* Represents an annotation type.
*
* @author Scott Seligman
* @since 1.5
*/
public class AnnotationTypeDocImpl
extends ClassDocImpl implements AnnotationTypeDoc {
public AnnotationTypeDocImpl(DocEnv env, ClassSymbol sym) {
this(env, sym, null, null, null);
}
public AnnotationTypeDocImpl(DocEnv env, ClassSymbol sym,
String doc, JCClassDecl tree, Position.LineMap lineMap) {
super(env, sym, doc, tree, lineMap);
}
/**
* Returns true, as this is an annotation type.
* (For legacy doclets, return false.)
*/
public boolean isAnnotationType() {
return !isInterface();
}
/**
* Returns false. Though technically an interface, an annotation
* type is not considered an interface for this purpose.
* (For legacy doclets, returns true.)
*/
public boolean isInterface() {
return env.legacyDoclet;
}
/**
* Returns an empty array, as all methods are annotation type elements.
* (For legacy doclets, returns the elements.)
* @see #elements()
*/
public MethodDoc[] methods(boolean filter) {
return env.legacyDoclet
? (MethodDoc[])elements()
: new MethodDoc[0];
}
/**
* Returns the elements of this annotation type.
* Returns an empty array if there are none.
* Elements are always public, so no need to filter them.
*/
public AnnotationTypeElementDoc[] elements() {
Names names = tsym.name.table.names;
List<AnnotationTypeElementDoc> elements = List.nil();
for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
if (e.sym != null && e.sym.kind == Kinds.MTH) {
MethodSymbol s = (MethodSymbol)e.sym;
elements = elements.prepend(env.getAnnotationTypeElementDoc(s));
}
}
return
elements.toArray(new AnnotationTypeElementDoc[elements.length()]);
}
}
| 3,574 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Messager.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/Messager.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
import com.sun.javadoc.*;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log; // Access to 'javac' output streams
/**
* Utility for integrating with javadoc tools and for localization.
* Handle Resources. Access to error and warning counts.
* Message formatting.
* <br>
* Also provides implementation for DocErrorReporter.
*
* @see java.util.ResourceBundle
* @see java.text.MessageFormat
* @author Neal Gafter (rewrite)
*/
public class Messager extends Log implements DocErrorReporter {
/** Get the current messager, which is also the compiler log. */
public static Messager instance0(Context context) {
Log instance = context.get(logKey);
if (instance == null || !(instance instanceof Messager))
throw new InternalError("no messager instance!");
return (Messager)instance;
}
public static void preRegister(Context context,
final String programName) {
context.put(logKey, new Context.Factory<Log>() {
public Log make(Context c) {
return new Messager(c,
programName);
}
});
}
public static void preRegister(Context context,
final String programName,
final PrintWriter errWriter,
final PrintWriter warnWriter,
final PrintWriter noticeWriter) {
context.put(logKey, new Context.Factory<Log>() {
public Log make(Context c) {
return new Messager(c,
programName,
errWriter,
warnWriter,
noticeWriter);
}
});
}
public class ExitJavadoc extends Error {
private static final long serialVersionUID = 0;
}
final String programName;
private ResourceBundle messageRB = null;
/** The default writer for diagnostics
*/
static final PrintWriter defaultErrWriter = new PrintWriter(System.err);
static final PrintWriter defaultWarnWriter = new PrintWriter(System.err);
static final PrintWriter defaultNoticeWriter = new PrintWriter(System.out);
/**
* Constructor
* @param programName Name of the program (for error messages).
*/
protected Messager(Context context, String programName) {
this(context, programName, defaultErrWriter, defaultWarnWriter, defaultNoticeWriter);
}
/**
* Constructor
* @param programName Name of the program (for error messages).
* @param errWriter Stream for error messages
* @param warnWriter Stream for warnings
* @param noticeWriter Stream for other messages
*/
@SuppressWarnings("deprecation")
protected Messager(Context context,
String programName,
PrintWriter errWriter,
PrintWriter warnWriter,
PrintWriter noticeWriter) {
super(context, errWriter, warnWriter, noticeWriter);
this.programName = programName;
}
@Override
protected int getDefaultMaxErrors() {
return Integer.MAX_VALUE;
}
@Override
protected int getDefaultMaxWarnings() {
return Integer.MAX_VALUE;
}
/**
* Reset resource bundle, eg. locale has changed.
*/
public void reset() {
messageRB = null;
}
/**
* Get string from ResourceBundle, initialize ResourceBundle
* if needed.
*/
private String getString(String key) {
if (messageRB == null) {
try {
messageRB = ResourceBundle.getBundle(
"com.sun.tools.javadoc.resources.javadoc");
} catch (MissingResourceException e) {
throw new Error("Fatal: Resource for javadoc is missing");
}
}
return messageRB.getString(key);
}
/**
* get and format message string from resource
*
* @param key selects message from resource
*/
String getText(String key) {
return getText(key, (String)null);
}
/**
* get and format message string from resource
*
* @param key selects message from resource
* @param a1 first argument
*/
String getText(String key, String a1) {
return getText(key, a1, null);
}
/**
* get and format message string from resource
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
*/
String getText(String key, String a1, String a2) {
return getText(key, a1, a2, null);
}
/**
* get and format message string from resource
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
String getText(String key, String a1, String a2, String a3) {
return getText(key, a1, a2, a3, null);
}
/**
* get and format message string from resource
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
* @param a4 fourth argument
*/
String getText(String key, String a1, String a2, String a3,
String a4) {
try {
String message = getString(key);
String[] args = new String[4];
args[0] = a1;
args[1] = a2;
args[2] = a3;
args[3] = a4;
return MessageFormat.format(message, (Object[])args);
} catch (MissingResourceException e) {
return "********** Resource for javadoc is broken. There is no " +
key + " key in resource.";
}
}
/**
* Print error message, increment error count.
* Part of DocErrorReporter.
*
* @param msg message to print
*/
public void printError(String msg) {
printError(null, msg);
}
/**
* Print error message, increment error count.
* Part of DocErrorReporter.
*
* @param pos the position where the error occurs
* @param msg message to print
*/
public void printError(SourcePosition pos, String msg) {
if (nerrors < MaxErrors) {
String prefix = (pos == null) ? programName : pos.toString();
errWriter.println(prefix + ": " + getText("javadoc.error") + " - " + msg);
errWriter.flush();
prompt();
nerrors++;
}
}
/**
* Print warning message, increment warning count.
* Part of DocErrorReporter.
*
* @param msg message to print
*/
public void printWarning(String msg) {
printWarning(null, msg);
}
/**
* Print warning message, increment warning count.
* Part of DocErrorReporter.
*
* @param pos the position where the error occurs
* @param msg message to print
*/
public void printWarning(SourcePosition pos, String msg) {
if (nwarnings < MaxWarnings) {
String prefix = (pos == null) ? programName : pos.toString();
warnWriter.println(prefix + ": " + getText("javadoc.warning") +" - " + msg);
warnWriter.flush();
nwarnings++;
}
}
/**
* Print a message.
* Part of DocErrorReporter.
*
* @param msg message to print
*/
public void printNotice(String msg) {
printNotice(null, msg);
}
/**
* Print a message.
* Part of DocErrorReporter.
*
* @param pos the position where the error occurs
* @param msg message to print
*/
public void printNotice(SourcePosition pos, String msg) {
if (pos == null)
noticeWriter.println(msg);
else
noticeWriter.println(pos + ": " + msg);
noticeWriter.flush();
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
*/
public void error(SourcePosition pos, String key) {
printError(pos, getText(key));
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
* @param a1 first argument
*/
public void error(SourcePosition pos, String key, String a1) {
printError(pos, getText(key, a1));
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
*/
public void error(SourcePosition pos, String key, String a1, String a2) {
printError(pos, getText(key, a1, a2));
}
/**
* Print error message, increment error count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
public void error(SourcePosition pos, String key, String a1, String a2, String a3) {
printError(pos, getText(key, a1, a2, a3));
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
*/
public void warning(SourcePosition pos, String key) {
printWarning(pos, getText(key));
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
* @param a1 first argument
*/
public void warning(SourcePosition pos, String key, String a1) {
printWarning(pos, getText(key, a1));
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
*/
public void warning(SourcePosition pos, String key, String a1, String a2) {
printWarning(pos, getText(key, a1, a2));
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
public void warning(SourcePosition pos, String key, String a1, String a2, String a3) {
printWarning(pos, getText(key, a1, a2, a3));
}
/**
* Print warning message, increment warning count.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
public void warning(SourcePosition pos, String key, String a1, String a2, String a3,
String a4) {
printWarning(pos, getText(key, a1, a2, a3, a4));
}
/**
* Print a message.
*
* @param key selects message from resource
*/
public void notice(String key) {
printNotice(getText(key));
}
/**
* Print a message.
*
* @param key selects message from resource
* @param a1 first argument
*/
public void notice(String key, String a1) {
printNotice(getText(key, a1));
}
/**
* Print a message.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
*/
public void notice(String key, String a1, String a2) {
printNotice(getText(key, a1, a2));
}
/**
* Print a message.
*
* @param key selects message from resource
* @param a1 first argument
* @param a2 second argument
* @param a3 third argument
*/
public void notice(String key, String a1, String a2, String a3) {
printNotice(getText(key, a1, a2, a3));
}
/**
* Return total number of errors, including those recorded
* in the compilation log.
*/
public int nerrors() { return nerrors; }
/**
* Return total number of warnings, including those recorded
* in the compilation log.
*/
public int nwarnings() { return nwarnings; }
/**
* Print exit message.
*/
public void exitNotice() {
if (nerrors > 0) {
notice((nerrors > 1) ? "main.errors" : "main.error",
"" + nerrors);
}
if (nwarnings > 0) {
notice((nwarnings > 1) ? "main.warnings" : "main.warning",
"" + nwarnings);
}
}
/**
* Force program exit, e.g., from a fatal error.
* <p>
* TODO: This method does not really belong here.
*/
public void exit() {
throw new ExitJavadoc();
}
}
| 14,157 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TagImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/TagImpl.java | /*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
/**
* Represents a documentation tag, e.g. @since, @author, @version.
* Given a tag (e.g. "@since 1.2"), holds tag name (e.g. "@since")
* and tag text (e.g. "1.2"). TagImpls with structure or which require
* special processing are handled by subclasses (ParamTagImpl, SeeTagImpl,
* and ThrowsTagImpl
*
* @author Robert Field
* @author Atul M Dambalkar
* @author Neal M Gafter
* @see SeeTagImpl
* @see ParamTagImpl
* @see ThrowsTagImpl
* @see Doc#tags()
*
*/
class TagImpl implements Tag {
protected final String text;
protected final String name;
protected final DocImpl holder;
/**
* Cached first sentence.
*/
private Tag[] firstSentence;
/**
* Cached inline tags.
*/
private Tag[] inlineTags;
/**
* Constructor
*/
TagImpl(DocImpl holder, String name, String text) {
this.holder = holder;
this.name = name;
this.text = text;
}
/**
* Return the name of this tag.
*/
public String name() {
return name;
}
/**
* Return the containing {@link Doc} of this Tag element.
*/
public Doc holder() {
return holder;
}
/**
* Return the kind of this tag.
*/
public String kind() {
return name;
}
/**
* Return the text of this tag, that is, portion beyond tag name.
*/
public String text() {
return text;
}
DocEnv docenv() {
return holder.env;
}
/**
* for use by subclasses which have two part tag text.
*/
String[] divideAtWhite() {
String[] sa = new String[2];
int len = text.length();
// if no white space found
sa[0] = text;
sa[1] = "";
for (int inx = 0; inx < len; ++inx) {
char ch = text.charAt(inx);
if (Character.isWhitespace(ch)) {
sa[0] = text.substring(0, inx);
for (; inx < len; ++inx) {
ch = text.charAt(inx);
if (!Character.isWhitespace(ch)) {
sa[1] = text.substring(inx, len);
break;
}
}
break;
}
}
return sa;
}
/**
* convert this object to a string.
*/
public String toString() {
return name + ":" + text;
}
/**
* For documentation comment with embedded @link tags, return the array of
* TagImpls consisting of SeeTagImpl(s) and text containing TagImpl(s).
* Within a comment string "This is an example of inline tags for a
* documentation comment {@link Doc {@link Doc commentlabel}}",
* where inside the inner braces, the first "Doc" carries exctly the same
* syntax as a SeeTagImpl and the second "commentlabel" is label for the Html
* Link, will return an array of TagImpl(s) with first element as TagImpl with
* comment text "This is an example of inline tags for a documentation
* comment" and second element as SeeTagImpl with referenced class as "Doc"
* and the label for the Html Link as "commentlabel".
*
* @return TagImpl[] Array of tags with inline SeeTagImpls.
* @see ParamTagImpl
* @see ThrowsTagImpl
*/
public Tag[] inlineTags() {
if (inlineTags == null) {
inlineTags = Comment.getInlineTags(holder, text);
}
return inlineTags;
}
/**
* Return array of tags for the first sentence in the doc comment text.
*/
public Tag[] firstSentenceTags() {
if (firstSentence == null) {
//Parse all sentences first to avoid duplicate warnings.
inlineTags();
try {
docenv().setSilent(true);
firstSentence = Comment.firstSentenceTags(holder, text);
} finally {
docenv().setSilent(false);
}
}
return firstSentence;
}
/**
* Return the doc item to which this tag is attached.
* @return the doc item to which this tag is attached.
*/
public SourcePosition position() {
return holder.position();
}
}
| 5,465 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationValueImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/AnnotationValueImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.TypeTags;
/**
* Represents a value of an annotation type element.
*
* @author Scott Seligman
* @since 1.5
*/
public class AnnotationValueImpl implements AnnotationValue {
private final DocEnv env;
private final Attribute attr;
AnnotationValueImpl(DocEnv env, Attribute attr) {
this.env = env;
this.attr = attr;
}
/**
* Returns the value.
* The type of the returned object is one of the following:
* <ul><li> a wrapper class for a primitive type
* <li> <code>String</code>
* <li> <code>Type</code> (representing a class literal)
* <li> <code>FieldDoc</code> (representing an enum constant)
* <li> <code>AnnotationDesc</code>
* <li> <code>AnnotationValue[]</code>
* </ul>
*/
public Object value() {
ValueVisitor vv = new ValueVisitor();
attr.accept(vv);
return vv.value;
}
private class ValueVisitor implements Attribute.Visitor {
public Object value;
public void visitConstant(Attribute.Constant c) {
if (c.type.tag == TypeTags.BOOLEAN) {
// javac represents false and true as integers 0 and 1
value = Boolean.valueOf(
((Integer)c.value).intValue() != 0);
} else {
value = c.value;
}
}
public void visitClass(Attribute.Class c) {
value = TypeMaker.getType(env,
env.types.erasure(c.type));
}
public void visitEnum(Attribute.Enum e) {
value = env.getFieldDoc(e.value);
}
public void visitCompound(Attribute.Compound c) {
value = new AnnotationDescImpl(env, c);
}
public void visitArray(Attribute.Array a) {
AnnotationValue vals[] = new AnnotationValue[a.values.length];
for (int i = 0; i < vals.length; i++) {
vals[i] = new AnnotationValueImpl(env, a.values[i]);
}
value = vals;
}
public void visitError(Attribute.Error e) {
value = "<error>";
}
}
/**
* Returns a string representation of the value.
*
* @return the text of a Java language annotation value expression
* whose value is the value of this annotation type element.
*/
@Override
public String toString() {
ToStringVisitor tv = new ToStringVisitor();
attr.accept(tv);
return tv.toString();
}
private class ToStringVisitor implements Attribute.Visitor {
private final StringBuilder sb = new StringBuilder();
@Override
public String toString() {
return sb.toString();
}
public void visitConstant(Attribute.Constant c) {
if (c.type.tag == TypeTags.BOOLEAN) {
// javac represents false and true as integers 0 and 1
sb.append(((Integer)c.value).intValue() != 0);
} else {
sb.append(FieldDocImpl.constantValueExpression(c.value));
}
}
public void visitClass(Attribute.Class c) {
sb.append(c);
}
public void visitEnum(Attribute.Enum e) {
sb.append(e);
}
public void visitCompound(Attribute.Compound c) {
sb.append(new AnnotationDescImpl(env, c));
}
public void visitArray(Attribute.Array a) {
// Omit braces from singleton.
if (a.values.length != 1) sb.append('{');
boolean first = true;
for (Attribute elem : a.values) {
if (first) {
first = false;
} else {
sb.append(", ");
}
elem.accept(this);
}
// Omit braces from singleton.
if (a.values.length != 1) sb.append('}');
}
public void visitError(Attribute.Error e) {
sb.append("<error>");
}
}
}
| 5,475 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Comment.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/Comment.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.util.ListBuffer;
/**
* Comment contains all information in comment part.
* It allows users to get first sentence of this comment, get
* comment for different tags...
*
* @author Kaiyang Liu (original)
* @author Robert Field (rewrite)
* @author Atul M Dambalkar
* @author Neal Gafter (rewrite)
*/
class Comment {
/**
* sorted comments with different tags.
*/
private final ListBuffer<Tag> tagList = new ListBuffer<Tag>();
/**
* text minus any tags.
*/
private String text;
/**
* Doc environment
*/
private final DocEnv docenv;
/**
* constructor of Comment.
*/
Comment(final DocImpl holder, final String commentString) {
this.docenv = holder.env;
/**
* Separate the comment into the text part and zero to N tags.
* Simple state machine is in one of three states:
* <pre>
* IN_TEXT: parsing the comment text or tag text.
* TAG_NAME: parsing the name of a tag.
* TAG_GAP: skipping through the gap between the tag name and
* the tag text.
* </pre>
*/
@SuppressWarnings("fallthrough")
class CommentStringParser {
/**
* The entry point to the comment string parser
*/
void parseCommentStateMachine() {
final int IN_TEXT = 1;
final int TAG_GAP = 2;
final int TAG_NAME = 3;
int state = TAG_GAP;
boolean newLine = true;
String tagName = null;
int tagStart = 0;
int textStart = 0;
int lastNonWhite = -1;
int len = commentString.length();
for (int inx = 0; inx < len; ++inx) {
char ch = commentString.charAt(inx);
boolean isWhite = Character.isWhitespace(ch);
switch (state) {
case TAG_NAME:
if (isWhite) {
tagName = commentString.substring(tagStart, inx);
state = TAG_GAP;
}
break;
case TAG_GAP:
if (isWhite) {
break;
}
textStart = inx;
state = IN_TEXT;
/* fall thru */
case IN_TEXT:
if (newLine && ch == '@') {
parseCommentComponent(tagName, textStart,
lastNonWhite+1);
tagStart = inx;
state = TAG_NAME;
}
break;
}
if (ch == '\n') {
newLine = true;
} else if (!isWhite) {
lastNonWhite = inx;
newLine = false;
}
}
// Finish what's currently being processed
switch (state) {
case TAG_NAME:
tagName = commentString.substring(tagStart, len);
/* fall thru */
case TAG_GAP:
textStart = len;
/* fall thru */
case IN_TEXT:
parseCommentComponent(tagName, textStart, lastNonWhite+1);
break;
}
}
/**
* Save away the last parsed item.
*/
void parseCommentComponent(String tagName,
int from, int upto) {
String tx = upto <= from ? "" : commentString.substring(from, upto);
if (tagName == null) {
text = tx;
} else {
TagImpl tag;
if (tagName.equals("@exception") || tagName.equals("@throws")) {
warnIfEmpty(tagName, tx);
tag = new ThrowsTagImpl(holder, tagName, tx);
} else if (tagName.equals("@param")) {
warnIfEmpty(tagName, tx);
tag = new ParamTagImpl(holder, tagName, tx);
} else if (tagName.equals("@see")) {
warnIfEmpty(tagName, tx);
tag = new SeeTagImpl(holder, tagName, tx);
} else if (tagName.equals("@serialField")) {
warnIfEmpty(tagName, tx);
tag = new SerialFieldTagImpl(holder, tagName, tx);
} else if (tagName.equals("@return")) {
warnIfEmpty(tagName, tx);
tag = new TagImpl(holder, tagName, tx);
} else if (tagName.equals("@author")) {
warnIfEmpty(tagName, tx);
tag = new TagImpl(holder, tagName, tx);
} else if (tagName.equals("@version")) {
warnIfEmpty(tagName, tx);
tag = new TagImpl(holder, tagName, tx);
} else {
tag = new TagImpl(holder, tagName, tx);
}
tagList.append(tag);
}
}
void warnIfEmpty(String tagName, String tx) {
if (tx.length() == 0) {
docenv.warning(holder, "tag.tag_has_no_arguments", tagName);
}
}
}
new CommentStringParser().parseCommentStateMachine();
}
/**
* Return the text of the comment.
*/
String commentText() {
return text;
}
/**
* Return all tags in this comment.
*/
Tag[] tags() {
return tagList.toArray(new Tag[tagList.length()]);
}
/**
* Return tags of the specified kind in this comment.
*/
Tag[] tags(String tagname) {
ListBuffer<Tag> found = new ListBuffer<Tag>();
String target = tagname;
if (target.charAt(0) != '@') {
target = "@" + target;
}
for (Tag tag : tagList) {
if (tag.kind().equals(target)) {
found.append(tag);
}
}
return found.toArray(new Tag[found.length()]);
}
/**
* Return throws tags in this comment.
*/
ThrowsTag[] throwsTags() {
ListBuffer<ThrowsTag> found = new ListBuffer<ThrowsTag>();
for (Tag next : tagList) {
if (next instanceof ThrowsTag) {
found.append((ThrowsTag)next);
}
}
return found.toArray(new ThrowsTag[found.length()]);
}
/**
* Return param tags (excluding type param tags) in this comment.
*/
ParamTag[] paramTags() {
return paramTags(false);
}
/**
* Return type param tags in this comment.
*/
ParamTag[] typeParamTags() {
return paramTags(true);
}
/**
* Return param tags in this comment. If typeParams is true
* include only type param tags, otherwise include only ordinary
* param tags.
*/
private ParamTag[] paramTags(boolean typeParams) {
ListBuffer<ParamTag> found = new ListBuffer<ParamTag>();
for (Tag next : tagList) {
if (next instanceof ParamTag) {
ParamTag p = (ParamTag)next;
if (typeParams == p.isTypeParameter()) {
found.append(p);
}
}
}
return found.toArray(new ParamTag[found.length()]);
}
/**
* Return see also tags in this comment.
*/
SeeTag[] seeTags() {
ListBuffer<SeeTag> found = new ListBuffer<SeeTag>();
for (Tag next : tagList) {
if (next instanceof SeeTag) {
found.append((SeeTag)next);
}
}
return found.toArray(new SeeTag[found.length()]);
}
/**
* Return serialField tags in this comment.
*/
SerialFieldTag[] serialFieldTags() {
ListBuffer<SerialFieldTag> found = new ListBuffer<SerialFieldTag>();
for (Tag next : tagList) {
if (next instanceof SerialFieldTag) {
found.append((SerialFieldTag)next);
}
}
return found.toArray(new SerialFieldTag[found.length()]);
}
/**
* Return array of tags with text and inline See Tags for a Doc comment.
*/
static Tag[] getInlineTags(DocImpl holder, String inlinetext) {
ListBuffer<Tag> taglist = new ListBuffer<Tag>();
int delimend = 0, textstart = 0, len = inlinetext.length();
DocEnv docenv = holder.env;
if (len == 0) {
return taglist.toArray(new Tag[taglist.length()]);
}
while (true) {
int linkstart;
if ((linkstart = inlineTagFound(holder, inlinetext,
textstart)) == -1) {
taglist.append(new TagImpl(holder, "Text",
inlinetext.substring(textstart)));
break;
} else {
int seetextstart = linkstart;
for (int i = linkstart; i < inlinetext.length(); i++) {
char c = inlinetext.charAt(i);
if (Character.isWhitespace(c) ||
c == '}') {
seetextstart = i;
break;
}
}
String linkName = inlinetext.substring(linkstart+2, seetextstart);
//Move past the white space after the inline tag name.
while (Character.isWhitespace(inlinetext.
charAt(seetextstart))) {
if (inlinetext.length() <= seetextstart) {
taglist.append(new TagImpl(holder, "Text",
inlinetext.substring(textstart, seetextstart)));
docenv.warning(holder,
"tag.Improper_Use_Of_Link_Tag",
inlinetext);
return taglist.toArray(new Tag[taglist.length()]);
} else {
seetextstart++;
}
}
taglist.append(new TagImpl(holder, "Text",
inlinetext.substring(textstart, linkstart)));
textstart = seetextstart; // this text is actually seetag
if ((delimend = findInlineTagDelim(inlinetext, textstart)) == -1) {
//Missing closing '}' character.
// store the text as it is with the {@link.
taglist.append(new TagImpl(holder, "Text",
inlinetext.substring(textstart)));
docenv.warning(holder,
"tag.End_delimiter_missing_for_possible_SeeTag",
inlinetext);
return taglist.toArray(new Tag[taglist.length()]);
} else {
//Found closing '}' character.
if (linkName.equals("see")
|| linkName.equals("link")
|| linkName.equals("linkplain")) {
taglist.append( new SeeTagImpl(holder, "@" + linkName,
inlinetext.substring(textstart, delimend)));
} else {
taglist.append( new TagImpl(holder, "@" + linkName,
inlinetext.substring(textstart, delimend)));
}
textstart = delimend + 1;
}
}
if (textstart == inlinetext.length()) {
break;
}
}
return taglist.toArray(new Tag[taglist.length()]);
}
/**
* Recursively find the index of the closing '}' character for an inline tag
* and return it. If it can't be found, return -1.
* @param inlineText the text to search in.
* @param searchStart the index of the place to start searching at.
* @return the index of the closing '}' character for an inline tag.
* If it can't be found, return -1.
*/
private static int findInlineTagDelim(String inlineText, int searchStart) {
int delimEnd, nestedOpenBrace;
if ((delimEnd = inlineText.indexOf("}", searchStart)) == -1) {
return -1;
} else if (((nestedOpenBrace = inlineText.indexOf("{", searchStart)) != -1) &&
nestedOpenBrace < delimEnd){
//Found a nested open brace.
int nestedCloseBrace = findInlineTagDelim(inlineText, nestedOpenBrace + 1);
return (nestedCloseBrace != -1) ?
findInlineTagDelim(inlineText, nestedCloseBrace + 1) :
-1;
} else {
return delimEnd;
}
}
/**
* Recursively search for the string "{@" followed by
* name of inline tag and white space,
* if found
* return the index of the text following the white space.
* else
* return -1.
*/
private static int inlineTagFound(DocImpl holder, String inlinetext, int start) {
DocEnv docenv = holder.env;
int linkstart = inlinetext.indexOf("{@", start);
if (start == inlinetext.length() || linkstart == -1) {
return -1;
} else if (inlinetext.indexOf('}', linkstart) == -1) {
//Missing '}'.
docenv.warning(holder, "tag.Improper_Use_Of_Link_Tag",
inlinetext.substring(linkstart, inlinetext.length()));
return -1;
} else {
return linkstart;
}
}
/**
* Return array of tags for the locale specific first sentence in the text.
*/
static Tag[] firstSentenceTags(DocImpl holder, String text) {
DocLocale doclocale = holder.env.doclocale;
return getInlineTags(holder,
doclocale.localeSpecificFirstSentence(holder, text));
}
/**
* Return text for this Doc comment.
*/
@Override
public String toString() {
return text;
}
}
| 15,997 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Main.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/Main.java | /*
* Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.io.PrintWriter;
/**
* Provides external entry points (tool and programmatic)
* for the javadoc program.
*
* @since 1.4
*/
public class Main {
/**
* Constructor should never be called.
*/
private Main() {
}
/**
* Command line interface.
* @param args The command line parameters.
*/
public static void main(String... args) {
System.exit(execute(args));
}
/**
* Programmatic interface.
* @param args The command line parameters.
* @return The return code.
*/
public static int execute(String... args) {
Start jdoc = new Start();
return jdoc.begin(args);
}
/**
* Programmatic interface.
* @param args The command line parameters.
* @param docletParentClassLoader The parent class loader used when
* creating the doclet classloader. If null, the class loader used
* to instantiate doclets will be created without specifying a parent
* class loader.
* @return The return code.
* @since 1.7
*/
public static int execute(ClassLoader docletParentClassLoader, String... args) {
Start jdoc = new Start(docletParentClassLoader);
return jdoc.begin(args);
}
/**
* Programmatic interface.
* @param programName Name of the program (for error messages).
* @param args The command line parameters.
* @return The return code.
*/
public static int execute(String programName, String... args) {
Start jdoc = new Start(programName);
return jdoc.begin(args);
}
/**
* Programmatic interface.
* @param programName Name of the program (for error messages).
* @param args The command line parameters.
* @param docletParentClassLoader The parent class loader used when
* creating the doclet classloader. If null, the class loader used
* to instantiate doclets will be created without specifying a parent
* class loader.
* @return The return code.
* @since 1.7
*/
public static int execute(String programName, ClassLoader docletParentClassLoader, String... args) {
Start jdoc = new Start(programName, docletParentClassLoader);
return jdoc.begin(args);
}
/**
* Programmatic interface.
* @param programName Name of the program (for error messages).
* @param defaultDocletClassName Fully qualified class name.
* @param args The command line parameters.
* @return The return code.
*/
public static int execute(String programName,
String defaultDocletClassName,
String... args) {
Start jdoc = new Start(programName, defaultDocletClassName);
return jdoc.begin(args);
}
/**
* Programmatic interface.
* @param programName Name of the program (for error messages).
* @param defaultDocletClassName Fully qualified class name.
* @param docletParentClassLoader The parent class loader used when
* creating the doclet classloader. If null, the class loader used
* to instantiate doclets will be created without specifying a parent
* class loader.
* @param args The command line parameters.
* @return The return code.
* @since 1.7
*/
public static int execute(String programName,
String defaultDocletClassName,
ClassLoader docletParentClassLoader,
String... args) {
Start jdoc = new Start(programName, defaultDocletClassName, docletParentClassLoader);
return jdoc.begin(args);
}
/**
* Programmatic interface.
* @param programName Name of the program (for error messages).
* @param errWriter PrintWriter to receive error messages.
* @param warnWriter PrintWriter to receive error messages.
* @param noticeWriter PrintWriter to receive error messages.
* @param defaultDocletClassName Fully qualified class name.
* @param args The command line parameters.
* @return The return code.
*/
public static int execute(String programName,
PrintWriter errWriter,
PrintWriter warnWriter,
PrintWriter noticeWriter,
String defaultDocletClassName,
String... args) {
Start jdoc = new Start(programName,
errWriter, warnWriter, noticeWriter,
defaultDocletClassName);
return jdoc.begin(args);
}
/**
* Programmatic interface.
* @param programName Name of the program (for error messages).
* @param errWriter PrintWriter to receive error messages.
* @param warnWriter PrintWriter to receive error messages.
* @param noticeWriter PrintWriter to receive error messages.
* @param defaultDocletClassName Fully qualified class name.
* @param docletParentClassLoader The parent class loader used when
* creating the doclet classloader. If null, the class loader used
* to instantiate doclets will be created without specifying a parent
* class loader.
* @param args The command line parameters.
* @return The return code.
* @since 1.7
*/
public static int execute(String programName,
PrintWriter errWriter,
PrintWriter warnWriter,
PrintWriter noticeWriter,
String defaultDocletClassName,
ClassLoader docletParentClassLoader,
String... args) {
Start jdoc = new Start(programName,
errWriter, warnWriter, noticeWriter,
defaultDocletClassName,
docletParentClassLoader);
return jdoc.begin(args);
}
}
| 7,314 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationTypeElementDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/AnnotationTypeElementDocImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import static com.sun.javadoc.LanguageVersion.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Position;
/**
* Represents an element of an annotation type.
*
* @author Scott Seligman
* @since 1.5
*/
public class AnnotationTypeElementDocImpl
extends MethodDocImpl implements AnnotationTypeElementDoc {
public AnnotationTypeElementDocImpl(DocEnv env, MethodSymbol sym) {
super(env, sym);
}
public AnnotationTypeElementDocImpl(DocEnv env, MethodSymbol sym,
String doc, JCMethodDecl tree, Position.LineMap lineMap) {
super(env, sym, doc, tree, lineMap);
}
/**
* Returns true, as this is an annotation type element.
* (For legacy doclets, return false.)
*/
public boolean isAnnotationTypeElement() {
return !isMethod();
}
/**
* Returns false. Although this is technically a method, we don't
* consider it one for this purpose.
* (For legacy doclets, return true.)
*/
public boolean isMethod() {
return env.legacyDoclet;
}
/**
* Returns false, even though this is indeed abstract. See
* MethodDocImpl.isAbstract() for the (il)logic behind this.
*/
public boolean isAbstract() {
return false;
}
/**
* Returns the default value of this element.
* Returns null if this element has no default.
*/
public AnnotationValue defaultValue() {
return (sym.defaultValue == null)
? null
: new AnnotationValueImpl(env, sym.defaultValue);
}
}
| 3,005 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DocLocale.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/DocLocale.java | /*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.util.Locale;
import java.util.HashSet;
import java.text.Collator;
import java.text.BreakIterator;
/**
* This class holds the information about locales.
*
* @since 1.4
* @author Robert Field
*/
class DocLocale {
/**
* The locale name will be set by Main, if option is provided on the
* command line.
*/
final String localeName;
/**
* The locale to be used. If user doesen't provide this,
* then set it to default locale value.
*/
final Locale locale;
/**
* The collator for this application. This is to take care of Locale
* Specific or Natural Language Text sorting.
*/
final Collator collator;
/**
* Enclosing DocEnv
*/
private final DocEnv docenv;
/**
* Sentence instance from the BreakIterator.
*/
private final BreakIterator sentenceBreaker;
/**
* True is we should use <code>BreakIterator</code>
* to compute first sentence.
*/
private boolean useBreakIterator = false;
/**
* The HTML sentence terminators.
*/
static final String[] sentenceTerminators =
{
"<p>", "</p>", "<h1>", "<h2>",
"<h3>", "<h4>", "<h5>", "<h6>",
"</h1>", "</h2>", "</h3>", "</h4>", "</h5>",
"</h6>", "<hr>", "<pre>", "</pre>"
};
/**
* Constructor
*/
DocLocale(DocEnv docenv, String localeName, boolean useBreakIterator) {
this.docenv = docenv;
this.localeName = localeName;
this.useBreakIterator = useBreakIterator;
locale = getLocale();
if (locale == null) {
docenv.exit();
} else {
Locale.setDefault(locale);
}
collator = Collator.getInstance(locale);
sentenceBreaker = BreakIterator.getSentenceInstance(locale);
}
/**
* Get the locale if specified on the command line
* else return null and if locale option is not used
* then return default locale.
*/
private Locale getLocale() {
Locale userlocale = null;
if (localeName.length() > 0) {
int firstuscore = localeName.indexOf('_');
int seconduscore = -1;
String language = null;
String country = null;
String variant = null;
if (firstuscore == 2) {
language = localeName.substring(0, firstuscore);
seconduscore = localeName.indexOf('_', firstuscore + 1);
if (seconduscore > 0) {
if (seconduscore != firstuscore + 3 ||
localeName.length() <= seconduscore + 1) {
docenv.error(null, "main.malformed_locale_name", localeName);
return null;
}
country = localeName.substring(firstuscore + 1,
seconduscore);
variant = localeName.substring(seconduscore + 1);
} else if (localeName.length() == firstuscore + 3) {
country = localeName.substring(firstuscore + 1);
} else {
docenv.error(null, "main.malformed_locale_name", localeName);
return null;
}
} else if (firstuscore == -1 && localeName.length() == 2) {
language = localeName;
} else {
docenv.error(null, "main.malformed_locale_name", localeName);
return null;
}
userlocale = searchLocale(language, country, variant);
if (userlocale == null) {
docenv.error(null, "main.illegal_locale_name", localeName);
return null;
} else {
return userlocale;
}
} else {
return Locale.getDefault();
}
}
/**
* Search the locale for specified language, specified country and
* specified variant.
*/
private Locale searchLocale(String language, String country,
String variant) {
Locale[] locales = Locale.getAvailableLocales();
for (int i = 0; i < locales.length; i++) {
if (locales[i].getLanguage().equals(language) &&
(country == null || locales[i].getCountry().equals(country)) &&
(variant == null || locales[i].getVariant().equals(variant))) {
return locales[i];
}
}
return null;
}
String localeSpecificFirstSentence(DocImpl doc, String s) {
if (s == null || s.length() == 0) {
return "";
}
int index = s.indexOf("-->");
if(s.trim().startsWith("<!--") && index != -1) {
return localeSpecificFirstSentence(doc, s.substring(index + 3, s.length()));
}
if (useBreakIterator || !locale.getLanguage().equals("en")) {
sentenceBreaker.setText(s.replace('\n', ' '));
int start = sentenceBreaker.first();
int end = sentenceBreaker.next();
return s.substring(start, end).trim();
} else {
return englishLanguageFirstSentence(s).trim();
}
}
/**
* Return the first sentence of a string, where a sentence ends
* with a period followed be white space.
*/
private String englishLanguageFirstSentence(String s) {
if (s == null) {
return null;
}
int len = s.length();
boolean period = false;
for (int i = 0 ; i < len ; i++) {
switch (s.charAt(i)) {
case '.':
period = true;
break;
case ' ':
case '\t':
case '\n':
case '\r':
case '\f':
if (period) {
return s.substring(0, i);
}
break;
case '<':
if (i > 0) {
if (htmlSentenceTerminatorFound(s, i)) {
return s.substring(0, i);
}
}
break;
default:
period = false;
}
}
return s;
}
/**
* Find out if there is any HTML tag in the given string. If found
* return true else return false.
*/
private boolean htmlSentenceTerminatorFound(String str, int index) {
for (int i = 0; i < sentenceTerminators.length; i++) {
String terminator = sentenceTerminators[i];
if (str.regionMatches(true, index, terminator,
0, terminator.length())) {
return true;
}
}
return false;
}
}
| 8,192 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavadocEnter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/JavadocEnter.java | /*
* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.tree.JCTree.*;
import javax.tools.JavaFileObject;
/**
* Javadoc's own enter phase does a few things above and beyond that
* done by javac.
* @author Neal Gafter
*/
public class JavadocEnter extends Enter {
public static JavadocEnter instance0(Context context) {
Enter instance = context.get(enterKey);
if (instance == null)
instance = new JavadocEnter(context);
return (JavadocEnter)instance;
}
public static void preRegister(Context context) {
context.put(enterKey, new Context.Factory<Enter>() {
public Enter make(Context c) {
return new JavadocEnter(c);
}
});
}
protected JavadocEnter(Context context) {
super(context);
messager = Messager.instance0(context);
docenv = DocEnv.instance(context);
}
final Messager messager;
final DocEnv docenv;
@Override
public void main(List<JCCompilationUnit> trees) {
// count all Enter errors as warnings.
int nerrors = messager.nerrors;
super.main(trees);
messager.nwarnings += (messager.nerrors - nerrors);
messager.nerrors = nerrors;
}
@Override
public void visitTopLevel(JCCompilationUnit tree) {
super.visitTopLevel(tree);
if (tree.sourcefile.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE)) {
String comment = tree.docComments.get(tree);
docenv.makePackageDoc(tree.packge, comment, tree);
}
}
@Override
public void visitClassDef(JCClassDecl tree) {
super.visitClassDef(tree);
if (tree.sym == null) return;
if (tree.sym.kind == Kinds.TYP || tree.sym.kind == Kinds.ERR) {
String comment = env.toplevel.docComments.get(tree);
ClassSymbol c = tree.sym;
docenv.makeClassDoc(c, comment, tree, env.toplevel.lineMap);
}
}
/** Don't complain about a duplicate class. */
@Override
protected void duplicateClass(DiagnosticPosition pos, ClassSymbol c) {}
}
| 3,617 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavadocTodo.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/JavadocTodo.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.tools.javac.comp.*;
import com.sun.tools.javac.util.*;
/**
* Javadoc's own todo queue doesn't queue its inputs, as javadoc
* doesn't perform attribution of method bodies or semantic checking.
* @author Neal Gafter
*/
public class JavadocTodo extends Todo {
public static void preRegister(Context context) {
context.put(todoKey, new Context.Factory<Todo>() {
public Todo make(Context c) {
return new JavadocTodo(c);
}
});
}
protected JavadocTodo(Context context) {
super(context);
}
@Override
public void append(Env<AttrContext> e) {
// do nothing; Javadoc doesn't perform attribution.
}
@Override
public boolean offer(Env<AttrContext> e) {
return false;
}
}
| 2,059 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/DocImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.text.CollationKey;
import javax.tools.FileObject;
import com.sun.javadoc.*;
import com.sun.tools.javac.util.Position;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* abstract base class of all Doc classes. Doc item's are representations
* of java language constructs (class, package, method,...) which have
* comments and have been processed by this run of javadoc. All Doc items
* are unique, that is, they are == comparable.
*
* @since 1.2
* @author Robert Field
* @author Atul M Dambalkar
* @author Neal Gafter (rewrite)
*/
public abstract class DocImpl implements Doc, Comparable<Object> {
/**
* Doc environment
*/
protected final DocEnv env; //### Rename this everywhere to 'docenv' ?
/**
* The complex comment object, lazily initialized.
*/
private Comment comment;
/**
* The cached sort key, to take care of Natural Language Text sorting.
*/
private CollationKey collationkey = null;
/**
* Raw documentation string.
*/
protected String documentation; // Accessed in PackageDocImpl, RootDocImpl
/**
* Cached first sentence.
*/
private Tag[] firstSentence;
/**
* Cached inline tags.
*/
private Tag[] inlineTags;
/**
* Constructor.
*/
DocImpl(DocEnv env, String documentation) {
this.documentation = documentation;
this.env = env;
}
/**
* So subclasses have the option to do lazy initialization of
* "documentation" string.
*/
protected String documentation() {
if (documentation == null) documentation = "";
return documentation;
}
/**
* For lazy initialization of comment.
*/
Comment comment() {
if (comment == null) {
comment = new Comment(this, documentation());
}
return comment;
}
/**
* Return the text of the comment for this doc item.
* TagImpls have been removed.
*/
public String commentText() {
return comment().commentText();
}
/**
* Return all tags in this Doc item.
*
* @return an array of TagImpl containing all tags on this Doc item.
*/
public Tag[] tags() {
return comment().tags();
}
/**
* Return tags of the specified kind in this Doc item.
*
* @param tagname name of the tag kind to search for.
* @return an array of TagImpl containing all tags whose 'kind()'
* matches 'tagname'.
*/
public Tag[] tags(String tagname) {
return comment().tags(tagname);
}
/**
* Return the see also tags in this Doc item.
*
* @return an array of SeeTag containing all @see tags.
*/
public SeeTag[] seeTags() {
return comment().seeTags();
}
public Tag[] inlineTags() {
if (inlineTags == null) {
inlineTags = Comment.getInlineTags(this, commentText());
}
return inlineTags;
}
public Tag[] firstSentenceTags() {
if (firstSentence == null) {
//Parse all sentences first to avoid duplicate warnings.
inlineTags();
try {
env.setSilent(true);
firstSentence = Comment.firstSentenceTags(this, commentText());
} finally {
env.setSilent(false);
}
}
return firstSentence;
}
/**
* Utility for subclasses which read HTML documentation files.
*/
String readHTMLDocumentation(InputStream input, FileObject filename) throws IOException {
byte[] filecontents = new byte[input.available()];
try {
DataInputStream dataIn = new DataInputStream(input);
dataIn.readFully(filecontents);
} finally {
input.close();
}
String encoding = env.getEncoding();
String rawDoc = (encoding!=null)
? new String(filecontents, encoding)
: new String(filecontents);
Pattern bodyPat = Pattern.compile("(?is).*<body\\b[^>]*>(.*)</body\\b.*");
Matcher m = bodyPat.matcher(rawDoc);
if (m.matches()) {
return m.group(1);
} else {
String key = rawDoc.matches("(?is).*<body\\b.*")
? "javadoc.End_body_missing_from_html_file"
: "javadoc.Body_missing_from_html_file";
env.error(SourcePositionImpl.make(filename, Position.NOPOS, null), key);
return "";
}
}
/**
* Return the full unprocessed text of the comment. Tags
* are included as text. Used mainly for store and retrieve
* operations like internalization.
*/
public String getRawCommentText() {
return documentation();
}
/**
* Set the full unprocessed text of the comment. Tags
* are included as text. Used mainly for store and retrieve
* operations like internalization.
*/
public void setRawCommentText(String rawDocumentation) {
documentation = rawDocumentation;
comment = null;
}
/**
* return a key for sorting.
*/
CollationKey key() {
if (collationkey == null) {
collationkey = generateKey();
}
return collationkey;
}
/**
* Generate a key for sorting.
* <p>
* Default is name().
*/
CollationKey generateKey() {
String k = name();
// System.out.println("COLLATION KEY FOR " + this + " is \"" + k + "\"");
return env.doclocale.collator.getCollationKey(k);
}
/**
* Returns a string representation of this Doc item.
*/
@Override
public String toString() {
return qualifiedName();
}
/**
* Returns the name of this Doc item.
*
* @return the name
*/
public abstract String name();
/**
* Returns the qualified name of this Doc item.
*
* @return the name
*/
public abstract String qualifiedName();
/**
* Compares this Object with the specified Object for order. Returns a
* negative integer, zero, or a positive integer as this Object is less
* than, equal to, or greater than the given Object.
* <p>
* Included so that Doc item are java.lang.Comparable.
*
* @param o the <code>Object</code> to be compared.
* @return a negative integer, zero, or a positive integer as this Object
* is less than, equal to, or greater than the given Object.
* @exception ClassCastException the specified Object's type prevents it
* from being compared to this Object.
*/
public int compareTo(Object obj) {
// System.out.println("COMPARE \"" + this + "\" to \"" + obj + "\" = " + key().compareTo(((DocImpl)obj).key()));
return key().compareTo(((DocImpl)obj).key());
}
/**
* Is this Doc item a field? False until overridden.
*
* @return true if it represents a field
*/
public boolean isField() {
return false;
}
/**
* Is this Doc item an enum constant? False until overridden.
*
* @return true if it represents an enum constant
*/
public boolean isEnumConstant() {
return false;
}
/**
* Is this Doc item a constructor? False until overridden.
*
* @return true if it represents a constructor
*/
public boolean isConstructor() {
return false;
}
/**
* Is this Doc item a method (but not a constructor or annotation
* type element)?
* False until overridden.
*
* @return true if it represents a method
*/
public boolean isMethod() {
return false;
}
/**
* Is this Doc item an annotation type element?
* False until overridden.
*
* @return true if it represents an annotation type element
*/
public boolean isAnnotationTypeElement() {
return false;
}
/**
* Is this Doc item a interface (but not an annotation type)?
* False until overridden.
*
* @return true if it represents a interface
*/
public boolean isInterface() {
return false;
}
/**
* Is this Doc item a exception class? False until overridden.
*
* @return true if it represents a exception
*/
public boolean isException() {
return false;
}
/**
* Is this Doc item a error class? False until overridden.
*
* @return true if it represents a error
*/
public boolean isError() {
return false;
}
/**
* Is this Doc item an enum type? False until overridden.
*
* @return true if it represents an enum type
*/
public boolean isEnum() {
return false;
}
/**
* Is this Doc item an annotation type? False until overridden.
*
* @return true if it represents an annotation type
*/
public boolean isAnnotationType() {
return false;
}
/**
* Is this Doc item an ordinary class (i.e. not an interface,
* annotation type, enumeration, exception, or error)?
* False until overridden.
*
* @return true if it represents an ordinary class
*/
public boolean isOrdinaryClass() {
return false;
}
/**
* Is this Doc item a class
* (and not an interface or annotation type)?
* This includes ordinary classes, enums, errors and exceptions.
* False until overridden.
*
* @return true if it represents a class
*/
public boolean isClass() {
return false;
}
/**
* return true if this Doc is include in the active set.
*/
public abstract boolean isIncluded();
/**
* Return the source position of the entity, or null if
* no position is available.
*/
public SourcePosition position() { return null; }
}
| 11,275 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SeeTagImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/SeeTagImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.tools.javac.util.*;
import com.sun.javadoc.*;
/**
* Represents a see also documentation tag.
* The @see tag can be plain text, or reference a class or member.
*
* @author Kaiyang Liu (original)
* @author Robert Field (rewrite)
* @author Atul M Dambalkar
*
*/
class SeeTagImpl extends TagImpl implements SeeTag, LayoutCharacters {
//### TODO: Searching for classes, fields, and methods
//### should follow the normal rules applied by the compiler.
/**
* where of where#what - i.e. the class name (may be empty)
*/
private String where;
/**
* what of where#what - i.e. the member (may be null)
*/
private String what;
private PackageDoc referencedPackage;
private ClassDoc referencedClass;
private MemberDoc referencedMember;
String label = "";
SeeTagImpl(DocImpl holder, String name, String text) {
super(holder, name, text);
parseSeeString();
if (where != null) {
ClassDocImpl container = null;
if (holder instanceof MemberDoc) {
container =
(ClassDocImpl)((ProgramElementDoc)holder).containingClass();
} else if (holder instanceof ClassDoc) {
container = (ClassDocImpl)holder;
}
findReferenced(container);
}
}
/**
* get the class name part of @see, For instance,
* if the comment is @see String#startsWith(java.lang.String) .
* This function returns String.
* Returns null if format was not that of java reference.
* Return empty string if class name was not specified..
*/
public String referencedClassName() {
return where;
}
/**
* get the package referenced by @see. For instance,
* if the comment is @see java.lang
* This function returns a PackageDocImpl for java.lang
* Returns null if no known package found.
*/
public PackageDoc referencedPackage() {
return referencedPackage;
}
/**
* get the class referenced by the class name part of @see, For instance,
* if the comment is @see String#startsWith(java.lang.String) .
* This function returns a ClassDocImpl for java.lang.String.
* Returns null if class is not a class specified on the javadoc command line..
*/
public ClassDoc referencedClass() {
return referencedClass;
}
/**
* get the name of the member referenced by the prototype part of @see,
* For instance,
* if the comment is @see String#startsWith(java.lang.String) .
* This function returns "startsWith(java.lang.String)"
* Returns null if format was not that of java reference.
* Return empty string if member name was not specified..
*/
public String referencedMemberName() {
return what;
}
/**
* get the member referenced by the prototype part of @see,
* For instance,
* if the comment is @see String#startsWith(java.lang.String) .
* This function returns a MethodDocImpl for startsWith.
* Returns null if member could not be determined.
*/
public MemberDoc referencedMember() {
return referencedMember;
}
/**
* parse @see part of comment. Determine 'where' and 'what'
*/
private void parseSeeString() {
int len = text.length();
if (len == 0) {
return;
}
switch (text.charAt(0)) {
case '<':
if (text.charAt(len-1) != '>') {
docenv().warning(holder,
"tag.see.no_close_bracket_on_url",
name, text);
}
return;
case '"':
if (len == 1 || text.charAt(len-1) != '"') {
docenv().warning(holder,
"tag.see.no_close_quote",
name, text);
} else {
// text = text.substring(1,len-1); // strip quotes
}
return;
}
// check that the text is one word, with possible parentheses
// this part of code doesn't allow
// @see <a href=.....>asfd</a>
// comment it.
// the code assumes that there is no initial white space.
int parens = 0;
int commentstart = 0;
int start = 0;
int cp;
for (int i = start; i < len ; i += Character.charCount(cp)) {
cp = text.codePointAt(i);
switch (cp) {
case '(': parens++; break;
case ')': parens--; break;
case '[': case ']': case '.': case '#': break;
case ',':
if (parens <= 0) {
docenv().warning(holder,
"tag.see.malformed_see_tag",
name, text);
return;
}
break;
case ' ': case '\t': case '\n': case CR:
if (parens == 0) { //here onwards the comment starts.
commentstart = i;
i = len;
}
break;
default:
if (!Character.isJavaIdentifierPart(cp)) {
docenv().warning(holder,
"tag.see.illegal_character",
name, ""+cp, text);
}
break;
}
}
if (parens != 0) {
docenv().warning(holder,
"tag.see.malformed_see_tag",
name, text);
return;
}
String seetext = "";
String labeltext = "";
if (commentstart > 0) {
seetext = text.substring(start, commentstart);
labeltext = text.substring(commentstart + 1);
// strip off the white space which can be between seetext and the
// actual label.
for (int i = 0; i < labeltext.length(); i++) {
char ch2 = labeltext.charAt(i);
if (!(ch2 == ' ' || ch2 == '\t' || ch2 == '\n')) {
label = labeltext.substring(i);
break;
}
}
} else {
seetext = text;
label = "";
}
int sharp = seetext.indexOf('#');
if (sharp >= 0) {
// class#member
where = seetext.substring(0, sharp);
what = seetext.substring(sharp + 1);
} else {
if (seetext.indexOf('(') >= 0) {
docenv().warning(holder,
"tag.see.missing_sharp",
name, text);
where = "";
what = seetext;
}
else {
// no member specified, text names class
where = seetext;
what = null;
}
}
}
/**
* Find what is referenced by the see also. If possible, sets
* referencedClass and referencedMember.
*
* @param containingClass the class containing the comment containing
* the tag. May be null, if, for example, it is a package comment.
*/
private void findReferenced(ClassDocImpl containingClass) {
if (where.length() > 0) {
if (containingClass != null) {
referencedClass = containingClass.findClass(where);
} else {
referencedClass = docenv().lookupClass(where);
}
if (referencedClass == null && holder() instanceof ProgramElementDoc) {
referencedClass = docenv().lookupClass(
((ProgramElementDoc) holder()).containingPackage().name() + "." + where);
}
if (referencedClass == null) { /* may just not be in this run */
// docenv().warning(holder, "tag.see.class_not_found",
// where, text);
// check if it's a package name
referencedPackage = docenv().lookupPackage(where);
return;
}
} else {
if (containingClass == null) {
docenv().warning(holder,
"tag.see.class_not_specified",
name, text);
return;
} else {
referencedClass = containingClass;
}
}
where = referencedClass.qualifiedName();
if (what == null) {
return;
} else {
int paren = what.indexOf('(');
String memName = (paren >= 0 ? what.substring(0, paren) : what);
String[] paramarr;
if (paren > 0) {
// has parameter list -- should be method or constructor
paramarr = new ParameterParseMachine(what.
substring(paren, what.length())).parseParameters();
if (paramarr != null) {
referencedMember = findExecutableMember(memName, paramarr,
referencedClass);
} else {
referencedMember = null;
}
} else {
// no parameter list -- should be field
referencedMember = findExecutableMember(memName, null,
referencedClass);
FieldDoc fd = ((ClassDocImpl)referencedClass).
findField(memName);
// when no args given, prefer fields over methods
if (referencedMember == null ||
(fd != null &&
fd.containingClass()
.subclassOf(referencedMember.containingClass()))) {
referencedMember = fd;
}
}
if (referencedMember == null) {
docenv().warning(holder,
"tag.see.can_not_find_member",
name, what, where);
}
}
}
private MemberDoc findReferencedMethod(String memName, String[] paramarr,
ClassDoc referencedClass) {
MemberDoc meth = findExecutableMember(memName, paramarr, referencedClass);
ClassDoc[] nestedclasses = referencedClass.innerClasses();
if (meth == null) {
for (int i = 0; i < nestedclasses.length; i++) {
meth = findReferencedMethod(memName, paramarr, nestedclasses[i]);
if (meth != null) {
return meth;
}
}
}
return null;
}
private MemberDoc findExecutableMember(String memName, String[] paramarr,
ClassDoc referencedClass) {
if (memName.equals(referencedClass.name())) {
return ((ClassDocImpl)referencedClass).findConstructor(memName,
paramarr);
} else { // it's a method.
return ((ClassDocImpl)referencedClass).findMethod(memName,
paramarr);
}
}
// separate "int, String" from "(int, String)"
// (int i, String s) ==> [0] = "int", [1] = String
// (int[][], String[]) ==> [0] = "int[][]" // [1] = "String[]"
class ParameterParseMachine {
static final int START = 0;
static final int TYPE = 1;
static final int NAME = 2;
static final int TNSPACE = 3; // space between type and name
static final int ARRAYDECORATION = 4;
static final int ARRAYSPACE = 5;
String parameters;
StringBuilder typeId;
ListBuffer<String> paramList;
ParameterParseMachine(String parameters) {
this.parameters = parameters;
this.paramList = new ListBuffer<String>();
typeId = new StringBuilder();
}
public String[] parseParameters() {
if (parameters.equals("()")) {
return new String[0];
} // now strip off '(' and ')'
int state = START;
int prevstate = START;
parameters = parameters.substring(1, parameters.length() - 1);
int cp;
for (int index = 0; index < parameters.length(); index += Character.charCount(cp)) {
cp = parameters.codePointAt(index);
switch (state) {
case START:
if (Character.isJavaIdentifierStart(cp)) {
typeId.append(Character.toChars(cp));
state = TYPE;
}
prevstate = START;
break;
case TYPE:
if (Character.isJavaIdentifierPart(cp) || cp == '.') {
typeId.append(Character.toChars(cp));
} else if (cp == '[') {
typeId.append('[');
state = ARRAYDECORATION;
} else if (Character.isWhitespace(cp)) {
state = TNSPACE;
} else if (cp == ',') { // no name, just type
addTypeToParamList();
state = START;
}
prevstate = TYPE;
break;
case TNSPACE:
if (Character.isJavaIdentifierStart(cp)) { // name
if (prevstate == ARRAYDECORATION) {
docenv().warning(holder,
"tag.missing_comma_space",
name,
"(" + parameters + ")");
return (String[])null;
}
addTypeToParamList();
state = NAME;
} else if (cp == '[') {
typeId.append('[');
state = ARRAYDECORATION;
} else if (cp == ',') { // just the type
addTypeToParamList();
state = START;
} // consume rest all
prevstate = TNSPACE;
break;
case ARRAYDECORATION:
if (cp == ']') {
typeId.append(']');
state = TNSPACE;
} else if (!Character.isWhitespace(cp)) {
docenv().warning(holder,
"tag.illegal_char_in_arr_dim",
name,
"(" + parameters + ")");
return (String[])null;
}
prevstate = ARRAYDECORATION;
break;
case NAME:
if (cp == ',') { // just consume everything till ','
state = START;
}
prevstate = NAME;
break;
}
}
if (state == ARRAYDECORATION ||
(state == START && prevstate == TNSPACE)) {
docenv().warning(holder,
"tag.illegal_see_tag",
"(" + parameters + ")");
}
if (typeId.length() > 0) {
paramList.append(typeId.toString());
}
return paramList.toArray(new String[paramList.length()]);
}
void addTypeToParamList() {
if (typeId.length() > 0) {
paramList.append(typeId.toString());
typeId.setLength(0);
}
}
}
/**
* Return the kind of this tag.
*/
@Override
public String kind() {
return "@see";
}
/**
* Return the label of the see tag.
*/
public String label() {
return label;
}
}
| 18,026 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PackageDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/PackageDocImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.io.InputStream;
import java.io.IOException;
import javax.tools.FileObject;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Position;
/**
* Represents a java package. Provides access to information
* about the package, the package's comment and tags, and the
* classes in the package.
*
* @since 1.2
* @author Kaiyang Liu (original)
* @author Robert Field (rewrite)
* @author Neal Gafter (rewrite)
* @author Scott Seligman (package-info.java)
*/
public class PackageDocImpl extends DocImpl implements PackageDoc {
protected PackageSymbol sym;
private JCCompilationUnit tree = null; // for source position
public FileObject docPath = null;
private boolean foundDoc; // found a doc comment in either
// package.html or package-info.java
boolean isIncluded = false; // Set in RootDocImpl.
public boolean setDocPath = false; //Flag to avoid setting doc path multiple times.
/**
* Constructor
*/
public PackageDocImpl(DocEnv env, PackageSymbol sym) {
this(env, sym, null, null);
}
/**
* Constructor
*/
public PackageDocImpl(DocEnv env, PackageSymbol sym,
String documentation, JCTree tree) {
super(env, documentation);
this.sym = sym;
this.tree = (JCCompilationUnit) tree;
foundDoc = (documentation != null);
}
void setTree(JCTree tree) {
this.tree = (JCCompilationUnit) tree;
}
public void setRawCommentText(String rawDocumentation) {
super.setRawCommentText(rawDocumentation);
checkDoc();
}
/**
* Do lazy initialization of "documentation" string.
*/
protected String documentation() {
if (documentation != null)
return documentation;
if (docPath != null) {
// read from file
try {
InputStream s = docPath.openInputStream();
documentation = readHTMLDocumentation(s, docPath);
} catch (IOException exc) {
documentation = "";
env.error(null, "javadoc.File_Read_Error", docPath.getName());
}
} else {
// no doc file to be had
documentation = "";
}
return documentation;
}
/**
* Cache of all classes contained in this package, including
* member classes of those classes, and their member classes, etc.
* Includes only those classes at the specified protection level
* and weaker.
*/
private List<ClassDocImpl> allClassesFiltered = null;
/**
* Cache of all classes contained in this package, including
* member classes of those classes, and their member classes, etc.
*/
private List<ClassDocImpl> allClasses = null;
/**
* Return a list of all classes contained in this package, including
* member classes of those classes, and their member classes, etc.
*/
private List<ClassDocImpl> getClasses(boolean filtered) {
if (allClasses != null && !filtered) {
return allClasses;
}
if (allClassesFiltered != null && filtered) {
return allClassesFiltered;
}
ListBuffer<ClassDocImpl> classes = new ListBuffer<ClassDocImpl>();
for (Scope.Entry e = sym.members().elems; e != null; e = e.sibling) {
if (e.sym != null) {
ClassSymbol s = (ClassSymbol)e.sym;
ClassDocImpl c = env.getClassDoc(s);
if (c != null && !c.isSynthetic())
c.addAllClasses(classes, filtered);
}
}
if (filtered)
return allClassesFiltered = classes.toList();
else
return allClasses = classes.toList();
}
/**
* Add all included classes (including Exceptions and Errors)
* and interfaces.
*/
public void addAllClassesTo(ListBuffer<ClassDocImpl> list) {
list.appendList(getClasses(true));
}
/**
* Get all classes (including Exceptions and Errors)
* and interfaces.
* @since J2SE1.4.
*
* @return all classes and interfaces in this package, filtered to include
* only the included classes if filter==true.
*/
public ClassDoc[] allClasses(boolean filter) {
List<ClassDocImpl> classes = getClasses(filter);
return classes.toArray(new ClassDocImpl[classes.length()]);
}
/**
* Get all included classes (including Exceptions and Errors)
* and interfaces. Same as allClasses(true).
*
* @return all included classes and interfaces in this package.
*/
public ClassDoc[] allClasses() {
return allClasses(true);
}
/**
* Get ordinary classes (that is, exclude exceptions, errors,
* enums, interfaces, and annotation types) in this package.
*
* @return included ordinary classes in this package.
*/
public ClassDoc[] ordinaryClasses() {
ListBuffer<ClassDocImpl> ret = new ListBuffer<ClassDocImpl>();
for (ClassDocImpl c : getClasses(true)) {
if (c.isOrdinaryClass()) {
ret.append(c);
}
}
return ret.toArray(new ClassDocImpl[ret.length()]);
}
/**
* Get Exception classes in this package.
*
* @return included Exceptions in this package.
*/
public ClassDoc[] exceptions() {
ListBuffer<ClassDocImpl> ret = new ListBuffer<ClassDocImpl>();
for (ClassDocImpl c : getClasses(true)) {
if (c.isException()) {
ret.append(c);
}
}
return ret.toArray(new ClassDocImpl[ret.length()]);
}
/**
* Get Error classes in this package.
*
* @return included Errors in this package.
*/
public ClassDoc[] errors() {
ListBuffer<ClassDocImpl> ret = new ListBuffer<ClassDocImpl>();
for (ClassDocImpl c : getClasses(true)) {
if (c.isError()) {
ret.append(c);
}
}
return ret.toArray(new ClassDocImpl[ret.length()]);
}
/**
* Get included enum types in this package.
*
* @return included enum types in this package.
*/
public ClassDoc[] enums() {
ListBuffer<ClassDocImpl> ret = new ListBuffer<ClassDocImpl>();
for (ClassDocImpl c : getClasses(true)) {
if (c.isEnum()) {
ret.append(c);
}
}
return ret.toArray(new ClassDocImpl[ret.length()]);
}
/**
* Get included interfaces in this package, omitting annotation types.
*
* @return included interfaces in this package.
*/
public ClassDoc[] interfaces() {
ListBuffer<ClassDocImpl> ret = new ListBuffer<ClassDocImpl>();
for (ClassDocImpl c : getClasses(true)) {
if (c.isInterface()) {
ret.append(c);
}
}
return ret.toArray(new ClassDocImpl[ret.length()]);
}
/**
* Get included annotation types in this package.
*
* @return included annotation types in this package.
*/
public AnnotationTypeDoc[] annotationTypes() {
ListBuffer<AnnotationTypeDocImpl> ret =
new ListBuffer<AnnotationTypeDocImpl>();
for (ClassDocImpl c : getClasses(true)) {
if (c.isAnnotationType()) {
ret.append((AnnotationTypeDocImpl)c);
}
}
return ret.toArray(new AnnotationTypeDocImpl[ret.length()]);
}
/**
* Get the annotations of this package.
* Return an empty array if there are none.
*/
public AnnotationDesc[] annotations() {
AnnotationDesc res[] = new AnnotationDesc[sym.getAnnotationMirrors().length()];
int i = 0;
for (Attribute.Compound a : sym.getAnnotationMirrors()) {
res[i++] = new AnnotationDescImpl(env, a);
}
return res;
}
/**
* Lookup for a class within this package.
*
* @return ClassDocImpl of found class, or null if not found.
*/
public ClassDoc findClass(String className) {
final boolean filtered = true;
for (ClassDocImpl c : getClasses(filtered)) {
if (c.name().equals(className)) {
return c;
}
}
return null;
}
/**
* Return true if this package is included in the active set.
*/
public boolean isIncluded() {
return isIncluded;
}
/**
* Get package name.
*
* Note that we do not provide a means of obtaining the simple
* name of a package -- package names are always returned in their
* uniquely qualified form.
*/
public String name() {
return qualifiedName();
}
/**
* Get package name.
*/
public String qualifiedName() {
Name fullname = sym.getQualifiedName();
// Some bogus tests depend on the interned "" being returned.
// See 6457276.
return fullname.isEmpty() ? "" : fullname.toString();
}
/**
* set doc path for an unzipped directory
*/
public void setDocPath(FileObject path) {
setDocPath = true;
if (path == null)
return;
if (!path.equals(docPath)) {
docPath = path;
checkDoc();
}
}
// Has checkDoc() sounded off yet?
private boolean checkDocWarningEmitted = false;
/**
* Invoked when a source of package doc comments is located.
* Emits a diagnostic if this is the second one.
*/
private void checkDoc() {
if (foundDoc) {
if (!checkDocWarningEmitted) {
env.warning(null, "javadoc.Multiple_package_comments", name());
checkDocWarningEmitted = true;
}
} else {
foundDoc = true;
}
}
/**
* Return the source position of the entity, or null if
* no position is available.
*/
public SourcePosition position() {
return (tree != null)
? SourcePositionImpl.make(tree.sourcefile, tree.pos, tree.lineMap)
: SourcePositionImpl.make(docPath, Position.NOPOS, null);
}
}
| 11,930 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavadocTool.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/JavadocTool.java | /*
* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.tools.JavaFileManager.Location;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.comp.Annotate;
import com.sun.tools.javac.parser.DocCommentScanner;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.Abort;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Position;
/**
* This class could be the main entry point for Javadoc when Javadoc is used as a
* component in a larger software system. It provides operations to
* construct a new javadoc processor, and to run it on a set of source
* files.
* @author Neal Gafter
*/
public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler {
DocEnv docenv;
final Context context;
final Messager messager;
final JavadocClassReader reader;
final JavadocEnter enter;
final Annotate annotate;
/**
* Construct a new JavaCompiler processor, using appropriately
* extended phases of the underlying compiler.
*/
protected JavadocTool(Context context) {
super(context);
this.context = context;
messager = Messager.instance0(context);
reader = JavadocClassReader.instance0(context);
enter = JavadocEnter.instance0(context);
annotate = Annotate.instance(context);
}
/**
* For javadoc, the parser needs to keep comments. Overrides method from JavaCompiler.
*/
protected boolean keepComments() {
return true;
}
/**
* Construct a new javadoc tool.
*/
public static JavadocTool make0(Context context) {
Messager messager = null;
try {
// force the use of Javadoc's class reader
JavadocClassReader.preRegister(context);
// force the use of Javadoc's own enter phase
JavadocEnter.preRegister(context);
// force the use of Javadoc's own member enter phase
JavadocMemberEnter.preRegister(context);
// force the use of Javadoc's own todo phase
JavadocTodo.preRegister(context);
// force the use of Messager as a Log
messager = Messager.instance0(context);
return new JavadocTool(context);
} catch (CompletionFailure ex) {
messager.error(Position.NOPOS, ex.getMessage());
return null;
}
}
public RootDocImpl getRootDocImpl(String doclocale,
String encoding,
ModifierFilter filter,
List<String> javaNames,
List<String[]> options,
boolean breakiterator,
List<String> subPackages,
List<String> excludedPackages,
boolean docClasses,
boolean legacyDoclet,
boolean quiet) throws IOException {
docenv = DocEnv.instance(context);
docenv.showAccess = filter;
docenv.quiet = quiet;
docenv.breakiterator = breakiterator;
docenv.setLocale(doclocale);
docenv.setEncoding(encoding);
docenv.docClasses = docClasses;
docenv.legacyDoclet = legacyDoclet;
reader.sourceCompleter = docClasses ? null : this;
ListBuffer<String> names = new ListBuffer<String>();
ListBuffer<JCCompilationUnit> classTrees = new ListBuffer<JCCompilationUnit>();
ListBuffer<JCCompilationUnit> packTrees = new ListBuffer<JCCompilationUnit>();
try {
StandardJavaFileManager fm = (StandardJavaFileManager) docenv.fileManager;
for (List<String> it = javaNames; it.nonEmpty(); it = it.tail) {
String name = it.head;
if (!docClasses && name.endsWith(".java") && new File(name).exists()) {
JavaFileObject fo = fm.getJavaFileObjects(name).iterator().next();
docenv.notice("main.Loading_source_file", name);
JCCompilationUnit tree = parse(fo);
classTrees.append(tree);
} else if (isValidPackageName(name)) {
names = names.append(name);
} else if (name.endsWith(".java")) {
docenv.error(null, "main.file_not_found", name);
} else {
docenv.error(null, "main.illegal_package_name", name);
}
}
if (!docClasses) {
// Recursively search given subpackages. If any packages
//are found, add them to the list.
Map<String,List<JavaFileObject>> packageFiles =
searchSubPackages(subPackages, names, excludedPackages);
// Parse the packages
for (List<String> packs = names.toList(); packs.nonEmpty(); packs = packs.tail) {
// Parse sources ostensibly belonging to package.
String packageName = packs.head;
parsePackageClasses(packageName, packageFiles.get(packageName), packTrees, excludedPackages);
}
if (messager.nerrors() != 0) return null;
// Enter symbols for all files
docenv.notice("main.Building_tree");
enter.main(classTrees.toList().appendList(packTrees.toList()));
}
} catch (Abort ex) {}
if (messager.nerrors() != 0)
return null;
if (docClasses)
return new RootDocImpl(docenv, javaNames, options);
else
return new RootDocImpl(docenv, listClasses(classTrees.toList()), names.toList(), options);
}
/** Is the given string a valid package name? */
boolean isValidPackageName(String s) {
int index;
while ((index = s.indexOf('.')) != -1) {
if (!isValidClassName(s.substring(0, index))) return false;
s = s.substring(index+1);
}
return isValidClassName(s);
}
/**
* search all directories in path for subdirectory name. Add all
* .java files found in such a directory to args.
*/
private void parsePackageClasses(String name,
Iterable<JavaFileObject> files,
ListBuffer<JCCompilationUnit> trees,
List<String> excludedPackages)
throws IOException {
if (excludedPackages.contains(name)) {
return;
}
boolean hasFiles = false;
docenv.notice("main.Loading_source_files_for_package", name);
if (files == null) {
Location location = docenv.fileManager.hasLocation(StandardLocation.SOURCE_PATH)
? StandardLocation.SOURCE_PATH : StandardLocation.CLASS_PATH;
ListBuffer<JavaFileObject> lb = new ListBuffer<JavaFileObject>();
for (JavaFileObject fo: docenv.fileManager.list(
location, name, EnumSet.of(JavaFileObject.Kind.SOURCE), false)) {
String binaryName = docenv.fileManager.inferBinaryName(location, fo);
String simpleName = getSimpleName(binaryName);
if (isValidClassName(simpleName)) {
lb.append(fo);
}
}
files = lb.toList();
}
for (JavaFileObject fo : files) {
// messager.notice("main.Loading_source_file", fn);
trees.append(parse(fo));
hasFiles = true;
}
if (!hasFiles) {
messager.warning(null, "main.no_source_files_for_package",
name.replace(File.separatorChar, '.'));
}
}
/**
* Recursively search all directories in path for subdirectory name.
* Add all packages found in such a directory to packages list.
*/
private Map<String,List<JavaFileObject>> searchSubPackages(
List<String> subPackages,
ListBuffer<String> packages,
List<String> excludedPackages)
throws IOException {
Map<String,List<JavaFileObject>> packageFiles =
new HashMap<String,List<JavaFileObject>>();
Map<String,Boolean> includedPackages = new HashMap<String,Boolean>();
includedPackages.put("", true);
for (String p: excludedPackages)
includedPackages.put(p, false);
StandardLocation path = docenv.fileManager.hasLocation(StandardLocation.SOURCE_PATH)
? StandardLocation.SOURCE_PATH : StandardLocation.CLASS_PATH;
searchSubPackages(subPackages,
includedPackages,
packages, packageFiles,
path,
EnumSet.of(JavaFileObject.Kind.SOURCE));
return packageFiles;
}
private void searchSubPackages(List<String> subPackages,
Map<String,Boolean> includedPackages,
ListBuffer<String> packages,
Map<String, List<JavaFileObject>> packageFiles,
StandardLocation location, Set<JavaFileObject.Kind> kinds)
throws IOException {
for (String subPackage: subPackages) {
if (!isIncluded(subPackage, includedPackages))
continue;
for (JavaFileObject fo: docenv.fileManager.list(location, subPackage, kinds, true)) {
String binaryName = docenv.fileManager.inferBinaryName(location, fo);
String packageName = getPackageName(binaryName);
String simpleName = getSimpleName(binaryName);
if (isIncluded(packageName, includedPackages) && isValidClassName(simpleName)) {
List<JavaFileObject> list = packageFiles.get(packageName);
list = (list == null ? List.of(fo) : list.prepend(fo));
packageFiles.put(packageName, list);
if (!packages.contains(packageName))
packages.add(packageName);
}
}
}
}
private String getPackageName(String name) {
int lastDot = name.lastIndexOf(".");
return (lastDot == -1 ? "" : name.substring(0, lastDot));
}
private String getSimpleName(String name) {
int lastDot = name.lastIndexOf(".");
return (lastDot == -1 ? name : name.substring(lastDot + 1));
}
private boolean isIncluded(String packageName, Map<String,Boolean> includedPackages) {
Boolean b = includedPackages.get(packageName);
if (b == null) {
b = isIncluded(getPackageName(packageName), includedPackages);
includedPackages.put(packageName, b);
}
return b;
}
/**
* Recursively search all directories in path for subdirectory name.
* Add all packages found in such a directory to packages list.
*/
private void searchSubPackage(String packageName,
ListBuffer<String> packages,
List<String> excludedPackages,
Collection<File> pathnames) {
if (excludedPackages.contains(packageName))
return;
String packageFilename = packageName.replace('.', File.separatorChar);
boolean addedPackage = false;
for (File pathname : pathnames) {
File f = new File(pathname, packageFilename);
String filenames[] = f.list();
// if filenames not null, then found directory
if (filenames != null) {
for (String filename : filenames) {
if (!addedPackage
&& (isValidJavaSourceFile(filename) ||
isValidJavaClassFile(filename))
&& !packages.contains(packageName)) {
packages.append(packageName);
addedPackage = true;
} else if (isValidClassName(filename) &&
(new File(f, filename)).isDirectory()) {
searchSubPackage(packageName + "." + filename,
packages, excludedPackages, pathnames);
}
}
}
}
}
/**
* Return true if given file name is a valid class file name.
* @param file the name of the file to check.
* @return true if given file name is a valid class file name
* and false otherwise.
*/
private static boolean isValidJavaClassFile(String file) {
if (!file.endsWith(".class")) return false;
String clazzName = file.substring(0, file.length() - ".class".length());
return isValidClassName(clazzName);
}
/**
* Return true if given file name is a valid Java source file name.
* @param file the name of the file to check.
* @return true if given file name is a valid Java source file name
* and false otherwise.
*/
private static boolean isValidJavaSourceFile(String file) {
if (!file.endsWith(".java")) return false;
String clazzName = file.substring(0, file.length() - ".java".length());
return isValidClassName(clazzName);
}
/** Are surrogates supported?
*/
final static boolean surrogatesSupported = surrogatesSupported();
private static boolean surrogatesSupported() {
try {
boolean b = Character.isHighSurrogate('a');
return true;
} catch (NoSuchMethodError ex) {
return false;
}
}
/**
* Return true if given file name is a valid class name
* (including "package-info").
* @param clazzname the name of the class to check.
* @return true if given class name is a valid class name
* and false otherwise.
*/
public static boolean isValidClassName(String s) {
if (s.length() < 1) return false;
if (s.equals("package-info")) return true;
if (surrogatesSupported) {
int cp = s.codePointAt(0);
if (!Character.isJavaIdentifierStart(cp))
return false;
for (int j=Character.charCount(cp); j<s.length(); j+=Character.charCount(cp)) {
cp = s.codePointAt(j);
if (!Character.isJavaIdentifierPart(cp))
return false;
}
} else {
if (!Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int j=1; j<s.length(); j++)
if (!Character.isJavaIdentifierPart(s.charAt(j)))
return false;
}
return true;
}
/**
* From a list of top level trees, return the list of contained class definitions
*/
List<JCClassDecl> listClasses(List<JCCompilationUnit> trees) {
ListBuffer<JCClassDecl> result = new ListBuffer<JCClassDecl>();
for (JCCompilationUnit t : trees) {
for (JCTree def : t.defs) {
if (def.getTag() == JCTree.CLASSDEF)
result.append((JCClassDecl)def);
}
}
return result.toList();
}
}
| 16,974 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ConstructorDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ConstructorDocImpl.java | /*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.util.Position;
/**
* Represents a constructor of a java class.
*
* @since 1.2
* @author Robert Field
* @author Neal Gafter (rewrite)
*/
public class ConstructorDocImpl
extends ExecutableMemberDocImpl implements ConstructorDoc {
/**
* constructor.
*/
public ConstructorDocImpl(DocEnv env, MethodSymbol sym) {
super(env, sym);
}
/**
* constructor.
*/
public ConstructorDocImpl(DocEnv env, MethodSymbol sym,
String docComment, JCMethodDecl tree, Position.LineMap lineMap) {
super(env, sym, docComment, tree, lineMap);
}
/**
* Return true if it is a constructor, which it is.
*
* @return true
*/
public boolean isConstructor() {
return true;
}
/**
* Get the name.
*
* @return the name of the member qualified by class (but not package)
*/
public String name() {
ClassSymbol c = sym.enclClass();
String n = c.name.toString();
for (c = c.owner.enclClass(); c != null; c = c.owner.enclClass()) {
n = c.name.toString() + "." + n;
}
return n;
}
/**
* Get the name.
*
* @return the qualified name of the member.
*/
public String qualifiedName() {
return sym.enclClass().getQualifiedName().toString();
}
/**
* Returns a string representation of this constructor. Includes the
* qualified signature and any type parameters.
* Type parameters precede the class name, as they do in the syntax
* for invoking constructors with explicit type parameters using "new".
* (This is unlike the syntax for invoking methods with explicit type
* parameters.)
*/
public String toString() {
return typeParametersString() + qualifiedName() + signature();
}
}
| 3,321 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SourcePositionImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/SourcePositionImpl.java | /*
* Copyright (c) 2001, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.io.File;
import javax.tools.FileObject;
import com.sun.javadoc.SourcePosition;
import com.sun.tools.javac.util.Position;
/**
* A source position: filename, line number, and column number.
*
* @since J2SE1.4
* @author Neal M Gafter
* @author Michael Van De Vanter (position representation changed to char offsets)
*/
public class SourcePositionImpl implements SourcePosition {
FileObject filename;
int position;
Position.LineMap lineMap;
/** The source file. Returns null if no file information is
* available. */
public File file() {
return (filename == null) ? null : new File(filename.getName());
}
/** The source file. Returns null if no file information is
* available. */
public FileObject fileObject() {
return filename;
}
/** The line in the source file. The first line is numbered 1;
* 0 means no line number information is available. */
public int line() {
if (lineMap == null) {
return 0;
} else {
return lineMap.getLineNumber(position);
}
}
/** The column in the source file. The first column is
* numbered 1; 0 means no column information is available.
* Columns count characters in the input stream; a tab
* advances the column number to the next 8-column tab stop.
*/
public int column() {
if (lineMap == null) {
return 0;
}else {
return lineMap.getColumnNumber(position);
}
}
private SourcePositionImpl(FileObject file, int position,
Position.LineMap lineMap) {
super();
this.filename = file;
this.position = position;
this.lineMap = lineMap;
}
public static SourcePosition make(FileObject file, int pos,
Position.LineMap lineMap) {
if (file == null) return null;
return new SourcePositionImpl(file, pos, lineMap);
}
public String toString() {
// Backwards compatibility hack. ZipFileObjects use the format
// zipfile(zipentry) but javadoc has been using zipfile/zipentry
String fn = filename.getName();
if (fn.endsWith(")")) {
int paren = fn.lastIndexOf("(");
if (paren != -1)
fn = fn.substring(0, paren)
+ File.separatorChar
+ fn.substring(paren + 1, fn.length() - 1);
}
if (position == Position.NOPOS)
return fn;
else
return fn + ":" + line();
}
}
| 3,862 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Start.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/Start.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.main.CommandLine;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Options;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import static com.sun.tools.javac.code.Flags.*;
/**
* Main program of Javadoc.
* Previously named "Main".
*
* @since 1.2
* @author Robert Field
* @author Neal Gafter (rewrite)
*/
class Start {
private final String defaultDocletClassName;
private final ClassLoader docletParentClassLoader;
private static final String javadocName = "javadoc";
private static final String standardDocletClassName =
"com.sun.tools.doclets.standard.Standard";
private ListBuffer<String[]> options = new ListBuffer<String[]>();
private ModifierFilter showAccess = null;
private long defaultFilter = PUBLIC | PROTECTED;
private Messager messager;
String docLocale = "";
boolean breakiterator = false;
boolean quiet = false;
String encoding = null;
private DocletInvoker docletInvoker;
private static final int F_VERBOSE = 1 << 0;
private static final int F_WARNINGS = 1 << 2;
/* Treat warnings as errors. */
private boolean rejectWarnings = false;
Start(String programName,
PrintWriter errWriter,
PrintWriter warnWriter,
PrintWriter noticeWriter,
String defaultDocletClassName) {
this(programName, errWriter, warnWriter, noticeWriter, defaultDocletClassName, null);
}
Start(String programName,
PrintWriter errWriter,
PrintWriter warnWriter,
PrintWriter noticeWriter,
String defaultDocletClassName,
ClassLoader docletParentClassLoader) {
Context tempContext = new Context(); // interim context until option decoding completed
messager = new Messager(tempContext, programName, errWriter, warnWriter, noticeWriter);
this.defaultDocletClassName = defaultDocletClassName;
this.docletParentClassLoader = docletParentClassLoader;
}
Start(String programName, String defaultDocletClassName) {
this(programName, defaultDocletClassName, null);
}
Start(String programName, String defaultDocletClassName,
ClassLoader docletParentClassLoader) {
Context tempContext = new Context(); // interim context until option decoding completed
messager = new Messager(tempContext, programName);
this.defaultDocletClassName = defaultDocletClassName;
this.docletParentClassLoader = docletParentClassLoader;
}
Start(String programName, ClassLoader docletParentClassLoader) {
this(programName, standardDocletClassName, docletParentClassLoader);
}
Start(String programName) {
this(programName, standardDocletClassName);
}
Start(ClassLoader docletParentClassLoader) {
this(javadocName, docletParentClassLoader);
}
Start() {
this(javadocName);
}
/**
* Usage
*/
private void usage() {
messager.notice("main.usage");
// let doclet print usage information (does nothing on error)
if (docletInvoker != null) {
docletInvoker.optionLength("-help");
}
}
/**
* Usage
*/
private void Xusage() {
messager.notice("main.Xusage");
}
/**
* Exit
*/
private void exit() {
messager.exit();
}
/**
* Main program - external wrapper
*/
int begin(String... argv) {
boolean failed = false;
try {
failed = !parseAndExecute(argv);
} catch(Messager.ExitJavadoc exc) {
// ignore, we just exit this way
} catch (OutOfMemoryError ee) {
messager.error(null, "main.out.of.memory");
failed = true;
} catch (Error ee) {
ee.printStackTrace();
messager.error(null, "main.fatal.error");
failed = true;
} catch (Exception ee) {
ee.printStackTrace();
messager.error(null, "main.fatal.exception");
failed = true;
} finally {
messager.exitNotice();
messager.flush();
}
failed |= messager.nerrors() > 0;
failed |= rejectWarnings && messager.nwarnings() > 0;
return failed ? 1 : 0;
}
private void addToList(ListBuffer<String> list, String str){
StringTokenizer st = new StringTokenizer(str, ":");
String current;
while(st.hasMoreTokens()){
current = st.nextToken();
list.append(current);
}
}
/**
* Main program - internal
*/
private boolean parseAndExecute(String... argv) throws IOException {
long tm = System.currentTimeMillis();
ListBuffer<String> javaNames = new ListBuffer<String>();
// Preprocess @file arguments
try {
argv = CommandLine.parse(argv);
} catch (FileNotFoundException e) {
messager.error(null, "main.cant.read", e.getMessage());
exit();
} catch (IOException e) {
e.printStackTrace();
exit();
}
setDocletInvoker(argv);
ListBuffer<String> subPackages = new ListBuffer<String>();
ListBuffer<String> excludedPackages = new ListBuffer<String>();
Context context = new Context();
// Setup a new Messager, using the same initial parameters as the
// existing Messager, except that this one will be able to use any
// options that may be set up below.
Messager.preRegister(context,
messager.programName,
messager.errWriter, messager.warnWriter, messager.noticeWriter);
Options compOpts = Options.instance(context);
boolean docClasses = false;
// Parse arguments
for (int i = 0 ; i < argv.length ; i++) {
String arg = argv[i];
if (arg.equals("-subpackages")) {
oneArg(argv, i++);
addToList(subPackages, argv[i]);
} else if (arg.equals("-exclude")){
oneArg(argv, i++);
addToList(excludedPackages, argv[i]);
} else if (arg.equals("-verbose")) {
setOption(arg);
compOpts.put("-verbose", "");
} else if (arg.equals("-encoding")) {
oneArg(argv, i++);
encoding = argv[i];
compOpts.put("-encoding", argv[i]);
} else if (arg.equals("-breakiterator")) {
breakiterator = true;
setOption("-breakiterator");
} else if (arg.equals("-quiet")) {
quiet = true;
setOption("-quiet");
} else if (arg.equals("-help")) {
usage();
exit();
} else if (arg.equals("-Xclasses")) {
setOption(arg);
docClasses = true;
} else if (arg.equals("-Xwerror")) {
setOption(arg);
rejectWarnings = true;
} else if (arg.equals("-private")) {
setOption(arg);
setFilter(ModifierFilter.ALL_ACCESS);
} else if (arg.equals("-package")) {
setOption(arg);
setFilter(PUBLIC | PROTECTED |
ModifierFilter.PACKAGE );
} else if (arg.equals("-protected")) {
setOption(arg);
setFilter(PUBLIC | PROTECTED );
} else if (arg.equals("-public")) {
setOption(arg);
setFilter(PUBLIC);
} else if (arg.equals("-source")) {
oneArg(argv, i++);
if (compOpts.get("-source") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-source", argv[i]);
} else if (arg.equals("-prompt")) {
compOpts.put("-prompt", "-prompt");
messager.promptOnError = true;
} else if (arg.equals("-sourcepath")) {
oneArg(argv, i++);
if (compOpts.get("-sourcepath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-sourcepath", argv[i]);
} else if (arg.equals("-classpath")) {
oneArg(argv, i++);
if (compOpts.get("-classpath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-classpath", argv[i]);
} else if (arg.equals("-sysclasspath")) {
oneArg(argv, i++);
if (compOpts.get("-bootclasspath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-bootclasspath", argv[i]);
} else if (arg.equals("-bootclasspath")) {
oneArg(argv, i++);
if (compOpts.get("-bootclasspath") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-bootclasspath", argv[i]);
} else if (arg.equals("-extdirs")) {
oneArg(argv, i++);
if (compOpts.get("-extdirs") != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put("-extdirs", argv[i]);
} else if (arg.equals("-overview")) {
oneArg(argv, i++);
} else if (arg.equals("-doclet")) {
i++; // handled in setDocletInvoker
} else if (arg.equals("-docletpath")) {
i++; // handled in setDocletInvoker
} else if (arg.equals("-locale")) {
if (i != 0)
usageError("main.locale_first");
oneArg(argv, i++);
docLocale = argv[i];
} else if (arg.equals("-Xmaxerrs") || arg.equals("-Xmaxwarns")) {
oneArg(argv, i++);
if (compOpts.get(arg) != null) {
usageError("main.option.already.seen", arg);
}
compOpts.put(arg, argv[i]);
} else if (arg.equals("-X")) {
Xusage();
exit();
} else if (arg.startsWith("-XD")) {
String s = arg.substring("-XD".length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
compOpts.put(key, value);
}
// call doclet for its options
// other arg starts with - is invalid
else if ( arg.startsWith("-") ) {
int optionLength;
optionLength = docletInvoker.optionLength(arg);
if (optionLength < 0) {
// error already displayed
exit();
} else if (optionLength == 0) {
// option not found
usageError("main.invalid_flag", arg);
} else {
// doclet added option
if ((i + optionLength) > argv.length) {
usageError("main.requires_argument", arg);
}
ListBuffer<String> args = new ListBuffer<String>();
for (int j = 0; j < optionLength-1; ++j) {
args.append(argv[++i]);
}
setOption(arg, args.toList());
}
} else {
javaNames.append(arg);
}
}
if (javaNames.isEmpty() && subPackages.isEmpty()) {
usageError("main.No_packages_or_classes_specified");
}
if (!docletInvoker.validOptions(options.toList())) {
// error message already displayed
exit();
}
JavadocTool comp = JavadocTool.make0(context);
if (comp == null) return false;
if (showAccess == null) {
setFilter(defaultFilter);
}
LanguageVersion languageVersion = docletInvoker.languageVersion();
RootDocImpl root = comp.getRootDocImpl(
docLocale, encoding, showAccess,
javaNames.toList(), options.toList(), breakiterator,
subPackages.toList(), excludedPackages.toList(),
docClasses,
// legacy?
languageVersion == null || languageVersion == LanguageVersion.JAVA_1_1, quiet);
// pass off control to the doclet
boolean ok = root != null;
if (ok) ok = docletInvoker.start(root);
Messager docletMessager = Messager.instance0(context);
messager.nwarnings += docletMessager.nwarnings;
messager.nerrors += docletMessager.nerrors;
// We're done.
if (compOpts.get("-verbose") != null) {
tm = System.currentTimeMillis() - tm;
messager.notice("main.done_in", Long.toString(tm));
}
return ok;
}
private void setDocletInvoker(String[] argv) {
String docletClassName = null;
String docletPath = null;
// Parse doclet specifying arguments
for (int i = 0 ; i < argv.length ; i++) {
String arg = argv[i];
if (arg.equals("-doclet")) {
oneArg(argv, i++);
if (docletClassName != null) {
usageError("main.more_than_one_doclet_specified_0_and_1",
docletClassName, argv[i]);
}
docletClassName = argv[i];
} else if (arg.equals("-docletpath")) {
oneArg(argv, i++);
if (docletPath == null) {
docletPath = argv[i];
} else {
docletPath += File.pathSeparator + argv[i];
}
}
}
if (docletClassName == null) {
docletClassName = defaultDocletClassName;
}
// attempt to find doclet
docletInvoker = new DocletInvoker(messager,
docletClassName, docletPath,
docletParentClassLoader);
}
private void setFilter(long filterBits) {
if (showAccess != null) {
messager.error(null, "main.incompatible.access.flags");
usage();
exit();
}
showAccess = new ModifierFilter(filterBits);
}
/**
* Set one arg option.
* Error and exit if one argument is not provided.
*/
private void oneArg(String[] args, int index) {
if ((index + 1) < args.length) {
setOption(args[index], args[index+1]);
} else {
usageError("main.requires_argument", args[index]);
}
}
private void usageError(String key) {
messager.error(null, key);
usage();
exit();
}
private void usageError(String key, String a1) {
messager.error(null, key, a1);
usage();
exit();
}
private void usageError(String key, String a1, String a2) {
messager.error(null, key, a1, a2);
usage();
exit();
}
/**
* indicate an option with no arguments was given.
*/
private void setOption(String opt) {
String[] option = { opt };
options.append(option);
}
/**
* indicate an option with one argument was given.
*/
private void setOption(String opt, String argument) {
String[] option = { opt, argument };
options.append(option);
}
/**
* indicate an option with the specified list of arguments was given.
*/
private void setOption(String opt, List<String> arguments) {
String[] args = new String[arguments.length() + 1];
int k = 0;
args[k++] = opt;
for (List<String> i = arguments; i.nonEmpty(); i=i.tail) {
args[k++] = i.head;
}
options = options.append(args);
}
}
| 17,674 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SerializedForm.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/SerializedForm.java | /*
* Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Names;
/**
* The serialized form is the specification of a class' serialization
* state. <p>
*
* It consists of the following information:<p>
*
* <pre>
* 1. Whether class is Serializable or Externalizable.
* 2. Javadoc for serialization methods.
* a. For Serializable, the optional readObject, writeObject,
* readResolve and writeReplace.
* serialData tag describes, in prose, the sequence and type
* of optional data written by writeObject.
* b. For Externalizable, writeExternal and readExternal.
* serialData tag describes, in prose, the sequence and type
* of optional data written by writeExternal.
* 3. Javadoc for serialization data layout.
* a. For Serializable, the name,type and description
* of each Serializable fields.
* b. For Externalizable, data layout is described by 2(b).
* </pre>
*
* @since 1.2
* @author Joe Fialli
* @author Neal Gafter (rewrite but not too proud)
*/
class SerializedForm {
ListBuffer<MethodDoc> methods = new ListBuffer<MethodDoc>();
/* List of FieldDocImpl - Serializable fields.
* Singleton list if class defines Serializable fields explicitly.
* Otherwise, list of default serializable fields.
* 0 length list for Externalizable.
*/
private final ListBuffer<FieldDocImpl> fields = new ListBuffer<FieldDocImpl>();
/* True if class specifies serializable fields explicitly.
* using special static member, serialPersistentFields.
*/
private boolean definesSerializableFields = false;
// Specially treated field/method names defined by Serialization.
private static final String SERIALIZABLE_FIELDS = "serialPersistentFields";
private static final String READOBJECT = "readObject";
private static final String WRITEOBJECT = "writeObject";
private static final String READRESOLVE = "readResolve";
private static final String WRITEREPLACE = "writeReplace";
private static final String READOBJECTNODATA = "readObjectNoData";
/**
* Constructor.
*
* Catalog Serializable fields for Serializable class.
* Catalog serialization methods for Serializable and
* Externalizable classes.
*/
SerializedForm(DocEnv env, ClassSymbol def, ClassDocImpl cd) {
if (cd.isExternalizable()) {
/* look up required public accessible methods,
* writeExternal and readExternal.
*/
String[] readExternalParamArr = { "java.io.ObjectInput" };
String[] writeExternalParamArr = { "java.io.ObjectOutput" };
MethodDoc md = cd.findMethod("readExternal", readExternalParamArr);
if (md != null) {
methods.append(md);
}
md = cd.findMethod("writeExternal", writeExternalParamArr);
if (md != null) {
methods.append(md);
Tag tag[] = md.tags("serialData");
}
// } else { // isSerializable() //### ???
} else if (cd.isSerializable()) {
VarSymbol dsf = getDefinedSerializableFields(def);
if (dsf != null) {
/* Define serializable fields with array of ObjectStreamField.
* Each ObjectStreamField should be documented by a
* serialField tag.
*/
definesSerializableFields = true;
//### No modifier filtering applied here.
FieldDocImpl dsfDoc = env.getFieldDoc(dsf);
fields.append(dsfDoc);
mapSerialFieldTagImplsToFieldDocImpls(dsfDoc, env, def);
} else {
/* Calculate default Serializable fields as all
* non-transient, non-static fields.
* Fields should be documented by serial tag.
*/
computeDefaultSerializableFields(env, def, cd);
}
/* Check for optional customized readObject, writeObject,
* readResolve and writeReplace, which can all contain
* the serialData tag. */
addMethodIfExist(env, def, READOBJECT);
addMethodIfExist(env, def, WRITEOBJECT);
addMethodIfExist(env, def, READRESOLVE);
addMethodIfExist(env, def, WRITEREPLACE);
addMethodIfExist(env, def, READOBJECTNODATA);
}
}
/*
* Check for explicit Serializable fields.
* Check for a private static array of ObjectStreamField with
* name SERIALIZABLE_FIELDS.
*/
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;
}
/*
* Compute default Serializable fields from all members of ClassSymbol.
*
* Since the fields of ClassDocImpl might not contain private or
* package accessible fields, must walk over all members of ClassSymbol.
*/
private void computeDefaultSerializableFields(DocEnv env,
ClassSymbol def,
ClassDocImpl cd) {
for (Scope.Entry e = def.members().elems; e != null; e = e.sibling) {
if (e.sym != null && e.sym.kind == Kinds.VAR) {
VarSymbol f = (VarSymbol)e.sym;
if ((f.flags() & Flags.STATIC) == 0 &&
(f.flags() & Flags.TRANSIENT) == 0) {
//### No modifier filtering applied here.
FieldDocImpl fd = env.getFieldDoc(f);
//### Add to beginning.
//### Preserve order used by old 'javadoc'.
fields.prepend(fd);
}
}
}
}
/*
* Catalog Serializable method if it exists in current ClassSymbol.
* Do not look for method in superclasses.
*
* Serialization requires these methods to be non-static.
*
* @param method should be an unqualified Serializable method
* name either READOBJECT, WRITEOBJECT, READRESOLVE
* or WRITEREPLACE.
* @param visibility the visibility flag for the given method.
*/
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));
}
}
}
}
/*
* Associate serialField tag fieldName with FieldDocImpl member.
* Note: A serialField tag does not have to map an existing field
* of a class.
*/
private void mapSerialFieldTagImplsToFieldDocImpls(FieldDocImpl spfDoc,
DocEnv env,
ClassSymbol def) {
Names names = def.name.table.names;
SerialFieldTag[] sfTag = spfDoc.serialFieldTags();
for (int i = 0; i < sfTag.length; i++) {
Name fieldName = names.fromString(sfTag[i].fieldName());
// Look for a FieldDocImpl that is documented by serialFieldTagImpl.
for (Scope.Entry e = def.members().lookup(fieldName); e.scope != null; e = e.next()) {
if (e.sym.kind == Kinds.VAR) {
VarSymbol f = (VarSymbol)e.sym;
FieldDocImpl fdi = env.getFieldDoc(f);
((SerialFieldTagImpl)(sfTag[i])).mapToFieldDocImpl(fdi);
break;
}
}
}
}
/**
* Return serializable fields in class. <p>
*
* Returns either a list of default fields documented by serial tag comment or
* javadoc comment<p>
* Or Returns a single FieldDocImpl for serialPersistentField. There is a
* serialField tag for each serializable field.<p>
*
* @return an array of FieldDocImpl for representing the visible
* fields in this class.
*/
FieldDoc[] fields() {
return (FieldDoc[])fields.toArray(new FieldDocImpl[fields.length()]);
}
/**
* Return serialization methods in class.
*
* @return an array of MethodDocImpl for serialization methods in this class.
*/
MethodDoc[] methods() {
return methods.toArray(new MethodDoc[methods.length()]);
}
/**
* Returns true if Serializable fields are defined explicitly using
* member, serialPersistentFields.
*
* @see #fields()
*/
boolean definesSerializableFields() {
return definesSerializableFields;
}
}
| 11,426 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ParamTagImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ParamTagImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.util.regex.*;
import com.sun.javadoc.*;
/**
* Represents an @param documentation tag.
* Parses and stores the name and comment parts of the parameter tag.
*
* @author Robert Field
*
*/
class ParamTagImpl extends TagImpl implements ParamTag {
private static Pattern typeParamRE = Pattern.compile("<([^<>]+)>");
private final String parameterName;
private final String parameterComment;
private final boolean isTypeParameter;
/**
* Cached inline tags.
*/
private Tag[] inlineTags;
ParamTagImpl(DocImpl holder, String name, String text) {
super(holder, name, text);
String[] sa = divideAtWhite();
Matcher m = typeParamRE.matcher(sa[0]);
isTypeParameter = m.matches();
parameterName = isTypeParameter ? m.group(1) : sa[0];
parameterComment = sa[1];
}
/**
* Return the parameter name.
*/
public String parameterName() {
return parameterName;
}
/**
* Return the parameter comment.
*/
public String parameterComment() {
return parameterComment;
}
/**
* Return the kind of this tag.
*/
@Override
public String kind() {
return "@param";
}
/**
* Return true if this ParamTag corresponds to a type parameter.
*/
public boolean isTypeParameter() {
return isTypeParameter;
}
/**
* convert this object to a string.
*/
@Override
public String toString() {
return name + ":" + text;
}
/**
* For the parameter comment with embedded @link tags return the array of
* TagImpls consisting of SeeTagImpl(s) and text containing TagImpl(s).
*
* @return TagImpl[] Array of tags with inline SeeTagImpls.
* @see TagImpl#inlineTagImpls()
* @see ThrowsTagImpl#inlineTagImpls()
*/
@Override
public Tag[] inlineTags() {
if (inlineTags == null) {
inlineTags = Comment.getInlineTags(holder, parameterComment);
}
return inlineTags;
}
}
| 3,314 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PrimitiveType.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/PrimitiveType.java | /*
* Copyright (c) 2001, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.code.Type.ClassType;
class PrimitiveType implements com.sun.javadoc.Type {
private final String name;
static final PrimitiveType voidType = new PrimitiveType("void");
static final PrimitiveType booleanType = new PrimitiveType("boolean");
static final PrimitiveType byteType = new PrimitiveType("byte");
static final PrimitiveType charType = new PrimitiveType("char");
static final PrimitiveType shortType = new PrimitiveType("short");
static final PrimitiveType intType = new PrimitiveType("int");
static final PrimitiveType longType = new PrimitiveType("long");
static final PrimitiveType floatType = new PrimitiveType("float");
static final PrimitiveType doubleType = new PrimitiveType("double");
// error type, should never actually be used
static final PrimitiveType errorType = new PrimitiveType("");
PrimitiveType(String name) {
this.name = name;
}
/**
* Return unqualified name of type excluding any dimension information.
* <p>
* For example, a two dimensional array of String returns 'String'.
*/
public String typeName() {
return name;
}
/**
* Return qualified name of type excluding any dimension information.
*<p>
* For example, a two dimensional array of String
* returns 'java.lang.String'.
*/
public String qualifiedTypeName() {
return name;
}
/**
* Return the simple name of this type.
*/
public String simpleTypeName() {
return name;
}
/**
* Return the type's dimension information, as a string.
* <p>
* For example, a two dimensional array of String returns '[][]'.
*/
public String dimension() {
return "";
}
/**
* Return this type as a class. Array dimensions are ignored.
*
* @return a ClassDocImpl if the type is a Class.
* Return null if it is a primitive type..
*/
public ClassDoc asClassDoc() {
return null;
}
/**
* Return null, as this is not an annotation type.
*/
public AnnotationTypeDoc asAnnotationTypeDoc() {
return null;
}
/**
* Return null, as this is not an instantiation.
*/
public ParameterizedType asParameterizedType() {
return null;
}
/**
* Return null, as this is not a type variable.
*/
public TypeVariable asTypeVariable() {
return null;
}
/**
* Return null, as this is not a wildcard type;
*/
public WildcardType asWildcardType() {
return null;
}
/**
* Returns a string representation of the type.
*
* Return name of type including any dimension information.
* <p>
* For example, a two dimensional array of String returns
* <code>String[][]</code>.
*
* @return name of type including any dimension information.
*/
public String toString() {
return qualifiedTypeName();
}
/**
* Return true if this is a primitive type.
*/
public boolean isPrimitive() {
return true;
}
}
| 4,582 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DocletInvoker.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/DocletInvoker.java | /*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import static com.sun.javadoc.LanguageVersion.*;
import com.sun.tools.javac.util.List;
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
/**
* Class creates, controls and invokes doclets.
* @author Neal Gafter (rewrite)
*/
public class DocletInvoker {
private final Class<?> docletClass;
private final String docletClassName;
private final ClassLoader appClassLoader;
private final Messager messager;
private static class DocletInvokeException extends Exception {
private static final long serialVersionUID = 0;
}
private String appendPath(String path1, String path2) {
if (path1 == null || path1.length() == 0) {
return path2 == null ? "." : path2;
} else if (path2 == null || path2.length() == 0) {
return path1;
} else {
return path1 + File.pathSeparator + path2;
}
}
public DocletInvoker(Messager messager,
String docletClassName, String docletPath,
ClassLoader docletParentClassLoader) {
this.messager = messager;
this.docletClassName = docletClassName;
// construct class loader
String cpString = null; // make sure env.class.path defaults to dot
// do prepends to get correct ordering
cpString = appendPath(System.getProperty("env.class.path"), cpString);
cpString = appendPath(System.getProperty("java.class.path"), cpString);
cpString = appendPath(docletPath, cpString);
URL[] urls = com.sun.tools.javac.file.Paths.pathToURLs(cpString);
if (docletParentClassLoader == null)
appClassLoader = new URLClassLoader(urls, getDelegationClassLoader(docletClassName));
else
appClassLoader = new URLClassLoader(urls, docletParentClassLoader);
// attempt to find doclet
Class<?> dc = null;
try {
dc = appClassLoader.loadClass(docletClassName);
} catch (ClassNotFoundException exc) {
messager.error(null, "main.doclet_class_not_found", docletClassName);
messager.exit();
}
docletClass = dc;
}
/*
* Returns the delegation class loader to use when creating
* appClassLoader (used to load the doclet). The context class
* loader is the best choice, but legacy behavior was to use the
* default delegation class loader (aka system class loader).
*
* Here we favor using the context class loader. To ensure
* compatibility with existing apps, we revert to legacy
* behavior if either or both of the following conditions hold:
*
* 1) the doclet is loadable from the system class loader but not
* from the context class loader,
*
* 2) this.getClass() is loadable from the system class loader but not
* from the context class loader.
*/
private ClassLoader getDelegationClassLoader(String docletClassName) {
ClassLoader ctxCL = Thread.currentThread().getContextClassLoader();
ClassLoader sysCL = ClassLoader.getSystemClassLoader();
if (sysCL == null)
return ctxCL;
if (ctxCL == null)
return sysCL;
// Condition 1.
try {
sysCL.loadClass(docletClassName);
try {
ctxCL.loadClass(docletClassName);
} catch (ClassNotFoundException e) {
return sysCL;
}
} catch (ClassNotFoundException e) {
}
// Condition 2.
try {
if (getClass() == sysCL.loadClass(getClass().getName())) {
try {
if (getClass() != ctxCL.loadClass(getClass().getName()))
return sysCL;
} catch (ClassNotFoundException e) {
return sysCL;
}
}
} catch (ClassNotFoundException e) {
}
return ctxCL;
}
/**
* Generate documentation here. Return true on success.
*/
public boolean start(RootDoc root) {
Object retVal;
String methodName = "start";
Class<?>[] paramTypes = { RootDoc.class };
Object[] params = { root };
try {
retVal = invoke(methodName, null, paramTypes, params);
} catch (DocletInvokeException exc) {
return false;
}
if (retVal instanceof Boolean) {
return ((Boolean)retVal).booleanValue();
} else {
messager.error(null, "main.must_return_boolean",
docletClassName, methodName);
return false;
}
}
/**
* Check for doclet added options here. Zero return means
* option not known. Positive value indicates number of
* arguments to option. Negative value means error occurred.
*/
public int optionLength(String option) {
Object retVal;
String methodName = "optionLength";
Class<?>[] paramTypes = { String.class };
Object[] params = { option };
try {
retVal = invoke(methodName, new Integer(0), paramTypes, params);
} catch (DocletInvokeException exc) {
return -1;
}
if (retVal instanceof Integer) {
return ((Integer)retVal).intValue();
} else {
messager.error(null, "main.must_return_int",
docletClassName, methodName);
return -1;
}
}
/**
* Let doclet check that all options are OK. Returning true means
* options are OK. If method does not exist, assume true.
*/
public boolean validOptions(List<String[]> optlist) {
Object retVal;
String options[][] = optlist.toArray(new String[optlist.length()][]);
String methodName = "validOptions";
DocErrorReporter reporter = messager;
Class<?>[] paramTypes = { String[][].class, DocErrorReporter.class };
Object[] params = { options, reporter };
try {
retVal = invoke(methodName, Boolean.TRUE, paramTypes, params);
} catch (DocletInvokeException exc) {
return false;
}
if (retVal instanceof Boolean) {
return ((Boolean)retVal).booleanValue();
} else {
messager.error(null, "main.must_return_boolean",
docletClassName, methodName);
return false;
}
}
/**
* Return the language version supported by this doclet.
* If the method does not exist in the doclet, assume version 1.1.
*/
public LanguageVersion languageVersion() {
try {
Object retVal;
String methodName = "languageVersion";
Class<?>[] paramTypes = new Class<?>[0];
Object[] params = new Object[0];
try {
retVal = invoke(methodName, JAVA_1_1, paramTypes, params);
} catch (DocletInvokeException exc) {
return JAVA_1_1;
}
if (retVal instanceof LanguageVersion) {
return (LanguageVersion)retVal;
} else {
messager.error(null, "main.must_return_languageversion",
docletClassName, methodName);
return JAVA_1_1;
}
} catch (NoClassDefFoundError ex) { // for boostrapping, no Enum class.
return null;
}
}
/**
* Utility method for calling doclet functionality
*/
private Object invoke(String methodName, Object returnValueIfNonExistent,
Class<?>[] paramTypes, Object[] params)
throws DocletInvokeException {
Method meth;
try {
meth = docletClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException exc) {
if (returnValueIfNonExistent == null) {
messager.error(null, "main.doclet_method_not_found",
docletClassName, methodName);
throw new DocletInvokeException();
} else {
return returnValueIfNonExistent;
}
} catch (SecurityException exc) {
messager.error(null, "main.doclet_method_not_accessible",
docletClassName, methodName);
throw new DocletInvokeException();
}
if (!Modifier.isStatic(meth.getModifiers())) {
messager.error(null, "main.doclet_method_must_be_static",
docletClassName, methodName);
throw new DocletInvokeException();
}
ClassLoader savedCCL =
Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(appClassLoader);
return meth.invoke(null , params);
} catch (IllegalArgumentException exc) {
messager.error(null, "main.internal_error_exception_thrown",
docletClassName, methodName, exc.toString());
throw new DocletInvokeException();
} catch (IllegalAccessException exc) {
messager.error(null, "main.doclet_method_not_accessible",
docletClassName, methodName);
throw new DocletInvokeException();
} catch (NullPointerException exc) {
messager.error(null, "main.internal_error_exception_thrown",
docletClassName, methodName, exc.toString());
throw new DocletInvokeException();
} catch (InvocationTargetException exc) {
Throwable err = exc.getTargetException();
if (err instanceof java.lang.OutOfMemoryError) {
messager.error(null, "main.out.of.memory");
} else {
messager.error(null, "main.exception_thrown",
docletClassName, methodName, exc.toString());
exc.getTargetException().printStackTrace();
}
throw new DocletInvokeException();
} finally {
Thread.currentThread().setContextClassLoader(savedCCL);
}
}
}
| 11,808 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
MethodDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/MethodDocImpl.java | /*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.util.Position;
import java.lang.reflect.Modifier;
/**
* Represents a method of a java class.
*
* @since 1.2
* @author Robert Field
* @author Neal Gafter (rewrite)
*/
public class MethodDocImpl
extends ExecutableMemberDocImpl implements MethodDoc {
/**
* constructor.
*/
public MethodDocImpl(DocEnv env, MethodSymbol sym) {
super(env, sym);
}
/**
* constructor.
*/
public MethodDocImpl(DocEnv env, MethodSymbol sym,
String docComment, JCMethodDecl tree, Position.LineMap lineMap) {
super(env, sym, docComment, tree, lineMap);
}
/**
* Return true if it is a method, which it is.
* Note: constructors are not methods.
* This method is overridden by AnnotationTypeElementDocImpl.
*
* @return true
*/
public boolean isMethod() {
return true;
}
/**
* Return true if this method is abstract
*/
public boolean isAbstract() {
//### This is dubious, but old 'javadoc' apparently does it.
//### I regard this as a bug and an obstacle to treating the
//### doclet API as a proper compile-time reflection facility.
//### (maddox 09/26/2000)
if (containingClass().isInterface()) {
//### Don't force creation of ClassDocImpl for super here.
// Abstract modifier is implicit. Strip/canonicalize it.
return false;
}
return Modifier.isAbstract(getModifiers());
}
/**
* Get return type.
*
* @return the return type of this method, null if it
* is a constructor.
*/
public com.sun.javadoc.Type returnType() {
return TypeMaker.getType(env, sym.type.getReturnType(), false);
}
/**
* Return the class that originally defined the method that
* is overridden by the current definition, or null if no
* such class exists.
*
* @return a ClassDocImpl representing the superclass that
* originally defined this method, null if this method does
* not override a definition in a superclass.
*/
public ClassDoc overriddenClass() {
com.sun.javadoc.Type t = overriddenType();
return (t != null) ? t.asClassDoc() : null;
}
/**
* Return the type containing the method that this method overrides.
* It may be a <code>ClassDoc</code> or a <code>ParameterizedType</code>.
*/
public com.sun.javadoc.Type overriddenType() {
if ((sym.flags() & Flags.STATIC) != 0) {
return null;
}
ClassSymbol origin = (ClassSymbol)sym.owner;
for (Type t = env.types.supertype(origin.type);
t.tag == TypeTags.CLASS;
t = env.types.supertype(t)) {
ClassSymbol c = (ClassSymbol)t.tsym;
for (Scope.Entry e = c.members().lookup(sym.name); e.scope != null; e = e.next()) {
if (sym.overrides(e.sym, origin, env.types, true)) {
return TypeMaker.getType(env, t);
}
}
}
return null;
}
/**
* Return the method that this method overrides.
*
* @return a MethodDoc representing a method definition
* in a superclass this method overrides, null if
* this method does not override.
*/
public MethodDoc overriddenMethod() {
// Real overriding only. Static members are simply hidden.
// Likewise for constructors, but the MethodSymbol.overrides
// method takes this into account.
if ((sym.flags() & Flags.STATIC) != 0) {
return null;
}
// Derived from com.sun.tools.javac.comp.Check.checkOverride .
ClassSymbol origin = (ClassSymbol)sym.owner;
for (Type t = env.types.supertype(origin.type);
t.tag == TypeTags.CLASS;
t = env.types.supertype(t)) {
ClassSymbol c = (ClassSymbol)t.tsym;
for (Scope.Entry e = c.members().lookup(sym.name); e.scope != null; e = e.next()) {
if (sym.overrides(e.sym, origin, env.types, true)) {
return env.getMethodDoc((MethodSymbol)e.sym);
}
}
}
return null;
}
/**
* Tests whether this method overrides another.
* The overridden method may be one declared in a superclass or
* a superinterface (unlike {@link #overriddenMethod()}).
*
* <p> When a non-abstract method overrides an abstract one, it is
* also said to <i>implement</i> the other.
*
* @param meth the other method to examine
* @return <tt>true</tt> if this method overrides the other
*/
public boolean overrides(MethodDoc meth) {
MethodSymbol overridee = ((MethodDocImpl) meth).sym;
ClassSymbol origin = (ClassSymbol) sym.owner;
return sym.name == overridee.name &&
// not reflexive as per JLS
sym != overridee &&
// we don't care if overridee is static, though that wouldn't
// compile
!sym.isStatic() &&
// sym, whose declaring type is the origin, must be
// in a subtype of overridee's type
env.types.asSuper(origin.type, overridee.owner) != null &&
// check access and signatures; don't check return types
sym.overrides(overridee, origin, env.types, false);
}
public String name() {
return sym.name.toString();
}
public String qualifiedName() {
return sym.enclClass().getQualifiedName() + "." + sym.name;
}
/**
* Returns a string representation of this method. Includes the
* qualified signature, the qualified method name, and any type
* parameters. Type parameters follow the class name, as they do
* in the syntax for invoking methods with explicit type parameters.
*/
public String toString() {
return sym.enclClass().getQualifiedName() +
"." + typeParametersString() + name() + signature();
}
}
| 7,612 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ParameterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ParameterImpl.java | /*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
/**
* ParameterImpl information.
* This includes a parameter type and parameter name.
*
* @author Kaiyang Liu (original)
* @author Robert Field (rewrite)
* @author Scott Seligman (generics, annotations)
*/
class ParameterImpl implements Parameter {
private final DocEnv env;
private final VarSymbol sym;
private final com.sun.javadoc.Type type;
/**
* Constructor of parameter info class.
*/
ParameterImpl(DocEnv env, VarSymbol sym) {
this.env = env;
this.sym = sym;
this.type = TypeMaker.getType(env, sym.type, false);
}
/**
* Get the type of this parameter.
*/
public com.sun.javadoc.Type type() {
return type;
}
/**
* Get local name of this parameter.
* For example if parameter is the short 'index', returns "index".
*/
public String name() {
return sym.toString();
}
/**
* Get type name of this parameter.
* For example if parameter is the short 'index', returns "short".
*/
public String typeName() {
return (type instanceof ClassDoc || type instanceof TypeVariable)
? type.typeName() // omit formal type params or bounds
: type.toString();
}
/**
* Returns a string representation of the parameter.
* <p>
* For example if parameter is the short 'index', returns "short index".
*
* @return type name and parameter name of this parameter.
*/
public String toString() {
return typeName() + " " + sym;
}
/**
* Get the annotations of this parameter.
* Return an empty array if there are none.
*/
public AnnotationDesc[] annotations() {
AnnotationDesc res[] = new AnnotationDesc[sym.getAnnotationMirrors().length()];
int i = 0;
for (Attribute.Compound a : sym.getAnnotationMirrors()) {
res[i++] = new AnnotationDescImpl(env, a);
}
return res;
}
}
| 3,390 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
RootDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/RootDocImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.io.IOException;
import java.util.Locale;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import com.sun.javadoc.*;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Position;
/**
* This class holds the information from one run of javadoc.
* Particularly the packages, classes and options specified
* by the user..
*
* @since 1.2
* @author Robert Field
* @author Atul M Dambalkar
* @author Neal Gafter (rewrite)
*/
public class RootDocImpl extends DocImpl implements RootDoc {
/**
* list of classes specified on the command line.
*/
private List<ClassDocImpl> cmdLineClasses;
/**
* list of packages specified on the command line.
*/
private List<PackageDocImpl> cmdLinePackages;
/**
* a collection of all options.
*/
private List<String[]> options;
/**
* Constructor used when reading source files.
*
* @param env the documentation environment, state for this javadoc run
* @param classes list of classes specified on the commandline
* @param packages list of package names specified on the commandline
* @param options list of options
*/
public RootDocImpl(DocEnv env, List<JCClassDecl> classes, List<String> packages, List<String[]> options) {
super(env, null);
this.options = options;
setPackages(env, packages);
setClasses(env, classes);
}
/**
* Constructor used when reading class files.
*
* @param env the documentation environment, state for this javadoc run
* @param classes list of class names specified on the commandline
* @param options list of options
*/
public RootDocImpl(DocEnv env, List<String> classes, List<String[]> options) {
super(env, null);
this.options = options;
cmdLinePackages = List.nil();
ListBuffer<ClassDocImpl> classList = new ListBuffer<ClassDocImpl>();
for (String className : classes) {
ClassDocImpl c = env.loadClass(className);
if (c == null)
env.error(null, "javadoc.class_not_found", className);
else
classList = classList.append(c);
}
cmdLineClasses = classList.toList();
}
/**
* Initialize classes information. Those classes are input from
* command line.
*
* @param env the compilation environment
* @param classes a list of ClassDeclaration
*/
private void setClasses(DocEnv env, List<JCClassDecl> classes) {
ListBuffer<ClassDocImpl> result = new ListBuffer<ClassDocImpl>();
for (JCClassDecl def : classes) {
//### Do we want modifier check here?
if (env.shouldDocument(def.sym)) {
ClassDocImpl cd = env.getClassDoc(def.sym);
if (cd != null) {
cd.isIncluded = true;
result.append(cd);
} //else System.out.println(" (classdoc is null)");//DEBUG
} //else System.out.println(" (env.shouldDocument() returned false)");//DEBUG
}
cmdLineClasses = result.toList();
}
/**
* Initialize packages information.
*
* @param env the compilation environment
* @param packages a list of package names (String)
*/
private void setPackages(DocEnv env, List<String> packages) {
ListBuffer<PackageDocImpl> packlist = new ListBuffer<PackageDocImpl>();
for (String name : packages) {
PackageDocImpl pkg = env.lookupPackage(name);
if (pkg != null) {
pkg.isIncluded = true;
packlist.append(pkg);
} else {
env.warning(null, "main.no_source_files_for_package", name);
}
}
cmdLinePackages = packlist.toList();
}
/**
* Command line options.
*
* <pre>
* For example, given:
* javadoc -foo this that -bar other ...
*
* This method will return:
* options()[0][0] = "-foo"
* options()[0][1] = "this"
* options()[0][2] = "that"
* options()[1][0] = "-bar"
* options()[1][1] = "other"
* </pre>
*
* @return an array of arrays of String.
*/
public String[][] options() {
return options.toArray(new String[options.length()][]);
}
/**
* Packages specified on the command line.
*/
public PackageDoc[] specifiedPackages() {
return (PackageDoc[])cmdLinePackages
.toArray(new PackageDocImpl[cmdLinePackages.length()]);
}
/**
* Classes and interfaces specified on the command line.
*/
public ClassDoc[] specifiedClasses() {
ListBuffer<ClassDocImpl> classesToDocument = new ListBuffer<ClassDocImpl>();
for (ClassDocImpl cd : cmdLineClasses) {
cd.addAllClasses(classesToDocument, true);
}
return (ClassDoc[])classesToDocument.toArray(new ClassDocImpl[classesToDocument.length()]);
}
/**
* Return all classes and interfaces (including those inside
* packages) to be documented.
*/
public ClassDoc[] classes() {
ListBuffer<ClassDocImpl> classesToDocument = new ListBuffer<ClassDocImpl>();
for (ClassDocImpl cd : cmdLineClasses) {
cd.addAllClasses(classesToDocument, true);
}
for (PackageDocImpl pd : cmdLinePackages) {
pd.addAllClassesTo(classesToDocument);
}
return classesToDocument.toArray(new ClassDocImpl[classesToDocument.length()]);
}
/**
* Return a ClassDoc for the specified class/interface name
*
* @param qualifiedName qualified class name
* (i.e. includes package name).
*
* @return a ClassDocImpl holding the specified class, null if
* this class is not referenced.
*/
public ClassDoc classNamed(String qualifiedName) {
return env.lookupClass(qualifiedName);
}
/**
* Return a PackageDoc for the specified package name
*
* @param name package name
*
* @return a PackageDoc holding the specified package, null if
* this package is not referenced.
*/
public PackageDoc packageNamed(String name) {
return env.lookupPackage(name);
}
/**
* Return the name of this Doc item.
*
* @return the string <code>"*RootDocImpl*"</code>.
*/
public String name() {
return "*RootDocImpl*";
}
/**
* Return the name of this Doc item.
*
* @return the string <code>"*RootDocImpl*"</code>.
*/
public String qualifiedName() {
return "*RootDocImpl*";
}
/**
* Return true if this Doc is include in the active set.
* RootDocImpl isn't even a program entity so it is always false.
*/
public boolean isIncluded() {
return false;
}
/**
* Print error message, increment error count.
*
* @param msg message to print
*/
public void printError(String msg) {
env.printError(msg);
}
/**
* Print error message, increment error count.
*
* @param msg message to print
*/
public void printError(SourcePosition pos, String msg) {
env.printError(pos, msg);
}
/**
* Print warning message, increment warning count.
*
* @param msg message to print
*/
public void printWarning(String msg) {
env.printWarning(msg);
}
/**
* Print warning message, increment warning count.
*
* @param msg message to print
*/
public void printWarning(SourcePosition pos, String msg) {
env.printWarning(pos, msg);
}
/**
* Print a message.
*
* @param msg message to print
*/
public void printNotice(String msg) {
env.printNotice(msg);
}
/**
* Print a message.
*
* @param msg message to print
*/
public void printNotice(SourcePosition pos, String msg) {
env.printNotice(pos, msg);
}
/**
* Return the path of the overview file and null if it does not exist.
* @return the path of the overview file and null if it does not exist.
*/
private JavaFileObject getOverviewPath() {
for (String[] opt : options) {
if (opt[0].equals("-overview")) {
if (env.fileManager instanceof StandardJavaFileManager) {
StandardJavaFileManager fm = (StandardJavaFileManager) env.fileManager;
return fm.getJavaFileObjects(opt[1]).iterator().next();
}
}
}
return null;
}
/**
* Do lazy initialization of "documentation" string.
*/
@Override
protected String documentation() {
if (documentation == null) {
int cnt = options.length();
JavaFileObject overviewPath = getOverviewPath();
if (overviewPath == null) {
// no doc file to be had
documentation = "";
} else {
// read from file
try {
documentation = readHTMLDocumentation(
overviewPath.openInputStream(),
overviewPath);
} catch (IOException exc) {
documentation = "";
env.error(null, "javadoc.File_Read_Error", overviewPath.getName());
}
}
}
return documentation;
}
/**
* Return the source position of the entity, or null if
* no position is available.
*/
@Override
public SourcePosition position() {
JavaFileObject path;
return ((path = getOverviewPath()) == null) ?
null :
SourcePositionImpl.make(path, Position.NOPOS, null);
}
/**
* Return the locale provided by the user or the default locale value.
*/
public Locale getLocale() {
return env.doclocale.locale;
}
}
| 11,428 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ExecutableMemberDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ExecutableMemberDocImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import java.lang.reflect.Modifier;
import java.text.CollationKey;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Position;
/**
* Represents a method or constructor of a java class.
*
* @since 1.2
* @author Robert Field
* @author Neal Gafter (rewrite)
* @author Scott Seligman (generics, annotations)
*/
public abstract class ExecutableMemberDocImpl
extends MemberDocImpl implements ExecutableMemberDoc {
protected final MethodSymbol sym;
/**
* Constructor.
*/
public ExecutableMemberDocImpl(DocEnv env, MethodSymbol sym,
String rawDocs, JCMethodDecl tree, Position.LineMap lineMap) {
super(env, sym, rawDocs, tree, lineMap);
this.sym = sym;
}
/**
* Constructor.
*/
public ExecutableMemberDocImpl(DocEnv env, MethodSymbol sym) {
this(env, sym, null, null, null);
}
/**
* Returns the flags in terms of javac's flags
*/
protected long getFlags() {
return sym.flags();
}
/**
* Identify the containing class
*/
protected ClassSymbol getContainingClass() {
return sym.enclClass();
}
/**
* Return true if this method is native
*/
public boolean isNative() {
return Modifier.isNative(getModifiers());
}
/**
* Return true if this method is synchronized
*/
public boolean isSynchronized() {
return Modifier.isSynchronized(getModifiers());
}
/**
* Return true if this method was declared to take a variable number
* of arguments.
*/
public boolean isVarArgs() {
return ((sym.flags() & Flags.VARARGS) != 0
&& !env.legacyDoclet);
}
/**
* Returns true if this field was synthesized by the compiler.
*/
public boolean isSynthetic() {
return ((sym.flags() & Flags.SYNTHETIC) != 0);
}
public boolean isIncluded() {
return containingClass().isIncluded() && env.shouldDocument(sym);
}
/**
* Return the throws tags in this method.
*
* @return an array of ThrowTagImpl containing all {@code @exception}
* and {@code @throws} tags.
*/
public ThrowsTag[] throwsTags() {
return comment().throwsTags();
}
/**
* Return the param tags in this method, excluding the type
* parameter tags.
*
* @return an array of ParamTagImpl containing all {@code @param} tags.
*/
public ParamTag[] paramTags() {
return comment().paramTags();
}
/**
* Return the type parameter tags in this method.
*/
public ParamTag[] typeParamTags() {
return env.legacyDoclet
? new ParamTag[0]
: comment().typeParamTags();
}
/**
* Return exceptions this method or constructor throws.
*
* @return an array of ClassDoc[] representing the exceptions
* thrown by this method.
*/
public ClassDoc[] thrownExceptions() {
ListBuffer<ClassDocImpl> l = new ListBuffer<ClassDocImpl>();
for (Type ex : sym.type.getThrownTypes()) {
ex = env.types.erasure(ex);
//### Will these casts succeed in the face of static semantic
//### errors in the documented code?
ClassDocImpl cdi = env.getClassDoc((ClassSymbol)ex.tsym);
if (cdi != null) l.append(cdi);
}
return l.toArray(new ClassDocImpl[l.length()]);
}
/**
* Return exceptions this method or constructor throws.
* Each array element is either a <code>ClassDoc</code> or a
* <code>TypeVariable</code>.
*/
public com.sun.javadoc.Type[] thrownExceptionTypes() {
return TypeMaker.getTypes(env, sym.type.getThrownTypes());
}
/**
* Get argument information.
*
* @see ParameterImpl
*
* @return an array of ParameterImpl, one element per argument
* in the order the arguments are present.
*/
public Parameter[] parameters() {
// generate the parameters on the fly: they're not cached
List<VarSymbol> params = sym.params();
Parameter result[] = new Parameter[params.length()];
int i = 0;
for (VarSymbol param : params) {
result[i++] = new ParameterImpl(env, param);
}
return result;
}
/**
* Return the formal type parameters of this method or constructor.
* Return an empty array if there are none.
*/
public TypeVariable[] typeParameters() {
if (env.legacyDoclet) {
return new TypeVariable[0];
}
TypeVariable res[] = new TypeVariable[sym.type.getTypeArguments().length()];
TypeMaker.getTypes(env, sym.type.getTypeArguments(), res);
return res;
}
/**
* Get the signature. It is the parameter list, type is qualified.
* For instance, for a method <code>mymethod(String x, int y)</code>,
* it will return <code>(java.lang.String,int)</code>.
*/
public String signature() {
return makeSignature(true);
}
/**
* Get flat signature. All types are not qualified.
* Return a String, which is the flat signiture of this member.
* It is the parameter list, type is not qualified.
* For instance, for a method <code>mymethod(String x, int y)</code>,
* it will return <code>(String, int)</code>.
*/
public String flatSignature() {
return makeSignature(false);
}
private String makeSignature(boolean full) {
StringBuilder result = new StringBuilder();
result.append("(");
for (List<Type> types = sym.type.getParameterTypes(); types.nonEmpty(); ) {
Type t = types.head;
result.append(TypeMaker.getTypeString(env, t, full));
types = types.tail;
if (types.nonEmpty()) {
result.append(", ");
}
}
if (isVarArgs()) {
int len = result.length();
result.replace(len - 2, len, "...");
}
result.append(")");
return result.toString();
}
protected String typeParametersString() {
return TypeMaker.typeParametersString(env, sym, true);
}
/**
* Generate a key for sorting.
*/
@Override
CollationKey generateKey() {
String k = name() + flatSignature() + typeParametersString();
// ',' and '&' are between '$' and 'a': normalize to spaces.
k = k.replace(',', ' ').replace('&', ' ');
// System.out.println("COLLATION KEY FOR " + this + " is \"" + k + "\"");
return env.doclocale.collator.getCollationKey(k);
}
/**
* Return the source position of the entity, or null if
* no position is available.
*/
@Override
public SourcePosition position() {
if (sym.enclClass().sourcefile == null) return null;
return SourcePositionImpl.make(sym.enclClass().sourcefile,
(tree==null) ? 0 : tree.pos,
lineMap);
}
}
| 8,593 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ParameterizedTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ParameterizedTypeImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import static com.sun.tools.javac.code.TypeTags.*;
/**
* Implementation of <code>ParameterizedType</code>, which
* represents an invocation of a generic class or interface.
*
* @author Scott Seligman
* @since 1.5
*/
public class ParameterizedTypeImpl
extends AbstractTypeImpl implements ParameterizedType {
ParameterizedTypeImpl(DocEnv env, Type type) {
super(env, type);
}
/**
* Return the generic class or interface that declared this type.
*/
@Override
public ClassDoc asClassDoc() {
return env.getClassDoc((ClassSymbol)type.tsym);
}
/**
* Return the actual type arguments of this type.
*/
public com.sun.javadoc.Type[] typeArguments() {
return TypeMaker.getTypes(env, type.getTypeArguments());
}
/**
* Return the class type that is a direct supertype of this one.
* Return null if this is an interface type.
*/
public com.sun.javadoc.Type superclassType() {
if (asClassDoc().isInterface()) {
return null;
}
Type sup = env.types.supertype(type);
return TypeMaker.getType(env,
(sup != type) ? sup : env.syms.objectType);
}
/**
* Return the interface types directly implemented by or extended by this
* parameterized type.
* Return an empty array if there are no interfaces.
*/
public com.sun.javadoc.Type[] interfaceTypes() {
return TypeMaker.getTypes(env, env.types.interfaces(type));
}
/**
* Return the type that contains this type as a member.
* Return null is this is a top-level type.
*/
public com.sun.javadoc.Type containingType() {
if (type.getEnclosingType().tag == CLASS) {
// This is the type of an inner class.
return TypeMaker.getType(env, type.getEnclosingType());
}
ClassSymbol enclosing = type.tsym.owner.enclClass();
if (enclosing != null) {
// Nested but not inner. Return the ClassDoc of the enclosing
// class or interface.
// See java.lang.reflect.ParameterizedType.getOwnerType().
return env.getClassDoc(enclosing);
}
return null;
}
// Asking for the "name" of a parameterized type doesn't exactly make
// sense. It's a type expression. Return the name of its generic
// type.
@Override
public String typeName() {
return TypeMaker.getTypeName(type, false);
}
@Override
public ParameterizedType asParameterizedType() {
return this;
}
@Override
public String toString() {
return parameterizedTypeToString(env, (ClassType)type, true);
}
static String parameterizedTypeToString(DocEnv env, ClassType cl,
boolean full) {
if (env.legacyDoclet) {
return TypeMaker.getTypeName(cl, full);
}
StringBuilder s = new StringBuilder();
if (cl.getEnclosingType().tag != CLASS) { // if not an inner class...
s.append(TypeMaker.getTypeName(cl, full));
} else {
ClassType encl = (ClassType)cl.getEnclosingType();
s.append(parameterizedTypeToString(env, encl, full))
.append('.')
.append(cl.tsym.name.toString());
}
s.append(TypeMaker.typeArgumentsString(env, cl, full));
return s.toString();
}
}
| 4,890 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ThrowsTagImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/ThrowsTagImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
/**
* Represents a @throws or @exception documentation tag.
* Parses and holds the exception name and exception comment.
* The exception name my be the name of a type variable.
* Note: @exception is a backwards compatible synonymy for @throws.
*
* @author Robert Field
* @author Atul M Dambalkar
* @see ExecutableMemberDocImpl#throwsTags()
*
*/
class ThrowsTagImpl extends TagImpl implements ThrowsTag {
private final String exceptionName;
private final String exceptionComment;
/**
* Cached inline tags.
*/
private Tag[] inlineTags;
ThrowsTagImpl(DocImpl holder, String name, String text) {
super(holder, name, text);
String[] sa = divideAtWhite();
exceptionName = sa[0];
exceptionComment = sa[1];
}
/**
* Return the exception name.
*/
public String exceptionName() {
return exceptionName;
}
/**
* Return the exception comment.
*/
public String exceptionComment() {
return exceptionComment;
}
/**
* Return the exception as a ClassDocImpl.
*/
public ClassDoc exception() {
ClassDocImpl exceptionClass;
if (!(holder instanceof ExecutableMemberDoc)) {
exceptionClass = null;
} else {
ExecutableMemberDocImpl emd = (ExecutableMemberDocImpl)holder;
ClassDocImpl con = (ClassDocImpl)emd.containingClass();
exceptionClass = (ClassDocImpl)con.findClass(exceptionName);
}
return exceptionClass;
}
/**
* Return the type that represents the exception.
* This may be a <code>ClassDoc</code> or a <code>TypeVariable</code>.
*/
public Type exceptionType() {
//###(gj) TypeVariable not yet supported.
return exception();
}
/**
* Return the kind of this tag. Always "@throws" for instances
* of ThrowsTagImpl.
*/
@Override
public String kind() {
return "@throws";
}
/**
* For the exception comment with embedded @link tags return the array of
* TagImpls consisting of SeeTagImpl(s) and text containing TagImpl(s).
*
* @return TagImpl[] Array of tags with inline SeeTagImpls.
* @see TagImpl#inlineTagImpls()
* @see ParamTagImpl#inlineTagImpls()
*/
@Override
public Tag[] inlineTags() {
if (inlineTags == null) {
inlineTags = Comment.getInlineTags(holder, exceptionComment());
}
return inlineTags;
}
}
| 3,784 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
MemberDocImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javadoc/MemberDocImpl.java | /*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javadoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Position;
/**
* Represents a member of a java class: field, constructor, or method.
* This is an abstract class dealing with information common to
* method, constructor and field members. Class members of a class
* (nested classes) are represented instead by ClassDocImpl.
*
* @see MethodDocImpl
* @see FieldDocImpl
* @see ClassDocImpl
*
* @author Robert Field
* @author Neal Gafter
*/
public abstract class MemberDocImpl
extends ProgramElementDocImpl
implements MemberDoc {
/**
* constructor.
*/
public MemberDocImpl(DocEnv env, Symbol sym, String doc, JCTree tree, Position.LineMap lineMap) {
super(env, sym, doc, tree, lineMap);
}
/**
* Returns true if this field was synthesized by the compiler.
*/
public abstract boolean isSynthetic();
}
| 2,201 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
EnclosingMethod_attribute.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/EnclosingMethod_attribute.java |
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.7.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class EnclosingMethod_attribute extends Attribute {
EnclosingMethod_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
class_index = cr.readUnsignedShort();
method_index = cr.readUnsignedShort();
}
public EnclosingMethod_attribute(ConstantPool constant_pool, int class_index, int method_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.EnclosingMethod), class_index, method_index);
}
public EnclosingMethod_attribute(int name_index, int class_index, int method_index) {
super(name_index, 4);
this.class_index = class_index;
this.method_index = method_index;
}
public String getClassName(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getClassInfo(class_index).getName();
}
public String getMethodName(ConstantPool constant_pool) throws ConstantPoolException {
if (method_index == 0)
return "";
return constant_pool.getNameAndTypeInfo(method_index).getName();
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitEnclosingMethod(this, data);
}
public final int class_index;
public final int method_index;
}
| 2,865 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Dependencies.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/Dependencies.java | /*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import com.sun.tools.classfile.Dependency.Finder;
import com.sun.tools.classfile.Dependency.Filter;
import com.sun.tools.classfile.Dependency.Location;
import com.sun.tools.classfile.Type.ArrayType;
import com.sun.tools.classfile.Type.ClassSigType;
import com.sun.tools.classfile.Type.ClassType;
import com.sun.tools.classfile.Type.MethodType;
import com.sun.tools.classfile.Type.SimpleType;
import com.sun.tools.classfile.Type.TypeParamType;
import com.sun.tools.classfile.Type.WildcardType;
import static com.sun.tools.classfile.ConstantPool.*;
/**
* A framework for determining {@link Dependency dependencies} between class files.
*
* A {@link Dependency.Finder finder} is used to identify the dependencies of
* individual classes. Some finders may return subtypes of {@code Dependency} to
* further characterize the type of dependency, such as a dependency on a
* method within a class.
*
* A {@link Dependency.Filter filter} may be used to restrict the set of
* dependencies found by a finder.
*
* Dependencies that are found may be passed to a {@link Dependencies.Recorder
* recorder} so that the dependencies can be stored in a custom data structure.
*/
public class Dependencies {
/**
* Thrown when a class file cannot be found.
*/
public static class ClassFileNotFoundException extends Exception {
private static final long serialVersionUID = 3632265927794475048L;
public ClassFileNotFoundException(String className) {
super(className);
this.className = className;
}
public ClassFileNotFoundException(String className, Throwable cause) {
this(className);
initCause(cause);
}
public final String className;
}
/**
* Thrown when an exception is found processing a class file.
*/
public static class ClassFileError extends Error {
private static final long serialVersionUID = 4111110813961313203L;
public ClassFileError(Throwable cause) {
initCause(cause);
}
}
/**
* Service provider interface to locate and read class files.
*/
public interface ClassFileReader {
/**
* Get the ClassFile object for a specified class.
* @param className the name of the class to be returned.
* @return the ClassFile for the given class
* @throws Dependencies#ClassFileNotFoundException if the classfile cannot be
* found
*/
public ClassFile getClassFile(String className)
throws ClassFileNotFoundException;
}
/**
* Service provide interface to handle results.
*/
public interface Recorder {
/**
* Record a dependency that has been found.
* @param d
*/
public void addDependency(Dependency d);
}
/**
* Get the default finder used to locate the dependencies for a class.
* @return the default finder
*/
public static Finder getDefaultFinder() {
return new APIDependencyFinder(AccessFlags.ACC_PRIVATE);
}
/**
* Get a finder used to locate the API dependencies for a class.
* These include the superclass, superinterfaces, and classes referenced in
* the declarations of fields and methods. The fields and methods that
* are checked can be limited according to a specified access.
* The access parameter must be one of {@link AccessFlags#ACC_PUBLIC ACC_PUBLIC},
* {@link AccessFlags#ACC_PRIVATE ACC_PRIVATE},
* {@link AccessFlags#ACC_PROTECTED ACC_PROTECTED}, or 0 for
* package private access. Members with greater than or equal accessibility
* to that specified will be searched for dependencies.
* @param access the access of members to be checked
* @return an API finder
*/
public static Finder getAPIFinder(int access) {
return new APIDependencyFinder(access);
}
/**
* Get the finder used to locate the dependencies for a class.
* @return the finder
*/
public Finder getFinder() {
if (finder == null)
finder = getDefaultFinder();
return finder;
}
/**
* Set the finder used to locate the dependencies for a class.
* @param f the finder
*/
public void setFinder(Finder f) {
f.getClass(); // null check
finder = f;
}
/**
* Get the default filter used to determine included when searching
* the transitive closure of all the dependencies.
* Unless overridden, the default filter accepts all dependencies.
* @return the default filter.
*/
public static Filter getDefaultFilter() {
return DefaultFilter.instance();
}
/**
* Get a filter which uses a regular expression on the target's class name
* to determine if a dependency is of interest.
* @param pattern the pattern used to match the target's class name
* @return a filter for matching the target class name with a regular expression
*/
public static Filter getRegexFilter(Pattern pattern) {
return new TargetRegexFilter(pattern);
}
/**
* Get a filter which checks the package of a target's class name
* to determine if a dependency is of interest. The filter checks if the
* package of the target's class matches any of a set of given package
* names. The match may optionally match subpackages of the given names as well.
* @param packageNames the package names used to match the target's class name
* @param matchSubpackages whether or not to match subpackages as well
* @return a filter for checking the target package name against a list of package names
*/
public static Filter getPackageFilter(Set<String> packageNames, boolean matchSubpackages) {
return new TargetPackageFilter(packageNames, matchSubpackages);
}
/**
* Get the filter used to determine the dependencies included when searching
* the transitive closure of all the dependencies.
* Unless overridden, the default filter accepts all dependencies.
* @return the filter
*/
public Filter getFilter() {
if (filter == null)
filter = getDefaultFilter();
return filter;
}
/**
* Set the filter used to determine the dependencies included when searching
* the transitive closure of all the dependencies.
* @param f the filter
*/
public void setFilter(Filter f) {
f.getClass(); // null check
filter = f;
}
/**
* Find the dependencies of a class, using the current
* {@link Dependencies#getFinder finder} and
* {@link Dependencies#getFilter filter}.
* The search may optionally include the transitive closure of all the
* filtered dependencies, by also searching in the classes named in those
* dependencies.
* @param classFinder a finder to locate class files
* @param rootClassNames the names of the root classes from which to begin
* searching
* @param transitiveClosure whether or not to also search those classes
* named in any filtered dependencies that are found.
* @return the set of dependencies that were found
* @throws ClassFileNotFoundException if a required class file cannot be found
* @throws ClassFileError if an error occurs while processing a class file,
* such as an error in the internal class file structure.
*/
public Set<Dependency> findAllDependencies(
ClassFileReader classFinder, Set<String> rootClassNames,
boolean transitiveClosure)
throws ClassFileNotFoundException {
final Set<Dependency> results = new HashSet<Dependency>();
Recorder r = new Recorder() {
public void addDependency(Dependency d) {
results.add(d);
}
};
findAllDependencies(classFinder, rootClassNames, transitiveClosure, r);
return results;
}
/**
* Find the dependencies of a class, using the current
* {@link Dependencies#getFinder finder} and
* {@link Dependencies#getFilter filter}.
* The search may optionally include the transitive closure of all the
* filtered dependencies, by also searching in the classes named in those
* dependencies.
* @param classFinder a finder to locate class files
* @param rootClassNames the names of the root classes from which to begin
* searching
* @param transitiveClosure whether or not to also search those classes
* named in any filtered dependencies that are found.
* @param recorder a recorder for handling the results
* @throws ClassFileNotFoundException if a required class file cannot be found
* @throws ClassFileError if an error occurs while processing a class file,
* such as an error in the internal class file structure.
*/
public void findAllDependencies(
ClassFileReader classFinder, Set<String> rootClassNames,
boolean transitiveClosure, Recorder recorder)
throws ClassFileNotFoundException {
Set<String> doneClasses = new HashSet<String>();
getFinder(); // ensure initialized
getFilter(); // ensure initialized
// Work queue of names of classfiles to be searched.
// Entries will be unique, and for classes that do not yet have
// dependencies in the results map.
Deque<String> deque = new LinkedList<String>(rootClassNames);
String className;
while ((className = deque.poll()) != null) {
assert (!doneClasses.contains(className));
doneClasses.add(className);
ClassFile cf = classFinder.getClassFile(className);
// The following code just applies the filter to the dependencies
// followed for the transitive closure.
for (Dependency d: finder.findDependencies(cf)) {
recorder.addDependency(d);
if (transitiveClosure && filter.accepts(d)) {
String cn = d.getTarget().getClassName();
if (!doneClasses.contains(cn))
deque.add(cn);
}
}
}
}
private Filter filter;
private Finder finder;
/**
* A location identifying a class.
*/
static class SimpleLocation implements Location {
public SimpleLocation(String className) {
this.className = className;
}
/**
* Get the name of the class being depended on. This name will be used to
* locate the class file for transitive dependency analysis.
* @return the name of the class being depended on
*/
public String getClassName() {
return className;
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof SimpleLocation))
return false;
return (className.equals(((SimpleLocation) other).className));
}
@Override
public int hashCode() {
return className.hashCode();
}
@Override
public String toString() {
return className;
}
private String className;
}
/**
* A dependency of one class on another.
*/
static class SimpleDependency implements Dependency {
public SimpleDependency(Location origin, Location target) {
this.origin = origin;
this.target = target;
}
public Location getOrigin() {
return origin;
}
public Location getTarget() {
return target;
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof SimpleDependency))
return false;
SimpleDependency o = (SimpleDependency) other;
return (origin.equals(o.origin) && target.equals(o.target));
}
@Override
public int hashCode() {
return origin.hashCode() * 31 + target.hashCode();
}
@Override
public String toString() {
return origin + ":" + target;
}
private Location origin;
private Location target;
}
/**
* This class accepts all dependencies.
*/
static class DefaultFilter implements Filter {
private static DefaultFilter instance;
static DefaultFilter instance() {
if (instance == null)
instance = new DefaultFilter();
return instance;
}
public boolean accepts(Dependency dependency) {
return true;
}
}
/**
* This class accepts those dependencies whose target's class name matches a
* regular expression.
*/
static class TargetRegexFilter implements Filter {
TargetRegexFilter(Pattern pattern) {
this.pattern = pattern;
}
public boolean accepts(Dependency dependency) {
return pattern.matcher(dependency.getTarget().getClassName()).matches();
}
private final Pattern pattern;
}
/**
* This class accepts those dependencies whose class name is in a given
* package.
*/
static class TargetPackageFilter implements Filter {
TargetPackageFilter(Set<String> packageNames, boolean matchSubpackages) {
for (String pn: packageNames) {
if (pn.length() == 0) // implies null check as well
throw new IllegalArgumentException();
}
this.packageNames = packageNames;
this.matchSubpackages = matchSubpackages;
}
public boolean accepts(Dependency dependency) {
String cn = dependency.getTarget().getClassName();
int lastSep = cn.lastIndexOf("/");
String pn = (lastSep == -1 ? "" : cn.substring(0, lastSep));
if (packageNames.contains(pn))
return true;
if (matchSubpackages) {
for (String n: packageNames) {
if (pn.startsWith(n + "."))
return true;
}
}
return false;
}
private final Set<String> packageNames;
private final boolean matchSubpackages;
}
/**
* This class identifies class names directly or indirectly in the constant pool.
*/
static class ClassDependencyFinder extends BasicDependencyFinder {
public Iterable<? extends Dependency> findDependencies(ClassFile classfile) {
Visitor v = new Visitor(classfile);
for (CPInfo cpInfo: classfile.constant_pool.entries()) {
v.scan(cpInfo);
}
return v.deps;
}
}
/**
* This class identifies class names in the signatures of classes, fields,
* and methods in a class.
*/
static class APIDependencyFinder extends BasicDependencyFinder {
APIDependencyFinder(int access) {
switch (access) {
case AccessFlags.ACC_PUBLIC:
case AccessFlags.ACC_PROTECTED:
case AccessFlags.ACC_PRIVATE:
case 0:
showAccess = access;
break;
default:
throw new IllegalArgumentException("invalid access 0x"
+ Integer.toHexString(access));
}
}
public Iterable<? extends Dependency> findDependencies(ClassFile classfile) {
try {
Visitor v = new Visitor(classfile);
v.addClass(classfile.super_class);
v.addClasses(classfile.interfaces);
// inner classes?
for (Field f : classfile.fields) {
if (checkAccess(f.access_flags))
v.scan(f.descriptor, f.attributes);
}
for (Method m : classfile.methods) {
if (checkAccess(m.access_flags)) {
v.scan(m.descriptor, m.attributes);
Exceptions_attribute e =
(Exceptions_attribute) m.attributes.get(Attribute.Exceptions);
if (e != null)
v.addClasses(e.exception_index_table);
}
}
return v.deps;
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
boolean checkAccess(AccessFlags flags) {
// code copied from javap.Options.checkAccess
boolean isPublic = flags.is(AccessFlags.ACC_PUBLIC);
boolean isProtected = flags.is(AccessFlags.ACC_PROTECTED);
boolean isPrivate = flags.is(AccessFlags.ACC_PRIVATE);
boolean isPackage = !(isPublic || isProtected || isPrivate);
if ((showAccess == AccessFlags.ACC_PUBLIC) && (isProtected || isPrivate || isPackage))
return false;
else if ((showAccess == AccessFlags.ACC_PROTECTED) && (isPrivate || isPackage))
return false;
else if ((showAccess == 0) && (isPrivate))
return false;
else
return true;
}
private int showAccess;
}
static abstract class BasicDependencyFinder implements Finder {
private Map<String,Location> locations = new HashMap<String,Location>();
Location getLocation(String className) {
Location l = locations.get(className);
if (l == null)
locations.put(className, l = new SimpleLocation(className));
return l;
}
class Visitor implements ConstantPool.Visitor<Void,Void>, Type.Visitor<Void, Void> {
private ConstantPool constant_pool;
private Location origin;
Set<Dependency> deps;
Visitor(ClassFile classFile) {
try {
constant_pool = classFile.constant_pool;
origin = getLocation(classFile.getName());
deps = new HashSet<Dependency>();
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
void scan(Descriptor d, Attributes attrs) {
try {
scan(new Signature(d.index).getType(constant_pool));
Signature_attribute sa = (Signature_attribute) attrs.get(Attribute.Signature);
if (sa != null)
scan(new Signature(sa.signature_index).getType(constant_pool));
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
void scan(CPInfo cpInfo) {
cpInfo.accept(this, null);
}
void scan(Type t) {
t.accept(this, null);
}
void addClass(int index) throws ConstantPoolException {
if (index != 0) {
String name = constant_pool.getClassInfo(index).getBaseName();
if (name != null)
addDependency(name);
}
}
void addClasses(int[] indices) throws ConstantPoolException {
for (int i: indices)
addClass(i);
}
private void addDependency(String name) {
deps.add(new SimpleDependency(origin, getLocation(name)));
}
// ConstantPool.Visitor methods
public Void visitClass(CONSTANT_Class_info info, Void p) {
try {
if (info.getName().startsWith("["))
new Signature(info.name_index).getType(constant_pool).accept(this, null);
else
addDependency(info.getBaseName());
return null;
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
public Void visitDouble(CONSTANT_Double_info info, Void p) {
return null;
}
public Void visitFieldref(CONSTANT_Fieldref_info info, Void p) {
return visitRef(info, p);
}
public Void visitFloat(CONSTANT_Float_info info, Void p) {
return null;
}
public Void visitInteger(CONSTANT_Integer_info info, Void p) {
return null;
}
public Void visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info info, Void p) {
return visitRef(info, p);
}
public Void visitInvokeDynamic(CONSTANT_InvokeDynamic_info info, Void p) {
return null;
}
public Void visitLong(CONSTANT_Long_info info, Void p) {
return null;
}
public Void visitMethodHandle(CONSTANT_MethodHandle_info info, Void p) {
return null;
}
public Void visitMethodType(CONSTANT_MethodType_info info, Void p) {
return null;
}
public Void visitMethodref(CONSTANT_Methodref_info info, Void p) {
return visitRef(info, p);
}
public Void visitNameAndType(CONSTANT_NameAndType_info info, Void p) {
try {
new Signature(info.type_index).getType(constant_pool).accept(this, null);
return null;
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
public Void visitString(CONSTANT_String_info info, Void p) {
return null;
}
public Void visitUtf8(CONSTANT_Utf8_info info, Void p) {
return null;
}
private Void visitRef(CPRefInfo info, Void p) {
try {
visitClass(info.getClassInfo(), p);
return null;
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
// Type.Visitor methods
private void findDependencies(Type t) {
if (t != null)
t.accept(this, null);
}
private void findDependencies(List<? extends Type> ts) {
if (ts != null) {
for (Type t: ts)
t.accept(this, null);
}
}
public Void visitSimpleType(SimpleType type, Void p) {
return null;
}
public Void visitArrayType(ArrayType type, Void p) {
findDependencies(type.elemType);
return null;
}
public Void visitMethodType(MethodType type, Void p) {
findDependencies(type.paramTypes);
findDependencies(type.returnType);
findDependencies(type.throwsTypes);
return null;
}
public Void visitClassSigType(ClassSigType type, Void p) {
findDependencies(type.superclassType);
findDependencies(type.superinterfaceTypes);
return null;
}
public Void visitClassType(ClassType type, Void p) {
findDependencies(type.outerType);
addDependency(type.name);
findDependencies(type.typeArgs);
return null;
}
public Void visitTypeParamType(TypeParamType type, Void p) {
findDependencies(type.classBound);
findDependencies(type.interfaceBounds);
return null;
}
public Void visitWildcardType(WildcardType type, Void p) {
findDependencies(type.boundType);
return null;
}
}
}
}
| 25,870 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
StackMap_attribute.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/StackMap_attribute.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class StackMap_attribute extends Attribute {
StackMap_attribute(ClassReader cr, int name_index, int length)
throws IOException, StackMapTable_attribute.InvalidStackMap {
super(name_index, length);
number_of_entries = cr.readUnsignedShort();
entries = new stack_map_frame[number_of_entries];
for (int i = 0; i < number_of_entries; i++)
entries[i] = new stack_map_frame(cr);
}
public StackMap_attribute(ConstantPool constant_pool, stack_map_frame[] entries)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.StackMap), entries);
}
public StackMap_attribute(int name_index, stack_map_frame[] entries) {
super(name_index, StackMapTable_attribute.length(entries));
this.number_of_entries = entries.length;
this.entries = entries;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitStackMap(this, data);
}
public final int number_of_entries;
public final stack_map_frame entries[];
public static class stack_map_frame extends StackMapTable_attribute.full_frame {
stack_map_frame(ClassReader cr)
throws IOException, StackMapTable_attribute.InvalidStackMap {
super(255, cr);
}
}
}
| 2,841 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Descriptor.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/Descriptor.java | /*
* Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.4.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Descriptor {
public class InvalidDescriptor extends DescriptorException {
private static final long serialVersionUID = 1L;
InvalidDescriptor(String desc) {
this.desc = desc;
this.index = -1;
}
InvalidDescriptor(String desc, int index) {
this.desc = desc;
this.index = index;
}
@Override
public String getMessage() {
// i18n
if (index == -1)
return "invalid descriptor \"" + desc + "\"";
else
return "descriptor is invalid at offset " + index + " in \"" + desc + "\"";
}
public final String desc;
public final int index;
}
public Descriptor(ClassReader cr) throws IOException {
this(cr.readUnsignedShort());
}
public Descriptor(int index) {
this.index = index;
}
public String getValue(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(index);
}
public int getParameterCount(ConstantPool constant_pool)
throws ConstantPoolException, InvalidDescriptor {
String desc = getValue(constant_pool);
int end = desc.indexOf(")");
if (end == -1)
throw new InvalidDescriptor(desc);
parse(desc, 0, end + 1);
return count;
}
public String getParameterTypes(ConstantPool constant_pool)
throws ConstantPoolException, InvalidDescriptor {
String desc = getValue(constant_pool);
int end = desc.indexOf(")");
if (end == -1)
throw new InvalidDescriptor(desc);
return parse(desc, 0, end + 1);
}
public String getReturnType(ConstantPool constant_pool)
throws ConstantPoolException, InvalidDescriptor {
String desc = getValue(constant_pool);
int end = desc.indexOf(")");
if (end == -1)
throw new InvalidDescriptor(desc);
return parse(desc, end + 1, desc.length());
}
public String getFieldType(ConstantPool constant_pool)
throws ConstantPoolException, InvalidDescriptor {
String desc = getValue(constant_pool);
return parse(desc, 0, desc.length());
}
private String parse(String desc, int start, int end)
throws InvalidDescriptor {
int p = start;
StringBuffer sb = new StringBuffer();
int dims = 0;
count = 0;
while (p < end) {
String type;
char ch;
switch (ch = desc.charAt(p++)) {
case '(':
sb.append('(');
continue;
case ')':
sb.append(')');
continue;
case '[':
dims++;
continue;
case 'B':
type = "byte";
break;
case 'C':
type = "char";
break;
case 'D':
type = "double";
break;
case 'F':
type = "float";
break;
case 'I':
type = "int";
break;
case 'J':
type = "long";
break;
case 'L':
int sep = desc.indexOf(';', p);
if (sep == -1)
throw new InvalidDescriptor(desc, p - 1);
type = desc.substring(p, sep).replace('/', '.');
p = sep + 1;
break;
case 'S':
type = "short";
break;
case 'Z':
type = "boolean";
break;
case 'V':
type = "void";
break;
default:
throw new InvalidDescriptor(desc, p - 1);
}
if (sb.length() > 1 && sb.charAt(0) == '(')
sb.append(", ");
sb.append(type);
for ( ; dims > 0; dims-- )
sb.append("[]");
count++;
}
return sb.toString();
}
public final int index;
private int count;
}
| 5,948 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Field.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/Field.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Field {
Field(ClassReader cr) throws IOException {
access_flags = new AccessFlags(cr);
name_index = cr.readUnsignedShort();
descriptor = new Descriptor(cr);
attributes = new Attributes(cr);
}
public Field(AccessFlags access_flags,
int name_index, Descriptor descriptor,
Attributes attributes) {
this.access_flags = access_flags;
this.name_index = name_index;
this.descriptor = descriptor;
this.attributes = attributes;
}
public int byteLength() {
return 6 + attributes.byteLength();
}
public String getName(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(name_index);
}
public final AccessFlags access_flags;
public final int name_index;
public final Descriptor descriptor;
public final Attributes attributes;
}
| 2,431 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Signature_attribute.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/Signature_attribute.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.9.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Signature_attribute extends Attribute {
Signature_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
signature_index = cr.readUnsignedShort();
}
public Signature_attribute(ConstantPool constant_pool, int signature_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.Signature), signature_index);
}
public Signature_attribute(int name_index, int signature_index) {
super(name_index, 2);
this.signature_index = signature_index;
}
public String getSignature(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(signature_index);
}
public Signature getParsedSignature() {
return new Signature(signature_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitSignature(this, data);
}
public final int signature_index;
}
| 2,549 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
RuntimeInvisibleParameterAnnotations_attribute.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/RuntimeInvisibleParameterAnnotations_attribute.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.18.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class RuntimeInvisibleParameterAnnotations_attribute extends RuntimeParameterAnnotations_attribute {
RuntimeInvisibleParameterAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(cr, name_index, length);
}
public RuntimeInvisibleParameterAnnotations_attribute(ConstantPool cp, Annotation[][] parameter_annotations)
throws ConstantPoolException {
this(cp.getUTF8Index(Attribute.RuntimeInvisibleParameterAnnotations), parameter_annotations);
}
public RuntimeInvisibleParameterAnnotations_attribute(int name_index, Annotation[][] parameter_annotations) {
super(name_index, parameter_annotations);
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitRuntimeInvisibleParameterAnnotations(this, p);
}
}
| 2,426 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationDefault_attribute.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/AnnotationDefault_attribute.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.15.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class AnnotationDefault_attribute extends Attribute {
AnnotationDefault_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(name_index, length);
default_value = Annotation.element_value.read(cr);
}
public AnnotationDefault_attribute(ConstantPool constant_pool, Annotation.element_value default_value)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.AnnotationDefault), default_value);
}
public AnnotationDefault_attribute(int name_index, Annotation.element_value default_value) {
super(name_index, default_value.length());
this.default_value = default_value;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitAnnotationDefault(this, data);
}
public final Annotation.element_value default_value;
}
| 2,467 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DescriptorException.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/DescriptorException.java | /*
* Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class DescriptorException extends Exception {
private static final long serialVersionUID = 2411890273788901032L;
}
| 1,603 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Attribute.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/Attribute.java | /*
* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class Attribute {
public static final String AnnotationDefault = "AnnotationDefault";
public static final String BootstrapMethods = "BootstrapMethods";
public static final String CharacterRangeTable = "CharacterRangeTable";
public static final String Code = "Code";
public static final String ConstantValue = "ConstantValue";
public static final String CompilationID = "CompilationID";
public static final String Deprecated = "Deprecated";
public static final String EnclosingMethod = "EnclosingMethod";
public static final String Exceptions = "Exceptions";
public static final String InnerClasses = "InnerClasses";
public static final String LineNumberTable = "LineNumberTable";
public static final String LocalVariableTable = "LocalVariableTable";
public static final String LocalVariableTypeTable = "LocalVariableTypeTable";
public static final String RuntimeVisibleAnnotations = "RuntimeVisibleAnnotations";
public static final String RuntimeInvisibleAnnotations = "RuntimeInvisibleAnnotations";
public static final String RuntimeVisibleParameterAnnotations = "RuntimeVisibleParameterAnnotations";
public static final String RuntimeInvisibleParameterAnnotations = "RuntimeInvisibleParameterAnnotations";
public static final String Signature = "Signature";
public static final String SourceDebugExtension = "SourceDebugExtension";
public static final String SourceFile = "SourceFile";
public static final String SourceID = "SourceID";
public static final String StackMap = "StackMap";
public static final String StackMapTable = "StackMapTable";
public static final String Synthetic = "Synthetic";
public static class Factory {
public Factory() {
// defer init of standardAttributeClasses until after options set up
}
public void setCompat(boolean compat) {
this.compat = compat;
}
public Attribute createAttribute(ClassReader cr, int name_index, byte[] data)
throws IOException {
if (standardAttributes == null)
init();
ConstantPool cp = cr.getConstantPool();
try {
String name = cp.getUTF8Value(name_index);
Class<? extends Attribute> attrClass = standardAttributes.get(name);
if (attrClass != null) {
try {
Class<?>[] constrArgTypes = {ClassReader.class, int.class, int.class};
Constructor<? extends Attribute> constr = attrClass.getDeclaredConstructor(constrArgTypes);
return constr.newInstance(new Object[] { cr, name_index, data.length });
} catch (Throwable t) {
// fall through and use DefaultAttribute
// t.printStackTrace();
}
}
} catch (ConstantPoolException e) {
// fall through and use DefaultAttribute
}
return new DefaultAttribute(cr, name_index, data);
}
protected void init() {
standardAttributes = new HashMap<String,Class<? extends Attribute>>();
standardAttributes.put(AnnotationDefault, AnnotationDefault_attribute.class);
standardAttributes.put(BootstrapMethods, BootstrapMethods_attribute.class);
standardAttributes.put(CharacterRangeTable, CharacterRangeTable_attribute.class);
standardAttributes.put(Code, Code_attribute.class);
standardAttributes.put(ConstantValue, ConstantValue_attribute.class);
standardAttributes.put(Deprecated, Deprecated_attribute.class);
standardAttributes.put(EnclosingMethod, EnclosingMethod_attribute.class);
standardAttributes.put(Exceptions, Exceptions_attribute.class);
standardAttributes.put(InnerClasses, InnerClasses_attribute.class);
standardAttributes.put(LineNumberTable, LineNumberTable_attribute.class);
standardAttributes.put(LocalVariableTable, LocalVariableTable_attribute.class);
standardAttributes.put(LocalVariableTypeTable, LocalVariableTypeTable_attribute.class);
if (!compat) { // old javap does not recognize recent attributes
standardAttributes.put(CompilationID, CompilationID_attribute.class);
standardAttributes.put(RuntimeInvisibleAnnotations, RuntimeInvisibleAnnotations_attribute.class);
standardAttributes.put(RuntimeInvisibleParameterAnnotations, RuntimeInvisibleParameterAnnotations_attribute.class);
standardAttributes.put(RuntimeVisibleAnnotations, RuntimeVisibleAnnotations_attribute.class);
standardAttributes.put(RuntimeVisibleParameterAnnotations, RuntimeVisibleParameterAnnotations_attribute.class);
standardAttributes.put(Signature, Signature_attribute.class);
standardAttributes.put(SourceID, SourceID_attribute.class);
}
standardAttributes.put(SourceDebugExtension, SourceDebugExtension_attribute.class);
standardAttributes.put(SourceFile, SourceFile_attribute.class);
standardAttributes.put(StackMap, StackMap_attribute.class);
standardAttributes.put(StackMapTable, StackMapTable_attribute.class);
standardAttributes.put(Synthetic, Synthetic_attribute.class);
}
private Map<String,Class<? extends Attribute>> standardAttributes;
private boolean compat; // don't support recent attrs in compatibility mode
}
public static Attribute read(ClassReader cr) throws IOException {
return cr.readAttribute();
}
protected Attribute(int name_index, int length) {
attribute_name_index = name_index;
attribute_length = length;
}
public String getName(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(attribute_name_index);
}
public abstract <R,D> R accept(Attribute.Visitor<R,D> visitor, D data);
public int byteLength() {
return 6 + attribute_length;
}
public final int attribute_name_index;
public final int attribute_length;
public interface Visitor<R,P> {
R visitBootstrapMethods(BootstrapMethods_attribute attr, P p);
R visitDefault(DefaultAttribute attr, P p);
R visitAnnotationDefault(AnnotationDefault_attribute attr, P p);
R visitCharacterRangeTable(CharacterRangeTable_attribute attr, P p);
R visitCode(Code_attribute attr, P p);
R visitCompilationID(CompilationID_attribute attr, P p);
R visitConstantValue(ConstantValue_attribute attr, P p);
R visitDeprecated(Deprecated_attribute attr, P p);
R visitEnclosingMethod(EnclosingMethod_attribute attr, P p);
R visitExceptions(Exceptions_attribute attr, P p);
R visitInnerClasses(InnerClasses_attribute attr, P p);
R visitLineNumberTable(LineNumberTable_attribute attr, P p);
R visitLocalVariableTable(LocalVariableTable_attribute attr, P p);
R visitLocalVariableTypeTable(LocalVariableTypeTable_attribute attr, P p);
R visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, P p);
R visitRuntimeInvisibleAnnotations(RuntimeInvisibleAnnotations_attribute attr, P p);
R visitRuntimeVisibleParameterAnnotations(RuntimeVisibleParameterAnnotations_attribute attr, P p);
R visitRuntimeInvisibleParameterAnnotations(RuntimeInvisibleParameterAnnotations_attribute attr, P p);
R visitSignature(Signature_attribute attr, P p);
R visitSourceDebugExtension(SourceDebugExtension_attribute attr, P p);
R visitSourceFile(SourceFile_attribute attr, P p);
R visitSourceID(SourceID_attribute attr, P p);
R visitStackMap(StackMap_attribute attr, P p);
R visitStackMapTable(StackMapTable_attribute attr, P p);
R visitSynthetic(Synthetic_attribute attr, P p);
}
}
| 9,978 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Exceptions_attribute.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/Exceptions_attribute.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.5.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Exceptions_attribute extends Attribute {
Exceptions_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
number_of_exceptions = cr.readUnsignedShort();
exception_index_table = new int[number_of_exceptions];
for (int i = 0; i < number_of_exceptions; i++)
exception_index_table[i] = cr.readUnsignedShort();
}
public Exceptions_attribute(ConstantPool constant_pool, int[] exception_index_table)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.Exceptions), exception_index_table);
}
public Exceptions_attribute(int name_index, int[] exception_index_table) {
super(name_index, 2 + 2 * exception_index_table.length);
this.number_of_exceptions = exception_index_table.length;
this.exception_index_table = exception_index_table;
}
public String getException(int index, ConstantPool constant_pool) throws ConstantPoolException {
int exception_index = exception_index_table[index];
return constant_pool.getClassInfo(exception_index).getName();
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitExceptions(this, data);
}
public final int number_of_exceptions;
public final int[] exception_index_table;
}
| 2,910 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
RuntimeParameterAnnotations_attribute.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/classfile/RuntimeParameterAnnotations_attribute.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.18 and 4.8.19.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class RuntimeParameterAnnotations_attribute extends Attribute {
RuntimeParameterAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(name_index, length);
int num_parameters = cr.readUnsignedByte();
parameter_annotations = new Annotation[num_parameters][];
for (int p = 0; p < parameter_annotations.length; p++) {
int num_annotations = cr.readUnsignedShort();
Annotation[] annotations = new Annotation[num_annotations];
for (int i = 0; i < num_annotations; i++)
annotations[i] = new Annotation(cr);
parameter_annotations[p] = annotations;
}
}
protected RuntimeParameterAnnotations_attribute(int name_index, Annotation[][] parameter_annotations) {
super(name_index, length(parameter_annotations));
this.parameter_annotations = parameter_annotations;
}
private static int length(Annotation[][] anno_arrays) {
int n = 1;
for (Annotation[] anno_array: anno_arrays) {
n += 2;
for (Annotation anno: anno_array)
n += anno.length();
}
return n;
}
public final Annotation[][] parameter_annotations;
}
| 2,862 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.