1 /*
   2  * Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.tools.javac;
  27 
  28 import sun.tools.java.*;
  29 import sun.tools.tree.*;
  30 import sun.tools.tree.CompoundStatement;
  31 import sun.tools.asm.Assembler;
  32 import sun.tools.asm.ConstantPool;
  33 import java.util.Vector;
  34 import java.util.Enumeration;
  35 import java.util.Hashtable;
  36 import java.util.Iterator;
  37 import java.io.IOException;
  38 import java.io.OutputStream;
  39 import java.io.DataOutputStream;
  40 import java.io.ByteArrayOutputStream;
  41 import java.io.File;
  42 
  43 /**
  44  * This class represents an Java class as it is read from
  45  * an Java source file.
  46  *
  47  * WARNING: The contents of this source file are not part of any
  48  * supported API.  Code that depends on them does so at its own risk:
  49  * they are subject to change or removal without notice.
  50  */
  51 @Deprecated
  52 public
  53 class SourceClass extends ClassDefinition {
  54 
  55     /**
  56      * The toplevel environment, shared with the parser
  57      */
  58     Environment toplevelEnv;
  59 
  60     /**
  61      * The default constructor
  62      */
  63     SourceMember defConstructor;
  64 
  65     /**
  66      * The constant pool
  67      */
  68     ConstantPool tab = new ConstantPool();
  69 
  70    /**
  71      * The list of class dependencies
  72      */
  73     Hashtable deps = new Hashtable(11);
  74 
  75     /**
  76      * The field used to represent "this" in all of my code.
  77      */
  78     LocalMember thisArg;
  79 
  80     /**
  81      * Last token of class, as reported by parser.
  82      */
  83     long endPosition;
  84 
  85     /**
  86      * Access methods for constructors are distinguished from
  87      * the constructors themselves by a dummy first argument.
  88      * A unique type used for this purpose and shared by all
  89      * constructor access methods within a package-member class is
  90      * maintained here.
  91      * <p>
  92      * This field is null except in an outermost class containing
  93      * one or more classes needing such an access method.
  94      */
  95     private Type dummyArgumentType = null;
  96 
  97     /**
  98      * Constructor
  99      */
 100     public SourceClass(Environment env, long where,
 101                        ClassDeclaration declaration, String documentation,
 102                        int modifiers, IdentifierToken superClass,
 103                        IdentifierToken interfaces[],
 104                        SourceClass outerClass, Identifier localName) {
 105         super(env.getSource(), where,
 106               declaration, modifiers, superClass, interfaces);
 107         setOuterClass(outerClass);
 108 
 109         this.toplevelEnv = env;
 110         this.documentation = documentation;
 111 
 112         if (ClassDefinition.containsDeprecated(documentation)) {
 113             this.modifiers |= M_DEPRECATED;
 114         }
 115 
 116         // Check for a package level class which is declared static.
 117         if (isStatic() && outerClass == null) {
 118             env.error(where, "static.class", this);
 119             this.modifiers &=~ M_STATIC;
 120         }
 121 
 122         // Inner classes cannot be static, nor can they be interfaces
 123         // (which are implicitly static).  Static classes and interfaces
 124         // can only occur as top-level entities.
 125         //
 126         // Note that we do not have to check for local classes declared
 127         // to be static (this is currently caught by the parser) but
 128         // we check anyway in case the parser is modified to allow this.
 129         if (isLocal() || (outerClass != null && !outerClass.isTopLevel())) {
 130             if (isInterface()) {
 131                 env.error(where, "inner.interface");
 132             } else if (isStatic()) {
 133                 env.error(where, "static.inner.class", this);
 134                 this.modifiers &=~ M_STATIC;
 135                 if (innerClassMember != null) {
 136                     innerClassMember.subModifiers(M_STATIC);
 137                 }
 138             }
 139         }
 140 
 141         if (isPrivate() && outerClass == null) {
 142             env.error(where, "private.class", this);
 143             this.modifiers &=~ M_PRIVATE;
 144         }
 145         if (isProtected() && outerClass == null) {
 146             env.error(where, "protected.class", this);
 147             this.modifiers &=~ M_PROTECTED;
 148         }
 149         /*----*
 150         if ((isPublic() || isProtected()) && isInsideLocal()) {
 151             env.error(where, "warn.public.local.class", this);
 152         }
 153          *----*/
 154 
 155         // maybe define an uplevel "A.this" current instance field
 156         if (!isTopLevel() && !isLocal()) {
 157             LocalMember outerArg = outerClass.getThisArgument();
 158             UplevelReference r = getReference(outerArg);
 159             setOuterMember(r.getLocalField(env));
 160         }
 161 
 162         // Set simple, unmangled local name for a local or anonymous class.
 163         // NOTE: It would be OK to do this unconditionally, as null is the
 164         // correct value for a member (non-local) class.
 165         if (localName != null)
 166             setLocalName(localName);
 167 
 168         // Check for inner class with same simple name as one of
 169         // its enclosing classes.  Note that 'getLocalName' returns
 170         // the simple, unmangled source-level name of any class.
 171         // The previous version of this code was not careful to avoid
 172         // mangled local class names.  This version fixes 4047746.
 173         Identifier thisName = getLocalName();
 174         if (thisName != idNull) {
 175             // Test above suppresses error for nested anonymous classes,
 176             // which have an internal "name", but are not named in source code.
 177             for (ClassDefinition scope = outerClass; scope != null;
 178                   scope = scope.getOuterClass()) {
 179                 Identifier outerName = scope.getLocalName();
 180                 if (thisName.equals(outerName))
 181                     env.error(where, "inner.redefined", thisName);
 182             }
 183         }
 184     }
 185 
 186     /**
 187      * Return last position in this class.
 188      * @see #getWhere
 189      */
 190     public long getEndPosition() {
 191         return endPosition;
 192     }
 193 
 194     public void setEndPosition(long endPosition) {
 195         this.endPosition = endPosition;
 196     }
 197 
 198 
 199 // JCOV
 200     /**
 201      * Return absolute name of source file
 202      */
 203     public String getAbsoluteName() {
 204         String AbsName = ((ClassFile)getSource()).getAbsoluteName();
 205 
 206         return AbsName;
 207     }
 208 //end JCOV
 209 
 210     /**
 211      * Return imports
 212      */
 213     public Imports getImports() {
 214         return toplevelEnv.getImports();
 215     }
 216 
 217     /**
 218      * Find or create my "this" argument, which is used for all methods.
 219      */
 220     public LocalMember getThisArgument() {
 221         if (thisArg == null) {
 222             thisArg = new LocalMember(where, this, 0, getType(), idThis);
 223         }
 224         return thisArg;
 225     }
 226 
 227     /**
 228      * Add a dependency
 229      */
 230     public void addDependency(ClassDeclaration c) {
 231         if (tab != null) {
 232             tab.put(c);
 233         }
 234         // If doing -xdepend option, save away list of class dependencies
 235         //   making sure to NOT include duplicates or the class we are in
 236         //   (Hashtable's put() makes sure we don't have duplicates)
 237         if ( toplevelEnv.print_dependencies() && c != getClassDeclaration() ) {
 238             deps.put(c,c);
 239         }
 240     }
 241 
 242     /**
 243      * Add a field (check it first)
 244      */
 245     public void addMember(Environment env, MemberDefinition f) {
 246         // Make sure the access permissions are self-consistent:
 247         switch (f.getModifiers() & (M_PUBLIC | M_PRIVATE | M_PROTECTED)) {
 248         case M_PUBLIC:
 249         case M_PRIVATE:
 250         case M_PROTECTED:
 251         case 0:
 252             break;
 253         default:
 254             env.error(f.getWhere(), "inconsistent.modifier", f);
 255             // Cut out the more restrictive modifier(s):
 256             if (f.isPublic()) {
 257                 f.subModifiers(M_PRIVATE | M_PROTECTED);
 258             } else {
 259                 f.subModifiers(M_PRIVATE);
 260             }
 261             break;
 262         }
 263 
 264         // Note exemption for synthetic members below.
 265         if (f.isStatic() && !isTopLevel() && !f.isSynthetic()) {
 266             if (f.isMethod()) {
 267                 env.error(f.getWhere(), "static.inner.method", f, this);
 268                 f.subModifiers(M_STATIC);
 269             } else if (f.isVariable()) {
 270                 if (!f.isFinal() || f.isBlankFinal()) {
 271                     env.error(f.getWhere(), "static.inner.field", f.getName(), this);
 272                     f.subModifiers(M_STATIC);
 273                 }
 274                 // Even if a static passes this test, there is still another
 275                 // check in 'SourceMember.check'.  The check is delayed so
 276                 // that the initializer may be inspected more closely, using
 277                 // 'isConstant()'.  Part of fix for 4095568.
 278             } else {
 279                 // Static inner classes are diagnosed in 'SourceClass.<init>'.
 280                 f.subModifiers(M_STATIC);
 281             }
 282         }
 283 
 284         if (f.isMethod()) {
 285             if (f.isConstructor()) {
 286                 if (f.getClassDefinition().isInterface()) {
 287                     env.error(f.getWhere(), "intf.constructor");
 288                     return;
 289                 }
 290                 if (f.isNative() || f.isAbstract() ||
 291                       f.isStatic() || f.isSynchronized() || f.isFinal()) {
 292                     env.error(f.getWhere(), "constr.modifier", f);
 293                     f.subModifiers(M_NATIVE | M_ABSTRACT |
 294                                    M_STATIC | M_SYNCHRONIZED | M_FINAL);
 295                 }
 296             } else if (f.isInitializer()) {
 297                 if (f.getClassDefinition().isInterface()) {
 298                     env.error(f.getWhere(), "intf.initializer");
 299                     return;
 300                 }
 301             }
 302 
 303             // f is not allowed to return an array of void
 304             if ((f.getType().getReturnType()).isVoidArray()) {
 305                 env.error(f.getWhere(), "void.array");
 306             }
 307 
 308             if (f.getClassDefinition().isInterface() &&
 309                 (f.isStatic() || f.isSynchronized() || f.isNative()
 310                  || f.isFinal() || f.isPrivate() || f.isProtected())) {
 311                 env.error(f.getWhere(), "intf.modifier.method", f);
 312                 f.subModifiers(M_STATIC |  M_SYNCHRONIZED | M_NATIVE |
 313                                M_FINAL | M_PRIVATE);
 314             }
 315             if (f.isTransient()) {
 316                 env.error(f.getWhere(), "transient.meth", f);
 317                 f.subModifiers(M_TRANSIENT);
 318             }
 319             if (f.isVolatile()) {
 320                 env.error(f.getWhere(), "volatile.meth", f);
 321                 f.subModifiers(M_VOLATILE);
 322             }
 323             if (f.isAbstract()) {
 324                 if (f.isPrivate()) {
 325                     env.error(f.getWhere(), "abstract.private.modifier", f);
 326                     f.subModifiers(M_PRIVATE);
 327                 }
 328                 if (f.isStatic()) {
 329                     env.error(f.getWhere(), "abstract.static.modifier", f);
 330                     f.subModifiers(M_STATIC);
 331                 }
 332                 if (f.isFinal()) {
 333                     env.error(f.getWhere(), "abstract.final.modifier", f);
 334                     f.subModifiers(M_FINAL);
 335                 }
 336                 if (f.isNative()) {
 337                     env.error(f.getWhere(), "abstract.native.modifier", f);
 338                     f.subModifiers(M_NATIVE);
 339                 }
 340                 if (f.isSynchronized()) {
 341                     env.error(f.getWhere(),"abstract.synchronized.modifier",f);
 342                     f.subModifiers(M_SYNCHRONIZED);
 343                 }
 344             }
 345             if (f.isAbstract() || f.isNative()) {
 346                 if (f.getValue() != null) {
 347                     env.error(f.getWhere(), "invalid.meth.body", f);
 348                     f.setValue(null);
 349                 }
 350             } else {
 351                 if (f.getValue() == null) {
 352                     if (f.isConstructor()) {
 353                         env.error(f.getWhere(), "no.constructor.body", f);
 354                     } else {
 355                         env.error(f.getWhere(), "no.meth.body", f);
 356                     }
 357                     f.addModifiers(M_ABSTRACT);
 358                 }
 359             }
 360             Vector arguments = f.getArguments();
 361             if (arguments != null) {
 362                 // arguments can be null if this is an implicit abstract method
 363                 int argumentLength = arguments.size();
 364                 Type argTypes[] = f.getType().getArgumentTypes();
 365                 for (int i = 0; i < argTypes.length; i++) {
 366                     Object arg = arguments.elementAt(i);
 367                     long where = f.getWhere();
 368                     if (arg instanceof MemberDefinition) {
 369                         where = ((MemberDefinition)arg).getWhere();
 370                         arg = ((MemberDefinition)arg).getName();
 371                     }
 372                     // (arg should be an Identifier now)
 373                     if (argTypes[i].isType(TC_VOID)
 374                         || argTypes[i].isVoidArray()) {
 375                         env.error(where, "void.argument", arg);
 376                     }
 377                 }
 378             }
 379         } else if (f.isInnerClass()) {
 380             if (f.isVolatile() ||
 381                 f.isTransient() || f.isNative() || f.isSynchronized()) {
 382                 env.error(f.getWhere(), "inner.modifier", f);
 383                 f.subModifiers(M_VOLATILE | M_TRANSIENT |
 384                                M_NATIVE | M_SYNCHRONIZED);
 385             }
 386             // same check as for fields, below:
 387             if (f.getClassDefinition().isInterface() &&
 388                   (f.isPrivate() || f.isProtected())) {
 389                 env.error(f.getWhere(), "intf.modifier.field", f);
 390                 f.subModifiers(M_PRIVATE | M_PROTECTED);
 391                 f.addModifiers(M_PUBLIC);
 392                 // Fix up the class itself to agree with
 393                 // the inner-class member.
 394                 ClassDefinition c = f.getInnerClass();
 395                 c.subModifiers(M_PRIVATE | M_PROTECTED);
 396                 c.addModifiers(M_PUBLIC);
 397             }
 398         } else {
 399             if (f.getType().isType(TC_VOID) || f.getType().isVoidArray()) {
 400                 env.error(f.getWhere(), "void.inst.var", f.getName());
 401                 // REMIND: set type to error
 402                 return;
 403             }
 404 
 405             if (f.isSynchronized() || f.isAbstract() || f.isNative()) {
 406                 env.error(f.getWhere(), "var.modifier", f);
 407                 f.subModifiers(M_SYNCHRONIZED | M_ABSTRACT | M_NATIVE);
 408             }
 409             if (f.isStrict()) {
 410                 env.error(f.getWhere(), "var.floatmodifier", f);
 411                 f.subModifiers(M_STRICTFP);
 412             }
 413             if (f.isTransient() && isInterface()) {
 414                 env.error(f.getWhere(), "transient.modifier", f);
 415                 f.subModifiers(M_TRANSIENT);
 416             }
 417             if (f.isVolatile() && (isInterface() || f.isFinal())) {
 418                 env.error(f.getWhere(), "volatile.modifier", f);
 419                 f.subModifiers(M_VOLATILE);
 420             }
 421             if (f.isFinal() && (f.getValue() == null) && isInterface()) {
 422                 env.error(f.getWhere(), "initializer.needed", f);
 423                 f.subModifiers(M_FINAL);
 424             }
 425 
 426             if (f.getClassDefinition().isInterface() &&
 427                   (f.isPrivate() || f.isProtected())) {
 428                 env.error(f.getWhere(), "intf.modifier.field", f);
 429                 f.subModifiers(M_PRIVATE | M_PROTECTED);
 430                 f.addModifiers(M_PUBLIC);
 431             }
 432         }
 433         // Do not check for repeated methods here:  Types are not yet resolved.
 434         if (!f.isInitializer()) {
 435             for (MemberDefinition f2 = getFirstMatch(f.getName());
 436                          f2 != null; f2 = f2.getNextMatch()) {
 437                 if (f.isVariable() && f2.isVariable()) {
 438                     env.error(f.getWhere(), "var.multidef", f, f2);
 439                     return;
 440                 } else if (f.isInnerClass() && f2.isInnerClass() &&
 441                            !f.getInnerClass().isLocal() &&
 442                            !f2.getInnerClass().isLocal()) {
 443                     // Found a duplicate inner-class member.
 444                     // Duplicate local classes are detected in
 445                     // 'VarDeclarationStatement.checkDeclaration'.
 446                     env.error(f.getWhere(), "inner.class.multidef", f);
 447                     return;
 448                 }
 449             }
 450         }
 451 
 452         super.addMember(env, f);
 453     }
 454 
 455     /**
 456      * Create an environment suitable for checking this class.
 457      * Make sure the source and imports are set right.
 458      * Make sure the environment contains no context information.
 459      * (Actually, throw away env altogether and use toplevelEnv instead.)
 460      */
 461     public Environment setupEnv(Environment env) {
 462         // In some cases, we go to some trouble to create the 'env' argument
 463         // that is discarded.  We should remove the 'env' argument entirely
 464         // as well as the vestigial code that supports it.  See comments on
 465         // 'newEnvironment' in 'checkInternal' below.
 466         return new Environment(toplevelEnv, this);
 467     }
 468 
 469     /**
 470      * A source class never reports deprecation, since the compiler
 471      * allows access to deprecated features that are being compiled
 472      * in the same job.
 473      */
 474     public boolean reportDeprecated(Environment env) {
 475         return false;
 476     }
 477 
 478     /**
 479      * See if the source file of this class is right.
 480      * @see ClassDefinition#noteUsedBy
 481      */
 482     public void noteUsedBy(ClassDefinition ref, long where, Environment env) {
 483         // If this class is not public, watch for cross-file references.
 484         super.noteUsedBy(ref, where, env);
 485         ClassDefinition def = this;
 486         while (def.isInnerClass()) {
 487             def = def.getOuterClass();
 488         }
 489         if (def.isPublic()) {
 490             return;             // already checked
 491         }
 492         while (ref.isInnerClass()) {
 493             ref = ref.getOuterClass();
 494         }
 495         if (def.getSource().equals(ref.getSource())) {
 496             return;             // intra-file reference
 497         }
 498         ((SourceClass)def).checkSourceFile(env, where);
 499     }
 500 
 501     /**
 502      * Check this class and all its fields.
 503      */
 504     public void check(Environment env) throws ClassNotFound {
 505         if (tracing) env.dtEnter("SourceClass.check: " + getName());
 506         if (isInsideLocal()) {
 507             // An inaccessible class gets checked when the surrounding
 508             // block is checked.
 509             // QUERY: Should this case ever occur?
 510             // What would invoke checking of a local class aside from
 511             // checking the surrounding method body?
 512             if (tracing) env.dtEvent("SourceClass.check: INSIDE LOCAL " +
 513                                      getOuterClass().getName());
 514             getOuterClass().check(env);
 515         } else {
 516             if (isInnerClass()) {
 517                 if (tracing) env.dtEvent("SourceClass.check: INNER CLASS " +
 518                                          getOuterClass().getName());
 519                 // Make sure the outer is checked first.
 520                 ((SourceClass)getOuterClass()).maybeCheck(env);
 521             }
 522             Vset vset = new Vset();
 523             Context ctx = null;
 524             if (tracing)
 525                 env.dtEvent("SourceClass.check: CHECK INTERNAL " + getName());
 526             vset = checkInternal(setupEnv(env), ctx, vset);
 527             // drop vset here
 528         }
 529         if (tracing) env.dtExit("SourceClass.check: " + getName());
 530     }
 531 
 532     private void maybeCheck(Environment env) throws ClassNotFound {
 533         if (tracing) env.dtEvent("SourceClass.maybeCheck: " + getName());
 534         // Check this class now, if it has not yet been checked.
 535         // Cf. Main.compile().  Perhaps this code belongs there somehow.
 536         ClassDeclaration c = getClassDeclaration();
 537         if (c.getStatus() == CS_PARSED) {
 538             // Set it first to avoid vicious circularity:
 539             c.setDefinition(this, CS_CHECKED);
 540             check(env);
 541         }
 542     }
 543 
 544     private Vset checkInternal(Environment env, Context ctx, Vset vset)
 545                 throws ClassNotFound {
 546         Identifier nm = getClassDeclaration().getName();
 547         if (env.verbose()) {
 548             env.output("[checking class " + nm + "]");
 549         }
 550 
 551         // Save context enclosing class for later access
 552         // by 'ClassDefinition.resolveName.'
 553         classContext = ctx;
 554 
 555         // At present, the call to 'newEnvironment' is not needed.
 556         // The incoming environment to 'basicCheck' is always passed to
 557         // 'setupEnv', which discards it completely.  This is also the
 558         // only call to 'newEnvironment', which is now apparently dead code.
 559         basicCheck(Context.newEnvironment(env, ctx));
 560 
 561         // Validate access for all inner-class components
 562         // of a qualified name, not just the last one, which
 563         // is checked below.  Yes, this is a dirty hack...
 564         // Much of this code was cribbed from 'checkSupers'.
 565         // Part of fix for 4094658.
 566         ClassDeclaration sup = getSuperClass();
 567         if (sup != null) {
 568             long where = getWhere();
 569             where = IdentifierToken.getWhere(superClassId, where);
 570             env.resolveExtendsByName(where, this, sup.getName());
 571         }
 572         for (int i = 0 ; i < interfaces.length ; i++) {
 573             ClassDeclaration intf = interfaces[i];
 574             long where = getWhere();
 575             // Error localization fails here if interfaces were
 576             // elided during error recovery from an invalid one.
 577             if (interfaceIds != null
 578                 && interfaceIds.length == interfaces.length) {
 579                 where = IdentifierToken.getWhere(interfaceIds[i], where);
 580             }
 581             env.resolveExtendsByName(where, this, intf.getName());
 582         }
 583 
 584         // Does the name already exist in an imported package?
 585         // See JLS 8.1 for the precise rules.
 586         if (!isInnerClass() && !isInsideLocal()) {
 587             // Discard package qualification for the import checks.
 588             Identifier simpleName = nm.getName();
 589             try {
 590                 // We want this to throw a ClassNotFound exception
 591                 Imports imports = toplevelEnv.getImports();
 592                 Identifier ID = imports.resolve(env, simpleName);
 593                 if (ID != getName())
 594                     env.error(where, "class.multidef.import", simpleName, ID);
 595             } catch (AmbiguousClass e) {
 596                 // At least one of e.name1 and e.name2 must be different
 597                 Identifier ID = (e.name1 != getName()) ? e.name1 : e.name2;
 598                 env.error(where, "class.multidef.import", simpleName, ID);
 599             }  catch (ClassNotFound e) {
 600                 // we want this to happen
 601             }
 602 
 603             // Make sure that no package with the same fully qualified
 604             // name exists.  This is required by JLS 7.1.  We only need
 605             // to perform this check for top level classes -- it isn't
 606             // necessary for inner classes.  (bug 4101529)
 607             //
 608             // This change has been backed out because, on WIN32, it
 609             // failed to distinguish between java.awt.event and
 610             // java.awt.Event when looking for a directory.  We will
 611             // add this back in later.
 612             //
 613             // try {
 614             //  if (env.getPackage(nm).exists()) {
 615             //      env.error(where, "class.package.conflict", nm);
 616             //  }
 617             // } catch (java.io.IOException ee) {
 618             //  env.error(where, "io.exception.package", nm);
 619             // }
 620 
 621             // Make sure it was defined in the right file
 622             if (isPublic()) {
 623                 checkSourceFile(env, getWhere());
 624             }
 625         }
 626 
 627         vset = checkMembers(env, ctx, vset);
 628         return vset;
 629     }
 630 
 631     private boolean sourceFileChecked = false;
 632 
 633     /**
 634      * See if the source file of this class is of the right name.
 635      */
 636     public void checkSourceFile(Environment env, long where) {
 637         // one error per offending class is sufficient
 638         if (sourceFileChecked)  return;
 639         sourceFileChecked = true;
 640 
 641         String fname = getName().getName() + ".java";
 642         String src = ((ClassFile)getSource()).getName();
 643         if (!src.equals(fname)) {
 644             if (isPublic()) {
 645                 env.error(where, "public.class.file", this, fname);
 646             } else {
 647                 env.error(where, "warn.package.class.file", this, src, fname);
 648             }
 649         }
 650     }
 651 
 652     // Set true if superclass (but not necessarily superinterfaces) have
 653     // been checked.  If the superclass is still unresolved, then an error
 654     // message should have been issued, and we assume that no further
 655     // resolution is possible.
 656     private boolean supersChecked = false;
 657 
 658     /**
 659      * Overrides 'ClassDefinition.getSuperClass'.
 660      */
 661 
 662     public ClassDeclaration getSuperClass(Environment env) {
 663         if (tracing) env.dtEnter("SourceClass.getSuperClass: " + this);
 664         // Superclass may fail to be set because of error recovery,
 665         // so resolve types here only if 'checkSupers' has not yet
 666         // completed its checks on the superclass.
 667         // QUERY: Can we eliminate the need to resolve superclasses on demand?
 668         // See comments in 'checkSupers' and in 'ClassDefinition.getInnerClass'.
 669         if (superClass == null && superClassId != null && !supersChecked) {
 670             resolveTypeStructure(env);
 671             // We used to report an error here if the superclass was not
 672             // resolved.  Having moved the call to 'checkSupers' from 'basicCheck'
 673             // into 'resolveTypeStructure', the errors reported here should have
 674             // already been reported.  Furthermore, error recovery can null out
 675             // the superclass, which would cause a spurious error from the test here.
 676         }
 677         if (tracing) env.dtExit("SourceClass.getSuperClass: " + this);
 678         return superClass;
 679     }
 680 
 681     /**
 682      * Check that all superclasses and superinterfaces are defined and
 683      * well formed.  Among other checks, verify that the inheritance
 684      * graph is acyclic.  Called from 'resolveTypeStructure'.
 685      */
 686 
 687     private void checkSupers(Environment env) throws ClassNotFound {
 688 
 689         // *** DEBUG ***
 690         supersCheckStarted = true;
 691 
 692         if (tracing) env.dtEnter("SourceClass.checkSupers: " + this);
 693 
 694         if (isInterface()) {
 695             if (isFinal()) {
 696                 Identifier nm = getClassDeclaration().getName();
 697                 env.error(getWhere(), "final.intf", nm);
 698                 // Interfaces have no superclass.  Superinterfaces
 699                 // are checked below, in code shared with the class case.
 700             }
 701         } else {
 702             // Check superclass.
 703             // Call to 'getSuperClass(env)' (note argument) attempts
 704             // 'resolveTypeStructure' if superclass has not successfully
 705             // been resolved.  Since we have just now called 'resolveSupers'
 706             // (see our call in 'resolveTypeStructure'), it is not clear
 707             // that this can do any good.  Why not 'getSuperClass()' here?
 708             if (getSuperClass(env) != null) {
 709                 long where = getWhere();
 710                 where = IdentifierToken.getWhere(superClassId, where);
 711                 try {
 712                     ClassDefinition def =
 713                         getSuperClass().getClassDefinition(env);
 714                     // Resolve superclass and its ancestors.
 715                     def.resolveTypeStructure(env);
 716                     // Access to the superclass should be checked relative
 717                     // to the surrounding context, not as if the reference
 718                     // appeared within the class body. Changed 'canAccess'
 719                     // to 'extendsCanAccess' to fix 4087314.
 720                     if (!extendsCanAccess(env, getSuperClass())) {
 721                         env.error(where, "cant.access.class", getSuperClass());
 722                         // Might it be a better recovery to let the access go through?
 723                         superClass = null;
 724                     } else if (def.isFinal()) {
 725                         env.error(where, "super.is.final", getSuperClass());
 726                         // Might it be a better recovery to let the access go through?
 727                         superClass = null;
 728                     } else if (def.isInterface()) {
 729                         env.error(where, "super.is.intf", getSuperClass());
 730                         superClass = null;
 731                     } else if (superClassOf(env, getSuperClass())) {
 732                         env.error(where, "cyclic.super");
 733                         superClass = null;
 734                     } else {
 735                         def.noteUsedBy(this, where, env);
 736                     }
 737                     if (superClass == null) {
 738                         def = null;
 739                     } else {
 740                         // If we have a valid superclass, check its
 741                         // supers as well, and so on up to root class.
 742                         // Call to 'enclosingClassOf' will raise
 743                         // 'NullPointerException' if 'def' is null,
 744                         // so omit this check as error recovery.
 745                         ClassDefinition sup = def;
 746                         for (;;) {
 747                             if (enclosingClassOf(sup)) {
 748                                 // Do we need a similar test for
 749                                 // interfaces?  See bugid 4038529.
 750                                 env.error(where, "super.is.inner");
 751                                 superClass = null;
 752                                 break;
 753                             }
 754                             // Since we resolved the superclass and its
 755                             // ancestors above, we should not discover
 756                             // any unresolved classes on the superclass
 757                             // chain.  It should thus be sufficient to
 758                             // call 'getSuperClass()' (no argument) here.
 759                             ClassDeclaration s = sup.getSuperClass(env);
 760                             if (s == null) {
 761                                 // Superclass not resolved due to error.
 762                                 break;
 763                             }
 764                             sup = s.getClassDefinition(env);
 765                         }
 766                     }
 767                 } catch (ClassNotFound e) {
 768                     // Error is detected in call to 'getClassDefinition'.
 769                     // The class may actually exist but be ambiguous.
 770                     // Call env.resolve(e.name) to see if it is.
 771                     // env.resolve(name) will definitely tell us if the
 772                     // class is ambiguous, but may not necessarily tell
 773                     // us if the class is not found.
 774                     // (part of solution for 4059855)
 775                 reportError: {
 776                         try {
 777                             env.resolve(e.name);
 778                         } catch (AmbiguousClass ee) {
 779                             env.error(where,
 780                                       "ambig.class", ee.name1, ee.name2);
 781                             superClass = null;
 782                             break reportError;
 783                         } catch (ClassNotFound ee) {
 784                             // fall through
 785                         }
 786                         env.error(where, "super.not.found", e.name, this);
 787                         superClass = null;
 788                     } // The break exits this block
 789                 }
 790 
 791             } else {
 792                 // Superclass was null on entry, after call to
 793                 // 'resolveSupers'.  This should normally not happen,
 794                 // as 'resolveSupers' sets 'superClass' to a non-null
 795                 // value for all named classes, except for one special
 796                 // case: 'java.lang.Object', which has no superclass.
 797                 if (isAnonymous()) {
 798                     // checker should have filled it in first
 799                     throw new CompilerError("anonymous super");
 800                 } else  if (!getName().equals(idJavaLangObject)) {
 801                     throw new CompilerError("unresolved super");
 802                 }
 803             }
 804         }
 805 
 806         // At this point, if 'superClass' is null due to an error
 807         // in the user program, a message should have been issued.
 808         supersChecked = true;
 809 
 810         // Check interfaces
 811         for (int i = 0 ; i < interfaces.length ; i++) {
 812             ClassDeclaration intf = interfaces[i];
 813             long where = getWhere();
 814             if (interfaceIds != null
 815                 && interfaceIds.length == interfaces.length) {
 816                 where = IdentifierToken.getWhere(interfaceIds[i], where);
 817             }
 818             try {
 819                 ClassDefinition def = intf.getClassDefinition(env);
 820                 // Resolve superinterface and its ancestors.
 821                 def.resolveTypeStructure(env);
 822                 // Check superinterface access in the correct context.
 823                 // Changed 'canAccess' to 'extendsCanAccess' to fix 4087314.
 824                 if (!extendsCanAccess(env, intf)) {
 825                     env.error(where, "cant.access.class", intf);
 826                 } else if (!intf.getClassDefinition(env).isInterface()) {
 827                     env.error(where, "not.intf", intf);
 828                 } else if (isInterface() && implementedBy(env, intf)) {
 829                     env.error(where, "cyclic.intf", intf);
 830                 } else {
 831                     def.noteUsedBy(this, where, env);
 832                     // Interface is OK, leave it in the interface list.
 833                     continue;
 834                 }
 835             } catch (ClassNotFound e) {
 836                 // The interface may actually exist but be ambiguous.
 837                 // Call env.resolve(e.name) to see if it is.
 838                 // env.resolve(name) will definitely tell us if the
 839                 // interface is ambiguous, but may not necessarily tell
 840                 // us if the interface is not found.
 841                 // (part of solution for 4059855)
 842             reportError2: {
 843                     try {
 844                         env.resolve(e.name);
 845                     } catch (AmbiguousClass ee) {
 846                         env.error(where,
 847                                   "ambig.class", ee.name1, ee.name2);
 848                         superClass = null;
 849                         break reportError2;
 850                     } catch (ClassNotFound ee) {
 851                         // fall through
 852                     }
 853                     env.error(where, "intf.not.found", e.name, this);
 854                     superClass = null;
 855                 } // The break exits this block
 856             }
 857             // Remove this interface from the list of interfaces
 858             // as recovery from an error.
 859             ClassDeclaration newInterfaces[] =
 860                 new ClassDeclaration[interfaces.length - 1];
 861             System.arraycopy(interfaces, 0, newInterfaces, 0, i);
 862             System.arraycopy(interfaces, i + 1, newInterfaces, i,
 863                              newInterfaces.length - i);
 864             interfaces = newInterfaces;
 865             --i;
 866         }
 867         if (tracing) env.dtExit("SourceClass.checkSupers: " + this);
 868     }
 869 
 870     /**
 871      * Check all of the members of this class.
 872      * <p>
 873      * Inner classes are checked in the following way.  Any class which
 874      * is immediately contained in a block (anonymous and local classes)
 875      * is checked along with its containing method; see the
 876      * SourceMember.check() method for more information.  Member classes
 877      * of this class are checked immediately after this class, unless this
 878      * class is insideLocal(), in which case, they are checked with the
 879      * rest of the members.
 880      */
 881     private Vset checkMembers(Environment env, Context ctx, Vset vset)
 882             throws ClassNotFound {
 883 
 884         // bail out if there were any errors
 885         if (getError()) {
 886             return vset;
 887         }
 888 
 889         // Make sure that all of our member classes have been
 890         // basicCheck'ed before we check the rest of our members.
 891         // If our member classes haven't been basicCheck'ed, then they
 892         // may not have <init> methods.  It is important that they
 893         // have <init> methods so we can process NewInstanceExpressions
 894         // correctly.  This problem didn't occur before 1.2beta1.
 895         // This is a fix for bug 4082816.
 896         for (MemberDefinition f = getFirstMember();
 897                      f != null; f = f.getNextMember()) {
 898             if (f.isInnerClass()) {
 899                 // System.out.println("Considering " + f + " in " + this);
 900                 SourceClass cdef = (SourceClass) f.getInnerClass();
 901                 if (cdef.isMember()) {
 902                     cdef.basicCheck(env);
 903                 }
 904             }
 905         }
 906 
 907         if (isFinal() && isAbstract()) {
 908             env.error(where, "final.abstract", this.getName().getName());
 909         }
 910 
 911         // This class should be abstract if there are any abstract methods
 912         // in our parent classes and interfaces which we do not override.
 913         // There are odd cases when, even though we cannot access some
 914         // abstract method from our superclass, that abstract method can
 915         // still force this class to be abstract.  See the discussion in
 916         // bug id 1240831.
 917         if (!isInterface() && !isAbstract() && mustBeAbstract(env)) {
 918             // Set the class abstract.
 919             modifiers |= M_ABSTRACT;
 920 
 921             // Tell the user which methods force this class to be abstract.
 922 
 923             // First list all of the "unimplementable" abstract methods.
 924             Iterator iter = getPermanentlyAbstractMethods();
 925             while (iter.hasNext()) {
 926                 MemberDefinition method = (MemberDefinition) iter.next();
 927                 // We couldn't override this method even if we
 928                 // wanted to.  Try to make the error message
 929                 // as non-confusing as possible.
 930                 env.error(where, "abstract.class.cannot.override",
 931                           getClassDeclaration(), method,
 932                           method.getDefiningClassDeclaration());
 933             }
 934 
 935             // Now list all of the traditional abstract methods.
 936             iter = getMethods(env);
 937             while (iter.hasNext()) {
 938                 // For each method, check if it is abstract.  If it is,
 939                 // output an appropriate error message.
 940                 MemberDefinition method = (MemberDefinition) iter.next();
 941                 if (method.isAbstract()) {
 942                     env.error(where, "abstract.class",
 943                               getClassDeclaration(), method,
 944                               method.getDefiningClassDeclaration());
 945                 }
 946             }
 947         }
 948 
 949         // Check the instance variables in a pre-pass before any constructors.
 950         // This lets constructors "in-line" any initializers directly.
 951         // It also lets us do some definite assignment checks on variables.
 952         Context ctxInit = new Context(ctx);
 953         Vset vsInst = vset.copy();
 954         Vset vsClass = vset.copy();
 955 
 956         // Do definite assignment checking on blank finals.
 957         // Other variables do not need such checks.  The simple textual
 958         // ordering constraints implemented by MemberDefinition.canReach()
 959         // are necessary and sufficient for the other variables.
 960         // Note that within non-static code, all statics are always
 961         // definitely assigned, and vice-versa.
 962         for (MemberDefinition f = getFirstMember();
 963                      f != null; f = f.getNextMember()) {
 964             if (f.isVariable() && f.isBlankFinal()) {
 965                 // The following allocates a LocalMember object as a proxy
 966                 // to represent the field.
 967                 int number = ctxInit.declareFieldNumber(f);
 968                 if (f.isStatic()) {
 969                     vsClass = vsClass.addVarUnassigned(number);
 970                     vsInst = vsInst.addVar(number);
 971                 } else {
 972                     vsInst = vsInst.addVarUnassigned(number);
 973                     vsClass = vsClass.addVar(number);
 974                 }
 975             }
 976         }
 977 
 978         // For instance variable checks, use a context with a "this" parameter.
 979         Context ctxInst = new Context(ctxInit, this);
 980         LocalMember thisArg = getThisArgument();
 981         int thisNumber = ctxInst.declare(env, thisArg);
 982         vsInst = vsInst.addVar(thisNumber);
 983 
 984         // Do all the initializers in order, checking the definite
 985         // assignment of blank finals.  Separate static from non-static.
 986         for (MemberDefinition f = getFirstMember();
 987                      f != null; f = f.getNextMember()) {
 988             try {
 989                 if (f.isVariable() || f.isInitializer()) {
 990                     if (f.isStatic()) {
 991                         vsClass = f.check(env, ctxInit, vsClass);
 992                     } else {
 993                         vsInst = f.check(env, ctxInst, vsInst);
 994                     }
 995                 }
 996             } catch (ClassNotFound ee) {
 997                 env.error(f.getWhere(), "class.not.found", ee.name, this);
 998             }
 999         }
1000 
1001         checkBlankFinals(env, ctxInit, vsClass, true);
1002 
1003         // Check the rest of the field definitions.
1004         // (Note:  Re-checking a field is a no-op.)
1005         for (MemberDefinition f = getFirstMember();
1006                      f != null; f = f.getNextMember()) {
1007             try {
1008                 if (f.isConstructor()) {
1009                     // When checking a constructor, an explicit call to
1010                     // 'this(...)' makes all blank finals definitely assigned.
1011                     // See 'MethodExpression.checkValue'.
1012                     Vset vsCon = f.check(env, ctxInit, vsInst.copy());
1013                     // May issue multiple messages for the same variable!!
1014                     checkBlankFinals(env, ctxInit, vsCon, false);
1015                     // (drop vsCon here)
1016                 } else {
1017                     Vset vsFld = f.check(env, ctx, vset.copy());
1018                     // (drop vsFld here)
1019                 }
1020             } catch (ClassNotFound ee) {
1021                 env.error(f.getWhere(), "class.not.found", ee.name, this);
1022             }
1023         }
1024 
1025         // Must mark class as checked before visiting inner classes,
1026         // as they may in turn request checking of the current class
1027         // as an outer class.  Fix for bug id 4056774.
1028         getClassDeclaration().setDefinition(this, CS_CHECKED);
1029 
1030         // Also check other classes in the same nest.
1031         // All checking of this nest must be finished before any
1032         // of its classes emit bytecode.
1033         // Otherwise, the inner classes might not have a chance to
1034         // add access or class literal fields to the outer class.
1035         for (MemberDefinition f = getFirstMember();
1036                      f != null; f = f.getNextMember()) {
1037             if (f.isInnerClass()) {
1038                 SourceClass cdef = (SourceClass) f.getInnerClass();
1039                 if (!cdef.isInsideLocal()) {
1040                     cdef.maybeCheck(env);
1041                 }
1042             }
1043         }
1044 
1045         // Note:  Since inner classes cannot set up-level variables,
1046         // the returned vset is always equal to the passed-in vset.
1047         // Still, we'll return it for the sake of regularity.
1048         return vset;
1049     }
1050 
1051     /** Make sure all my blank finals exist now. */
1052 
1053     private void checkBlankFinals(Environment env, Context ctxInit, Vset vset,
1054                                   boolean isStatic) {
1055         for (int i = 0; i < ctxInit.getVarNumber(); i++) {
1056             if (!vset.testVar(i)) {
1057                 MemberDefinition ff = ctxInit.getElement(i);
1058                 if (ff != null && ff.isBlankFinal()
1059                     && ff.isStatic() == isStatic
1060                     && ff.getClassDefinition() == this) {
1061                     env.error(ff.getWhere(),
1062                               "final.var.not.initialized", ff.getName());
1063                 }
1064             }
1065         }
1066     }
1067 
1068     /**
1069      * Check this class has its superclass and its interfaces.  Also
1070      * force it to have an <init> method (if it doesn't already have one)
1071      * and to have all the abstract methods of its parents.
1072      */
1073     private boolean basicChecking = false;
1074     private boolean basicCheckDone = false;
1075     protected void basicCheck(Environment env) throws ClassNotFound {
1076 
1077         if (tracing) env.dtEnter("SourceClass.basicCheck: " + getName());
1078 
1079         super.basicCheck(env);
1080 
1081         if (basicChecking || basicCheckDone) {
1082             if (tracing) env.dtExit("SourceClass.basicCheck: OK " + getName());
1083             return;
1084         }
1085 
1086         if (tracing) env.dtEvent("SourceClass.basicCheck: CHECKING " + getName());
1087 
1088         basicChecking = true;
1089 
1090         env = setupEnv(env);
1091 
1092         Imports imports = env.getImports();
1093         if (imports != null) {
1094             imports.resolve(env);
1095         }
1096 
1097         resolveTypeStructure(env);
1098 
1099         // Check the existence of the superclass and all interfaces.
1100         // Also responsible for breaking inheritance cycles.  This call
1101         // has been moved to 'resolveTypeStructure', just after the call
1102         // to 'resolveSupers', as inheritance cycles must be broken before
1103         // resolving types within the members.  Fixes 4073739.
1104         //   checkSupers(env);
1105 
1106         if (!isInterface()) {
1107 
1108             // Add implicit <init> method, if necessary.
1109             // QUERY:  What keeps us from adding an implicit constructor
1110             // when the user explicitly declares one?  Is it truly guaranteed
1111             // that the declaration for such an explicit constructor will have
1112             // been processed by the time we arrive here?  In general, 'basicCheck'
1113             // is called very early, prior to the normal member checking phase.
1114             if (!hasConstructor()) {
1115                 Node code = new CompoundStatement(getWhere(), new Statement[0]);
1116                 Type t = Type.tMethod(Type.tVoid);
1117 
1118                 // Default constructors inherit the access modifiers of their
1119                 // class.  For non-inner classes, this follows from JLS 8.6.7,
1120                 // as the only possible modifier is 'public'.  For the sake of
1121                 // robustness in the presence of errors, we ignore any other
1122                 // modifiers.  For inner classes, the rule needs to be extended
1123                 // in some way to account for the possibility of private and
1124                 // protected classes.  We make the 'obvious' extension, however,
1125                 // the inner classes spec is silent on this issue, and a definitive
1126                 // resolution is needed.  See bugid 4087421.
1127                 // WORKAROUND: A private constructor might need an access method,
1128                 // but it is not possible to create one due to a restriction in
1129                 // the verifier.  (This is a known problem -- see 4015397.)
1130                 // We therefore do not inherit the 'private' modifier from the class,
1131                 // allowing the default constructor to be package private.  This
1132                 // workaround can be observed via reflection, but is otherwise
1133                 // undetectable, as the constructor is always accessible within
1134                 // the class in which its containing (private) class appears.
1135                 int accessModifiers = getModifiers() &
1136                     (isInnerClass() ? (M_PUBLIC | M_PROTECTED) : M_PUBLIC);
1137                 env.makeMemberDefinition(env, getWhere(), this, null,
1138                                          accessModifiers,
1139                                          t, idInit, null, null, code);
1140             }
1141         }
1142 
1143         // Only do the inheritance/override checks if they are turned on.
1144         // The idea here is that they will be done in javac, but not
1145         // in javadoc.  See the comment for turnOffChecks(), above.
1146         if (doInheritanceChecks) {
1147 
1148             // Verify the compatibility of all inherited method definitions
1149             // by collecting all of our inheritable methods.
1150             collectInheritedMethods(env);
1151         }
1152 
1153         basicChecking = false;
1154         basicCheckDone = true;
1155         if (tracing) env.dtExit("SourceClass.basicCheck: " + getName());
1156     }
1157 
1158     /**
1159      * Add a group of methods to this class as miranda methods.
1160      *
1161      * For a definition of Miranda methods, see the comment above the
1162      * method addMirandaMethods() in the file
1163      * sun/tools/java/ClassDeclaration.java
1164      */
1165     protected void addMirandaMethods(Environment env,
1166                                      Iterator mirandas) {
1167 
1168         while(mirandas.hasNext()) {
1169             MemberDefinition method =
1170                 (MemberDefinition)mirandas.next();
1171 
1172             addMember(method);
1173 
1174             //System.out.println("adding miranda method " + newMethod +
1175             //                   " to " + this);
1176         }
1177     }
1178 
1179     /**
1180      * <em>After parsing is complete</em>, resolve all names
1181      * except those inside method bodies or initializers.
1182      * In particular, this is the point at which we find out what
1183      * kinds of variables and methods there are in the classes,
1184      * and therefore what is each class's interface to the world.
1185      * <p>
1186      * Also perform certain other transformations, such as inserting
1187      * "this$C" arguments into constructors, and reorganizing structure
1188      * to flatten qualified member names.
1189      * <p>
1190      * Do not perform type-based or name-based consistency checks
1191      * or normalizations (such as default nullary constructors),
1192      * and do not attempt to compile code against this class,
1193      * until after this phase.
1194      */
1195 
1196     private boolean resolving = false;
1197 
1198     public void resolveTypeStructure(Environment env) {
1199 
1200         if (tracing)
1201             env.dtEnter("SourceClass.resolveTypeStructure: " + getName());
1202 
1203         // Resolve immediately enclosing type, which in turn
1204         // forces resolution of all enclosing type declarations.
1205         ClassDefinition oc = getOuterClass();
1206         if (oc != null && oc instanceof SourceClass
1207             && !((SourceClass)oc).resolved) {
1208             // Do the outer class first, always.
1209             ((SourceClass)oc).resolveTypeStructure(env);
1210             // (Note:  this.resolved is probably true at this point.)
1211         }
1212 
1213         // Punt if we've already resolved this class, or are currently
1214         // in the process of doing so.
1215         if (resolved || resolving) {
1216             if (tracing)
1217                 env.dtExit("SourceClass.resolveTypeStructure: OK " + getName());
1218             return;
1219         }
1220 
1221         // Previously, 'resolved' was set here, and served to prevent
1222         // duplicate resolutions here as well as its function in
1223         // 'ClassDefinition.addMember'.  Now, 'resolving' serves the
1224         // former purpose, distinct from that of 'resolved'.
1225         resolving = true;
1226 
1227         if (tracing)
1228             env.dtEvent("SourceClass.resolveTypeStructure: RESOLVING " + getName());
1229 
1230         env = setupEnv(env);
1231 
1232         // Resolve superclass names to class declarations
1233         // for the immediate superclass and superinterfaces.
1234         resolveSupers(env);
1235 
1236         // Check all ancestor superclasses for various
1237         // errors, verifying definition of all superclasses
1238         // and superinterfaces.  Also breaks inheritance cycles.
1239         // Calls 'resolveTypeStructure' recursively for ancestors
1240         // This call used to appear in 'basicCheck', but was not
1241         // performed early enough.  Most of the compiler will barf
1242         // on inheritance cycles!
1243         try {
1244             checkSupers(env);
1245         } catch (ClassNotFound ee) {
1246             // Undefined classes should be reported by 'checkSupers'.
1247             env.error(where, "class.not.found", ee.name, this);
1248         }
1249 
1250         for (MemberDefinition
1251                  f = getFirstMember() ; f != null ; f = f.getNextMember()) {
1252             if (f instanceof SourceMember)
1253                 ((SourceMember)f).resolveTypeStructure(env);
1254         }
1255 
1256         resolving = false;
1257 
1258         // Mark class as resolved.  If new members are subsequently
1259         // added to the class, they will be resolved at that time.
1260         // See 'ClassDefinition.addMember'.  Previously, this variable was
1261         // set prior to the calls to 'checkSupers' and 'resolveTypeStructure'
1262         // (which may engender further calls to 'checkSupers').  This could
1263         // lead to duplicate resolution of implicit constructors, as the call to
1264         // 'basicCheck' from 'checkSupers' could add the constructor while
1265         // its class is marked resolved, and thus would resolve the constructor,
1266         // believing it to be a "late addition".  It would then be resolved
1267         // redundantly during the normal traversal of the members, which
1268         // immediately follows in the code above.
1269         resolved = true;
1270 
1271         // Now we have enough information to detect method repeats.
1272         for (MemberDefinition
1273                  f = getFirstMember() ; f != null ; f = f.getNextMember()) {
1274             if (f.isInitializer())  continue;
1275             if (!f.isMethod())  continue;
1276             for (MemberDefinition f2 = f; (f2 = f2.getNextMatch()) != null; ) {
1277                 if (!f2.isMethod())  continue;
1278                 if (f.getType().equals(f2.getType())) {
1279                     env.error(f.getWhere(), "meth.multidef", f);
1280                     continue;
1281                 }
1282                 if (f.getType().equalArguments(f2.getType())) {
1283                     env.error(f.getWhere(), "meth.redef.rettype", f, f2);
1284                     continue;
1285                 }
1286             }
1287         }
1288         if (tracing)
1289             env.dtExit("SourceClass.resolveTypeStructure: " + getName());
1290     }
1291 
1292     protected void resolveSupers(Environment env) {
1293         if (tracing)
1294             env.dtEnter("SourceClass.resolveSupers: " + this);
1295         // Find the super class
1296         if (superClassId != null && superClass == null) {
1297             superClass = resolveSuper(env, superClassId);
1298             // Special-case java.lang.Object here (not in the parser).
1299             // In all other cases, if we have a valid 'superClassId',
1300             // we return with a valid and non-null 'superClass' value.
1301             if (superClass == getClassDeclaration()
1302                 && getName().equals(idJavaLangObject)) {
1303                     superClass = null;
1304                     superClassId = null;
1305             }
1306         }
1307         // Find interfaces
1308         if (interfaceIds != null && interfaces == null) {
1309             interfaces = new ClassDeclaration[interfaceIds.length];
1310             for (int i = 0 ; i < interfaces.length ; i++) {
1311                 interfaces[i] = resolveSuper(env, interfaceIds[i]);
1312                 for (int j = 0; j < i; j++) {
1313                     if (interfaces[i] == interfaces[j]) {
1314                         Identifier id = interfaceIds[i].getName();
1315                         long where = interfaceIds[j].getWhere();
1316                         env.error(where, "intf.repeated", id);
1317                     }
1318                 }
1319             }
1320         }
1321         if (tracing)
1322             env.dtExit("SourceClass.resolveSupers: " + this);
1323     }
1324 
1325     private ClassDeclaration resolveSuper(Environment env, IdentifierToken t) {
1326         Identifier name = t.getName();
1327         if (tracing)
1328             env.dtEnter("SourceClass.resolveSuper: " + name);
1329         if (isInnerClass())
1330             name = outerClass.resolveName(env, name);
1331         else
1332             name = env.resolveName(name);
1333         ClassDeclaration result = env.getClassDeclaration(name);
1334         // Result is never null, as a new 'ClassDeclaration' is
1335         // created if one with the given name does not exist.
1336         if (tracing) env.dtExit("SourceClass.resolveSuper: " + name);
1337         return result;
1338     }
1339 
1340     /**
1341      * During the type-checking of an outer method body or initializer,
1342      * this routine is called to check a local class body
1343      * in the proper context.
1344      * @param   sup     the named super class or interface (if anonymous)
1345      * @param   args    the actual arguments (if anonymous)
1346      */
1347     public Vset checkLocalClass(Environment env, Context ctx, Vset vset,
1348                                 ClassDefinition sup,
1349                                 Expression args[], Type argTypes[]
1350                                 ) throws ClassNotFound {
1351         env = setupEnv(env);
1352 
1353         if ((sup != null) != isAnonymous()) {
1354             throw new CompilerError("resolveAnonymousStructure");
1355         }
1356         if (isAnonymous()) {
1357             resolveAnonymousStructure(env, sup, args, argTypes);
1358         }
1359 
1360         // Run the checks in the lexical context from the outer class.
1361         vset = checkInternal(env, ctx, vset);
1362 
1363         // This is now done by 'checkInternal' via its call to 'checkMembers'.
1364         // getClassDeclaration().setDefinition(this, CS_CHECKED);
1365 
1366         return vset;
1367     }
1368 
1369     /**
1370      * As with checkLocalClass, run the inline phase for a local class.
1371      */
1372     public void inlineLocalClass(Environment env) {
1373         for (MemberDefinition
1374                  f = getFirstMember(); f != null; f = f.getNextMember()) {
1375             if ((f.isVariable() || f.isInitializer()) && !f.isStatic()) {
1376                 continue;       // inlined inside of constructors only
1377             }
1378             try {
1379                 ((SourceMember)f).inline(env);
1380             } catch (ClassNotFound ee) {
1381                 env.error(f.getWhere(), "class.not.found", ee.name, this);
1382             }
1383         }
1384         if (getReferencesFrozen() != null && !inlinedLocalClass) {
1385             inlinedLocalClass = true;
1386             // add more constructor arguments for uplevel references
1387             for (MemberDefinition
1388                      f = getFirstMember(); f != null; f = f.getNextMember()) {
1389                 if (f.isConstructor()) {
1390                     //((SourceMember)f).addUplevelArguments(false);
1391                     ((SourceMember)f).addUplevelArguments();
1392                 }
1393             }
1394         }
1395     }
1396     private boolean inlinedLocalClass = false;
1397 
1398     /**
1399      * Check a class which is inside a local class, but is not itself local.
1400      */
1401     public Vset checkInsideClass(Environment env, Context ctx, Vset vset)
1402                 throws ClassNotFound {
1403         if (!isInsideLocal() || isLocal()) {
1404             throw new CompilerError("checkInsideClass");
1405         }
1406         return checkInternal(env, ctx, vset);
1407     }
1408 
1409     /**
1410      * Just before checking an anonymous class, decide its true
1411      * inheritance, and build its (sole, implicit) constructor.
1412      */
1413     private void resolveAnonymousStructure(Environment env,
1414                                            ClassDefinition sup,
1415                                            Expression args[], Type argTypes[]
1416                                            ) throws ClassNotFound {
1417 
1418         if (tracing) env.dtEvent("SourceClass.resolveAnonymousStructure: " +
1419                                  this + ", super " + sup);
1420 
1421         // Decide now on the superclass.
1422 
1423         // This check has been removed as part of the fix for 4055017.
1424         // In the anonymous class created to hold the 'class$' method
1425         // of an interface, 'superClassId' refers to 'java.lang.Object'.
1426         /*---------------------*
1427         if (!(superClass == null && superClassId.getName() == idNull)) {
1428             throw new CompilerError("superclass "+superClass);
1429         }
1430         *---------------------*/
1431 
1432         if (sup.isInterface()) {
1433             // allow an interface in the "super class" position
1434             int ni = (interfaces == null) ? 0 : interfaces.length;
1435             ClassDeclaration i1[] = new ClassDeclaration[1+ni];
1436             if (ni > 0) {
1437                 System.arraycopy(interfaces, 0, i1, 1, ni);
1438                 if (interfaceIds != null && interfaceIds.length == ni) {
1439                     IdentifierToken id1[] = new IdentifierToken[1+ni];
1440                     System.arraycopy(interfaceIds, 0, id1, 1, ni);
1441                     id1[0] = new IdentifierToken(sup.getName());
1442                 }
1443             }
1444             i1[0] = sup.getClassDeclaration();
1445             interfaces = i1;
1446 
1447             sup = toplevelEnv.getClassDefinition(idJavaLangObject);
1448         }
1449         superClass = sup.getClassDeclaration();
1450 
1451         if (hasConstructor()) {
1452             throw new CompilerError("anonymous constructor");
1453         }
1454 
1455         // Synthesize an appropriate constructor.
1456         Type t = Type.tMethod(Type.tVoid, argTypes);
1457         IdentifierToken names[] = new IdentifierToken[argTypes.length];
1458         for (int i = 0; i < names.length; i++) {
1459             names[i] = new IdentifierToken(args[i].getWhere(),
1460                                            Identifier.lookup("$"+i));
1461         }
1462         int outerArg = (sup.isTopLevel() || sup.isLocal()) ? 0 : 1;
1463         Expression superArgs[] = new Expression[-outerArg + args.length];
1464         for (int i = outerArg ; i < args.length ; i++) {
1465             superArgs[-outerArg + i] = new IdentifierExpression(names[i]);
1466         }
1467         long where = getWhere();
1468         Expression superExp;
1469         if (outerArg == 0) {
1470             superExp = new SuperExpression(where);
1471         } else {
1472             superExp = new SuperExpression(where,
1473                                            new IdentifierExpression(names[0]));
1474         }
1475         Expression superCall = new MethodExpression(where,
1476                                                     superExp, idInit,
1477                                                     superArgs);
1478         Statement body[] = { new ExpressionStatement(where, superCall) };
1479         Node code = new CompoundStatement(where, body);
1480         int mod = M_SYNTHETIC; // ISSUE: make M_PRIVATE, with wrapper?
1481         env.makeMemberDefinition(env, where, this, null,
1482                                 mod, t, idInit, names, null, code);
1483     }
1484 
1485     /**
1486      * Convert class modifiers to a string for diagnostic purposes.
1487      * Accepts modifiers applicable to inner classes and that appear
1488      * in the InnerClasses attribute only, as well as those that may
1489      * appear in the class modifier proper.
1490      */
1491 
1492     private static int classModifierBits[] =
1493         { ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
1494           ACC_INTERFACE, ACC_ABSTRACT, ACC_SUPER, M_ANONYMOUS, M_LOCAL,
1495           M_STRICTFP, ACC_STRICT};
1496 
1497     private static String classModifierNames[] =
1498         { "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL",
1499           "INTERFACE", "ABSTRACT", "SUPER", "ANONYMOUS", "LOCAL",
1500           "STRICTFP", "STRICT"};
1501 
1502     static String classModifierString(int mods) {
1503         String s = "";
1504         for (int i = 0; i < classModifierBits.length; i++) {
1505             if ((mods & classModifierBits[i]) != 0) {
1506                 s = s + " " + classModifierNames[i];
1507                 mods &= ~classModifierBits[i];
1508             }
1509         }
1510         if (mods != 0) {
1511             s = s + " ILLEGAL:" + Integer.toHexString(mods);
1512         }
1513         return s;
1514     }
1515 
1516     /**
1517      * Find or create an access method for a private member,
1518      * or return null if this is not possible.
1519      */
1520     public MemberDefinition getAccessMember(Environment env, Context ctx,
1521                                           MemberDefinition field, boolean isSuper) {
1522         return getAccessMember(env, ctx, field, false, isSuper);
1523     }
1524 
1525     public MemberDefinition getUpdateMember(Environment env, Context ctx,
1526                                           MemberDefinition field, boolean isSuper) {
1527         if (!field.isVariable()) {
1528             throw new CompilerError("method");
1529         }
1530         return getAccessMember(env, ctx, field, true, isSuper);
1531     }
1532 
1533     private MemberDefinition getAccessMember(Environment env, Context ctx,
1534                                              MemberDefinition field,
1535                                              boolean isUpdate,
1536                                              boolean isSuper) {
1537 
1538         // The 'isSuper' argument is really only meaningful when the
1539         // target member is a method, in which case an 'invokespecial'
1540         // is needed.  For fields, 'getfield' and 'putfield' instructions
1541         // are generated in either case, and 'isSuper' currently plays
1542         // no essential role.  Nonetheless, we maintain the distinction
1543         // consistently for the time being.
1544 
1545         boolean isStatic = field.isStatic();
1546         boolean isMethod = field.isMethod();
1547 
1548         // Find pre-existing access method.
1549         // In the case of a field access method, we only look for the getter.
1550         // A getter is always created whenever a setter is.
1551         // QUERY: Why doesn't the 'MemberDefinition' object for the field
1552         // itself just have fields for its getter and setter?
1553         MemberDefinition af;
1554         for (af = getFirstMember(); af != null; af = af.getNextMember()) {
1555             if (af.getAccessMethodTarget() == field) {
1556                 if (isMethod && af.isSuperAccessMethod() == isSuper) {
1557                     break;
1558                 }
1559                 // Distinguish the getter and the setter by the number of
1560                 // arguments.
1561                 int nargs = af.getType().getArgumentTypes().length;
1562                 // This was (nargs == (isStatic ? 0 : 1) + (isUpdate ? 1 : 0))
1563                 // in order to find a setter as well as a getter.  This caused
1564                 // allocation of multiple getters.
1565                 if (nargs == (isStatic ? 0 : 1)) {
1566                     break;
1567                 }
1568             }
1569         }
1570 
1571         if (af != null) {
1572             if (!isUpdate) {
1573                 return af;
1574             } else {
1575                 MemberDefinition uf = af.getAccessUpdateMember();
1576                 if (uf != null) {
1577                     return uf;
1578                 }
1579             }
1580         } else if (isUpdate) {
1581             // must find or create the getter before creating the setter
1582             af = getAccessMember(env, ctx, field, false, isSuper);
1583         }
1584 
1585         // If we arrive here, we are creating a new access member.
1586 
1587         Identifier anm;
1588         Type dummyType = null;
1589 
1590         if (field.isConstructor()) {
1591             // For a constructor, we use the same name as for all
1592             // constructors ("<init>"), but add a distinguishing
1593             // argument of an otherwise unused "dummy" type.
1594             anm = idInit;
1595             // Get the dummy class, creating it if necessary.
1596             SourceClass outerMostClass = (SourceClass)getTopClass();
1597             dummyType = outerMostClass.dummyArgumentType;
1598             if (dummyType == null) {
1599                 // Create dummy class.
1600                 IdentifierToken sup =
1601                     new IdentifierToken(0, idJavaLangObject);
1602                 IdentifierToken interfaces[] = {};
1603                 IdentifierToken t = new IdentifierToken(0, idNull);
1604                 int mod = M_ANONYMOUS | M_STATIC | M_SYNTHETIC;
1605                 // If an interface has a public inner class, the dummy class for
1606                 // the constructor must always be accessible. Fix for 4221648.
1607                 if (outerMostClass.isInterface()) {
1608                     mod |= M_PUBLIC;
1609                 }
1610                 ClassDefinition dummyClass =
1611                     toplevelEnv.makeClassDefinition(toplevelEnv,
1612                                                     0, t, null, mod,
1613                                                     sup, interfaces,
1614                                                     outerMostClass);
1615                 // Check the class.
1616                 // It is likely that a full check is not really necessary,
1617                 // but it is essential that the class be marked as parsed.
1618                 dummyClass.getClassDeclaration().setDefinition(dummyClass, CS_PARSED);
1619                 Expression argsX[] = {};
1620                 Type argTypesX[] = {};
1621                 try {
1622                     ClassDefinition supcls =
1623                         toplevelEnv.getClassDefinition(idJavaLangObject);
1624                     dummyClass.checkLocalClass(toplevelEnv, null,
1625                                                new Vset(), supcls, argsX, argTypesX);
1626                 } catch (ClassNotFound ee) {};
1627                 // Get class type.
1628                 dummyType = dummyClass.getType();
1629                 outerMostClass.dummyArgumentType = dummyType;
1630             }
1631         } else {
1632             // Otherwise, we use the name "access$N", for the
1633             // smallest value of N >= 0 yielding an unused name.
1634             for (int i = 0; ; i++) {
1635                 anm = Identifier.lookup(prefixAccess + i);
1636                 if (getFirstMatch(anm) == null) {
1637                     break;
1638                 }
1639             }
1640         }
1641 
1642         Type argTypes[];
1643         Type t = field.getType();
1644 
1645         if (isStatic) {
1646             if (!isMethod) {
1647                 if (!isUpdate) {
1648                     Type at[] = { };
1649                     argTypes = at;
1650                     t = Type.tMethod(t); // nullary getter
1651                 } else {
1652                     Type at[] = { t };
1653                     argTypes = at;
1654                     t = Type.tMethod(Type.tVoid, argTypes); // unary setter
1655                 }
1656             } else {
1657                 // Since constructors are never static, we don't
1658                 // have to worry about a dummy argument here.
1659                 argTypes = t.getArgumentTypes();
1660             }
1661         } else {
1662             // All access methods for non-static members get an explicit
1663             // 'this' pointer as an extra argument, as the access methods
1664             // themselves must be static. EXCEPTION: Access methods for
1665             // constructors are non-static.
1666             Type classType = this.getType();
1667             if (!isMethod) {
1668                 if (!isUpdate) {
1669                     Type at[] = { classType };
1670                     argTypes = at;
1671                     t = Type.tMethod(t, argTypes); // nullary getter
1672                 } else {
1673                     Type at[] = { classType, t };
1674                     argTypes = at;
1675                     t = Type.tMethod(Type.tVoid, argTypes); // unary setter
1676                 }
1677             } else {
1678                 // Target is a method, possibly a constructor.
1679                 Type at[] = t.getArgumentTypes();
1680                 int nargs = at.length;
1681                 if (field.isConstructor()) {
1682                     // Access method is a constructor.
1683                     // Requires a dummy argument.
1684                     MemberDefinition outerThisArg =
1685                         ((SourceMember)field).getOuterThisArg();
1686                     if (outerThisArg != null) {
1687                         // Outer instance link must be the first argument.
1688                         // The following is a sanity check that will catch
1689                         // most cases in which in this requirement is violated.
1690                         if (at[0] != outerThisArg.getType()) {
1691                             throw new CompilerError("misplaced outer this");
1692                         }
1693                         // Strip outer 'this' argument.
1694                         // It will be added back when the access method is checked.
1695                         argTypes = new Type[nargs];
1696                         argTypes[0] = dummyType;
1697                         for (int i = 1; i < nargs; i++) {
1698                             argTypes[i] = at[i];
1699                         }
1700                     } else {
1701                         // There is no outer instance.
1702                         argTypes = new Type[nargs+1];
1703                         argTypes[0] = dummyType;
1704                         for (int i = 0; i < nargs; i++) {
1705                             argTypes[i+1] = at[i];
1706                         }
1707                     }
1708                 } else {
1709                     // Access method is static.
1710                     // Requires an explicit 'this' argument.
1711                     argTypes = new Type[nargs+1];
1712                     argTypes[0] = classType;
1713                     for (int i = 0; i < nargs; i++) {
1714                         argTypes[i+1] = at[i];
1715                     }
1716                 }
1717                 t = Type.tMethod(t.getReturnType(), argTypes);
1718             }
1719         }
1720 
1721         int nlen = argTypes.length;
1722         long where = field.getWhere();
1723         IdentifierToken names[] = new IdentifierToken[nlen];
1724         for (int i = 0; i < nlen; i++) {
1725             names[i] = new IdentifierToken(where, Identifier.lookup("$"+i));
1726         }
1727 
1728         Expression access = null;
1729         Expression thisArg = null;
1730         Expression args[] = null;
1731 
1732         if (isStatic) {
1733             args = new Expression[nlen];
1734             for (int i = 0 ; i < nlen ; i++) {
1735                 args[i] = new IdentifierExpression(names[i]);
1736             }
1737         } else {
1738             if (field.isConstructor()) {
1739                 // Constructor access method is non-static, so
1740                 // 'this' works normally.
1741                 thisArg = new ThisExpression(where);
1742                 // Remove dummy argument, as it is not
1743                 // passed to the target method.
1744                 args = new Expression[nlen-1];
1745                 for (int i = 1 ; i < nlen ; i++) {
1746                     args[i-1] = new IdentifierExpression(names[i]);
1747                 }
1748             } else {
1749                 // Non-constructor access method is static, so
1750                 // we use the first argument as 'this'.
1751                 thisArg = new IdentifierExpression(names[0]);
1752                 // Remove first argument.
1753                 args = new Expression[nlen-1];
1754                 for (int i = 1 ; i < nlen ; i++) {
1755                     args[i-1] = new IdentifierExpression(names[i]);
1756                 }
1757             }
1758             access = thisArg;
1759         }
1760 
1761         if (!isMethod) {
1762             access = new FieldExpression(where, access, field);
1763             if (isUpdate) {
1764                 access = new AssignExpression(where, access, args[0]);
1765             }
1766         } else {
1767             // If true, 'isSuper' forces a non-virtual call.
1768             access = new MethodExpression(where, access, field, args, isSuper);
1769         }
1770 
1771         Statement code;
1772         if (t.getReturnType().isType(TC_VOID)) {
1773             code = new ExpressionStatement(where, access);
1774         } else {
1775             code = new ReturnStatement(where, access);
1776         }
1777         Statement body[] = { code };
1778         code = new CompoundStatement(where, body);
1779 
1780         // Access methods are now static (constructors excepted), and no longer final.
1781         // This change was mandated by the interaction of the access method
1782         // naming conventions and the restriction against overriding final
1783         // methods.
1784         int mod = M_SYNTHETIC;
1785         if (!field.isConstructor()) {
1786             mod |= M_STATIC;
1787         }
1788 
1789         // Create the synthetic method within the class in which the referenced
1790         // private member appears.  The 'env' argument to 'makeMemberDefinition'
1791         // is suspect because it represents the environment at the point at
1792         // which a reference takes place, while it should represent the
1793         // environment in which the definition of the synthetic method appears.
1794         // We get away with this because 'env' is used only to access globals
1795         // such as 'Environment.error', and also as an argument to
1796         // 'resolveTypeStructure', which immediately discards it using
1797         // 'setupEnv'. Apparently, the current definition of 'setupEnv'
1798         // represents a design change that has not been thoroughly propagated.
1799         // An access method is declared with same list of exceptions as its
1800         // target. As the exceptions are simply listed by name, the correctness
1801         // of this approach requires that the access method be checked
1802         // (name-resolved) in the same context as its target method  This
1803         // should always be the case.
1804         SourceMember newf = (SourceMember)
1805             env.makeMemberDefinition(env, where, this,
1806                                      null, mod, t, anm, names,
1807                                      field.getExceptionIds(), code);
1808         // Just to be safe, copy over the name-resolved exceptions from the
1809         // target so that the context in which the access method is checked
1810         // doesn't matter.
1811         newf.setExceptions(field.getExceptions(env));
1812 
1813         newf.setAccessMethodTarget(field);
1814         if (isUpdate) {
1815             af.setAccessUpdateMember(newf);
1816         }
1817         newf.setIsSuperAccessMethod(isSuper);
1818 
1819         // The call to 'check' is not needed, as the access method will be
1820         // checked by the containing class after it is added.  This is the
1821         // idiom followed in the implementation of class literals. (See
1822         // 'FieldExpression.java'.) In any case, the context is wrong in the
1823         // call below.  The access method must be checked in the context in
1824         // which it is declared, i.e., the class containing the referenced
1825         // private member, not the (inner) class in which the original member
1826         // reference occurs.
1827         //
1828         // try {
1829         //     newf.check(env, ctx, new Vset());
1830         // } catch (ClassNotFound ee) {
1831         //     env.error(where, "class.not.found", ee.name, this);
1832         // }
1833 
1834         // The comment above is inaccurate.  While it is often the case
1835         // that the containing class will check the access method, this is
1836         // by no means guaranteed.  In fact, an access method may be added
1837         // after the checking of its class is complete.  In this case, however,
1838         // the context in which the class was checked will have been saved in
1839         // the class definition object (by the fix for 4095716), allowing us
1840         // to check the field now, and in the correct context.
1841         // This fixes bug 4098093.
1842 
1843         Context checkContext = newf.getClassDefinition().getClassContext();
1844         if (checkContext != null) {
1845             //System.out.println("checking late addition: " + this);
1846             try {
1847                 newf.check(env, checkContext, new Vset());
1848             } catch (ClassNotFound ee) {
1849                 env.error(where, "class.not.found", ee.name, this);
1850             }
1851         }
1852 
1853 
1854         //System.out.println("[Access member '" +
1855         //                      newf + "' created for field '" +
1856         //                      field +"' in class '" + this + "']");
1857 
1858         return newf;
1859     }
1860 
1861     /**
1862      * Find an inner class of 'this', chosen arbitrarily.
1863      * Result is always an actual class, never an interface.
1864      * Returns null if none found.
1865      */
1866     SourceClass findLookupContext() {
1867         // Look for an immediate inner class.
1868         for (MemberDefinition f = getFirstMember();
1869              f != null;
1870              f = f.getNextMember()) {
1871             if (f.isInnerClass()) {
1872                 SourceClass ic = (SourceClass)f.getInnerClass();
1873                 if (!ic.isInterface()) {
1874                     return ic;
1875                 }
1876             }
1877         }
1878         // Look for a class nested within an immediate inner interface.
1879         // At this point, we have given up on finding a minimally-nested
1880         // class (which would require a breadth-first traversal).  It doesn't
1881         // really matter which inner class we find.
1882         for (MemberDefinition f = getFirstMember();
1883              f != null;
1884              f = f.getNextMember()) {
1885             if (f.isInnerClass()) {
1886                 SourceClass lc =
1887                     ((SourceClass)f.getInnerClass()).findLookupContext();
1888                 if (lc != null) {
1889                     return lc;
1890                 }
1891             }
1892         }
1893         // No inner classes.
1894         return null;
1895     }
1896 
1897     private MemberDefinition lookup = null;
1898 
1899     /**
1900      * Get helper method for class literal lookup.
1901      */
1902     public MemberDefinition getClassLiteralLookup(long fwhere) {
1903 
1904         // If we have already created a lookup method, reuse it.
1905         if (lookup != null) {
1906             return lookup;
1907         }
1908 
1909         // If the current class is a nested class, make sure we put the
1910         // lookup method in the outermost class.  Set 'lookup' for the
1911         // intervening inner classes so we won't have to do the search
1912         // again.
1913         if (outerClass != null) {
1914             lookup = outerClass.getClassLiteralLookup(fwhere);
1915             return lookup;
1916         }
1917 
1918         // If we arrive here, there was no existing 'class$' method.
1919 
1920         ClassDefinition c = this;
1921         boolean needNewClass = false;
1922 
1923         if (isInterface()) {
1924             // The top-level type is an interface.  Try to find an existing
1925             // inner class in which to create the helper method.  Any will do.
1926             c = findLookupContext();
1927             if (c == null) {
1928                 // The interface has no inner classes.  Create an anonymous
1929                 // inner class to hold the helper method, as an interface must
1930                 // not have any methods.  The tests above for prior creation
1931                 // of a 'class$' method assure that only one such class is
1932                 // allocated for each outermost class containing a class
1933                 // literal embedded somewhere within.  Part of fix for 4055017.
1934                 needNewClass = true;
1935                 IdentifierToken sup =
1936                     new IdentifierToken(fwhere, idJavaLangObject);
1937                 IdentifierToken interfaces[] = {};
1938                 IdentifierToken t = new IdentifierToken(fwhere, idNull);
1939                 int mod = M_PUBLIC | M_ANONYMOUS | M_STATIC | M_SYNTHETIC;
1940                 c = (SourceClass)
1941                     toplevelEnv.makeClassDefinition(toplevelEnv,
1942                                                     fwhere, t, null, mod,
1943                                                     sup, interfaces, this);
1944             }
1945         }
1946 
1947 
1948         // The name of the class-getter stub is "class$"
1949         Identifier idDClass = Identifier.lookup(prefixClass);
1950         Type strarg[] = { Type.tString };
1951 
1952         // Some sanity checks of questionable value.
1953         //
1954         // This check became useless after matchMethod() was modified
1955         // to not return synthetic methods.
1956         //
1957         //try {
1958         //    lookup = c.matchMethod(toplevelEnv, c, idDClass, strarg);
1959         //} catch (ClassNotFound ee) {
1960         //    throw new CompilerError("unexpected missing class");
1961         //} catch (AmbiguousMember ee) {
1962         //    throw new CompilerError("synthetic name clash");
1963         //}
1964         //if (lookup != null && lookup.getClassDefinition() == c) {
1965         //    // Error if method found was not inherited.
1966         //    throw new CompilerError("unexpected duplicate");
1967         //}
1968         // Some sanity checks of questionable value.
1969 
1970         /*  // The helper function looks like this.
1971          *  // It simply maps a checked exception to an unchecked one.
1972          *  static Class class$(String class$) {
1973          *    try { return Class.forName(class$); }
1974          *    catch (ClassNotFoundException forName) {
1975          *      throw new NoClassDefFoundError(forName.getMessage());
1976          *    }
1977          *  }
1978          */
1979         long w = c.getWhere();
1980         IdentifierToken arg = new IdentifierToken(w, idDClass);
1981         Expression e = new IdentifierExpression(arg);
1982         Expression a1[] = { e };
1983         Identifier idForName = Identifier.lookup("forName");
1984         e = new MethodExpression(w, new TypeExpression(w, Type.tClassDesc),
1985                                  idForName, a1);
1986         Statement body = new ReturnStatement(w, e);
1987         // map the exceptions
1988         Identifier idClassNotFound =
1989             Identifier.lookup("java.lang.ClassNotFoundException");
1990         Identifier idNoClassDefFound =
1991             Identifier.lookup("java.lang.NoClassDefFoundError");
1992         Type ctyp = Type.tClass(idClassNotFound);
1993         Type exptyp = Type.tClass(idNoClassDefFound);
1994         Identifier idGetMessage = Identifier.lookup("getMessage");
1995         e = new IdentifierExpression(w, idForName);
1996         e = new MethodExpression(w, e, idGetMessage, new Expression[0]);
1997         Expression a2[] = { e };
1998         e = new NewInstanceExpression(w, new TypeExpression(w, exptyp), a2);
1999         Statement handler = new CatchStatement(w, new TypeExpression(w, ctyp),
2000                                                new IdentifierToken(idForName),
2001                                                new ThrowStatement(w, e));
2002         Statement handlers[] = { handler };
2003         body = new TryStatement(w, body, handlers);
2004 
2005         Type mtype = Type.tMethod(Type.tClassDesc, strarg);
2006         IdentifierToken args[] = { arg };
2007 
2008         // Use default (package) access.  If private, an access method would
2009         // be needed in the event that the class literal belonged to an interface.
2010         // Also, making it private tickles bug 4098316.
2011         lookup = toplevelEnv.makeMemberDefinition(toplevelEnv, w,
2012                                                   c, null,
2013                                                   M_STATIC | M_SYNTHETIC,
2014                                                   mtype, idDClass,
2015                                                   args, null, body);
2016 
2017         // If a new class was created to contain the helper method,
2018         // check it now.
2019         if (needNewClass) {
2020             if (c.getClassDeclaration().getStatus() == CS_CHECKED) {
2021                 throw new CompilerError("duplicate check");
2022             }
2023             c.getClassDeclaration().setDefinition(c, CS_PARSED);
2024             Expression argsX[] = {};
2025             Type argTypesX[] = {};
2026             try {
2027                 ClassDefinition sup =
2028                     toplevelEnv.getClassDefinition(idJavaLangObject);
2029                 c.checkLocalClass(toplevelEnv, null,
2030                                   new Vset(), sup, argsX, argTypesX);
2031             } catch (ClassNotFound ee) {};
2032         }
2033 
2034         return lookup;
2035     }
2036 
2037 
2038     /**
2039      * A list of active ongoing compilations. This list
2040      * is used to stop two compilations from saving the
2041      * same class.
2042      */
2043     private static Vector active = new Vector();
2044 
2045     /**
2046      * Compile this class
2047      */
2048     public void compile(OutputStream out)
2049                 throws InterruptedException, IOException {
2050         Environment env = toplevelEnv;
2051         synchronized (active) {
2052             while (active.contains(getName())) {
2053                 active.wait();
2054             }
2055             active.addElement(getName());
2056         }
2057 
2058         try {
2059             compileClass(env, out);
2060         } catch (ClassNotFound e) {
2061             throw new CompilerError(e);
2062         } finally {
2063             synchronized (active) {
2064                 active.removeElement(getName());
2065                 active.notifyAll();
2066             }
2067         }
2068     }
2069 
2070     /**
2071      * Verify that the modifier bits included in 'required' are
2072      * all present in 'mods', otherwise signal an internal error.
2073      * Note that errors in the source program may corrupt the modifiers,
2074      * thus we rely on the fact that 'CompilerError' exceptions are
2075      * silently ignored after an error message has been issued.
2076      */
2077     private static void assertModifiers(int mods, int required) {
2078         if ((mods & required) != required) {
2079             throw new CompilerError("illegal class modifiers");
2080         }
2081     }
2082 
2083     protected void compileClass(Environment env, OutputStream out)
2084                 throws IOException, ClassNotFound {
2085         Vector variables = new Vector();
2086         Vector methods = new Vector();
2087         Vector innerClasses = new Vector();
2088         CompilerMember init = new CompilerMember(new MemberDefinition(getWhere(), this, M_STATIC, Type.tMethod(Type.tVoid), idClassInit, null, null), new Assembler());
2089         Context ctx = new Context((Context)null, init.field);
2090 
2091         for (ClassDefinition def = this; def.isInnerClass(); def = def.getOuterClass()) {
2092             innerClasses.addElement(def);
2093         }
2094         // Reverse the order, so that outer levels come first:
2095         int ncsize = innerClasses.size();
2096         for (int i = ncsize; --i >= 0; )
2097             innerClasses.addElement(innerClasses.elementAt(i));
2098         for (int i = ncsize; --i >= 0; )
2099             innerClasses.removeElementAt(i);
2100 
2101         // System.out.println("compile class " + getName());
2102 
2103         boolean haveDeprecated = this.isDeprecated();
2104         boolean haveSynthetic = this.isSynthetic();
2105         boolean haveConstantValue = false;
2106         boolean haveExceptions = false;
2107 
2108         // Generate code for all fields
2109         for (SourceMember field = (SourceMember)getFirstMember();
2110              field != null;
2111              field = (SourceMember)field.getNextMember()) {
2112 
2113             //System.out.println("compile field " + field.getName());
2114 
2115             haveDeprecated |= field.isDeprecated();
2116             haveSynthetic |= field.isSynthetic();
2117 
2118             try {
2119                 if (field.isMethod()) {
2120                     haveExceptions |=
2121                         (field.getExceptions(env).length > 0);
2122 
2123                     if (field.isInitializer()) {
2124                         if (field.isStatic()) {
2125                             field.code(env, init.asm);
2126                         }
2127                     } else {
2128                         CompilerMember f =
2129                             new CompilerMember(field, new Assembler());
2130                         field.code(env, f.asm);
2131                         methods.addElement(f);
2132                     }
2133                 } else if (field.isInnerClass()) {
2134                     innerClasses.addElement(field.getInnerClass());
2135                 } else if (field.isVariable()) {
2136                     field.inline(env);
2137                     CompilerMember f = new CompilerMember(field, null);
2138                     variables.addElement(f);
2139                     if (field.isStatic()) {
2140                         field.codeInit(env, ctx, init.asm);
2141 
2142                     }
2143                     haveConstantValue |=
2144                         (field.getInitialValue() != null);
2145                 }
2146             } catch (CompilerError ee) {
2147                 ee.printStackTrace();
2148                 env.error(field, 0, "generic",
2149                           field.getClassDeclaration() + ":" + field +
2150                           "@" + ee.toString(), null, null);
2151             }
2152         }
2153         if (!init.asm.empty()) {
2154            init.asm.add(getWhere(), opc_return, true);
2155             methods.addElement(init);
2156         }
2157 
2158         // bail out if there were any errors
2159         if (getNestError()) {
2160             return;
2161         }
2162 
2163         int nClassAttrs = 0;
2164 
2165         // Insert constants
2166         if (methods.size() > 0) {
2167             tab.put("Code");
2168         }
2169         if (haveConstantValue) {
2170             tab.put("ConstantValue");
2171         }
2172 
2173         String sourceFile = null;
2174         if (env.debug_source()) {
2175             sourceFile = ((ClassFile)getSource()).getName();
2176             tab.put("SourceFile");
2177             tab.put(sourceFile);
2178             nClassAttrs += 1;
2179         }
2180 
2181         if (haveExceptions) {
2182             tab.put("Exceptions");
2183         }
2184 
2185         if (env.debug_lines()) {
2186             tab.put("LineNumberTable");
2187         }
2188         if (haveDeprecated) {
2189             tab.put("Deprecated");
2190             if (this.isDeprecated()) {
2191                 nClassAttrs += 1;
2192             }
2193         }
2194         if (haveSynthetic) {
2195             tab.put("Synthetic");
2196             if (this.isSynthetic()) {
2197                 nClassAttrs += 1;
2198             }
2199         }
2200 // JCOV
2201         if (env.coverage()) {
2202             nClassAttrs += 2;           // AbsoluteSourcePath, TimeStamp
2203             tab.put("AbsoluteSourcePath");
2204             tab.put("TimeStamp");
2205             tab.put("CoverageTable");
2206         }
2207 // end JCOV
2208         if (env.debug_vars()) {
2209             tab.put("LocalVariableTable");
2210         }
2211         if (innerClasses.size() > 0) {
2212             tab.put("InnerClasses");
2213             nClassAttrs += 1;           // InnerClasses
2214         }
2215 
2216 // JCOV
2217         String absoluteSourcePath = "";
2218         long timeStamp = 0;
2219 
2220         if (env.coverage()) {
2221                 absoluteSourcePath = getAbsoluteName();
2222                 timeStamp = System.currentTimeMillis();
2223                 tab.put(absoluteSourcePath);
2224         }
2225 // end JCOV
2226         tab.put(getClassDeclaration());
2227         if (getSuperClass() != null) {
2228             tab.put(getSuperClass());
2229         }
2230         for (int i = 0 ; i < interfaces.length ; i++) {
2231             tab.put(interfaces[i]);
2232         }
2233 
2234         // Sort the methods in order to make sure both constant pool
2235         // entries and methods are in a deterministic order from run
2236         // to run (this allows comparing class files for a fixed point
2237         // to validate the compiler)
2238         CompilerMember[] ordered_methods =
2239             new CompilerMember[methods.size()];
2240         methods.copyInto(ordered_methods);
2241         java.util.Arrays.sort(ordered_methods);
2242         for (int i=0; i<methods.size(); i++)
2243             methods.setElementAt(ordered_methods[i], i);
2244 
2245         // Optimize Code and Collect method constants
2246         for (Enumeration e = methods.elements() ; e.hasMoreElements() ; ) {
2247             CompilerMember f = (CompilerMember)e.nextElement();
2248             try {
2249                 f.asm.optimize(env);
2250                 f.asm.collect(env, f.field, tab);
2251                 tab.put(f.name);
2252                 tab.put(f.sig);
2253                 ClassDeclaration exp[] = f.field.getExceptions(env);
2254                 for (int i = 0 ; i < exp.length ; i++) {
2255                     tab.put(exp[i]);
2256                 }
2257             } catch (Exception ee) {
2258                 ee.printStackTrace();
2259                 env.error(f.field, -1, "generic", f.field.getName() + "@" + ee.toString(), null, null);
2260                 f.asm.listing(System.out);
2261             }
2262         }
2263 
2264         // Collect field constants
2265         for (Enumeration e = variables.elements() ; e.hasMoreElements() ; ) {
2266             CompilerMember f = (CompilerMember)e.nextElement();
2267             tab.put(f.name);
2268             tab.put(f.sig);
2269 
2270             Object val = f.field.getInitialValue();
2271             if (val != null) {
2272                 tab.put((val instanceof String) ? new StringExpression(f.field.getWhere(), (String)val) : val);
2273             }
2274         }
2275 
2276         // Collect inner class constants
2277         for (Enumeration e = innerClasses.elements();
2278              e.hasMoreElements() ; ) {
2279             ClassDefinition inner = (ClassDefinition)e.nextElement();
2280             tab.put(inner.getClassDeclaration());
2281 
2282             // If the inner class is local, we do not need to add its
2283             // outer class here -- the outer_class_info_index is zero.
2284             if (!inner.isLocal()) {
2285                 ClassDefinition outer = inner.getOuterClass();
2286                 tab.put(outer.getClassDeclaration());
2287             }
2288 
2289             // If the local name of the class is idNull, don't bother to
2290             // add it to the constant pool.  We won't need it.
2291             Identifier inner_local_name = inner.getLocalName();
2292             if (inner_local_name != idNull) {
2293                 tab.put(inner_local_name.toString());
2294             }
2295         }
2296 
2297         // Write header
2298         DataOutputStream data = new DataOutputStream(out);
2299         data.writeInt(JAVA_MAGIC);
2300         data.writeShort(toplevelEnv.getMinorVersion());
2301         data.writeShort(toplevelEnv.getMajorVersion());
2302         tab.write(env, data);
2303 
2304         // Write class information
2305         int cmods = getModifiers() & MM_CLASS;
2306 
2307         // Certain modifiers are implied:
2308         // 1.  Any interface (nested or not) is implicitly deemed to be abstract,
2309         //     whether it is explicitly marked so or not.  (Java 1.0.)
2310         // 2.  A interface which is a member of a type is implicitly deemed to
2311         //     be static, whether it is explicitly marked so or not.
2312         // 3a. A type which is a member of an interface is implicitly deemed
2313         //     to be public, whether it is explicitly marked so or not.
2314         // 3b. A type which is a member of an interface is implicitly deemed
2315         //     to be static, whether it is explicitly marked so or not.
2316         // All of these rules are implemented in 'BatchParser.beginClass',
2317         // but the results are verified here.
2318 
2319         if (isInterface()) {
2320             // Rule 1.
2321             // The VM spec states that ACC_ABSTRACT must be set when
2322             // ACC_INTERFACE is; this was not done by javac prior to 1.2,
2323             // and the runtime compensates by setting it.  Making sure
2324             // it is set here will allow the runtime hack to eventually
2325             // be removed. Rule 2 doesn't apply to transformed modifiers.
2326             assertModifiers(cmods, ACC_ABSTRACT);
2327         } else {
2328             // Contrary to the JVM spec, we only set ACC_SUPER for classes,
2329             // not interfaces.  This is a workaround for a bug in IE3.0,
2330             // which refuses interfaces with ACC_SUPER on.
2331             cmods |= ACC_SUPER;
2332         }
2333 
2334         // If this is a nested class, transform access modifiers.
2335         if (outerClass != null) {
2336             // If private, transform to default (package) access.
2337             // If protected, transform to public.
2338             // M_PRIVATE and M_PROTECTED are already masked off by MM_CLASS above.
2339             // cmods &= ~(M_PRIVATE | M_PROTECTED);
2340             if (isProtected()) cmods |= M_PUBLIC;
2341             // Rule 3a.  Note that Rule 3b doesn't apply to transformed modifiers.
2342             if (outerClass.isInterface()) {
2343                 assertModifiers(cmods, M_PUBLIC);
2344             }
2345         }
2346 
2347         data.writeShort(cmods);
2348 
2349         if (env.dumpModifiers()) {
2350             Identifier cn = getName();
2351             Identifier nm =
2352                 Identifier.lookup(cn.getQualifier(), cn.getFlatName());
2353             System.out.println();
2354             System.out.println("CLASSFILE  " + nm);
2355             System.out.println("---" + classModifierString(cmods));
2356         }
2357 
2358         data.writeShort(tab.index(getClassDeclaration()));
2359         data.writeShort((getSuperClass() != null) ? tab.index(getSuperClass()) : 0);
2360         data.writeShort(interfaces.length);
2361         for (int i = 0 ; i < interfaces.length ; i++) {
2362             data.writeShort(tab.index(interfaces[i]));
2363         }
2364 
2365         // write variables
2366         ByteArrayOutputStream buf = new ByteArrayOutputStream(256);
2367         ByteArrayOutputStream attbuf = new ByteArrayOutputStream(256);
2368         DataOutputStream databuf = new DataOutputStream(buf);
2369 
2370         data.writeShort(variables.size());
2371         for (Enumeration e = variables.elements() ; e.hasMoreElements() ; ) {
2372             CompilerMember f = (CompilerMember)e.nextElement();
2373             Object val = f.field.getInitialValue();
2374 
2375             data.writeShort(f.field.getModifiers() & MM_FIELD);
2376             data.writeShort(tab.index(f.name));
2377             data.writeShort(tab.index(f.sig));
2378 
2379             int fieldAtts = (val != null ? 1 : 0);
2380             boolean dep = f.field.isDeprecated();
2381             boolean syn = f.field.isSynthetic();
2382             fieldAtts += (dep ? 1 : 0) + (syn ? 1 : 0);
2383 
2384             data.writeShort(fieldAtts);
2385             if (val != null) {
2386                 data.writeShort(tab.index("ConstantValue"));
2387                 data.writeInt(2);
2388                 data.writeShort(tab.index((val instanceof String) ? new StringExpression(f.field.getWhere(), (String)val) : val));
2389             }
2390             if (dep) {
2391                 data.writeShort(tab.index("Deprecated"));
2392                 data.writeInt(0);
2393             }
2394             if (syn) {
2395                 data.writeShort(tab.index("Synthetic"));
2396                 data.writeInt(0);
2397             }
2398         }
2399 
2400         // write methods
2401 
2402         data.writeShort(methods.size());
2403         for (Enumeration e = methods.elements() ; e.hasMoreElements() ; ) {
2404             CompilerMember f = (CompilerMember)e.nextElement();
2405 
2406             int xmods = f.field.getModifiers() & MM_METHOD;
2407             // Transform floating point modifiers.  M_STRICTFP
2408             // of member + status of enclosing class turn into
2409             // ACC_STRICT bit.
2410             if (((xmods & M_STRICTFP)!=0) || ((cmods & M_STRICTFP)!=0)) {
2411                 xmods |= ACC_STRICT;
2412             } else {
2413                 // Use the default
2414                 if (env.strictdefault()) {
2415                     xmods |= ACC_STRICT;
2416                 }
2417             }
2418             data.writeShort(xmods);
2419 
2420             data.writeShort(tab.index(f.name));
2421             data.writeShort(tab.index(f.sig));
2422             ClassDeclaration exp[] = f.field.getExceptions(env);
2423             int methodAtts = ((exp.length > 0) ? 1 : 0);
2424             boolean dep = f.field.isDeprecated();
2425             boolean syn = f.field.isSynthetic();
2426             methodAtts += (dep ? 1 : 0) + (syn ? 1 : 0);
2427 
2428             if (!f.asm.empty()) {
2429                 data.writeShort(methodAtts+1);
2430                 f.asm.write(env, databuf, f.field, tab);
2431                 int natts = 0;
2432                 if (env.debug_lines()) {
2433                     natts++;
2434                 }
2435 // JCOV
2436                 if (env.coverage()) {
2437                     natts++;
2438                 }
2439 // end JCOV
2440                 if (env.debug_vars()) {
2441                     natts++;
2442                 }
2443                 databuf.writeShort(natts);
2444 
2445                 if (env.debug_lines()) {
2446                     f.asm.writeLineNumberTable(env, new DataOutputStream(attbuf), tab);
2447                     databuf.writeShort(tab.index("LineNumberTable"));
2448                     databuf.writeInt(attbuf.size());
2449                     attbuf.writeTo(buf);
2450                     attbuf.reset();
2451                 }
2452 
2453 //JCOV
2454                 if (env.coverage()) {
2455                     f.asm.writeCoverageTable(env, (ClassDefinition)this, new DataOutputStream(attbuf), tab, f.field.getWhere());
2456                     databuf.writeShort(tab.index("CoverageTable"));
2457                     databuf.writeInt(attbuf.size());
2458                     attbuf.writeTo(buf);
2459                     attbuf.reset();
2460                 }
2461 // end JCOV
2462                 if (env.debug_vars()) {
2463                     f.asm.writeLocalVariableTable(env, f.field, new DataOutputStream(attbuf), tab);
2464                     databuf.writeShort(tab.index("LocalVariableTable"));
2465                     databuf.writeInt(attbuf.size());
2466                     attbuf.writeTo(buf);
2467                     attbuf.reset();
2468                 }
2469 
2470                 data.writeShort(tab.index("Code"));
2471                 data.writeInt(buf.size());
2472                 buf.writeTo(data);
2473                 buf.reset();
2474             } else {
2475 //JCOV
2476                 if ((env.coverage()) && ((f.field.getModifiers() & M_NATIVE) > 0))
2477                     f.asm.addNativeToJcovTab(env, (ClassDefinition)this);
2478 // end JCOV
2479                 data.writeShort(methodAtts);
2480             }
2481 
2482             if (exp.length > 0) {
2483                 data.writeShort(tab.index("Exceptions"));
2484                 data.writeInt(2 + exp.length * 2);
2485                 data.writeShort(exp.length);
2486                 for (int i = 0 ; i < exp.length ; i++) {
2487                     data.writeShort(tab.index(exp[i]));
2488                 }
2489             }
2490             if (dep) {
2491                 data.writeShort(tab.index("Deprecated"));
2492                 data.writeInt(0);
2493             }
2494             if (syn) {
2495                 data.writeShort(tab.index("Synthetic"));
2496                 data.writeInt(0);
2497             }
2498         }
2499 
2500         // class attributes
2501         data.writeShort(nClassAttrs);
2502 
2503         if (env.debug_source()) {
2504             data.writeShort(tab.index("SourceFile"));
2505             data.writeInt(2);
2506             data.writeShort(tab.index(sourceFile));
2507         }
2508 
2509         if (this.isDeprecated()) {
2510             data.writeShort(tab.index("Deprecated"));
2511             data.writeInt(0);
2512         }
2513         if (this.isSynthetic()) {
2514             data.writeShort(tab.index("Synthetic"));
2515             data.writeInt(0);
2516         }
2517 
2518 // JCOV
2519         if (env.coverage()) {
2520             data.writeShort(tab.index("AbsoluteSourcePath"));
2521             data.writeInt(2);
2522             data.writeShort(tab.index(absoluteSourcePath));
2523             data.writeShort(tab.index("TimeStamp"));
2524             data.writeInt(8);
2525             data.writeLong(timeStamp);
2526         }
2527 // end JCOV
2528 
2529         if (innerClasses.size() > 0) {
2530             data.writeShort(tab.index("InnerClasses"));
2531             data.writeInt(2 + 2*4*innerClasses.size());
2532             data.writeShort(innerClasses.size());
2533             for (Enumeration e = innerClasses.elements() ;
2534                  e.hasMoreElements() ; ) {
2535                 // For each inner class name transformation, we have a record
2536                 // with the following fields:
2537                 //
2538                 //    u2 inner_class_info_index;   // CONSTANT_Class_info index
2539                 //    u2 outer_class_info_index;   // CONSTANT_Class_info index
2540                 //    u2 inner_name_index;         // CONSTANT_Utf8_info index
2541                 //    u2 inner_class_access_flags; // access_flags bitmask
2542                 //
2543                 // The spec states that outer_class_info_index is 0 iff
2544                 // the inner class is not a member of its enclosing class (i.e.
2545                 // it is a local or anonymous class).  The spec also states
2546                 // that if a class is anonymous then inner_name_index should
2547                 // be 0.
2548                 //
2549                 // See also the initInnerClasses() method in BinaryClass.java.
2550 
2551                 // Generate inner_class_info_index.
2552                 ClassDefinition inner = (ClassDefinition)e.nextElement();
2553                 data.writeShort(tab.index(inner.getClassDeclaration()));
2554 
2555                 // Generate outer_class_info_index.
2556                 //
2557                 // Checking isLocal() should probably be enough here,
2558                 // but the check for isAnonymous is added for good
2559                 // measure.
2560                 if (inner.isLocal() || inner.isAnonymous()) {
2561                     data.writeShort(0);
2562                 } else {
2563                     // Query: what about if inner.isInsideLocal()?
2564                     // For now we continue to generate a nonzero
2565                     // outer_class_info_index.
2566                     ClassDefinition outer = inner.getOuterClass();
2567                     data.writeShort(tab.index(outer.getClassDeclaration()));
2568                 }
2569 
2570                 // Generate inner_name_index.
2571                 Identifier inner_name = inner.getLocalName();
2572                 if (inner_name == idNull) {
2573                     if (!inner.isAnonymous()) {
2574                         throw new CompilerError("compileClass(), anonymous");
2575                     }
2576                     data.writeShort(0);
2577                 } else {
2578                     data.writeShort(tab.index(inner_name.toString()));
2579                 }
2580 
2581                 // Generate inner_class_access_flags.
2582                 int imods = inner.getInnerClassMember().getModifiers()
2583                             & ACCM_INNERCLASS;
2584 
2585                 // Certain modifiers are implied for nested types.
2586                 // See rules 1, 2, 3a, and 3b enumerated above.
2587                 // All of these rules are implemented in 'BatchParser.beginClass',
2588                 // but are verified here.
2589 
2590                 if (inner.isInterface()) {
2591                     // Rules 1 and 2.
2592                     assertModifiers(imods, M_ABSTRACT | M_STATIC);
2593                 }
2594                 if (inner.getOuterClass().isInterface()) {
2595                     // Rules 3a and 3b.
2596                     imods &= ~(M_PRIVATE | M_PROTECTED); // error recovery
2597                     assertModifiers(imods, M_PUBLIC | M_STATIC);
2598                 }
2599 
2600                 data.writeShort(imods);
2601 
2602                 if (env.dumpModifiers()) {
2603                     Identifier fn = inner.getInnerClassMember().getName();
2604                     Identifier nm =
2605                         Identifier.lookup(fn.getQualifier(), fn.getFlatName());
2606                     System.out.println("INNERCLASS " + nm);
2607                     System.out.println("---" + classModifierString(imods));
2608                 }
2609 
2610             }
2611         }
2612 
2613         // Cleanup
2614         data.flush();
2615         tab = null;
2616 
2617 // JCOV
2618         // generate coverage data
2619         if (env.covdata()) {
2620             Assembler CovAsm = new Assembler();
2621             CovAsm.GenVecJCov(env, (ClassDefinition)this, timeStamp);
2622         }
2623 // end JCOV
2624     }
2625 
2626     /**
2627      * Print out the dependencies for this class (-xdepend) option
2628      */
2629 
2630     public void printClassDependencies(Environment env) {
2631 
2632         // Only do this if the -xdepend flag is on
2633         if ( toplevelEnv.print_dependencies() ) {
2634 
2635             // Name of java source file this class was in (full path)
2636             //    e.g. /home/ohair/Test.java
2637             String src = ((ClassFile)getSource()).getAbsoluteName();
2638 
2639             // Class name, fully qualified
2640             //   e.g. "java.lang.Object" or "FooBar" or "sun.tools.javac.Main"
2641             // Inner class names must be mangled, as ordinary '.' qualification
2642             // is used internally where the spec requires '$' separators.
2643             //   String className = getName().toString();
2644             String className = Type.mangleInnerType(getName()).toString();
2645 
2646             // Line number where class starts in the src file
2647             long startLine = getWhere() >> WHEREOFFSETBITS;
2648 
2649             // Line number where class ends in the src file (not used yet)
2650             long endLine = getEndPosition() >> WHEREOFFSETBITS;
2651 
2652             // First line looks like:
2653             //    CLASS:src,startLine,endLine,className
2654             System.out.println( "CLASS:"
2655                     + src               + ","
2656                     + startLine         + ","
2657                     + endLine   + ","
2658                     + className);
2659 
2660             // For each class this class is dependent on:
2661             //    CLDEP:className1,className2
2662             //  where className1 is the name of the class we are in, and
2663             //        classname2 is the name of the class className1
2664             //          is dependent on.
2665             for(Enumeration e = deps.elements();  e.hasMoreElements(); ) {
2666                 ClassDeclaration data = (ClassDeclaration) e.nextElement();
2667                 // Mangle name of class dependend on.
2668                 String depName =
2669                     Type.mangleInnerType(data.getName()).toString();
2670                 env.output("CLDEP:" + className + "," + depName);
2671             }
2672         }
2673     }
2674 }