Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/tools/javac/SourceClass.java
38918 views
/*1* Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.tools.javac;2627import sun.tools.java.*;28import sun.tools.tree.*;29import sun.tools.tree.CompoundStatement;30import sun.tools.asm.Assembler;31import sun.tools.asm.ConstantPool;32import java.util.Vector;33import java.util.Enumeration;34import java.util.Hashtable;35import java.util.Iterator;36import java.io.IOException;37import java.io.OutputStream;38import java.io.DataOutputStream;39import java.io.ByteArrayOutputStream;40import java.io.File;4142/**43* This class represents an Java class as it is read from44* an Java source file.45*46* WARNING: The contents of this source file are not part of any47* supported API. Code that depends on them does so at its own risk:48* they are subject to change or removal without notice.49*/50@Deprecated51public52class SourceClass extends ClassDefinition {5354/**55* The toplevel environment, shared with the parser56*/57Environment toplevelEnv;5859/**60* The default constructor61*/62SourceMember defConstructor;6364/**65* The constant pool66*/67ConstantPool tab = new ConstantPool();6869/**70* The list of class dependencies71*/72Hashtable deps = new Hashtable(11);7374/**75* The field used to represent "this" in all of my code.76*/77LocalMember thisArg;7879/**80* Last token of class, as reported by parser.81*/82long endPosition;8384/**85* Access methods for constructors are distinguished from86* the constructors themselves by a dummy first argument.87* A unique type used for this purpose and shared by all88* constructor access methods within a package-member class is89* maintained here.90* <p>91* This field is null except in an outermost class containing92* one or more classes needing such an access method.93*/94private Type dummyArgumentType = null;9596/**97* Constructor98*/99public SourceClass(Environment env, long where,100ClassDeclaration declaration, String documentation,101int modifiers, IdentifierToken superClass,102IdentifierToken interfaces[],103SourceClass outerClass, Identifier localName) {104super(env.getSource(), where,105declaration, modifiers, superClass, interfaces);106setOuterClass(outerClass);107108this.toplevelEnv = env;109this.documentation = documentation;110111if (ClassDefinition.containsDeprecated(documentation)) {112this.modifiers |= M_DEPRECATED;113}114115// Check for a package level class which is declared static.116if (isStatic() && outerClass == null) {117env.error(where, "static.class", this);118this.modifiers &=~ M_STATIC;119}120121// Inner classes cannot be static, nor can they be interfaces122// (which are implicitly static). Static classes and interfaces123// can only occur as top-level entities.124//125// Note that we do not have to check for local classes declared126// to be static (this is currently caught by the parser) but127// we check anyway in case the parser is modified to allow this.128if (isLocal() || (outerClass != null && !outerClass.isTopLevel())) {129if (isInterface()) {130env.error(where, "inner.interface");131} else if (isStatic()) {132env.error(where, "static.inner.class", this);133this.modifiers &=~ M_STATIC;134if (innerClassMember != null) {135innerClassMember.subModifiers(M_STATIC);136}137}138}139140if (isPrivate() && outerClass == null) {141env.error(where, "private.class", this);142this.modifiers &=~ M_PRIVATE;143}144if (isProtected() && outerClass == null) {145env.error(where, "protected.class", this);146this.modifiers &=~ M_PROTECTED;147}148/*----*149if ((isPublic() || isProtected()) && isInsideLocal()) {150env.error(where, "warn.public.local.class", this);151}152*----*/153154// maybe define an uplevel "A.this" current instance field155if (!isTopLevel() && !isLocal()) {156LocalMember outerArg = ((SourceClass)outerClass).getThisArgument();157UplevelReference r = getReference(outerArg);158setOuterMember(r.getLocalField(env));159}160161// Set simple, unmangled local name for a local or anonymous class.162// NOTE: It would be OK to do this unconditionally, as null is the163// correct value for a member (non-local) class.164if (localName != null)165setLocalName(localName);166167// Check for inner class with same simple name as one of168// its enclosing classes. Note that 'getLocalName' returns169// the simple, unmangled source-level name of any class.170// The previous version of this code was not careful to avoid171// mangled local class names. This version fixes 4047746.172Identifier thisName = getLocalName();173if (thisName != idNull) {174// Test above suppresses error for nested anonymous classes,175// which have an internal "name", but are not named in source code.176for (ClassDefinition scope = outerClass; scope != null;177scope = scope.getOuterClass()) {178Identifier outerName = scope.getLocalName();179if (thisName.equals(outerName))180env.error(where, "inner.redefined", thisName);181}182}183}184185/**186* Return last position in this class.187* @see #getWhere188*/189public long getEndPosition() {190return endPosition;191}192193public void setEndPosition(long endPosition) {194this.endPosition = endPosition;195}196197198// JCOV199/**200* Return absolute name of source file201*/202public String getAbsoluteName() {203String AbsName = ((ClassFile)getSource()).getAbsoluteName();204205return AbsName;206}207//end JCOV208209/**210* Return imports211*/212public Imports getImports() {213return toplevelEnv.getImports();214}215216/**217* Find or create my "this" argument, which is used for all methods.218*/219public LocalMember getThisArgument() {220if (thisArg == null) {221thisArg = new LocalMember(where, this, 0, getType(), idThis);222}223return thisArg;224}225226/**227* Add a dependency228*/229public void addDependency(ClassDeclaration c) {230if (tab != null) {231tab.put(c);232}233// If doing -xdepend option, save away list of class dependencies234// making sure to NOT include duplicates or the class we are in235// (Hashtable's put() makes sure we don't have duplicates)236if ( toplevelEnv.print_dependencies() && c != getClassDeclaration() ) {237deps.put(c,c);238}239}240241/**242* Add a field (check it first)243*/244public void addMember(Environment env, MemberDefinition f) {245// Make sure the access permissions are self-consistent:246switch (f.getModifiers() & (M_PUBLIC | M_PRIVATE | M_PROTECTED)) {247case M_PUBLIC:248case M_PRIVATE:249case M_PROTECTED:250case 0:251break;252default:253env.error(f.getWhere(), "inconsistent.modifier", f);254// Cut out the more restrictive modifier(s):255if (f.isPublic()) {256f.subModifiers(M_PRIVATE | M_PROTECTED);257} else {258f.subModifiers(M_PRIVATE);259}260break;261}262263// Note exemption for synthetic members below.264if (f.isStatic() && !isTopLevel() && !f.isSynthetic()) {265if (f.isMethod()) {266env.error(f.getWhere(), "static.inner.method", f, this);267f.subModifiers(M_STATIC);268} else if (f.isVariable()) {269if (!f.isFinal() || f.isBlankFinal()) {270env.error(f.getWhere(), "static.inner.field", f.getName(), this);271f.subModifiers(M_STATIC);272}273// Even if a static passes this test, there is still another274// check in 'SourceMember.check'. The check is delayed so275// that the initializer may be inspected more closely, using276// 'isConstant()'. Part of fix for 4095568.277} else {278// Static inner classes are diagnosed in 'SourceClass.<init>'.279f.subModifiers(M_STATIC);280}281}282283if (f.isMethod()) {284if (f.isConstructor()) {285if (f.getClassDefinition().isInterface()) {286env.error(f.getWhere(), "intf.constructor");287return;288}289if (f.isNative() || f.isAbstract() ||290f.isStatic() || f.isSynchronized() || f.isFinal()) {291env.error(f.getWhere(), "constr.modifier", f);292f.subModifiers(M_NATIVE | M_ABSTRACT |293M_STATIC | M_SYNCHRONIZED | M_FINAL);294}295} else if (f.isInitializer()) {296if (f.getClassDefinition().isInterface()) {297env.error(f.getWhere(), "intf.initializer");298return;299}300}301302// f is not allowed to return an array of void303if ((f.getType().getReturnType()).isVoidArray()) {304env.error(f.getWhere(), "void.array");305}306307if (f.getClassDefinition().isInterface() &&308(f.isStatic() || f.isSynchronized() || f.isNative()309|| f.isFinal() || f.isPrivate() || f.isProtected())) {310env.error(f.getWhere(), "intf.modifier.method", f);311f.subModifiers(M_STATIC | M_SYNCHRONIZED | M_NATIVE |312M_FINAL | M_PRIVATE);313}314if (f.isTransient()) {315env.error(f.getWhere(), "transient.meth", f);316f.subModifiers(M_TRANSIENT);317}318if (f.isVolatile()) {319env.error(f.getWhere(), "volatile.meth", f);320f.subModifiers(M_VOLATILE);321}322if (f.isAbstract()) {323if (f.isPrivate()) {324env.error(f.getWhere(), "abstract.private.modifier", f);325f.subModifiers(M_PRIVATE);326}327if (f.isStatic()) {328env.error(f.getWhere(), "abstract.static.modifier", f);329f.subModifiers(M_STATIC);330}331if (f.isFinal()) {332env.error(f.getWhere(), "abstract.final.modifier", f);333f.subModifiers(M_FINAL);334}335if (f.isNative()) {336env.error(f.getWhere(), "abstract.native.modifier", f);337f.subModifiers(M_NATIVE);338}339if (f.isSynchronized()) {340env.error(f.getWhere(),"abstract.synchronized.modifier",f);341f.subModifiers(M_SYNCHRONIZED);342}343}344if (f.isAbstract() || f.isNative()) {345if (f.getValue() != null) {346env.error(f.getWhere(), "invalid.meth.body", f);347f.setValue(null);348}349} else {350if (f.getValue() == null) {351if (f.isConstructor()) {352env.error(f.getWhere(), "no.constructor.body", f);353} else {354env.error(f.getWhere(), "no.meth.body", f);355}356f.addModifiers(M_ABSTRACT);357}358}359Vector arguments = f.getArguments();360if (arguments != null) {361// arguments can be null if this is an implicit abstract method362int argumentLength = arguments.size();363Type argTypes[] = f.getType().getArgumentTypes();364for (int i = 0; i < argTypes.length; i++) {365Object arg = arguments.elementAt(i);366long where = f.getWhere();367if (arg instanceof MemberDefinition) {368where = ((MemberDefinition)arg).getWhere();369arg = ((MemberDefinition)arg).getName();370}371// (arg should be an Identifier now)372if (argTypes[i].isType(TC_VOID)373|| argTypes[i].isVoidArray()) {374env.error(where, "void.argument", arg);375}376}377}378} else if (f.isInnerClass()) {379if (f.isVolatile() ||380f.isTransient() || f.isNative() || f.isSynchronized()) {381env.error(f.getWhere(), "inner.modifier", f);382f.subModifiers(M_VOLATILE | M_TRANSIENT |383M_NATIVE | M_SYNCHRONIZED);384}385// same check as for fields, below:386if (f.getClassDefinition().isInterface() &&387(f.isPrivate() || f.isProtected())) {388env.error(f.getWhere(), "intf.modifier.field", f);389f.subModifiers(M_PRIVATE | M_PROTECTED);390f.addModifiers(M_PUBLIC);391// Fix up the class itself to agree with392// the inner-class member.393ClassDefinition c = f.getInnerClass();394c.subModifiers(M_PRIVATE | M_PROTECTED);395c.addModifiers(M_PUBLIC);396}397} else {398if (f.getType().isType(TC_VOID) || f.getType().isVoidArray()) {399env.error(f.getWhere(), "void.inst.var", f.getName());400// REMIND: set type to error401return;402}403404if (f.isSynchronized() || f.isAbstract() || f.isNative()) {405env.error(f.getWhere(), "var.modifier", f);406f.subModifiers(M_SYNCHRONIZED | M_ABSTRACT | M_NATIVE);407}408if (f.isStrict()) {409env.error(f.getWhere(), "var.floatmodifier", f);410f.subModifiers(M_STRICTFP);411}412if (f.isTransient() && isInterface()) {413env.error(f.getWhere(), "transient.modifier", f);414f.subModifiers(M_TRANSIENT);415}416if (f.isVolatile() && (isInterface() || f.isFinal())) {417env.error(f.getWhere(), "volatile.modifier", f);418f.subModifiers(M_VOLATILE);419}420if (f.isFinal() && (f.getValue() == null) && isInterface()) {421env.error(f.getWhere(), "initializer.needed", f);422f.subModifiers(M_FINAL);423}424425if (f.getClassDefinition().isInterface() &&426(f.isPrivate() || f.isProtected())) {427env.error(f.getWhere(), "intf.modifier.field", f);428f.subModifiers(M_PRIVATE | M_PROTECTED);429f.addModifiers(M_PUBLIC);430}431}432// Do not check for repeated methods here: Types are not yet resolved.433if (!f.isInitializer()) {434for (MemberDefinition f2 = getFirstMatch(f.getName());435f2 != null; f2 = f2.getNextMatch()) {436if (f.isVariable() && f2.isVariable()) {437env.error(f.getWhere(), "var.multidef", f, f2);438return;439} else if (f.isInnerClass() && f2.isInnerClass() &&440!f.getInnerClass().isLocal() &&441!f2.getInnerClass().isLocal()) {442// Found a duplicate inner-class member.443// Duplicate local classes are detected in444// 'VarDeclarationStatement.checkDeclaration'.445env.error(f.getWhere(), "inner.class.multidef", f);446return;447}448}449}450451super.addMember(env, f);452}453454/**455* Create an environment suitable for checking this class.456* Make sure the source and imports are set right.457* Make sure the environment contains no context information.458* (Actually, throw away env altogether and use toplevelEnv instead.)459*/460public Environment setupEnv(Environment env) {461// In some cases, we go to some trouble to create the 'env' argument462// that is discarded. We should remove the 'env' argument entirely463// as well as the vestigial code that supports it. See comments on464// 'newEnvironment' in 'checkInternal' below.465return new Environment(toplevelEnv, this);466}467468/**469* A source class never reports deprecation, since the compiler470* allows access to deprecated features that are being compiled471* in the same job.472*/473public boolean reportDeprecated(Environment env) {474return false;475}476477/**478* See if the source file of this class is right.479* @see ClassDefinition#noteUsedBy480*/481public void noteUsedBy(ClassDefinition ref, long where, Environment env) {482// If this class is not public, watch for cross-file references.483super.noteUsedBy(ref, where, env);484ClassDefinition def = this;485while (def.isInnerClass()) {486def = def.getOuterClass();487}488if (def.isPublic()) {489return; // already checked490}491while (ref.isInnerClass()) {492ref = ref.getOuterClass();493}494if (def.getSource().equals(ref.getSource())) {495return; // intra-file reference496}497((SourceClass)def).checkSourceFile(env, where);498}499500/**501* Check this class and all its fields.502*/503public void check(Environment env) throws ClassNotFound {504if (tracing) env.dtEnter("SourceClass.check: " + getName());505if (isInsideLocal()) {506// An inaccessible class gets checked when the surrounding507// block is checked.508// QUERY: Should this case ever occur?509// What would invoke checking of a local class aside from510// checking the surrounding method body?511if (tracing) env.dtEvent("SourceClass.check: INSIDE LOCAL " +512getOuterClass().getName());513getOuterClass().check(env);514} else {515if (isInnerClass()) {516if (tracing) env.dtEvent("SourceClass.check: INNER CLASS " +517getOuterClass().getName());518// Make sure the outer is checked first.519((SourceClass)getOuterClass()).maybeCheck(env);520}521Vset vset = new Vset();522Context ctx = null;523if (tracing)524env.dtEvent("SourceClass.check: CHECK INTERNAL " + getName());525vset = checkInternal(setupEnv(env), ctx, vset);526// drop vset here527}528if (tracing) env.dtExit("SourceClass.check: " + getName());529}530531private void maybeCheck(Environment env) throws ClassNotFound {532if (tracing) env.dtEvent("SourceClass.maybeCheck: " + getName());533// Check this class now, if it has not yet been checked.534// Cf. Main.compile(). Perhaps this code belongs there somehow.535ClassDeclaration c = getClassDeclaration();536if (c.getStatus() == CS_PARSED) {537// Set it first to avoid vicious circularity:538c.setDefinition(this, CS_CHECKED);539check(env);540}541}542543private Vset checkInternal(Environment env, Context ctx, Vset vset)544throws ClassNotFound {545Identifier nm = getClassDeclaration().getName();546if (env.verbose()) {547env.output("[checking class " + nm + "]");548}549550// Save context enclosing class for later access551// by 'ClassDefinition.resolveName.'552classContext = ctx;553554// At present, the call to 'newEnvironment' is not needed.555// The incoming environment to 'basicCheck' is always passed to556// 'setupEnv', which discards it completely. This is also the557// only call to 'newEnvironment', which is now apparently dead code.558basicCheck(Context.newEnvironment(env, ctx));559560// Validate access for all inner-class components561// of a qualified name, not just the last one, which562// is checked below. Yes, this is a dirty hack...563// Much of this code was cribbed from 'checkSupers'.564// Part of fix for 4094658.565ClassDeclaration sup = getSuperClass();566if (sup != null) {567long where = getWhere();568where = IdentifierToken.getWhere(superClassId, where);569env.resolveExtendsByName(where, this, sup.getName());570}571for (int i = 0 ; i < interfaces.length ; i++) {572ClassDeclaration intf = interfaces[i];573long where = getWhere();574// Error localization fails here if interfaces were575// elided during error recovery from an invalid one.576if (interfaceIds != null577&& interfaceIds.length == interfaces.length) {578where = IdentifierToken.getWhere(interfaceIds[i], where);579}580env.resolveExtendsByName(where, this, intf.getName());581}582583// Does the name already exist in an imported package?584// See JLS 8.1 for the precise rules.585if (!isInnerClass() && !isInsideLocal()) {586// Discard package qualification for the import checks.587Identifier simpleName = nm.getName();588try {589// We want this to throw a ClassNotFound exception590Imports imports = toplevelEnv.getImports();591Identifier ID = imports.resolve(env, simpleName);592if (ID != getName())593env.error(where, "class.multidef.import", simpleName, ID);594} catch (AmbiguousClass e) {595// At least one of e.name1 and e.name2 must be different596Identifier ID = (e.name1 != getName()) ? e.name1 : e.name2;597env.error(where, "class.multidef.import", simpleName, ID);598} catch (ClassNotFound e) {599// we want this to happen600}601602// Make sure that no package with the same fully qualified603// name exists. This is required by JLS 7.1. We only need604// to perform this check for top level classes -- it isn't605// necessary for inner classes. (bug 4101529)606//607// This change has been backed out because, on WIN32, it608// failed to distinguish between java.awt.event and609// java.awt.Event when looking for a directory. We will610// add this back in later.611//612// try {613// if (env.getPackage(nm).exists()) {614// env.error(where, "class.package.conflict", nm);615// }616// } catch (java.io.IOException ee) {617// env.error(where, "io.exception.package", nm);618// }619620// Make sure it was defined in the right file621if (isPublic()) {622checkSourceFile(env, getWhere());623}624}625626vset = checkMembers(env, ctx, vset);627return vset;628}629630private boolean sourceFileChecked = false;631632/**633* See if the source file of this class is of the right name.634*/635public void checkSourceFile(Environment env, long where) {636// one error per offending class is sufficient637if (sourceFileChecked) return;638sourceFileChecked = true;639640String fname = getName().getName() + ".java";641String src = ((ClassFile)getSource()).getName();642if (!src.equals(fname)) {643if (isPublic()) {644env.error(where, "public.class.file", this, fname);645} else {646env.error(where, "warn.package.class.file", this, src, fname);647}648}649}650651// Set true if superclass (but not necessarily superinterfaces) have652// been checked. If the superclass is still unresolved, then an error653// message should have been issued, and we assume that no further654// resolution is possible.655private boolean supersChecked = false;656657/**658* Overrides 'ClassDefinition.getSuperClass'.659*/660661public ClassDeclaration getSuperClass(Environment env) {662if (tracing) env.dtEnter("SourceClass.getSuperClass: " + this);663// Superclass may fail to be set because of error recovery,664// so resolve types here only if 'checkSupers' has not yet665// completed its checks on the superclass.666// QUERY: Can we eliminate the need to resolve superclasses on demand?667// See comments in 'checkSupers' and in 'ClassDefinition.getInnerClass'.668if (superClass == null && superClassId != null && !supersChecked) {669resolveTypeStructure(env);670// We used to report an error here if the superclass was not671// resolved. Having moved the call to 'checkSupers' from 'basicCheck'672// into 'resolveTypeStructure', the errors reported here should have673// already been reported. Furthermore, error recovery can null out674// the superclass, which would cause a spurious error from the test here.675}676if (tracing) env.dtExit("SourceClass.getSuperClass: " + this);677return superClass;678}679680/**681* Check that all superclasses and superinterfaces are defined and682* well formed. Among other checks, verify that the inheritance683* graph is acyclic. Called from 'resolveTypeStructure'.684*/685686private void checkSupers(Environment env) throws ClassNotFound {687688// *** DEBUG ***689supersCheckStarted = true;690691if (tracing) env.dtEnter("SourceClass.checkSupers: " + this);692693if (isInterface()) {694if (isFinal()) {695Identifier nm = getClassDeclaration().getName();696env.error(getWhere(), "final.intf", nm);697// Interfaces have no superclass. Superinterfaces698// are checked below, in code shared with the class case.699}700} else {701// Check superclass.702// Call to 'getSuperClass(env)' (note argument) attempts703// 'resolveTypeStructure' if superclass has not successfully704// been resolved. Since we have just now called 'resolveSupers'705// (see our call in 'resolveTypeStructure'), it is not clear706// that this can do any good. Why not 'getSuperClass()' here?707if (getSuperClass(env) != null) {708long where = getWhere();709where = IdentifierToken.getWhere(superClassId, where);710try {711ClassDefinition def =712getSuperClass().getClassDefinition(env);713// Resolve superclass and its ancestors.714def.resolveTypeStructure(env);715// Access to the superclass should be checked relative716// to the surrounding context, not as if the reference717// appeared within the class body. Changed 'canAccess'718// to 'extendsCanAccess' to fix 4087314.719if (!extendsCanAccess(env, getSuperClass())) {720env.error(where, "cant.access.class", getSuperClass());721// Might it be a better recovery to let the access go through?722superClass = null;723} else if (def.isFinal()) {724env.error(where, "super.is.final", getSuperClass());725// Might it be a better recovery to let the access go through?726superClass = null;727} else if (def.isInterface()) {728env.error(where, "super.is.intf", getSuperClass());729superClass = null;730} else if (superClassOf(env, getSuperClass())) {731env.error(where, "cyclic.super");732superClass = null;733} else {734def.noteUsedBy(this, where, env);735}736if (superClass == null) {737def = null;738} else {739// If we have a valid superclass, check its740// supers as well, and so on up to root class.741// Call to 'enclosingClassOf' will raise742// 'NullPointerException' if 'def' is null,743// so omit this check as error recovery.744ClassDefinition sup = def;745for (;;) {746if (enclosingClassOf(sup)) {747// Do we need a similar test for748// interfaces? See bugid 4038529.749env.error(where, "super.is.inner");750superClass = null;751break;752}753// Since we resolved the superclass and its754// ancestors above, we should not discover755// any unresolved classes on the superclass756// chain. It should thus be sufficient to757// call 'getSuperClass()' (no argument) here.758ClassDeclaration s = sup.getSuperClass(env);759if (s == null) {760// Superclass not resolved due to error.761break;762}763sup = s.getClassDefinition(env);764}765}766} catch (ClassNotFound e) {767// Error is detected in call to 'getClassDefinition'.768// The class may actually exist but be ambiguous.769// Call env.resolve(e.name) to see if it is.770// env.resolve(name) will definitely tell us if the771// class is ambiguous, but may not necessarily tell772// us if the class is not found.773// (part of solution for 4059855)774reportError: {775try {776env.resolve(e.name);777} catch (AmbiguousClass ee) {778env.error(where,779"ambig.class", ee.name1, ee.name2);780superClass = null;781break reportError;782} catch (ClassNotFound ee) {783// fall through784}785env.error(where, "super.not.found", e.name, this);786superClass = null;787} // The break exits this block788}789790} else {791// Superclass was null on entry, after call to792// 'resolveSupers'. This should normally not happen,793// as 'resolveSupers' sets 'superClass' to a non-null794// value for all named classes, except for one special795// case: 'java.lang.Object', which has no superclass.796if (isAnonymous()) {797// checker should have filled it in first798throw new CompilerError("anonymous super");799} else if (!getName().equals(idJavaLangObject)) {800throw new CompilerError("unresolved super");801}802}803}804805// At this point, if 'superClass' is null due to an error806// in the user program, a message should have been issued.807supersChecked = true;808809// Check interfaces810for (int i = 0 ; i < interfaces.length ; i++) {811ClassDeclaration intf = interfaces[i];812long where = getWhere();813if (interfaceIds != null814&& interfaceIds.length == interfaces.length) {815where = IdentifierToken.getWhere(interfaceIds[i], where);816}817try {818ClassDefinition def = intf.getClassDefinition(env);819// Resolve superinterface and its ancestors.820def.resolveTypeStructure(env);821// Check superinterface access in the correct context.822// Changed 'canAccess' to 'extendsCanAccess' to fix 4087314.823if (!extendsCanAccess(env, intf)) {824env.error(where, "cant.access.class", intf);825} else if (!intf.getClassDefinition(env).isInterface()) {826env.error(where, "not.intf", intf);827} else if (isInterface() && implementedBy(env, intf)) {828env.error(where, "cyclic.intf", intf);829} else {830def.noteUsedBy(this, where, env);831// Interface is OK, leave it in the interface list.832continue;833}834} catch (ClassNotFound e) {835// The interface may actually exist but be ambiguous.836// Call env.resolve(e.name) to see if it is.837// env.resolve(name) will definitely tell us if the838// interface is ambiguous, but may not necessarily tell839// us if the interface is not found.840// (part of solution for 4059855)841reportError2: {842try {843env.resolve(e.name);844} catch (AmbiguousClass ee) {845env.error(where,846"ambig.class", ee.name1, ee.name2);847superClass = null;848break reportError2;849} catch (ClassNotFound ee) {850// fall through851}852env.error(where, "intf.not.found", e.name, this);853superClass = null;854} // The break exits this block855}856// Remove this interface from the list of interfaces857// as recovery from an error.858ClassDeclaration newInterfaces[] =859new ClassDeclaration[interfaces.length - 1];860System.arraycopy(interfaces, 0, newInterfaces, 0, i);861System.arraycopy(interfaces, i + 1, newInterfaces, i,862newInterfaces.length - i);863interfaces = newInterfaces;864--i;865}866if (tracing) env.dtExit("SourceClass.checkSupers: " + this);867}868869/**870* Check all of the members of this class.871* <p>872* Inner classes are checked in the following way. Any class which873* is immediately contained in a block (anonymous and local classes)874* is checked along with its containing method; see the875* SourceMember.check() method for more information. Member classes876* of this class are checked immediately after this class, unless this877* class is insideLocal(), in which case, they are checked with the878* rest of the members.879*/880private Vset checkMembers(Environment env, Context ctx, Vset vset)881throws ClassNotFound {882883// bail out if there were any errors884if (getError()) {885return vset;886}887888// Make sure that all of our member classes have been889// basicCheck'ed before we check the rest of our members.890// If our member classes haven't been basicCheck'ed, then they891// may not have <init> methods. It is important that they892// have <init> methods so we can process NewInstanceExpressions893// correctly. This problem didn't occur before 1.2beta1.894// This is a fix for bug 4082816.895for (MemberDefinition f = getFirstMember();896f != null; f = f.getNextMember()) {897if (f.isInnerClass()) {898// System.out.println("Considering " + f + " in " + this);899SourceClass cdef = (SourceClass) f.getInnerClass();900if (cdef.isMember()) {901cdef.basicCheck(env);902}903}904}905906if (isFinal() && isAbstract()) {907env.error(where, "final.abstract", this.getName().getName());908}909910// This class should be abstract if there are any abstract methods911// in our parent classes and interfaces which we do not override.912// There are odd cases when, even though we cannot access some913// abstract method from our superclass, that abstract method can914// still force this class to be abstract. See the discussion in915// bug id 1240831.916if (!isInterface() && !isAbstract() && mustBeAbstract(env)) {917// Set the class abstract.918modifiers |= M_ABSTRACT;919920// Tell the user which methods force this class to be abstract.921922// First list all of the "unimplementable" abstract methods.923Iterator iter = getPermanentlyAbstractMethods();924while (iter.hasNext()) {925MemberDefinition method = (MemberDefinition) iter.next();926// We couldn't override this method even if we927// wanted to. Try to make the error message928// as non-confusing as possible.929env.error(where, "abstract.class.cannot.override",930getClassDeclaration(), method,931method.getDefiningClassDeclaration());932}933934// Now list all of the traditional abstract methods.935iter = getMethods(env);936while (iter.hasNext()) {937// For each method, check if it is abstract. If it is,938// output an appropriate error message.939MemberDefinition method = (MemberDefinition) iter.next();940if (method.isAbstract()) {941env.error(where, "abstract.class",942getClassDeclaration(), method,943method.getDefiningClassDeclaration());944}945}946}947948// Check the instance variables in a pre-pass before any constructors.949// This lets constructors "in-line" any initializers directly.950// It also lets us do some definite assignment checks on variables.951Context ctxInit = new Context(ctx);952Vset vsInst = vset.copy();953Vset vsClass = vset.copy();954955// Do definite assignment checking on blank finals.956// Other variables do not need such checks. The simple textual957// ordering constraints implemented by MemberDefinition.canReach()958// are necessary and sufficient for the other variables.959// Note that within non-static code, all statics are always960// definitely assigned, and vice-versa.961for (MemberDefinition f = getFirstMember();962f != null; f = f.getNextMember()) {963if (f.isVariable() && f.isBlankFinal()) {964// The following allocates a LocalMember object as a proxy965// to represent the field.966int number = ctxInit.declareFieldNumber(f);967if (f.isStatic()) {968vsClass = vsClass.addVarUnassigned(number);969vsInst = vsInst.addVar(number);970} else {971vsInst = vsInst.addVarUnassigned(number);972vsClass = vsClass.addVar(number);973}974}975}976977// For instance variable checks, use a context with a "this" parameter.978Context ctxInst = new Context(ctxInit, this);979LocalMember thisArg = getThisArgument();980int thisNumber = ctxInst.declare(env, thisArg);981vsInst = vsInst.addVar(thisNumber);982983// Do all the initializers in order, checking the definite984// assignment of blank finals. Separate static from non-static.985for (MemberDefinition f = getFirstMember();986f != null; f = f.getNextMember()) {987try {988if (f.isVariable() || f.isInitializer()) {989if (f.isStatic()) {990vsClass = f.check(env, ctxInit, vsClass);991} else {992vsInst = f.check(env, ctxInst, vsInst);993}994}995} catch (ClassNotFound ee) {996env.error(f.getWhere(), "class.not.found", ee.name, this);997}998}9991000checkBlankFinals(env, ctxInit, vsClass, true);10011002// Check the rest of the field definitions.1003// (Note: Re-checking a field is a no-op.)1004for (MemberDefinition f = getFirstMember();1005f != null; f = f.getNextMember()) {1006try {1007if (f.isConstructor()) {1008// When checking a constructor, an explicit call to1009// 'this(...)' makes all blank finals definitely assigned.1010// See 'MethodExpression.checkValue'.1011Vset vsCon = f.check(env, ctxInit, vsInst.copy());1012// May issue multiple messages for the same variable!!1013checkBlankFinals(env, ctxInit, vsCon, false);1014// (drop vsCon here)1015} else {1016Vset vsFld = f.check(env, ctx, vset.copy());1017// (drop vsFld here)1018}1019} catch (ClassNotFound ee) {1020env.error(f.getWhere(), "class.not.found", ee.name, this);1021}1022}10231024// Must mark class as checked before visiting inner classes,1025// as they may in turn request checking of the current class1026// as an outer class. Fix for bug id 4056774.1027getClassDeclaration().setDefinition(this, CS_CHECKED);10281029// Also check other classes in the same nest.1030// All checking of this nest must be finished before any1031// of its classes emit bytecode.1032// Otherwise, the inner classes might not have a chance to1033// add access or class literal fields to the outer class.1034for (MemberDefinition f = getFirstMember();1035f != null; f = f.getNextMember()) {1036if (f.isInnerClass()) {1037SourceClass cdef = (SourceClass) f.getInnerClass();1038if (!cdef.isInsideLocal()) {1039cdef.maybeCheck(env);1040}1041}1042}10431044// Note: Since inner classes cannot set up-level variables,1045// the returned vset is always equal to the passed-in vset.1046// Still, we'll return it for the sake of regularity.1047return vset;1048}10491050/** Make sure all my blank finals exist now. */10511052private void checkBlankFinals(Environment env, Context ctxInit, Vset vset,1053boolean isStatic) {1054for (int i = 0; i < ctxInit.getVarNumber(); i++) {1055if (!vset.testVar(i)) {1056MemberDefinition ff = ctxInit.getElement(i);1057if (ff != null && ff.isBlankFinal()1058&& ff.isStatic() == isStatic1059&& ff.getClassDefinition() == this) {1060env.error(ff.getWhere(),1061"final.var.not.initialized", ff.getName());1062}1063}1064}1065}10661067/**1068* Check this class has its superclass and its interfaces. Also1069* force it to have an <init> method (if it doesn't already have one)1070* and to have all the abstract methods of its parents.1071*/1072private boolean basicChecking = false;1073private boolean basicCheckDone = false;1074protected void basicCheck(Environment env) throws ClassNotFound {10751076if (tracing) env.dtEnter("SourceClass.basicCheck: " + getName());10771078super.basicCheck(env);10791080if (basicChecking || basicCheckDone) {1081if (tracing) env.dtExit("SourceClass.basicCheck: OK " + getName());1082return;1083}10841085if (tracing) env.dtEvent("SourceClass.basicCheck: CHECKING " + getName());10861087basicChecking = true;10881089env = setupEnv(env);10901091Imports imports = env.getImports();1092if (imports != null) {1093imports.resolve(env);1094}10951096resolveTypeStructure(env);10971098// Check the existence of the superclass and all interfaces.1099// Also responsible for breaking inheritance cycles. This call1100// has been moved to 'resolveTypeStructure', just after the call1101// to 'resolveSupers', as inheritance cycles must be broken before1102// resolving types within the members. Fixes 4073739.1103// checkSupers(env);11041105if (!isInterface()) {11061107// Add implicit <init> method, if necessary.1108// QUERY: What keeps us from adding an implicit constructor1109// when the user explicitly declares one? Is it truly guaranteed1110// that the declaration for such an explicit constructor will have1111// been processed by the time we arrive here? In general, 'basicCheck'1112// is called very early, prior to the normal member checking phase.1113if (!hasConstructor()) {1114Node code = new CompoundStatement(getWhere(), new Statement[0]);1115Type t = Type.tMethod(Type.tVoid);11161117// Default constructors inherit the access modifiers of their1118// class. For non-inner classes, this follows from JLS 8.6.7,1119// as the only possible modifier is 'public'. For the sake of1120// robustness in the presence of errors, we ignore any other1121// modifiers. For inner classes, the rule needs to be extended1122// in some way to account for the possibility of private and1123// protected classes. We make the 'obvious' extension, however,1124// the inner classes spec is silent on this issue, and a definitive1125// resolution is needed. See bugid 4087421.1126// WORKAROUND: A private constructor might need an access method,1127// but it is not possible to create one due to a restriction in1128// the verifier. (This is a known problem -- see 4015397.)1129// We therefore do not inherit the 'private' modifier from the class,1130// allowing the default constructor to be package private. This1131// workaround can be observed via reflection, but is otherwise1132// undetectable, as the constructor is always accessible within1133// the class in which its containing (private) class appears.1134int accessModifiers = getModifiers() &1135(isInnerClass() ? (M_PUBLIC | M_PROTECTED) : M_PUBLIC);1136env.makeMemberDefinition(env, getWhere(), this, null,1137accessModifiers,1138t, idInit, null, null, code);1139}1140}11411142// Only do the inheritance/override checks if they are turned on.1143// The idea here is that they will be done in javac, but not1144// in javadoc. See the comment for turnOffChecks(), above.1145if (doInheritanceChecks) {11461147// Verify the compatibility of all inherited method definitions1148// by collecting all of our inheritable methods.1149collectInheritedMethods(env);1150}11511152basicChecking = false;1153basicCheckDone = true;1154if (tracing) env.dtExit("SourceClass.basicCheck: " + getName());1155}11561157/**1158* Add a group of methods to this class as miranda methods.1159*1160* For a definition of Miranda methods, see the comment above the1161* method addMirandaMethods() in the file1162* sun/tools/java/ClassDeclaration.java1163*/1164protected void addMirandaMethods(Environment env,1165Iterator mirandas) {11661167while(mirandas.hasNext()) {1168MemberDefinition method =1169(MemberDefinition)mirandas.next();11701171addMember(method);11721173//System.out.println("adding miranda method " + newMethod +1174// " to " + this);1175}1176}11771178/**1179* <em>After parsing is complete</em>, resolve all names1180* except those inside method bodies or initializers.1181* In particular, this is the point at which we find out what1182* kinds of variables and methods there are in the classes,1183* and therefore what is each class's interface to the world.1184* <p>1185* Also perform certain other transformations, such as inserting1186* "this$C" arguments into constructors, and reorganizing structure1187* to flatten qualified member names.1188* <p>1189* Do not perform type-based or name-based consistency checks1190* or normalizations (such as default nullary constructors),1191* and do not attempt to compile code against this class,1192* until after this phase.1193*/11941195private boolean resolving = false;11961197public void resolveTypeStructure(Environment env) {11981199if (tracing)1200env.dtEnter("SourceClass.resolveTypeStructure: " + getName());12011202// Resolve immediately enclosing type, which in turn1203// forces resolution of all enclosing type declarations.1204ClassDefinition oc = getOuterClass();1205if (oc != null && oc instanceof SourceClass1206&& !((SourceClass)oc).resolved) {1207// Do the outer class first, always.1208((SourceClass)oc).resolveTypeStructure(env);1209// (Note: this.resolved is probably true at this point.)1210}12111212// Punt if we've already resolved this class, or are currently1213// in the process of doing so.1214if (resolved || resolving) {1215if (tracing)1216env.dtExit("SourceClass.resolveTypeStructure: OK " + getName());1217return;1218}12191220// Previously, 'resolved' was set here, and served to prevent1221// duplicate resolutions here as well as its function in1222// 'ClassDefinition.addMember'. Now, 'resolving' serves the1223// former purpose, distinct from that of 'resolved'.1224resolving = true;12251226if (tracing)1227env.dtEvent("SourceClass.resolveTypeStructure: RESOLVING " + getName());12281229env = setupEnv(env);12301231// Resolve superclass names to class declarations1232// for the immediate superclass and superinterfaces.1233resolveSupers(env);12341235// Check all ancestor superclasses for various1236// errors, verifying definition of all superclasses1237// and superinterfaces. Also breaks inheritance cycles.1238// Calls 'resolveTypeStructure' recursively for ancestors1239// This call used to appear in 'basicCheck', but was not1240// performed early enough. Most of the compiler will barf1241// on inheritance cycles!1242try {1243checkSupers(env);1244} catch (ClassNotFound ee) {1245// Undefined classes should be reported by 'checkSupers'.1246env.error(where, "class.not.found", ee.name, this);1247}12481249for (MemberDefinition1250f = getFirstMember() ; f != null ; f = f.getNextMember()) {1251if (f instanceof SourceMember)1252((SourceMember)f).resolveTypeStructure(env);1253}12541255resolving = false;12561257// Mark class as resolved. If new members are subsequently1258// added to the class, they will be resolved at that time.1259// See 'ClassDefinition.addMember'. Previously, this variable was1260// set prior to the calls to 'checkSupers' and 'resolveTypeStructure'1261// (which may engender further calls to 'checkSupers'). This could1262// lead to duplicate resolution of implicit constructors, as the call to1263// 'basicCheck' from 'checkSupers' could add the constructor while1264// its class is marked resolved, and thus would resolve the constructor,1265// believing it to be a "late addition". It would then be resolved1266// redundantly during the normal traversal of the members, which1267// immediately follows in the code above.1268resolved = true;12691270// Now we have enough information to detect method repeats.1271for (MemberDefinition1272f = getFirstMember() ; f != null ; f = f.getNextMember()) {1273if (f.isInitializer()) continue;1274if (!f.isMethod()) continue;1275for (MemberDefinition f2 = f; (f2 = f2.getNextMatch()) != null; ) {1276if (!f2.isMethod()) continue;1277if (f.getType().equals(f2.getType())) {1278env.error(f.getWhere(), "meth.multidef", f);1279continue;1280}1281if (f.getType().equalArguments(f2.getType())) {1282env.error(f.getWhere(), "meth.redef.rettype", f, f2);1283continue;1284}1285}1286}1287if (tracing)1288env.dtExit("SourceClass.resolveTypeStructure: " + getName());1289}12901291protected void resolveSupers(Environment env) {1292if (tracing)1293env.dtEnter("SourceClass.resolveSupers: " + this);1294// Find the super class1295if (superClassId != null && superClass == null) {1296superClass = resolveSuper(env, superClassId);1297// Special-case java.lang.Object here (not in the parser).1298// In all other cases, if we have a valid 'superClassId',1299// we return with a valid and non-null 'superClass' value.1300if (superClass == getClassDeclaration()1301&& getName().equals(idJavaLangObject)) {1302superClass = null;1303superClassId = null;1304}1305}1306// Find interfaces1307if (interfaceIds != null && interfaces == null) {1308interfaces = new ClassDeclaration[interfaceIds.length];1309for (int i = 0 ; i < interfaces.length ; i++) {1310interfaces[i] = resolveSuper(env, interfaceIds[i]);1311for (int j = 0; j < i; j++) {1312if (interfaces[i] == interfaces[j]) {1313Identifier id = interfaceIds[i].getName();1314long where = interfaceIds[j].getWhere();1315env.error(where, "intf.repeated", id);1316}1317}1318}1319}1320if (tracing)1321env.dtExit("SourceClass.resolveSupers: " + this);1322}13231324private ClassDeclaration resolveSuper(Environment env, IdentifierToken t) {1325Identifier name = t.getName();1326if (tracing)1327env.dtEnter("SourceClass.resolveSuper: " + name);1328if (isInnerClass())1329name = outerClass.resolveName(env, name);1330else1331name = env.resolveName(name);1332ClassDeclaration result = env.getClassDeclaration(name);1333// Result is never null, as a new 'ClassDeclaration' is1334// created if one with the given name does not exist.1335if (tracing) env.dtExit("SourceClass.resolveSuper: " + name);1336return result;1337}13381339/**1340* During the type-checking of an outer method body or initializer,1341* this routine is called to check a local class body1342* in the proper context.1343* @param sup the named super class or interface (if anonymous)1344* @param args the actual arguments (if anonymous)1345*/1346public Vset checkLocalClass(Environment env, Context ctx, Vset vset,1347ClassDefinition sup,1348Expression args[], Type argTypes[]1349) throws ClassNotFound {1350env = setupEnv(env);13511352if ((sup != null) != isAnonymous()) {1353throw new CompilerError("resolveAnonymousStructure");1354}1355if (isAnonymous()) {1356resolveAnonymousStructure(env, sup, args, argTypes);1357}13581359// Run the checks in the lexical context from the outer class.1360vset = checkInternal(env, ctx, vset);13611362// This is now done by 'checkInternal' via its call to 'checkMembers'.1363// getClassDeclaration().setDefinition(this, CS_CHECKED);13641365return vset;1366}13671368/**1369* As with checkLocalClass, run the inline phase for a local class.1370*/1371public void inlineLocalClass(Environment env) {1372for (MemberDefinition1373f = getFirstMember(); f != null; f = f.getNextMember()) {1374if ((f.isVariable() || f.isInitializer()) && !f.isStatic()) {1375continue; // inlined inside of constructors only1376}1377try {1378((SourceMember)f).inline(env);1379} catch (ClassNotFound ee) {1380env.error(f.getWhere(), "class.not.found", ee.name, this);1381}1382}1383if (getReferencesFrozen() != null && !inlinedLocalClass) {1384inlinedLocalClass = true;1385// add more constructor arguments for uplevel references1386for (MemberDefinition1387f = getFirstMember(); f != null; f = f.getNextMember()) {1388if (f.isConstructor()) {1389//((SourceMember)f).addUplevelArguments(false);1390((SourceMember)f).addUplevelArguments();1391}1392}1393}1394}1395private boolean inlinedLocalClass = false;13961397/**1398* Check a class which is inside a local class, but is not itself local.1399*/1400public Vset checkInsideClass(Environment env, Context ctx, Vset vset)1401throws ClassNotFound {1402if (!isInsideLocal() || isLocal()) {1403throw new CompilerError("checkInsideClass");1404}1405return checkInternal(env, ctx, vset);1406}14071408/**1409* Just before checking an anonymous class, decide its true1410* inheritance, and build its (sole, implicit) constructor.1411*/1412private void resolveAnonymousStructure(Environment env,1413ClassDefinition sup,1414Expression args[], Type argTypes[]1415) throws ClassNotFound {14161417if (tracing) env.dtEvent("SourceClass.resolveAnonymousStructure: " +1418this + ", super " + sup);14191420// Decide now on the superclass.14211422// This check has been removed as part of the fix for 4055017.1423// In the anonymous class created to hold the 'class$' method1424// of an interface, 'superClassId' refers to 'java.lang.Object'.1425/*---------------------*1426if (!(superClass == null && superClassId.getName() == idNull)) {1427throw new CompilerError("superclass "+superClass);1428}1429*---------------------*/14301431if (sup.isInterface()) {1432// allow an interface in the "super class" position1433int ni = (interfaces == null) ? 0 : interfaces.length;1434ClassDeclaration i1[] = new ClassDeclaration[1+ni];1435if (ni > 0) {1436System.arraycopy(interfaces, 0, i1, 1, ni);1437if (interfaceIds != null && interfaceIds.length == ni) {1438IdentifierToken id1[] = new IdentifierToken[1+ni];1439System.arraycopy(interfaceIds, 0, id1, 1, ni);1440id1[0] = new IdentifierToken(sup.getName());1441}1442}1443i1[0] = sup.getClassDeclaration();1444interfaces = i1;14451446sup = toplevelEnv.getClassDefinition(idJavaLangObject);1447}1448superClass = sup.getClassDeclaration();14491450if (hasConstructor()) {1451throw new CompilerError("anonymous constructor");1452}14531454// Synthesize an appropriate constructor.1455Type t = Type.tMethod(Type.tVoid, argTypes);1456IdentifierToken names[] = new IdentifierToken[argTypes.length];1457for (int i = 0; i < names.length; i++) {1458names[i] = new IdentifierToken(args[i].getWhere(),1459Identifier.lookup("$"+i));1460}1461int outerArg = (sup.isTopLevel() || sup.isLocal()) ? 0 : 1;1462Expression superArgs[] = new Expression[-outerArg + args.length];1463for (int i = outerArg ; i < args.length ; i++) {1464superArgs[-outerArg + i] = new IdentifierExpression(names[i]);1465}1466long where = getWhere();1467Expression superExp;1468if (outerArg == 0) {1469superExp = new SuperExpression(where);1470} else {1471superExp = new SuperExpression(where,1472new IdentifierExpression(names[0]));1473}1474Expression superCall = new MethodExpression(where,1475superExp, idInit,1476superArgs);1477Statement body[] = { new ExpressionStatement(where, superCall) };1478Node code = new CompoundStatement(where, body);1479int mod = M_SYNTHETIC; // ISSUE: make M_PRIVATE, with wrapper?1480env.makeMemberDefinition(env, where, this, null,1481mod, t, idInit, names, null, code);1482}14831484/**1485* Convert class modifiers to a string for diagnostic purposes.1486* Accepts modifiers applicable to inner classes and that appear1487* in the InnerClasses attribute only, as well as those that may1488* appear in the class modifier proper.1489*/14901491private static int classModifierBits[] =1492{ ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,1493ACC_INTERFACE, ACC_ABSTRACT, ACC_SUPER, M_ANONYMOUS, M_LOCAL,1494M_STRICTFP, ACC_STRICT};14951496private static String classModifierNames[] =1497{ "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL",1498"INTERFACE", "ABSTRACT", "SUPER", "ANONYMOUS", "LOCAL",1499"STRICTFP", "STRICT"};15001501static String classModifierString(int mods) {1502String s = "";1503for (int i = 0; i < classModifierBits.length; i++) {1504if ((mods & classModifierBits[i]) != 0) {1505s = s + " " + classModifierNames[i];1506mods &= ~classModifierBits[i];1507}1508}1509if (mods != 0) {1510s = s + " ILLEGAL:" + Integer.toHexString(mods);1511}1512return s;1513}15141515/**1516* Find or create an access method for a private member,1517* or return null if this is not possible.1518*/1519public MemberDefinition getAccessMember(Environment env, Context ctx,1520MemberDefinition field, boolean isSuper) {1521return getAccessMember(env, ctx, field, false, isSuper);1522}15231524public MemberDefinition getUpdateMember(Environment env, Context ctx,1525MemberDefinition field, boolean isSuper) {1526if (!field.isVariable()) {1527throw new CompilerError("method");1528}1529return getAccessMember(env, ctx, field, true, isSuper);1530}15311532private MemberDefinition getAccessMember(Environment env, Context ctx,1533MemberDefinition field,1534boolean isUpdate,1535boolean isSuper) {15361537// The 'isSuper' argument is really only meaningful when the1538// target member is a method, in which case an 'invokespecial'1539// is needed. For fields, 'getfield' and 'putfield' instructions1540// are generated in either case, and 'isSuper' currently plays1541// no essential role. Nonetheless, we maintain the distinction1542// consistently for the time being.15431544boolean isStatic = field.isStatic();1545boolean isMethod = field.isMethod();15461547// Find pre-existing access method.1548// In the case of a field access method, we only look for the getter.1549// A getter is always created whenever a setter is.1550// QUERY: Why doesn't the 'MemberDefinition' object for the field1551// itself just have fields for its getter and setter?1552MemberDefinition af;1553for (af = getFirstMember(); af != null; af = af.getNextMember()) {1554if (af.getAccessMethodTarget() == field) {1555if (isMethod && af.isSuperAccessMethod() == isSuper) {1556break;1557}1558// Distinguish the getter and the setter by the number of1559// arguments.1560int nargs = af.getType().getArgumentTypes().length;1561// This was (nargs == (isStatic ? 0 : 1) + (isUpdate ? 1 : 0))1562// in order to find a setter as well as a getter. This caused1563// allocation of multiple getters.1564if (nargs == (isStatic ? 0 : 1)) {1565break;1566}1567}1568}15691570if (af != null) {1571if (!isUpdate) {1572return af;1573} else {1574MemberDefinition uf = af.getAccessUpdateMember();1575if (uf != null) {1576return uf;1577}1578}1579} else if (isUpdate) {1580// must find or create the getter before creating the setter1581af = getAccessMember(env, ctx, field, false, isSuper);1582}15831584// If we arrive here, we are creating a new access member.15851586Identifier anm;1587Type dummyType = null;15881589if (field.isConstructor()) {1590// For a constructor, we use the same name as for all1591// constructors ("<init>"), but add a distinguishing1592// argument of an otherwise unused "dummy" type.1593anm = idInit;1594// Get the dummy class, creating it if necessary.1595SourceClass outerMostClass = (SourceClass)getTopClass();1596dummyType = outerMostClass.dummyArgumentType;1597if (dummyType == null) {1598// Create dummy class.1599IdentifierToken sup =1600new IdentifierToken(0, idJavaLangObject);1601IdentifierToken interfaces[] = {};1602IdentifierToken t = new IdentifierToken(0, idNull);1603int mod = M_ANONYMOUS | M_STATIC | M_SYNTHETIC;1604// If an interface has a public inner class, the dummy class for1605// the constructor must always be accessible. Fix for 4221648.1606if (outerMostClass.isInterface()) {1607mod |= M_PUBLIC;1608}1609ClassDefinition dummyClass =1610toplevelEnv.makeClassDefinition(toplevelEnv,16110, t, null, mod,1612sup, interfaces,1613outerMostClass);1614// Check the class.1615// It is likely that a full check is not really necessary,1616// but it is essential that the class be marked as parsed.1617dummyClass.getClassDeclaration().setDefinition(dummyClass, CS_PARSED);1618Expression argsX[] = {};1619Type argTypesX[] = {};1620try {1621ClassDefinition supcls =1622toplevelEnv.getClassDefinition(idJavaLangObject);1623dummyClass.checkLocalClass(toplevelEnv, null,1624new Vset(), supcls, argsX, argTypesX);1625} catch (ClassNotFound ee) {};1626// Get class type.1627dummyType = dummyClass.getType();1628outerMostClass.dummyArgumentType = dummyType;1629}1630} else {1631// Otherwise, we use the name "access$N", for the1632// smallest value of N >= 0 yielding an unused name.1633for (int i = 0; ; i++) {1634anm = Identifier.lookup(prefixAccess + i);1635if (getFirstMatch(anm) == null) {1636break;1637}1638}1639}16401641Type argTypes[];1642Type t = field.getType();16431644if (isStatic) {1645if (!isMethod) {1646if (!isUpdate) {1647Type at[] = { };1648argTypes = at;1649t = Type.tMethod(t); // nullary getter1650} else {1651Type at[] = { t };1652argTypes = at;1653t = Type.tMethod(Type.tVoid, argTypes); // unary setter1654}1655} else {1656// Since constructors are never static, we don't1657// have to worry about a dummy argument here.1658argTypes = t.getArgumentTypes();1659}1660} else {1661// All access methods for non-static members get an explicit1662// 'this' pointer as an extra argument, as the access methods1663// themselves must be static. EXCEPTION: Access methods for1664// constructors are non-static.1665Type classType = this.getType();1666if (!isMethod) {1667if (!isUpdate) {1668Type at[] = { classType };1669argTypes = at;1670t = Type.tMethod(t, argTypes); // nullary getter1671} else {1672Type at[] = { classType, t };1673argTypes = at;1674t = Type.tMethod(Type.tVoid, argTypes); // unary setter1675}1676} else {1677// Target is a method, possibly a constructor.1678Type at[] = t.getArgumentTypes();1679int nargs = at.length;1680if (field.isConstructor()) {1681// Access method is a constructor.1682// Requires a dummy argument.1683MemberDefinition outerThisArg =1684((SourceMember)field).getOuterThisArg();1685if (outerThisArg != null) {1686// Outer instance link must be the first argument.1687// The following is a sanity check that will catch1688// most cases in which in this requirement is violated.1689if (at[0] != outerThisArg.getType()) {1690throw new CompilerError("misplaced outer this");1691}1692// Strip outer 'this' argument.1693// It will be added back when the access method is checked.1694argTypes = new Type[nargs];1695argTypes[0] = dummyType;1696for (int i = 1; i < nargs; i++) {1697argTypes[i] = at[i];1698}1699} else {1700// There is no outer instance.1701argTypes = new Type[nargs+1];1702argTypes[0] = dummyType;1703for (int i = 0; i < nargs; i++) {1704argTypes[i+1] = at[i];1705}1706}1707} else {1708// Access method is static.1709// Requires an explicit 'this' argument.1710argTypes = new Type[nargs+1];1711argTypes[0] = classType;1712for (int i = 0; i < nargs; i++) {1713argTypes[i+1] = at[i];1714}1715}1716t = Type.tMethod(t.getReturnType(), argTypes);1717}1718}17191720int nlen = argTypes.length;1721long where = field.getWhere();1722IdentifierToken names[] = new IdentifierToken[nlen];1723for (int i = 0; i < nlen; i++) {1724names[i] = new IdentifierToken(where, Identifier.lookup("$"+i));1725}17261727Expression access = null;1728Expression thisArg = null;1729Expression args[] = null;17301731if (isStatic) {1732args = new Expression[nlen];1733for (int i = 0 ; i < nlen ; i++) {1734args[i] = new IdentifierExpression(names[i]);1735}1736} else {1737if (field.isConstructor()) {1738// Constructor access method is non-static, so1739// 'this' works normally.1740thisArg = new ThisExpression(where);1741// Remove dummy argument, as it is not1742// passed to the target method.1743args = new Expression[nlen-1];1744for (int i = 1 ; i < nlen ; i++) {1745args[i-1] = new IdentifierExpression(names[i]);1746}1747} else {1748// Non-constructor access method is static, so1749// we use the first argument as 'this'.1750thisArg = new IdentifierExpression(names[0]);1751// Remove first argument.1752args = new Expression[nlen-1];1753for (int i = 1 ; i < nlen ; i++) {1754args[i-1] = new IdentifierExpression(names[i]);1755}1756}1757access = thisArg;1758}17591760if (!isMethod) {1761access = new FieldExpression(where, access, field);1762if (isUpdate) {1763access = new AssignExpression(where, access, args[0]);1764}1765} else {1766// If true, 'isSuper' forces a non-virtual call.1767access = new MethodExpression(where, access, field, args, isSuper);1768}17691770Statement code;1771if (t.getReturnType().isType(TC_VOID)) {1772code = new ExpressionStatement(where, access);1773} else {1774code = new ReturnStatement(where, access);1775}1776Statement body[] = { code };1777code = new CompoundStatement(where, body);17781779// Access methods are now static (constructors excepted), and no longer final.1780// This change was mandated by the interaction of the access method1781// naming conventions and the restriction against overriding final1782// methods.1783int mod = M_SYNTHETIC;1784if (!field.isConstructor()) {1785mod |= M_STATIC;1786}17871788// Create the synthetic method within the class in which the referenced1789// private member appears. The 'env' argument to 'makeMemberDefinition'1790// is suspect because it represents the environment at the point at1791// which a reference takes place, while it should represent the1792// environment in which the definition of the synthetic method appears.1793// We get away with this because 'env' is used only to access globals1794// such as 'Environment.error', and also as an argument to1795// 'resolveTypeStructure', which immediately discards it using1796// 'setupEnv'. Apparently, the current definition of 'setupEnv'1797// represents a design change that has not been thoroughly propagated.1798// An access method is declared with same list of exceptions as its1799// target. As the exceptions are simply listed by name, the correctness1800// of this approach requires that the access method be checked1801// (name-resolved) in the same context as its target method This1802// should always be the case.1803SourceMember newf = (SourceMember)1804env.makeMemberDefinition(env, where, this,1805null, mod, t, anm, names,1806field.getExceptionIds(), code);1807// Just to be safe, copy over the name-resolved exceptions from the1808// target so that the context in which the access method is checked1809// doesn't matter.1810newf.setExceptions(field.getExceptions(env));18111812newf.setAccessMethodTarget(field);1813if (isUpdate) {1814af.setAccessUpdateMember(newf);1815}1816newf.setIsSuperAccessMethod(isSuper);18171818// The call to 'check' is not needed, as the access method will be1819// checked by the containing class after it is added. This is the1820// idiom followed in the implementation of class literals. (See1821// 'FieldExpression.java'.) In any case, the context is wrong in the1822// call below. The access method must be checked in the context in1823// which it is declared, i.e., the class containing the referenced1824// private member, not the (inner) class in which the original member1825// reference occurs.1826//1827// try {1828// newf.check(env, ctx, new Vset());1829// } catch (ClassNotFound ee) {1830// env.error(where, "class.not.found", ee.name, this);1831// }18321833// The comment above is inaccurate. While it is often the case1834// that the containing class will check the access method, this is1835// by no means guaranteed. In fact, an access method may be added1836// after the checking of its class is complete. In this case, however,1837// the context in which the class was checked will have been saved in1838// the class definition object (by the fix for 4095716), allowing us1839// to check the field now, and in the correct context.1840// This fixes bug 4098093.18411842Context checkContext = newf.getClassDefinition().getClassContext();1843if (checkContext != null) {1844//System.out.println("checking late addition: " + this);1845try {1846newf.check(env, checkContext, new Vset());1847} catch (ClassNotFound ee) {1848env.error(where, "class.not.found", ee.name, this);1849}1850}185118521853//System.out.println("[Access member '" +1854// newf + "' created for field '" +1855// field +"' in class '" + this + "']");18561857return newf;1858}18591860/**1861* Find an inner class of 'this', chosen arbitrarily.1862* Result is always an actual class, never an interface.1863* Returns null if none found.1864*/1865SourceClass findLookupContext() {1866// Look for an immediate inner class.1867for (MemberDefinition f = getFirstMember();1868f != null;1869f = f.getNextMember()) {1870if (f.isInnerClass()) {1871SourceClass ic = (SourceClass)f.getInnerClass();1872if (!ic.isInterface()) {1873return ic;1874}1875}1876}1877// Look for a class nested within an immediate inner interface.1878// At this point, we have given up on finding a minimally-nested1879// class (which would require a breadth-first traversal). It doesn't1880// really matter which inner class we find.1881for (MemberDefinition f = getFirstMember();1882f != null;1883f = f.getNextMember()) {1884if (f.isInnerClass()) {1885SourceClass lc =1886((SourceClass)f.getInnerClass()).findLookupContext();1887if (lc != null) {1888return lc;1889}1890}1891}1892// No inner classes.1893return null;1894}18951896private MemberDefinition lookup = null;18971898/**1899* Get helper method for class literal lookup.1900*/1901public MemberDefinition getClassLiteralLookup(long fwhere) {19021903// If we have already created a lookup method, reuse it.1904if (lookup != null) {1905return lookup;1906}19071908// If the current class is a nested class, make sure we put the1909// lookup method in the outermost class. Set 'lookup' for the1910// intervening inner classes so we won't have to do the search1911// again.1912if (outerClass != null) {1913lookup = outerClass.getClassLiteralLookup(fwhere);1914return lookup;1915}19161917// If we arrive here, there was no existing 'class$' method.19181919ClassDefinition c = this;1920boolean needNewClass = false;19211922if (isInterface()) {1923// The top-level type is an interface. Try to find an existing1924// inner class in which to create the helper method. Any will do.1925c = findLookupContext();1926if (c == null) {1927// The interface has no inner classes. Create an anonymous1928// inner class to hold the helper method, as an interface must1929// not have any methods. The tests above for prior creation1930// of a 'class$' method assure that only one such class is1931// allocated for each outermost class containing a class1932// literal embedded somewhere within. Part of fix for 4055017.1933needNewClass = true;1934IdentifierToken sup =1935new IdentifierToken(fwhere, idJavaLangObject);1936IdentifierToken interfaces[] = {};1937IdentifierToken t = new IdentifierToken(fwhere, idNull);1938int mod = M_PUBLIC | M_ANONYMOUS | M_STATIC | M_SYNTHETIC;1939c = (SourceClass)1940toplevelEnv.makeClassDefinition(toplevelEnv,1941fwhere, t, null, mod,1942sup, interfaces, this);1943}1944}194519461947// The name of the class-getter stub is "class$"1948Identifier idDClass = Identifier.lookup(prefixClass);1949Type strarg[] = { Type.tString };19501951// Some sanity checks of questionable value.1952//1953// This check became useless after matchMethod() was modified1954// to not return synthetic methods.1955//1956//try {1957// lookup = c.matchMethod(toplevelEnv, c, idDClass, strarg);1958//} catch (ClassNotFound ee) {1959// throw new CompilerError("unexpected missing class");1960//} catch (AmbiguousMember ee) {1961// throw new CompilerError("synthetic name clash");1962//}1963//if (lookup != null && lookup.getClassDefinition() == c) {1964// // Error if method found was not inherited.1965// throw new CompilerError("unexpected duplicate");1966//}1967// Some sanity checks of questionable value.19681969/* // The helper function looks like this.1970* // It simply maps a checked exception to an unchecked one.1971* static Class class$(String class$) {1972* try { return Class.forName(class$); }1973* catch (ClassNotFoundException forName) {1974* throw new NoClassDefFoundError(forName.getMessage());1975* }1976* }1977*/1978long w = c.getWhere();1979IdentifierToken arg = new IdentifierToken(w, idDClass);1980Expression e = new IdentifierExpression(arg);1981Expression a1[] = { e };1982Identifier idForName = Identifier.lookup("forName");1983e = new MethodExpression(w, new TypeExpression(w, Type.tClassDesc),1984idForName, a1);1985Statement body = new ReturnStatement(w, e);1986// map the exceptions1987Identifier idClassNotFound =1988Identifier.lookup("java.lang.ClassNotFoundException");1989Identifier idNoClassDefFound =1990Identifier.lookup("java.lang.NoClassDefFoundError");1991Type ctyp = Type.tClass(idClassNotFound);1992Type exptyp = Type.tClass(idNoClassDefFound);1993Identifier idGetMessage = Identifier.lookup("getMessage");1994e = new IdentifierExpression(w, idForName);1995e = new MethodExpression(w, e, idGetMessage, new Expression[0]);1996Expression a2[] = { e };1997e = new NewInstanceExpression(w, new TypeExpression(w, exptyp), a2);1998Statement handler = new CatchStatement(w, new TypeExpression(w, ctyp),1999new IdentifierToken(idForName),2000new ThrowStatement(w, e));2001Statement handlers[] = { handler };2002body = new TryStatement(w, body, handlers);20032004Type mtype = Type.tMethod(Type.tClassDesc, strarg);2005IdentifierToken args[] = { arg };20062007// Use default (package) access. If private, an access method would2008// be needed in the event that the class literal belonged to an interface.2009// Also, making it private tickles bug 4098316.2010lookup = toplevelEnv.makeMemberDefinition(toplevelEnv, w,2011c, null,2012M_STATIC | M_SYNTHETIC,2013mtype, idDClass,2014args, null, body);20152016// If a new class was created to contain the helper method,2017// check it now.2018if (needNewClass) {2019if (c.getClassDeclaration().getStatus() == CS_CHECKED) {2020throw new CompilerError("duplicate check");2021}2022c.getClassDeclaration().setDefinition(c, CS_PARSED);2023Expression argsX[] = {};2024Type argTypesX[] = {};2025try {2026ClassDefinition sup =2027toplevelEnv.getClassDefinition(idJavaLangObject);2028c.checkLocalClass(toplevelEnv, null,2029new Vset(), sup, argsX, argTypesX);2030} catch (ClassNotFound ee) {};2031}20322033return lookup;2034}203520362037/**2038* A list of active ongoing compilations. This list2039* is used to stop two compilations from saving the2040* same class.2041*/2042private static Vector active = new Vector();20432044/**2045* Compile this class2046*/2047public void compile(OutputStream out)2048throws InterruptedException, IOException {2049Environment env = toplevelEnv;2050synchronized (active) {2051while (active.contains(getName())) {2052active.wait();2053}2054active.addElement(getName());2055}20562057try {2058compileClass(env, out);2059} catch (ClassNotFound e) {2060throw new CompilerError(e);2061} finally {2062synchronized (active) {2063active.removeElement(getName());2064active.notifyAll();2065}2066}2067}20682069/**2070* Verify that the modifier bits included in 'required' are2071* all present in 'mods', otherwise signal an internal error.2072* Note that errors in the source program may corrupt the modifiers,2073* thus we rely on the fact that 'CompilerError' exceptions are2074* silently ignored after an error message has been issued.2075*/2076private static void assertModifiers(int mods, int required) {2077if ((mods & required) != required) {2078throw new CompilerError("illegal class modifiers");2079}2080}20812082protected void compileClass(Environment env, OutputStream out)2083throws IOException, ClassNotFound {2084Vector variables = new Vector();2085Vector methods = new Vector();2086Vector innerClasses = new Vector();2087CompilerMember init = new CompilerMember(new MemberDefinition(getWhere(), this, M_STATIC, Type.tMethod(Type.tVoid), idClassInit, null, null), new Assembler());2088Context ctx = new Context((Context)null, init.field);20892090for (ClassDefinition def = this; def.isInnerClass(); def = def.getOuterClass()) {2091innerClasses.addElement(def);2092}2093// Reverse the order, so that outer levels come first:2094int ncsize = innerClasses.size();2095for (int i = ncsize; --i >= 0; )2096innerClasses.addElement(innerClasses.elementAt(i));2097for (int i = ncsize; --i >= 0; )2098innerClasses.removeElementAt(i);20992100// System.out.println("compile class " + getName());21012102boolean haveDeprecated = this.isDeprecated();2103boolean haveSynthetic = this.isSynthetic();2104boolean haveConstantValue = false;2105boolean haveExceptions = false;21062107// Generate code for all fields2108for (SourceMember field = (SourceMember)getFirstMember();2109field != null;2110field = (SourceMember)field.getNextMember()) {21112112//System.out.println("compile field " + field.getName());21132114haveDeprecated |= field.isDeprecated();2115haveSynthetic |= field.isSynthetic();21162117try {2118if (field.isMethod()) {2119haveExceptions |=2120(field.getExceptions(env).length > 0);21212122if (field.isInitializer()) {2123if (field.isStatic()) {2124field.code(env, init.asm);2125}2126} else {2127CompilerMember f =2128new CompilerMember(field, new Assembler());2129field.code(env, f.asm);2130methods.addElement(f);2131}2132} else if (field.isInnerClass()) {2133innerClasses.addElement(field.getInnerClass());2134} else if (field.isVariable()) {2135field.inline(env);2136CompilerMember f = new CompilerMember(field, null);2137variables.addElement(f);2138if (field.isStatic()) {2139field.codeInit(env, ctx, init.asm);21402141}2142haveConstantValue |=2143(field.getInitialValue() != null);2144}2145} catch (CompilerError ee) {2146ee.printStackTrace();2147env.error(field, 0, "generic",2148field.getClassDeclaration() + ":" + field +2149"@" + ee.toString(), null, null);2150}2151}2152if (!init.asm.empty()) {2153init.asm.add(getWhere(), opc_return, true);2154methods.addElement(init);2155}21562157// bail out if there were any errors2158if (getNestError()) {2159return;2160}21612162int nClassAttrs = 0;21632164// Insert constants2165if (methods.size() > 0) {2166tab.put("Code");2167}2168if (haveConstantValue) {2169tab.put("ConstantValue");2170}21712172String sourceFile = null;2173if (env.debug_source()) {2174sourceFile = ((ClassFile)getSource()).getName();2175tab.put("SourceFile");2176tab.put(sourceFile);2177nClassAttrs += 1;2178}21792180if (haveExceptions) {2181tab.put("Exceptions");2182}21832184if (env.debug_lines()) {2185tab.put("LineNumberTable");2186}2187if (haveDeprecated) {2188tab.put("Deprecated");2189if (this.isDeprecated()) {2190nClassAttrs += 1;2191}2192}2193if (haveSynthetic) {2194tab.put("Synthetic");2195if (this.isSynthetic()) {2196nClassAttrs += 1;2197}2198}2199// JCOV2200if (env.coverage()) {2201nClassAttrs += 2; // AbsoluteSourcePath, TimeStamp2202tab.put("AbsoluteSourcePath");2203tab.put("TimeStamp");2204tab.put("CoverageTable");2205}2206// end JCOV2207if (env.debug_vars()) {2208tab.put("LocalVariableTable");2209}2210if (innerClasses.size() > 0) {2211tab.put("InnerClasses");2212nClassAttrs += 1; // InnerClasses2213}22142215// JCOV2216String absoluteSourcePath = "";2217long timeStamp = 0;22182219if (env.coverage()) {2220absoluteSourcePath = getAbsoluteName();2221timeStamp = System.currentTimeMillis();2222tab.put(absoluteSourcePath);2223}2224// end JCOV2225tab.put(getClassDeclaration());2226if (getSuperClass() != null) {2227tab.put(getSuperClass());2228}2229for (int i = 0 ; i < interfaces.length ; i++) {2230tab.put(interfaces[i]);2231}22322233// Sort the methods in order to make sure both constant pool2234// entries and methods are in a deterministic order from run2235// to run (this allows comparing class files for a fixed point2236// to validate the compiler)2237CompilerMember[] ordered_methods =2238new CompilerMember[methods.size()];2239methods.copyInto(ordered_methods);2240java.util.Arrays.sort(ordered_methods);2241for (int i=0; i<methods.size(); i++)2242methods.setElementAt(ordered_methods[i], i);22432244// Optimize Code and Collect method constants2245for (Enumeration e = methods.elements() ; e.hasMoreElements() ; ) {2246CompilerMember f = (CompilerMember)e.nextElement();2247try {2248f.asm.optimize(env);2249f.asm.collect(env, f.field, tab);2250tab.put(f.name);2251tab.put(f.sig);2252ClassDeclaration exp[] = f.field.getExceptions(env);2253for (int i = 0 ; i < exp.length ; i++) {2254tab.put(exp[i]);2255}2256} catch (Exception ee) {2257ee.printStackTrace();2258env.error(f.field, -1, "generic", f.field.getName() + "@" + ee.toString(), null, null);2259f.asm.listing(System.out);2260}2261}22622263// Collect field constants2264for (Enumeration e = variables.elements() ; e.hasMoreElements() ; ) {2265CompilerMember f = (CompilerMember)e.nextElement();2266tab.put(f.name);2267tab.put(f.sig);22682269Object val = f.field.getInitialValue();2270if (val != null) {2271tab.put((val instanceof String) ? new StringExpression(f.field.getWhere(), (String)val) : val);2272}2273}22742275// Collect inner class constants2276for (Enumeration e = innerClasses.elements();2277e.hasMoreElements() ; ) {2278ClassDefinition inner = (ClassDefinition)e.nextElement();2279tab.put(inner.getClassDeclaration());22802281// If the inner class is local, we do not need to add its2282// outer class here -- the outer_class_info_index is zero.2283if (!inner.isLocal()) {2284ClassDefinition outer = inner.getOuterClass();2285tab.put(outer.getClassDeclaration());2286}22872288// If the local name of the class is idNull, don't bother to2289// add it to the constant pool. We won't need it.2290Identifier inner_local_name = inner.getLocalName();2291if (inner_local_name != idNull) {2292tab.put(inner_local_name.toString());2293}2294}22952296// Write header2297DataOutputStream data = new DataOutputStream(out);2298data.writeInt(JAVA_MAGIC);2299data.writeShort(toplevelEnv.getMinorVersion());2300data.writeShort(toplevelEnv.getMajorVersion());2301tab.write(env, data);23022303// Write class information2304int cmods = getModifiers() & MM_CLASS;23052306// Certain modifiers are implied:2307// 1. Any interface (nested or not) is implicitly deemed to be abstract,2308// whether it is explicitly marked so or not. (Java 1.0.)2309// 2. A interface which is a member of a type is implicitly deemed to2310// be static, whether it is explicitly marked so or not.2311// 3a. A type which is a member of an interface is implicitly deemed2312// to be public, whether it is explicitly marked so or not.2313// 3b. A type which is a member of an interface is implicitly deemed2314// to be static, whether it is explicitly marked so or not.2315// All of these rules are implemented in 'BatchParser.beginClass',2316// but the results are verified here.23172318if (isInterface()) {2319// Rule 1.2320// The VM spec states that ACC_ABSTRACT must be set when2321// ACC_INTERFACE is; this was not done by javac prior to 1.2,2322// and the runtime compensates by setting it. Making sure2323// it is set here will allow the runtime hack to eventually2324// be removed. Rule 2 doesn't apply to transformed modifiers.2325assertModifiers(cmods, ACC_ABSTRACT);2326} else {2327// Contrary to the JVM spec, we only set ACC_SUPER for classes,2328// not interfaces. This is a workaround for a bug in IE3.0,2329// which refuses interfaces with ACC_SUPER on.2330cmods |= ACC_SUPER;2331}23322333// If this is a nested class, transform access modifiers.2334if (outerClass != null) {2335// If private, transform to default (package) access.2336// If protected, transform to public.2337// M_PRIVATE and M_PROTECTED are already masked off by MM_CLASS above.2338// cmods &= ~(M_PRIVATE | M_PROTECTED);2339if (isProtected()) cmods |= M_PUBLIC;2340// Rule 3a. Note that Rule 3b doesn't apply to transformed modifiers.2341if (outerClass.isInterface()) {2342assertModifiers(cmods, M_PUBLIC);2343}2344}23452346data.writeShort(cmods);23472348if (env.dumpModifiers()) {2349Identifier cn = getName();2350Identifier nm =2351Identifier.lookup(cn.getQualifier(), cn.getFlatName());2352System.out.println();2353System.out.println("CLASSFILE " + nm);2354System.out.println("---" + classModifierString(cmods));2355}23562357data.writeShort(tab.index(getClassDeclaration()));2358data.writeShort((getSuperClass() != null) ? tab.index(getSuperClass()) : 0);2359data.writeShort(interfaces.length);2360for (int i = 0 ; i < interfaces.length ; i++) {2361data.writeShort(tab.index(interfaces[i]));2362}23632364// write variables2365ByteArrayOutputStream buf = new ByteArrayOutputStream(256);2366ByteArrayOutputStream attbuf = new ByteArrayOutputStream(256);2367DataOutputStream databuf = new DataOutputStream(buf);23682369data.writeShort(variables.size());2370for (Enumeration e = variables.elements() ; e.hasMoreElements() ; ) {2371CompilerMember f = (CompilerMember)e.nextElement();2372Object val = f.field.getInitialValue();23732374data.writeShort(f.field.getModifiers() & MM_FIELD);2375data.writeShort(tab.index(f.name));2376data.writeShort(tab.index(f.sig));23772378int fieldAtts = (val != null ? 1 : 0);2379boolean dep = f.field.isDeprecated();2380boolean syn = f.field.isSynthetic();2381fieldAtts += (dep ? 1 : 0) + (syn ? 1 : 0);23822383data.writeShort(fieldAtts);2384if (val != null) {2385data.writeShort(tab.index("ConstantValue"));2386data.writeInt(2);2387data.writeShort(tab.index((val instanceof String) ? new StringExpression(f.field.getWhere(), (String)val) : val));2388}2389if (dep) {2390data.writeShort(tab.index("Deprecated"));2391data.writeInt(0);2392}2393if (syn) {2394data.writeShort(tab.index("Synthetic"));2395data.writeInt(0);2396}2397}23982399// write methods24002401data.writeShort(methods.size());2402for (Enumeration e = methods.elements() ; e.hasMoreElements() ; ) {2403CompilerMember f = (CompilerMember)e.nextElement();24042405int xmods = f.field.getModifiers() & MM_METHOD;2406// Transform floating point modifiers. M_STRICTFP2407// of member + status of enclosing class turn into2408// ACC_STRICT bit.2409if (((xmods & M_STRICTFP)!=0) || ((cmods & M_STRICTFP)!=0)) {2410xmods |= ACC_STRICT;2411} else {2412// Use the default2413if (env.strictdefault()) {2414xmods |= ACC_STRICT;2415}2416}2417data.writeShort(xmods);24182419data.writeShort(tab.index(f.name));2420data.writeShort(tab.index(f.sig));2421ClassDeclaration exp[] = f.field.getExceptions(env);2422int methodAtts = ((exp.length > 0) ? 1 : 0);2423boolean dep = f.field.isDeprecated();2424boolean syn = f.field.isSynthetic();2425methodAtts += (dep ? 1 : 0) + (syn ? 1 : 0);24262427if (!f.asm.empty()) {2428data.writeShort(methodAtts+1);2429f.asm.write(env, databuf, f.field, tab);2430int natts = 0;2431if (env.debug_lines()) {2432natts++;2433}2434// JCOV2435if (env.coverage()) {2436natts++;2437}2438// end JCOV2439if (env.debug_vars()) {2440natts++;2441}2442databuf.writeShort(natts);24432444if (env.debug_lines()) {2445f.asm.writeLineNumberTable(env, new DataOutputStream(attbuf), tab);2446databuf.writeShort(tab.index("LineNumberTable"));2447databuf.writeInt(attbuf.size());2448attbuf.writeTo(buf);2449attbuf.reset();2450}24512452//JCOV2453if (env.coverage()) {2454f.asm.writeCoverageTable(env, (ClassDefinition)this, new DataOutputStream(attbuf), tab, f.field.getWhere());2455databuf.writeShort(tab.index("CoverageTable"));2456databuf.writeInt(attbuf.size());2457attbuf.writeTo(buf);2458attbuf.reset();2459}2460// end JCOV2461if (env.debug_vars()) {2462f.asm.writeLocalVariableTable(env, f.field, new DataOutputStream(attbuf), tab);2463databuf.writeShort(tab.index("LocalVariableTable"));2464databuf.writeInt(attbuf.size());2465attbuf.writeTo(buf);2466attbuf.reset();2467}24682469data.writeShort(tab.index("Code"));2470data.writeInt(buf.size());2471buf.writeTo(data);2472buf.reset();2473} else {2474//JCOV2475if ((env.coverage()) && ((f.field.getModifiers() & M_NATIVE) > 0))2476f.asm.addNativeToJcovTab(env, (ClassDefinition)this);2477// end JCOV2478data.writeShort(methodAtts);2479}24802481if (exp.length > 0) {2482data.writeShort(tab.index("Exceptions"));2483data.writeInt(2 + exp.length * 2);2484data.writeShort(exp.length);2485for (int i = 0 ; i < exp.length ; i++) {2486data.writeShort(tab.index(exp[i]));2487}2488}2489if (dep) {2490data.writeShort(tab.index("Deprecated"));2491data.writeInt(0);2492}2493if (syn) {2494data.writeShort(tab.index("Synthetic"));2495data.writeInt(0);2496}2497}24982499// class attributes2500data.writeShort(nClassAttrs);25012502if (env.debug_source()) {2503data.writeShort(tab.index("SourceFile"));2504data.writeInt(2);2505data.writeShort(tab.index(sourceFile));2506}25072508if (this.isDeprecated()) {2509data.writeShort(tab.index("Deprecated"));2510data.writeInt(0);2511}2512if (this.isSynthetic()) {2513data.writeShort(tab.index("Synthetic"));2514data.writeInt(0);2515}25162517// JCOV2518if (env.coverage()) {2519data.writeShort(tab.index("AbsoluteSourcePath"));2520data.writeInt(2);2521data.writeShort(tab.index(absoluteSourcePath));2522data.writeShort(tab.index("TimeStamp"));2523data.writeInt(8);2524data.writeLong(timeStamp);2525}2526// end JCOV25272528if (innerClasses.size() > 0) {2529data.writeShort(tab.index("InnerClasses"));2530data.writeInt(2 + 2*4*innerClasses.size());2531data.writeShort(innerClasses.size());2532for (Enumeration e = innerClasses.elements() ;2533e.hasMoreElements() ; ) {2534// For each inner class name transformation, we have a record2535// with the following fields:2536//2537// u2 inner_class_info_index; // CONSTANT_Class_info index2538// u2 outer_class_info_index; // CONSTANT_Class_info index2539// u2 inner_name_index; // CONSTANT_Utf8_info index2540// u2 inner_class_access_flags; // access_flags bitmask2541//2542// The spec states that outer_class_info_index is 0 iff2543// the inner class is not a member of its enclosing class (i.e.2544// it is a local or anonymous class). The spec also states2545// that if a class is anonymous then inner_name_index should2546// be 0.2547//2548// See also the initInnerClasses() method in BinaryClass.java.25492550// Generate inner_class_info_index.2551ClassDefinition inner = (ClassDefinition)e.nextElement();2552data.writeShort(tab.index(inner.getClassDeclaration()));25532554// Generate outer_class_info_index.2555//2556// Checking isLocal() should probably be enough here,2557// but the check for isAnonymous is added for good2558// measure.2559if (inner.isLocal() || inner.isAnonymous()) {2560data.writeShort(0);2561} else {2562// Query: what about if inner.isInsideLocal()?2563// For now we continue to generate a nonzero2564// outer_class_info_index.2565ClassDefinition outer = inner.getOuterClass();2566data.writeShort(tab.index(outer.getClassDeclaration()));2567}25682569// Generate inner_name_index.2570Identifier inner_name = inner.getLocalName();2571if (inner_name == idNull) {2572if (!inner.isAnonymous()) {2573throw new CompilerError("compileClass(), anonymous");2574}2575data.writeShort(0);2576} else {2577data.writeShort(tab.index(inner_name.toString()));2578}25792580// Generate inner_class_access_flags.2581int imods = inner.getInnerClassMember().getModifiers()2582& ACCM_INNERCLASS;25832584// Certain modifiers are implied for nested types.2585// See rules 1, 2, 3a, and 3b enumerated above.2586// All of these rules are implemented in 'BatchParser.beginClass',2587// but are verified here.25882589if (inner.isInterface()) {2590// Rules 1 and 2.2591assertModifiers(imods, M_ABSTRACT | M_STATIC);2592}2593if (inner.getOuterClass().isInterface()) {2594// Rules 3a and 3b.2595imods &= ~(M_PRIVATE | M_PROTECTED); // error recovery2596assertModifiers(imods, M_PUBLIC | M_STATIC);2597}25982599data.writeShort(imods);26002601if (env.dumpModifiers()) {2602Identifier fn = inner.getInnerClassMember().getName();2603Identifier nm =2604Identifier.lookup(fn.getQualifier(), fn.getFlatName());2605System.out.println("INNERCLASS " + nm);2606System.out.println("---" + classModifierString(imods));2607}26082609}2610}26112612// Cleanup2613data.flush();2614tab = null;26152616// JCOV2617// generate coverage data2618if (env.covdata()) {2619Assembler CovAsm = new Assembler();2620CovAsm.GenVecJCov(env, (ClassDefinition)this, timeStamp);2621}2622// end JCOV2623}26242625/**2626* Print out the dependencies for this class (-xdepend) option2627*/26282629public void printClassDependencies(Environment env) {26302631// Only do this if the -xdepend flag is on2632if ( toplevelEnv.print_dependencies() ) {26332634// Name of java source file this class was in (full path)2635// e.g. /home/ohair/Test.java2636String src = ((ClassFile)getSource()).getAbsoluteName();26372638// Class name, fully qualified2639// e.g. "java.lang.Object" or "FooBar" or "sun.tools.javac.Main"2640// Inner class names must be mangled, as ordinary '.' qualification2641// is used internally where the spec requires '$' separators.2642// String className = getName().toString();2643String className = Type.mangleInnerType(getName()).toString();26442645// Line number where class starts in the src file2646long startLine = getWhere() >> WHEREOFFSETBITS;26472648// Line number where class ends in the src file (not used yet)2649long endLine = getEndPosition() >> WHEREOFFSETBITS;26502651// First line looks like:2652// CLASS:src,startLine,endLine,className2653System.out.println( "CLASS:"2654+ src + ","2655+ startLine + ","2656+ endLine + ","2657+ className);26582659// For each class this class is dependent on:2660// CLDEP:className1,className22661// where className1 is the name of the class we are in, and2662// classname2 is the name of the class className12663// is dependent on.2664for(Enumeration e = deps.elements(); e.hasMoreElements(); ) {2665ClassDeclaration data = (ClassDeclaration) e.nextElement();2666// Mangle name of class dependend on.2667String depName =2668Type.mangleInnerType(data.getName()).toString();2669env.output("CLDEP:" + className + "," + depName);2670}2671}2672}2673}267426752676