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<ClassDeclaration, ClassDeclaration> 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 */ SourceClass(Environment env, long where, ClassDeclaration declaration, String documentation, int modifiers, IdentifierToken superClass, IdentifierToken interfaces[], SourceClass outerClass, Identifier localName)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 */ getEndPosition()190 public long getEndPosition() { 191 return endPosition; 192 } 193 setEndPosition(long endPosition)194 public void setEndPosition(long endPosition) { 195 this.endPosition = endPosition; 196 } 197 198 199 // JCOV 200 /** 201 * Return absolute name of source file 202 */ getAbsoluteName()203 public String getAbsoluteName() { 204 String AbsName = ((ClassFile)getSource()).getAbsoluteName(); 205 206 return AbsName; 207 } 208 //end JCOV 209 210 /** 211 * Return imports 212 */ getImports()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 */ getThisArgument()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 */ addDependency(ClassDeclaration c)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 */ addMember(Environment env, MemberDefinition f)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<MemberDefinition> 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 */ setupEnv(Environment env)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 */ reportDeprecated(Environment env)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 */ noteUsedBy(ClassDefinition ref, long where, Environment env)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 */ check(Environment env)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 maybeCheck(Environment env)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 checkInternal(Environment env, Context ctx, Vset vset)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 */ checkSourceFile(Environment env, long where)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 getSuperClass(Environment env)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 checkSupers(Environment env)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 */ checkMembers(Environment env, Context ctx, Vset vset)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<MemberDefinition> iter = getPermanentlyAbstractMethods(); 925 while (iter.hasNext()) { 926 MemberDefinition method = 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 = 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 checkBlankFinals(Environment env, Context ctxInit, Vset vset, boolean isStatic)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; basicCheck(Environment env)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 */ addMirandaMethods(Environment env, Iterator<MemberDefinition> mirandas)1165 protected void addMirandaMethods(Environment env, 1166 Iterator<MemberDefinition> mirandas) { 1167 1168 while(mirandas.hasNext()) { 1169 MemberDefinition method = mirandas.next(); 1170 1171 addMember(method); 1172 1173 //System.out.println("adding miranda method " + newMethod + 1174 // " to " + this); 1175 } 1176 } 1177 1178 /** 1179 * <em>After parsing is complete</em>, resolve all names 1180 * except those inside method bodies or initializers. 1181 * In particular, this is the point at which we find out what 1182 * kinds of variables and methods there are in the classes, 1183 * and therefore what is each class's interface to the world. 1184 * <p> 1185 * Also perform certain other transformations, such as inserting 1186 * "this$C" arguments into constructors, and reorganizing structure 1187 * to flatten qualified member names. 1188 * <p> 1189 * Do not perform type-based or name-based consistency checks 1190 * or normalizations (such as default nullary constructors), 1191 * and do not attempt to compile code against this class, 1192 * until after this phase. 1193 */ 1194 1195 private boolean resolving = false; 1196 resolveTypeStructure(Environment env)1197 public void resolveTypeStructure(Environment env) { 1198 1199 if (tracing) 1200 env.dtEnter("SourceClass.resolveTypeStructure: " + getName()); 1201 1202 // Resolve immediately enclosing type, which in turn 1203 // forces resolution of all enclosing type declarations. 1204 ClassDefinition oc = getOuterClass(); 1205 if (oc != null && oc instanceof SourceClass 1206 && !((SourceClass)oc).resolved) { 1207 // Do the outer class first, always. 1208 ((SourceClass)oc).resolveTypeStructure(env); 1209 // (Note: this.resolved is probably true at this point.) 1210 } 1211 1212 // Punt if we've already resolved this class, or are currently 1213 // in the process of doing so. 1214 if (resolved || resolving) { 1215 if (tracing) 1216 env.dtExit("SourceClass.resolveTypeStructure: OK " + getName()); 1217 return; 1218 } 1219 1220 // Previously, 'resolved' was set here, and served to prevent 1221 // duplicate resolutions here as well as its function in 1222 // 'ClassDefinition.addMember'. Now, 'resolving' serves the 1223 // former purpose, distinct from that of 'resolved'. 1224 resolving = true; 1225 1226 if (tracing) 1227 env.dtEvent("SourceClass.resolveTypeStructure: RESOLVING " + getName()); 1228 1229 env = setupEnv(env); 1230 1231 // Resolve superclass names to class declarations 1232 // for the immediate superclass and superinterfaces. 1233 resolveSupers(env); 1234 1235 // Check all ancestor superclasses for various 1236 // errors, verifying definition of all superclasses 1237 // and superinterfaces. Also breaks inheritance cycles. 1238 // Calls 'resolveTypeStructure' recursively for ancestors 1239 // This call used to appear in 'basicCheck', but was not 1240 // performed early enough. Most of the compiler will barf 1241 // on inheritance cycles! 1242 try { 1243 checkSupers(env); 1244 } catch (ClassNotFound ee) { 1245 // Undefined classes should be reported by 'checkSupers'. 1246 env.error(where, "class.not.found", ee.name, this); 1247 } 1248 1249 for (MemberDefinition 1250 f = getFirstMember() ; f != null ; f = f.getNextMember()) { 1251 if (f instanceof SourceMember) 1252 ((SourceMember)f).resolveTypeStructure(env); 1253 } 1254 1255 resolving = false; 1256 1257 // Mark class as resolved. If new members are subsequently 1258 // added to the class, they will be resolved at that time. 1259 // See 'ClassDefinition.addMember'. Previously, this variable was 1260 // set prior to the calls to 'checkSupers' and 'resolveTypeStructure' 1261 // (which may engender further calls to 'checkSupers'). This could 1262 // lead to duplicate resolution of implicit constructors, as the call to 1263 // 'basicCheck' from 'checkSupers' could add the constructor while 1264 // its class is marked resolved, and thus would resolve the constructor, 1265 // believing it to be a "late addition". It would then be resolved 1266 // redundantly during the normal traversal of the members, which 1267 // immediately follows in the code above. 1268 resolved = true; 1269 1270 // Now we have enough information to detect method repeats. 1271 for (MemberDefinition 1272 f = getFirstMember() ; f != null ; f = f.getNextMember()) { 1273 if (f.isInitializer()) continue; 1274 if (!f.isMethod()) continue; 1275 for (MemberDefinition f2 = f; (f2 = f2.getNextMatch()) != null; ) { 1276 if (!f2.isMethod()) continue; 1277 if (f.getType().equals(f2.getType())) { 1278 env.error(f.getWhere(), "meth.multidef", f); 1279 continue; 1280 } 1281 if (f.getType().equalArguments(f2.getType())) { 1282 env.error(f.getWhere(), "meth.redef.rettype", f, f2); 1283 continue; 1284 } 1285 } 1286 } 1287 if (tracing) 1288 env.dtExit("SourceClass.resolveTypeStructure: " + getName()); 1289 } 1290 resolveSupers(Environment env)1291 protected void resolveSupers(Environment env) { 1292 if (tracing) 1293 env.dtEnter("SourceClass.resolveSupers: " + this); 1294 // Find the super class 1295 if (superClassId != null && superClass == null) { 1296 superClass = resolveSuper(env, superClassId); 1297 // Special-case java.lang.Object here (not in the parser). 1298 // In all other cases, if we have a valid 'superClassId', 1299 // we return with a valid and non-null 'superClass' value. 1300 if (superClass == getClassDeclaration() 1301 && getName().equals(idJavaLangObject)) { 1302 superClass = null; 1303 superClassId = null; 1304 } 1305 } 1306 // Find interfaces 1307 if (interfaceIds != null && interfaces == null) { 1308 interfaces = new ClassDeclaration[interfaceIds.length]; 1309 for (int i = 0 ; i < interfaces.length ; i++) { 1310 interfaces[i] = resolveSuper(env, interfaceIds[i]); 1311 for (int j = 0; j < i; j++) { 1312 if (interfaces[i] == interfaces[j]) { 1313 Identifier id = interfaceIds[i].getName(); 1314 long where = interfaceIds[j].getWhere(); 1315 env.error(where, "intf.repeated", id); 1316 } 1317 } 1318 } 1319 } 1320 if (tracing) 1321 env.dtExit("SourceClass.resolveSupers: " + this); 1322 } 1323 resolveSuper(Environment env, IdentifierToken t)1324 private ClassDeclaration resolveSuper(Environment env, IdentifierToken t) { 1325 Identifier name = t.getName(); 1326 if (tracing) 1327 env.dtEnter("SourceClass.resolveSuper: " + name); 1328 if (isInnerClass()) 1329 name = outerClass.resolveName(env, name); 1330 else 1331 name = env.resolveName(name); 1332 ClassDeclaration result = env.getClassDeclaration(name); 1333 // Result is never null, as a new 'ClassDeclaration' is 1334 // created if one with the given name does not exist. 1335 if (tracing) env.dtExit("SourceClass.resolveSuper: " + name); 1336 return result; 1337 } 1338 1339 /** 1340 * During the type-checking of an outer method body or initializer, 1341 * this routine is called to check a local class body 1342 * in the proper context. 1343 * @param sup the named super class or interface (if anonymous) 1344 * @param args the actual arguments (if anonymous) 1345 */ checkLocalClass(Environment env, Context ctx, Vset vset, ClassDefinition sup, Expression args[], Type argTypes[] )1346 public Vset checkLocalClass(Environment env, Context ctx, Vset vset, 1347 ClassDefinition sup, 1348 Expression args[], Type argTypes[] 1349 ) throws ClassNotFound { 1350 env = setupEnv(env); 1351 1352 if ((sup != null) != isAnonymous()) { 1353 throw new CompilerError("resolveAnonymousStructure"); 1354 } 1355 if (isAnonymous()) { 1356 resolveAnonymousStructure(env, sup, args, argTypes); 1357 } 1358 1359 // Run the checks in the lexical context from the outer class. 1360 vset = checkInternal(env, ctx, vset); 1361 1362 // This is now done by 'checkInternal' via its call to 'checkMembers'. 1363 // getClassDeclaration().setDefinition(this, CS_CHECKED); 1364 1365 return vset; 1366 } 1367 1368 /** 1369 * As with checkLocalClass, run the inline phase for a local class. 1370 */ inlineLocalClass(Environment env)1371 public void inlineLocalClass(Environment env) { 1372 for (MemberDefinition 1373 f = getFirstMember(); f != null; f = f.getNextMember()) { 1374 if ((f.isVariable() || f.isInitializer()) && !f.isStatic()) { 1375 continue; // inlined inside of constructors only 1376 } 1377 try { 1378 ((SourceMember)f).inline(env); 1379 } catch (ClassNotFound ee) { 1380 env.error(f.getWhere(), "class.not.found", ee.name, this); 1381 } 1382 } 1383 if (getReferencesFrozen() != null && !inlinedLocalClass) { 1384 inlinedLocalClass = true; 1385 // add more constructor arguments for uplevel references 1386 for (MemberDefinition 1387 f = getFirstMember(); f != null; f = f.getNextMember()) { 1388 if (f.isConstructor()) { 1389 //((SourceMember)f).addUplevelArguments(false); 1390 ((SourceMember)f).addUplevelArguments(); 1391 } 1392 } 1393 } 1394 } 1395 private boolean inlinedLocalClass = false; 1396 1397 /** 1398 * Check a class which is inside a local class, but is not itself local. 1399 */ checkInsideClass(Environment env, Context ctx, Vset vset)1400 public Vset checkInsideClass(Environment env, Context ctx, Vset vset) 1401 throws ClassNotFound { 1402 if (!isInsideLocal() || isLocal()) { 1403 throw new CompilerError("checkInsideClass"); 1404 } 1405 return checkInternal(env, ctx, vset); 1406 } 1407 1408 /** 1409 * Just before checking an anonymous class, decide its true 1410 * inheritance, and build its (sole, implicit) constructor. 1411 */ resolveAnonymousStructure(Environment env, ClassDefinition sup, Expression args[], Type argTypes[] )1412 private void resolveAnonymousStructure(Environment env, 1413 ClassDefinition sup, 1414 Expression args[], Type argTypes[] 1415 ) throws ClassNotFound { 1416 1417 if (tracing) env.dtEvent("SourceClass.resolveAnonymousStructure: " + 1418 this + ", super " + sup); 1419 1420 // Decide now on the superclass. 1421 1422 // This check has been removed as part of the fix for 4055017. 1423 // In the anonymous class created to hold the 'class$' method 1424 // of an interface, 'superClassId' refers to 'java.lang.Object'. 1425 /*---------------------* 1426 if (!(superClass == null && superClassId.getName() == idNull)) { 1427 throw new CompilerError("superclass "+superClass); 1428 } 1429 *---------------------*/ 1430 1431 if (sup.isInterface()) { 1432 // allow an interface in the "super class" position 1433 int ni = (interfaces == null) ? 0 : interfaces.length; 1434 ClassDeclaration i1[] = new ClassDeclaration[1+ni]; 1435 if (ni > 0) { 1436 System.arraycopy(interfaces, 0, i1, 1, ni); 1437 if (interfaceIds != null && interfaceIds.length == ni) { 1438 IdentifierToken id1[] = new IdentifierToken[1+ni]; 1439 System.arraycopy(interfaceIds, 0, id1, 1, ni); 1440 id1[0] = new IdentifierToken(sup.getName()); 1441 } 1442 } 1443 i1[0] = sup.getClassDeclaration(); 1444 interfaces = i1; 1445 1446 sup = toplevelEnv.getClassDefinition(idJavaLangObject); 1447 } 1448 superClass = sup.getClassDeclaration(); 1449 1450 if (hasConstructor()) { 1451 throw new CompilerError("anonymous constructor"); 1452 } 1453 1454 // Synthesize an appropriate constructor. 1455 Type t = Type.tMethod(Type.tVoid, argTypes); 1456 IdentifierToken names[] = new IdentifierToken[argTypes.length]; 1457 for (int i = 0; i < names.length; i++) { 1458 names[i] = new IdentifierToken(args[i].getWhere(), 1459 Identifier.lookup("$"+i)); 1460 } 1461 int outerArg = (sup.isTopLevel() || sup.isLocal()) ? 0 : 1; 1462 Expression superArgs[] = new Expression[-outerArg + args.length]; 1463 for (int i = outerArg ; i < args.length ; i++) { 1464 superArgs[-outerArg + i] = new IdentifierExpression(names[i]); 1465 } 1466 long where = getWhere(); 1467 Expression superExp; 1468 if (outerArg == 0) { 1469 superExp = new SuperExpression(where); 1470 } else { 1471 superExp = new SuperExpression(where, 1472 new IdentifierExpression(names[0])); 1473 } 1474 Expression superCall = new MethodExpression(where, 1475 superExp, idInit, 1476 superArgs); 1477 Statement body[] = { new ExpressionStatement(where, superCall) }; 1478 Node code = new CompoundStatement(where, body); 1479 int mod = M_SYNTHETIC; // ISSUE: make M_PRIVATE, with wrapper? 1480 env.makeMemberDefinition(env, where, this, null, 1481 mod, t, idInit, names, null, code); 1482 } 1483 1484 /** 1485 * Convert class modifiers to a string for diagnostic purposes. 1486 * Accepts modifiers applicable to inner classes and that appear 1487 * in the InnerClasses attribute only, as well as those that may 1488 * appear in the class modifier proper. 1489 */ 1490 1491 private static int classModifierBits[] = 1492 { ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, 1493 ACC_INTERFACE, ACC_ABSTRACT, ACC_SUPER, M_ANONYMOUS, M_LOCAL, 1494 M_STRICTFP, ACC_STRICT}; 1495 1496 private static String classModifierNames[] = 1497 { "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL", 1498 "INTERFACE", "ABSTRACT", "SUPER", "ANONYMOUS", "LOCAL", 1499 "STRICTFP", "STRICT"}; 1500 classModifierString(int mods)1501 static String classModifierString(int mods) { 1502 String s = ""; 1503 for (int i = 0; i < classModifierBits.length; i++) { 1504 if ((mods & classModifierBits[i]) != 0) { 1505 s = s + " " + classModifierNames[i]; 1506 mods &= ~classModifierBits[i]; 1507 } 1508 } 1509 if (mods != 0) { 1510 s = s + " ILLEGAL:" + Integer.toHexString(mods); 1511 } 1512 return s; 1513 } 1514 1515 /** 1516 * Find or create an access method for a private member, 1517 * or return null if this is not possible. 1518 */ getAccessMember(Environment env, Context ctx, MemberDefinition field, boolean isSuper)1519 public MemberDefinition getAccessMember(Environment env, Context ctx, 1520 MemberDefinition field, boolean isSuper) { 1521 return getAccessMember(env, ctx, field, false, isSuper); 1522 } 1523 getUpdateMember(Environment env, Context ctx, MemberDefinition field, boolean isSuper)1524 public MemberDefinition getUpdateMember(Environment env, Context ctx, 1525 MemberDefinition field, boolean isSuper) { 1526 if (!field.isVariable()) { 1527 throw new CompilerError("method"); 1528 } 1529 return getAccessMember(env, ctx, field, true, isSuper); 1530 } 1531 getAccessMember(Environment env, Context ctx, MemberDefinition field, boolean isUpdate, boolean isSuper)1532 private MemberDefinition getAccessMember(Environment env, Context ctx, 1533 MemberDefinition field, 1534 boolean isUpdate, 1535 boolean isSuper) { 1536 1537 // The 'isSuper' argument is really only meaningful when the 1538 // target member is a method, in which case an 'invokespecial' 1539 // is needed. For fields, 'getfield' and 'putfield' instructions 1540 // are generated in either case, and 'isSuper' currently plays 1541 // no essential role. Nonetheless, we maintain the distinction 1542 // consistently for the time being. 1543 1544 boolean isStatic = field.isStatic(); 1545 boolean isMethod = field.isMethod(); 1546 1547 // Find pre-existing access method. 1548 // In the case of a field access method, we only look for the getter. 1549 // A getter is always created whenever a setter is. 1550 // QUERY: Why doesn't the 'MemberDefinition' object for the field 1551 // itself just have fields for its getter and setter? 1552 MemberDefinition af; 1553 for (af = getFirstMember(); af != null; af = af.getNextMember()) { 1554 if (af.getAccessMethodTarget() == field) { 1555 if (isMethod && af.isSuperAccessMethod() == isSuper) { 1556 break; 1557 } 1558 // Distinguish the getter and the setter by the number of 1559 // arguments. 1560 int nargs = af.getType().getArgumentTypes().length; 1561 // This was (nargs == (isStatic ? 0 : 1) + (isUpdate ? 1 : 0)) 1562 // in order to find a setter as well as a getter. This caused 1563 // allocation of multiple getters. 1564 if (nargs == (isStatic ? 0 : 1)) { 1565 break; 1566 } 1567 } 1568 } 1569 1570 if (af != null) { 1571 if (!isUpdate) { 1572 return af; 1573 } else { 1574 MemberDefinition uf = af.getAccessUpdateMember(); 1575 if (uf != null) { 1576 return uf; 1577 } 1578 } 1579 } else if (isUpdate) { 1580 // must find or create the getter before creating the setter 1581 af = getAccessMember(env, ctx, field, false, isSuper); 1582 } 1583 1584 // If we arrive here, we are creating a new access member. 1585 1586 Identifier anm; 1587 Type dummyType = null; 1588 1589 if (field.isConstructor()) { 1590 // For a constructor, we use the same name as for all 1591 // constructors ("<init>"), but add a distinguishing 1592 // argument of an otherwise unused "dummy" type. 1593 anm = idInit; 1594 // Get the dummy class, creating it if necessary. 1595 SourceClass outerMostClass = (SourceClass)getTopClass(); 1596 dummyType = outerMostClass.dummyArgumentType; 1597 if (dummyType == null) { 1598 // Create dummy class. 1599 IdentifierToken sup = 1600 new IdentifierToken(0, idJavaLangObject); 1601 IdentifierToken interfaces[] = {}; 1602 IdentifierToken t = new IdentifierToken(0, idNull); 1603 int mod = M_ANONYMOUS | M_STATIC | M_SYNTHETIC; 1604 // If an interface has a public inner class, the dummy class for 1605 // the constructor must always be accessible. Fix for 4221648. 1606 if (outerMostClass.isInterface()) { 1607 mod |= M_PUBLIC; 1608 } 1609 ClassDefinition dummyClass = 1610 toplevelEnv.makeClassDefinition(toplevelEnv, 1611 0, t, null, mod, 1612 sup, interfaces, 1613 outerMostClass); 1614 // Check the class. 1615 // It is likely that a full check is not really necessary, 1616 // but it is essential that the class be marked as parsed. 1617 dummyClass.getClassDeclaration().setDefinition(dummyClass, CS_PARSED); 1618 Expression argsX[] = {}; 1619 Type argTypesX[] = {}; 1620 try { 1621 ClassDefinition supcls = 1622 toplevelEnv.getClassDefinition(idJavaLangObject); 1623 dummyClass.checkLocalClass(toplevelEnv, null, 1624 new Vset(), supcls, argsX, argTypesX); 1625 } catch (ClassNotFound ee) {}; 1626 // Get class type. 1627 dummyType = dummyClass.getType(); 1628 outerMostClass.dummyArgumentType = dummyType; 1629 } 1630 } else { 1631 // Otherwise, we use the name "access$N", for the 1632 // smallest value of N >= 0 yielding an unused name. 1633 for (int i = 0; ; i++) { 1634 anm = Identifier.lookup(prefixAccess + i); 1635 if (getFirstMatch(anm) == null) { 1636 break; 1637 } 1638 } 1639 } 1640 1641 Type argTypes[]; 1642 Type t = field.getType(); 1643 1644 if (isStatic) { 1645 if (!isMethod) { 1646 if (!isUpdate) { 1647 Type at[] = { }; 1648 argTypes = at; 1649 t = Type.tMethod(t); // nullary getter 1650 } else { 1651 Type at[] = { t }; 1652 argTypes = at; 1653 t = Type.tMethod(Type.tVoid, argTypes); // unary setter 1654 } 1655 } else { 1656 // Since constructors are never static, we don't 1657 // have to worry about a dummy argument here. 1658 argTypes = t.getArgumentTypes(); 1659 } 1660 } else { 1661 // All access methods for non-static members get an explicit 1662 // 'this' pointer as an extra argument, as the access methods 1663 // themselves must be static. EXCEPTION: Access methods for 1664 // constructors are non-static. 1665 Type classType = this.getType(); 1666 if (!isMethod) { 1667 if (!isUpdate) { 1668 Type at[] = { classType }; 1669 argTypes = at; 1670 t = Type.tMethod(t, argTypes); // nullary getter 1671 } else { 1672 Type at[] = { classType, t }; 1673 argTypes = at; 1674 t = Type.tMethod(Type.tVoid, argTypes); // unary setter 1675 } 1676 } else { 1677 // Target is a method, possibly a constructor. 1678 Type at[] = t.getArgumentTypes(); 1679 int nargs = at.length; 1680 if (field.isConstructor()) { 1681 // Access method is a constructor. 1682 // Requires a dummy argument. 1683 MemberDefinition outerThisArg = 1684 ((SourceMember)field).getOuterThisArg(); 1685 if (outerThisArg != null) { 1686 // Outer instance link must be the first argument. 1687 // The following is a sanity check that will catch 1688 // most cases in which in this requirement is violated. 1689 if (at[0] != outerThisArg.getType()) { 1690 throw new CompilerError("misplaced outer this"); 1691 } 1692 // Strip outer 'this' argument. 1693 // It will be added back when the access method is checked. 1694 argTypes = new Type[nargs]; 1695 argTypes[0] = dummyType; 1696 for (int i = 1; i < nargs; i++) { 1697 argTypes[i] = at[i]; 1698 } 1699 } else { 1700 // There is no outer instance. 1701 argTypes = new Type[nargs+1]; 1702 argTypes[0] = dummyType; 1703 for (int i = 0; i < nargs; i++) { 1704 argTypes[i+1] = at[i]; 1705 } 1706 } 1707 } else { 1708 // Access method is static. 1709 // Requires an explicit 'this' argument. 1710 argTypes = new Type[nargs+1]; 1711 argTypes[0] = classType; 1712 for (int i = 0; i < nargs; i++) { 1713 argTypes[i+1] = at[i]; 1714 } 1715 } 1716 t = Type.tMethod(t.getReturnType(), argTypes); 1717 } 1718 } 1719 1720 int nlen = argTypes.length; 1721 long where = field.getWhere(); 1722 IdentifierToken names[] = new IdentifierToken[nlen]; 1723 for (int i = 0; i < nlen; i++) { 1724 names[i] = new IdentifierToken(where, Identifier.lookup("$"+i)); 1725 } 1726 1727 Expression access = null; 1728 Expression thisArg = null; 1729 Expression args[] = null; 1730 1731 if (isStatic) { 1732 args = new Expression[nlen]; 1733 for (int i = 0 ; i < nlen ; i++) { 1734 args[i] = new IdentifierExpression(names[i]); 1735 } 1736 } else { 1737 if (field.isConstructor()) { 1738 // Constructor access method is non-static, so 1739 // 'this' works normally. 1740 thisArg = new ThisExpression(where); 1741 // Remove dummy argument, as it is not 1742 // passed to the target method. 1743 args = new Expression[nlen-1]; 1744 for (int i = 1 ; i < nlen ; i++) { 1745 args[i-1] = new IdentifierExpression(names[i]); 1746 } 1747 } else { 1748 // Non-constructor access method is static, so 1749 // we use the first argument as 'this'. 1750 thisArg = new IdentifierExpression(names[0]); 1751 // Remove first argument. 1752 args = new Expression[nlen-1]; 1753 for (int i = 1 ; i < nlen ; i++) { 1754 args[i-1] = new IdentifierExpression(names[i]); 1755 } 1756 } 1757 access = thisArg; 1758 } 1759 1760 if (!isMethod) { 1761 access = new FieldExpression(where, access, field); 1762 if (isUpdate) { 1763 access = new AssignExpression(where, access, args[0]); 1764 } 1765 } else { 1766 // If true, 'isSuper' forces a non-virtual call. 1767 access = new MethodExpression(where, access, field, args, isSuper); 1768 } 1769 1770 Statement code; 1771 if (t.getReturnType().isType(TC_VOID)) { 1772 code = new ExpressionStatement(where, access); 1773 } else { 1774 code = new ReturnStatement(where, access); 1775 } 1776 Statement body[] = { code }; 1777 code = new CompoundStatement(where, body); 1778 1779 // Access methods are now static (constructors excepted), and no longer final. 1780 // This change was mandated by the interaction of the access method 1781 // naming conventions and the restriction against overriding final 1782 // methods. 1783 int mod = M_SYNTHETIC; 1784 if (!field.isConstructor()) { 1785 mod |= M_STATIC; 1786 } 1787 1788 // Create the synthetic method within the class in which the referenced 1789 // private member appears. The 'env' argument to 'makeMemberDefinition' 1790 // is suspect because it represents the environment at the point at 1791 // which a reference takes place, while it should represent the 1792 // environment in which the definition of the synthetic method appears. 1793 // We get away with this because 'env' is used only to access globals 1794 // such as 'Environment.error', and also as an argument to 1795 // 'resolveTypeStructure', which immediately discards it using 1796 // 'setupEnv'. Apparently, the current definition of 'setupEnv' 1797 // represents a design change that has not been thoroughly propagated. 1798 // An access method is declared with same list of exceptions as its 1799 // target. As the exceptions are simply listed by name, the correctness 1800 // of this approach requires that the access method be checked 1801 // (name-resolved) in the same context as its target method This 1802 // should always be the case. 1803 SourceMember newf = (SourceMember) 1804 env.makeMemberDefinition(env, where, this, 1805 null, mod, t, anm, names, 1806 field.getExceptionIds(), code); 1807 // Just to be safe, copy over the name-resolved exceptions from the 1808 // target so that the context in which the access method is checked 1809 // doesn't matter. 1810 newf.setExceptions(field.getExceptions(env)); 1811 1812 newf.setAccessMethodTarget(field); 1813 if (isUpdate) { 1814 af.setAccessUpdateMember(newf); 1815 } 1816 newf.setIsSuperAccessMethod(isSuper); 1817 1818 // The call to 'check' is not needed, as the access method will be 1819 // checked by the containing class after it is added. This is the 1820 // idiom followed in the implementation of class literals. (See 1821 // 'FieldExpression.java'.) In any case, the context is wrong in the 1822 // call below. The access method must be checked in the context in 1823 // which it is declared, i.e., the class containing the referenced 1824 // private member, not the (inner) class in which the original member 1825 // reference occurs. 1826 // 1827 // try { 1828 // newf.check(env, ctx, new Vset()); 1829 // } catch (ClassNotFound ee) { 1830 // env.error(where, "class.not.found", ee.name, this); 1831 // } 1832 1833 // The comment above is inaccurate. While it is often the case 1834 // that the containing class will check the access method, this is 1835 // by no means guaranteed. In fact, an access method may be added 1836 // after the checking of its class is complete. In this case, however, 1837 // the context in which the class was checked will have been saved in 1838 // the class definition object (by the fix for 4095716), allowing us 1839 // to check the field now, and in the correct context. 1840 // This fixes bug 4098093. 1841 1842 Context checkContext = newf.getClassDefinition().getClassContext(); 1843 if (checkContext != null) { 1844 //System.out.println("checking late addition: " + this); 1845 try { 1846 newf.check(env, checkContext, new Vset()); 1847 } catch (ClassNotFound ee) { 1848 env.error(where, "class.not.found", ee.name, this); 1849 } 1850 } 1851 1852 1853 //System.out.println("[Access member '" + 1854 // newf + "' created for field '" + 1855 // field +"' in class '" + this + "']"); 1856 1857 return newf; 1858 } 1859 1860 /** 1861 * Find an inner class of 'this', chosen arbitrarily. 1862 * Result is always an actual class, never an interface. 1863 * Returns null if none found. 1864 */ findLookupContext()1865 SourceClass findLookupContext() { 1866 // Look for an immediate inner class. 1867 for (MemberDefinition f = getFirstMember(); 1868 f != null; 1869 f = f.getNextMember()) { 1870 if (f.isInnerClass()) { 1871 SourceClass ic = (SourceClass)f.getInnerClass(); 1872 if (!ic.isInterface()) { 1873 return ic; 1874 } 1875 } 1876 } 1877 // Look for a class nested within an immediate inner interface. 1878 // At this point, we have given up on finding a minimally-nested 1879 // class (which would require a breadth-first traversal). It doesn't 1880 // really matter which inner class we find. 1881 for (MemberDefinition f = getFirstMember(); 1882 f != null; 1883 f = f.getNextMember()) { 1884 if (f.isInnerClass()) { 1885 SourceClass lc = 1886 ((SourceClass)f.getInnerClass()).findLookupContext(); 1887 if (lc != null) { 1888 return lc; 1889 } 1890 } 1891 } 1892 // No inner classes. 1893 return null; 1894 } 1895 1896 private MemberDefinition lookup = null; 1897 1898 /** 1899 * Get helper method for class literal lookup. 1900 */ getClassLiteralLookup(long fwhere)1901 public MemberDefinition getClassLiteralLookup(long fwhere) { 1902 1903 // If we have already created a lookup method, reuse it. 1904 if (lookup != null) { 1905 return lookup; 1906 } 1907 1908 // If the current class is a nested class, make sure we put the 1909 // lookup method in the outermost class. Set 'lookup' for the 1910 // intervening inner classes so we won't have to do the search 1911 // again. 1912 if (outerClass != null) { 1913 lookup = outerClass.getClassLiteralLookup(fwhere); 1914 return lookup; 1915 } 1916 1917 // If we arrive here, there was no existing 'class$' method. 1918 1919 ClassDefinition c = this; 1920 boolean needNewClass = false; 1921 1922 if (isInterface()) { 1923 // The top-level type is an interface. Try to find an existing 1924 // inner class in which to create the helper method. Any will do. 1925 c = findLookupContext(); 1926 if (c == null) { 1927 // The interface has no inner classes. Create an anonymous 1928 // inner class to hold the helper method, as an interface must 1929 // not have any methods. The tests above for prior creation 1930 // of a 'class$' method assure that only one such class is 1931 // allocated for each outermost class containing a class 1932 // literal embedded somewhere within. Part of fix for 4055017. 1933 needNewClass = true; 1934 IdentifierToken sup = 1935 new IdentifierToken(fwhere, idJavaLangObject); 1936 IdentifierToken interfaces[] = {}; 1937 IdentifierToken t = new IdentifierToken(fwhere, idNull); 1938 int mod = M_PUBLIC | M_ANONYMOUS | M_STATIC | M_SYNTHETIC; 1939 c = (SourceClass) 1940 toplevelEnv.makeClassDefinition(toplevelEnv, 1941 fwhere, t, null, mod, 1942 sup, interfaces, this); 1943 } 1944 } 1945 1946 1947 // The name of the class-getter stub is "class$" 1948 Identifier idDClass = Identifier.lookup(prefixClass); 1949 Type strarg[] = { Type.tString }; 1950 1951 // Some sanity checks of questionable value. 1952 // 1953 // This check became useless after matchMethod() was modified 1954 // to not return synthetic methods. 1955 // 1956 //try { 1957 // lookup = c.matchMethod(toplevelEnv, c, idDClass, strarg); 1958 //} catch (ClassNotFound ee) { 1959 // throw new CompilerError("unexpected missing class"); 1960 //} catch (AmbiguousMember ee) { 1961 // throw new CompilerError("synthetic name clash"); 1962 //} 1963 //if (lookup != null && lookup.getClassDefinition() == c) { 1964 // // Error if method found was not inherited. 1965 // throw new CompilerError("unexpected duplicate"); 1966 //} 1967 // Some sanity checks of questionable value. 1968 1969 /* // The helper function looks like this. 1970 * // It simply maps a checked exception to an unchecked one. 1971 * static Class class$(String class$) { 1972 * try { return Class.forName(class$); } 1973 * catch (ClassNotFoundException forName) { 1974 * throw new NoClassDefFoundError(forName.getMessage()); 1975 * } 1976 * } 1977 */ 1978 long w = c.getWhere(); 1979 IdentifierToken arg = new IdentifierToken(w, idDClass); 1980 Expression e = new IdentifierExpression(arg); 1981 Expression a1[] = { e }; 1982 Identifier idForName = Identifier.lookup("forName"); 1983 e = new MethodExpression(w, new TypeExpression(w, Type.tClassDesc), 1984 idForName, a1); 1985 Statement body = new ReturnStatement(w, e); 1986 // map the exceptions 1987 Identifier idClassNotFound = 1988 Identifier.lookup("java.lang.ClassNotFoundException"); 1989 Identifier idNoClassDefFound = 1990 Identifier.lookup("java.lang.NoClassDefFoundError"); 1991 Type ctyp = Type.tClass(idClassNotFound); 1992 Type exptyp = Type.tClass(idNoClassDefFound); 1993 Identifier idGetMessage = Identifier.lookup("getMessage"); 1994 e = new IdentifierExpression(w, idForName); 1995 e = new MethodExpression(w, e, idGetMessage, new Expression[0]); 1996 Expression a2[] = { e }; 1997 e = new NewInstanceExpression(w, new TypeExpression(w, exptyp), a2); 1998 Statement handler = new CatchStatement(w, new TypeExpression(w, ctyp), 1999 new IdentifierToken(idForName), 2000 new ThrowStatement(w, e)); 2001 Statement handlers[] = { handler }; 2002 body = new TryStatement(w, body, handlers); 2003 2004 Type mtype = Type.tMethod(Type.tClassDesc, strarg); 2005 IdentifierToken args[] = { arg }; 2006 2007 // Use default (package) access. If private, an access method would 2008 // be needed in the event that the class literal belonged to an interface. 2009 // Also, making it private tickles bug 4098316. 2010 lookup = toplevelEnv.makeMemberDefinition(toplevelEnv, w, 2011 c, null, 2012 M_STATIC | M_SYNTHETIC, 2013 mtype, idDClass, 2014 args, null, body); 2015 2016 // If a new class was created to contain the helper method, 2017 // check it now. 2018 if (needNewClass) { 2019 if (c.getClassDeclaration().getStatus() == CS_CHECKED) { 2020 throw new CompilerError("duplicate check"); 2021 } 2022 c.getClassDeclaration().setDefinition(c, CS_PARSED); 2023 Expression argsX[] = {}; 2024 Type argTypesX[] = {}; 2025 try { 2026 ClassDefinition sup = 2027 toplevelEnv.getClassDefinition(idJavaLangObject); 2028 c.checkLocalClass(toplevelEnv, null, 2029 new Vset(), sup, argsX, argTypesX); 2030 } catch (ClassNotFound ee) {}; 2031 } 2032 2033 return lookup; 2034 } 2035 2036 2037 /** 2038 * A list of active ongoing compilations. This list 2039 * is used to stop two compilations from saving the 2040 * same class. 2041 */ 2042 private static Vector<Object> active = new Vector<>(); 2043 2044 /** 2045 * Compile this class 2046 */ compile(OutputStream out)2047 public void compile(OutputStream out) 2048 throws InterruptedException, IOException { 2049 Environment env = toplevelEnv; 2050 synchronized (active) { 2051 while (active.contains(getName())) { 2052 active.wait(); 2053 } 2054 active.addElement(getName()); 2055 } 2056 2057 try { 2058 compileClass(env, out); 2059 } catch (ClassNotFound e) { 2060 throw new CompilerError(e); 2061 } finally { 2062 synchronized (active) { 2063 active.removeElement(getName()); 2064 active.notifyAll(); 2065 } 2066 } 2067 } 2068 2069 /** 2070 * Verify that the modifier bits included in 'required' are 2071 * all present in 'mods', otherwise signal an internal error. 2072 * Note that errors in the source program may corrupt the modifiers, 2073 * thus we rely on the fact that 'CompilerError' exceptions are 2074 * silently ignored after an error message has been issued. 2075 */ assertModifiers(int mods, int required)2076 private static void assertModifiers(int mods, int required) { 2077 if ((mods & required) != required) { 2078 throw new CompilerError("illegal class modifiers"); 2079 } 2080 } 2081 compileClass(Environment env, OutputStream out)2082 protected void compileClass(Environment env, OutputStream out) 2083 throws IOException, ClassNotFound { 2084 Vector<CompilerMember> variables = new Vector<>(); 2085 Vector<CompilerMember> methods = new Vector<>(); 2086 Vector<ClassDefinition> innerClasses = new Vector<>(); 2087 CompilerMember init = new CompilerMember(new MemberDefinition(getWhere(), this, M_STATIC, Type.tMethod(Type.tVoid), idClassInit, null, null), new Assembler()); 2088 Context ctx = new Context((Context)null, init.field); 2089 2090 for (ClassDefinition def = this; def.isInnerClass(); def = def.getOuterClass()) { 2091 innerClasses.addElement(def); 2092 } 2093 // Reverse the order, so that outer levels come first: 2094 int ncsize = innerClasses.size(); 2095 for (int i = ncsize; --i >= 0; ) 2096 innerClasses.addElement(innerClasses.elementAt(i)); 2097 for (int i = ncsize; --i >= 0; ) 2098 innerClasses.removeElementAt(i); 2099 2100 // System.out.println("compile class " + getName()); 2101 2102 boolean haveDeprecated = this.isDeprecated(); 2103 boolean haveSynthetic = this.isSynthetic(); 2104 boolean haveConstantValue = false; 2105 boolean haveExceptions = false; 2106 2107 // Generate code for all fields 2108 for (SourceMember field = (SourceMember)getFirstMember(); 2109 field != null; 2110 field = (SourceMember)field.getNextMember()) { 2111 2112 //System.out.println("compile field " + field.getName()); 2113 2114 haveDeprecated |= field.isDeprecated(); 2115 haveSynthetic |= field.isSynthetic(); 2116 2117 try { 2118 if (field.isMethod()) { 2119 haveExceptions |= 2120 (field.getExceptions(env).length > 0); 2121 2122 if (field.isInitializer()) { 2123 if (field.isStatic()) { 2124 field.code(env, init.asm); 2125 } 2126 } else { 2127 CompilerMember f = 2128 new CompilerMember(field, new Assembler()); 2129 field.code(env, f.asm); 2130 methods.addElement(f); 2131 } 2132 } else if (field.isInnerClass()) { 2133 innerClasses.addElement(field.getInnerClass()); 2134 } else if (field.isVariable()) { 2135 field.inline(env); 2136 CompilerMember f = new CompilerMember(field, null); 2137 variables.addElement(f); 2138 if (field.isStatic()) { 2139 field.codeInit(env, ctx, init.asm); 2140 2141 } 2142 haveConstantValue |= 2143 (field.getInitialValue() != null); 2144 } 2145 } catch (CompilerError ee) { 2146 ee.printStackTrace(); 2147 env.error(field, 0, "generic", 2148 field.getClassDeclaration() + ":" + field + 2149 "@" + ee.toString(), null, null); 2150 } 2151 } 2152 if (!init.asm.empty()) { 2153 init.asm.add(getWhere(), opc_return, true); 2154 methods.addElement(init); 2155 } 2156 2157 // bail out if there were any errors 2158 if (getNestError()) { 2159 return; 2160 } 2161 2162 int nClassAttrs = 0; 2163 2164 // Insert constants 2165 if (methods.size() > 0) { 2166 tab.put("Code"); 2167 } 2168 if (haveConstantValue) { 2169 tab.put("ConstantValue"); 2170 } 2171 2172 String sourceFile = null; 2173 if (env.debug_source()) { 2174 sourceFile = ((ClassFile)getSource()).getName(); 2175 tab.put("SourceFile"); 2176 tab.put(sourceFile); 2177 nClassAttrs += 1; 2178 } 2179 2180 if (haveExceptions) { 2181 tab.put("Exceptions"); 2182 } 2183 2184 if (env.debug_lines()) { 2185 tab.put("LineNumberTable"); 2186 } 2187 if (haveDeprecated) { 2188 tab.put("Deprecated"); 2189 if (this.isDeprecated()) { 2190 nClassAttrs += 1; 2191 } 2192 } 2193 if (haveSynthetic) { 2194 tab.put("Synthetic"); 2195 if (this.isSynthetic()) { 2196 nClassAttrs += 1; 2197 } 2198 } 2199 // JCOV 2200 if (env.coverage()) { 2201 nClassAttrs += 2; // AbsoluteSourcePath, TimeStamp 2202 tab.put("AbsoluteSourcePath"); 2203 tab.put("TimeStamp"); 2204 tab.put("CoverageTable"); 2205 } 2206 // end JCOV 2207 if (env.debug_vars()) { 2208 tab.put("LocalVariableTable"); 2209 } 2210 if (innerClasses.size() > 0) { 2211 tab.put("InnerClasses"); 2212 nClassAttrs += 1; // InnerClasses 2213 } 2214 2215 // JCOV 2216 String absoluteSourcePath = ""; 2217 long timeStamp = 0; 2218 2219 if (env.coverage()) { 2220 absoluteSourcePath = getAbsoluteName(); 2221 timeStamp = System.currentTimeMillis(); 2222 tab.put(absoluteSourcePath); 2223 } 2224 // end JCOV 2225 tab.put(getClassDeclaration()); 2226 if (getSuperClass() != null) { 2227 tab.put(getSuperClass()); 2228 } 2229 for (int i = 0 ; i < interfaces.length ; i++) { 2230 tab.put(interfaces[i]); 2231 } 2232 2233 // Sort the methods in order to make sure both constant pool 2234 // entries and methods are in a deterministic order from run 2235 // to run (this allows comparing class files for a fixed point 2236 // to validate the compiler) 2237 CompilerMember[] ordered_methods = 2238 new CompilerMember[methods.size()]; 2239 methods.copyInto(ordered_methods); 2240 java.util.Arrays.sort(ordered_methods); 2241 for (int i=0; i<methods.size(); i++) 2242 methods.setElementAt(ordered_methods[i], i); 2243 2244 // Optimize Code and Collect method constants 2245 for (Enumeration<CompilerMember> e = methods.elements() ; e.hasMoreElements() ; ) { 2246 CompilerMember f = e.nextElement(); 2247 try { 2248 f.asm.optimize(env); 2249 f.asm.collect(env, f.field, tab); 2250 tab.put(f.name); 2251 tab.put(f.sig); 2252 ClassDeclaration exp[] = f.field.getExceptions(env); 2253 for (int i = 0 ; i < exp.length ; i++) { 2254 tab.put(exp[i]); 2255 } 2256 } catch (Exception ee) { 2257 ee.printStackTrace(); 2258 env.error(f.field, -1, "generic", f.field.getName() + "@" + ee.toString(), null, null); 2259 f.asm.listing(System.out); 2260 } 2261 } 2262 2263 // Collect field constants 2264 for (Enumeration<CompilerMember> e = variables.elements() ; e.hasMoreElements() ; ) { 2265 CompilerMember f = e.nextElement(); 2266 tab.put(f.name); 2267 tab.put(f.sig); 2268 2269 Object val = f.field.getInitialValue(); 2270 if (val != null) { 2271 tab.put((val instanceof String) ? new StringExpression(f.field.getWhere(), (String)val) : val); 2272 } 2273 } 2274 2275 // Collect inner class constants 2276 for (Enumeration<ClassDefinition> e = innerClasses.elements(); 2277 e.hasMoreElements() ; ) { 2278 ClassDefinition inner = e.nextElement(); 2279 tab.put(inner.getClassDeclaration()); 2280 2281 // If the inner class is local, we do not need to add its 2282 // outer class here -- the outer_class_info_index is zero. 2283 if (!inner.isLocal()) { 2284 ClassDefinition outer = inner.getOuterClass(); 2285 tab.put(outer.getClassDeclaration()); 2286 } 2287 2288 // If the local name of the class is idNull, don't bother to 2289 // add it to the constant pool. We won't need it. 2290 Identifier inner_local_name = inner.getLocalName(); 2291 if (inner_local_name != idNull) { 2292 tab.put(inner_local_name.toString()); 2293 } 2294 } 2295 2296 // Write header 2297 DataOutputStream data = new DataOutputStream(out); 2298 data.writeInt(JAVA_MAGIC); 2299 data.writeShort(toplevelEnv.getMinorVersion()); 2300 data.writeShort(toplevelEnv.getMajorVersion()); 2301 tab.write(env, data); 2302 2303 // Write class information 2304 int cmods = getModifiers() & MM_CLASS; 2305 2306 // Certain modifiers are implied: 2307 // 1. Any interface (nested or not) is implicitly deemed to be abstract, 2308 // whether it is explicitly marked so or not. (Java 1.0.) 2309 // 2. A interface which is a member of a type is implicitly deemed to 2310 // be static, whether it is explicitly marked so or not. 2311 // 3a. A type which is a member of an interface is implicitly deemed 2312 // to be public, whether it is explicitly marked so or not. 2313 // 3b. A type which is a member of an interface is implicitly deemed 2314 // to be static, whether it is explicitly marked so or not. 2315 // All of these rules are implemented in 'BatchParser.beginClass', 2316 // but the results are verified here. 2317 2318 if (isInterface()) { 2319 // Rule 1. 2320 // The VM spec states that ACC_ABSTRACT must be set when 2321 // ACC_INTERFACE is; this was not done by javac prior to 1.2, 2322 // and the runtime compensates by setting it. Making sure 2323 // it is set here will allow the runtime hack to eventually 2324 // be removed. Rule 2 doesn't apply to transformed modifiers. 2325 assertModifiers(cmods, ACC_ABSTRACT); 2326 } else { 2327 // Contrary to the JVM spec, we only set ACC_SUPER for classes, 2328 // not interfaces. This is a workaround for a bug in IE3.0, 2329 // which refuses interfaces with ACC_SUPER on. 2330 cmods |= ACC_SUPER; 2331 } 2332 2333 // If this is a nested class, transform access modifiers. 2334 if (outerClass != null) { 2335 // If private, transform to default (package) access. 2336 // If protected, transform to public. 2337 // M_PRIVATE and M_PROTECTED are already masked off by MM_CLASS above. 2338 // cmods &= ~(M_PRIVATE | M_PROTECTED); 2339 if (isProtected()) cmods |= M_PUBLIC; 2340 // Rule 3a. Note that Rule 3b doesn't apply to transformed modifiers. 2341 if (outerClass.isInterface()) { 2342 assertModifiers(cmods, M_PUBLIC); 2343 } 2344 } 2345 2346 data.writeShort(cmods); 2347 2348 if (env.dumpModifiers()) { 2349 Identifier cn = getName(); 2350 Identifier nm = 2351 Identifier.lookup(cn.getQualifier(), cn.getFlatName()); 2352 System.out.println(); 2353 System.out.println("CLASSFILE " + nm); 2354 System.out.println("---" + classModifierString(cmods)); 2355 } 2356 2357 data.writeShort(tab.index(getClassDeclaration())); 2358 data.writeShort((getSuperClass() != null) ? tab.index(getSuperClass()) : 0); 2359 data.writeShort(interfaces.length); 2360 for (int i = 0 ; i < interfaces.length ; i++) { 2361 data.writeShort(tab.index(interfaces[i])); 2362 } 2363 2364 // write variables 2365 ByteArrayOutputStream buf = new ByteArrayOutputStream(256); 2366 ByteArrayOutputStream attbuf = new ByteArrayOutputStream(256); 2367 DataOutputStream databuf = new DataOutputStream(buf); 2368 2369 data.writeShort(variables.size()); 2370 for (Enumeration<CompilerMember> e = variables.elements() ; e.hasMoreElements() ; ) { 2371 CompilerMember f = e.nextElement(); 2372 Object val = f.field.getInitialValue(); 2373 2374 data.writeShort(f.field.getModifiers() & MM_FIELD); 2375 data.writeShort(tab.index(f.name)); 2376 data.writeShort(tab.index(f.sig)); 2377 2378 int fieldAtts = (val != null ? 1 : 0); 2379 boolean dep = f.field.isDeprecated(); 2380 boolean syn = f.field.isSynthetic(); 2381 fieldAtts += (dep ? 1 : 0) + (syn ? 1 : 0); 2382 2383 data.writeShort(fieldAtts); 2384 if (val != null) { 2385 data.writeShort(tab.index("ConstantValue")); 2386 data.writeInt(2); 2387 data.writeShort(tab.index((val instanceof String) ? new StringExpression(f.field.getWhere(), (String)val) : val)); 2388 } 2389 if (dep) { 2390 data.writeShort(tab.index("Deprecated")); 2391 data.writeInt(0); 2392 } 2393 if (syn) { 2394 data.writeShort(tab.index("Synthetic")); 2395 data.writeInt(0); 2396 } 2397 } 2398 2399 // write methods 2400 2401 data.writeShort(methods.size()); 2402 for (Enumeration<CompilerMember> e = methods.elements() ; e.hasMoreElements() ; ) { 2403 CompilerMember f = e.nextElement(); 2404 2405 int xmods = f.field.getModifiers() & MM_METHOD; 2406 // Transform floating point modifiers. M_STRICTFP 2407 // of member + status of enclosing class turn into 2408 // ACC_STRICT bit. 2409 if (((xmods & M_STRICTFP)!=0) || ((cmods & M_STRICTFP)!=0)) { 2410 xmods |= ACC_STRICT; 2411 } else { 2412 // Use the default 2413 if (env.strictdefault()) { 2414 xmods |= ACC_STRICT; 2415 } 2416 } 2417 data.writeShort(xmods); 2418 2419 data.writeShort(tab.index(f.name)); 2420 data.writeShort(tab.index(f.sig)); 2421 ClassDeclaration exp[] = f.field.getExceptions(env); 2422 int methodAtts = ((exp.length > 0) ? 1 : 0); 2423 boolean dep = f.field.isDeprecated(); 2424 boolean syn = f.field.isSynthetic(); 2425 methodAtts += (dep ? 1 : 0) + (syn ? 1 : 0); 2426 2427 if (!f.asm.empty()) { 2428 data.writeShort(methodAtts+1); 2429 f.asm.write(env, databuf, f.field, tab); 2430 int natts = 0; 2431 if (env.debug_lines()) { 2432 natts++; 2433 } 2434 // JCOV 2435 if (env.coverage()) { 2436 natts++; 2437 } 2438 // end JCOV 2439 if (env.debug_vars()) { 2440 natts++; 2441 } 2442 databuf.writeShort(natts); 2443 2444 if (env.debug_lines()) { 2445 f.asm.writeLineNumberTable(env, new DataOutputStream(attbuf), tab); 2446 databuf.writeShort(tab.index("LineNumberTable")); 2447 databuf.writeInt(attbuf.size()); 2448 attbuf.writeTo(buf); 2449 attbuf.reset(); 2450 } 2451 2452 //JCOV 2453 if (env.coverage()) { 2454 f.asm.writeCoverageTable(env, (ClassDefinition)this, new DataOutputStream(attbuf), tab, f.field.getWhere()); 2455 databuf.writeShort(tab.index("CoverageTable")); 2456 databuf.writeInt(attbuf.size()); 2457 attbuf.writeTo(buf); 2458 attbuf.reset(); 2459 } 2460 // end JCOV 2461 if (env.debug_vars()) { 2462 f.asm.writeLocalVariableTable(env, f.field, new DataOutputStream(attbuf), tab); 2463 databuf.writeShort(tab.index("LocalVariableTable")); 2464 databuf.writeInt(attbuf.size()); 2465 attbuf.writeTo(buf); 2466 attbuf.reset(); 2467 } 2468 2469 data.writeShort(tab.index("Code")); 2470 data.writeInt(buf.size()); 2471 buf.writeTo(data); 2472 buf.reset(); 2473 } else { 2474 //JCOV 2475 if ((env.coverage()) && ((f.field.getModifiers() & M_NATIVE) > 0)) 2476 f.asm.addNativeToJcovTab(env, (ClassDefinition)this); 2477 // end JCOV 2478 data.writeShort(methodAtts); 2479 } 2480 2481 if (exp.length > 0) { 2482 data.writeShort(tab.index("Exceptions")); 2483 data.writeInt(2 + exp.length * 2); 2484 data.writeShort(exp.length); 2485 for (int i = 0 ; i < exp.length ; i++) { 2486 data.writeShort(tab.index(exp[i])); 2487 } 2488 } 2489 if (dep) { 2490 data.writeShort(tab.index("Deprecated")); 2491 data.writeInt(0); 2492 } 2493 if (syn) { 2494 data.writeShort(tab.index("Synthetic")); 2495 data.writeInt(0); 2496 } 2497 } 2498 2499 // class attributes 2500 data.writeShort(nClassAttrs); 2501 2502 if (env.debug_source()) { 2503 data.writeShort(tab.index("SourceFile")); 2504 data.writeInt(2); 2505 data.writeShort(tab.index(sourceFile)); 2506 } 2507 2508 if (this.isDeprecated()) { 2509 data.writeShort(tab.index("Deprecated")); 2510 data.writeInt(0); 2511 } 2512 if (this.isSynthetic()) { 2513 data.writeShort(tab.index("Synthetic")); 2514 data.writeInt(0); 2515 } 2516 2517 // JCOV 2518 if (env.coverage()) { 2519 data.writeShort(tab.index("AbsoluteSourcePath")); 2520 data.writeInt(2); 2521 data.writeShort(tab.index(absoluteSourcePath)); 2522 data.writeShort(tab.index("TimeStamp")); 2523 data.writeInt(8); 2524 data.writeLong(timeStamp); 2525 } 2526 // end JCOV 2527 2528 if (innerClasses.size() > 0) { 2529 data.writeShort(tab.index("InnerClasses")); 2530 data.writeInt(2 + 2*4*innerClasses.size()); 2531 data.writeShort(innerClasses.size()); 2532 for (Enumeration<ClassDefinition> e = innerClasses.elements() ; 2533 e.hasMoreElements() ; ) { 2534 // For each inner class name transformation, we have a record 2535 // with the following fields: 2536 // 2537 // u2 inner_class_info_index; // CONSTANT_Class_info index 2538 // u2 outer_class_info_index; // CONSTANT_Class_info index 2539 // u2 inner_name_index; // CONSTANT_Utf8_info index 2540 // u2 inner_class_access_flags; // access_flags bitmask 2541 // 2542 // The spec states that outer_class_info_index is 0 iff 2543 // the inner class is not a member of its enclosing class (i.e. 2544 // it is a local or anonymous class). The spec also states 2545 // that if a class is anonymous then inner_name_index should 2546 // be 0. 2547 // 2548 // See also the initInnerClasses() method in BinaryClass.java. 2549 2550 // Generate inner_class_info_index. 2551 ClassDefinition inner = e.nextElement(); 2552 data.writeShort(tab.index(inner.getClassDeclaration())); 2553 2554 // Generate outer_class_info_index. 2555 // 2556 // Checking isLocal() should probably be enough here, 2557 // but the check for isAnonymous is added for good 2558 // measure. 2559 if (inner.isLocal() || inner.isAnonymous()) { 2560 data.writeShort(0); 2561 } else { 2562 // Query: what about if inner.isInsideLocal()? 2563 // For now we continue to generate a nonzero 2564 // outer_class_info_index. 2565 ClassDefinition outer = inner.getOuterClass(); 2566 data.writeShort(tab.index(outer.getClassDeclaration())); 2567 } 2568 2569 // Generate inner_name_index. 2570 Identifier inner_name = inner.getLocalName(); 2571 if (inner_name == idNull) { 2572 if (!inner.isAnonymous()) { 2573 throw new CompilerError("compileClass(), anonymous"); 2574 } 2575 data.writeShort(0); 2576 } else { 2577 data.writeShort(tab.index(inner_name.toString())); 2578 } 2579 2580 // Generate inner_class_access_flags. 2581 int imods = inner.getInnerClassMember().getModifiers() 2582 & ACCM_INNERCLASS; 2583 2584 // Certain modifiers are implied for nested types. 2585 // See rules 1, 2, 3a, and 3b enumerated above. 2586 // All of these rules are implemented in 'BatchParser.beginClass', 2587 // but are verified here. 2588 2589 if (inner.isInterface()) { 2590 // Rules 1 and 2. 2591 assertModifiers(imods, M_ABSTRACT | M_STATIC); 2592 } 2593 if (inner.getOuterClass().isInterface()) { 2594 // Rules 3a and 3b. 2595 imods &= ~(M_PRIVATE | M_PROTECTED); // error recovery 2596 assertModifiers(imods, M_PUBLIC | M_STATIC); 2597 } 2598 2599 data.writeShort(imods); 2600 2601 if (env.dumpModifiers()) { 2602 Identifier fn = inner.getInnerClassMember().getName(); 2603 Identifier nm = 2604 Identifier.lookup(fn.getQualifier(), fn.getFlatName()); 2605 System.out.println("INNERCLASS " + nm); 2606 System.out.println("---" + classModifierString(imods)); 2607 } 2608 2609 } 2610 } 2611 2612 // Cleanup 2613 data.flush(); 2614 tab = null; 2615 2616 // JCOV 2617 // generate coverage data 2618 if (env.covdata()) { 2619 Assembler CovAsm = new Assembler(); 2620 CovAsm.GenVecJCov(env, (ClassDefinition)this, timeStamp); 2621 } 2622 // end JCOV 2623 } 2624 2625 /** 2626 * Print out the dependencies for this class (-xdepend) option 2627 */ 2628 printClassDependencies(Environment env)2629 public void printClassDependencies(Environment env) { 2630 2631 // Only do this if the -xdepend flag is on 2632 if ( toplevelEnv.print_dependencies() ) { 2633 2634 // Name of java source file this class was in (full path) 2635 // e.g. /home/ohair/Test.java 2636 String src = ((ClassFile)getSource()).getAbsoluteName(); 2637 2638 // Class name, fully qualified 2639 // e.g. "java.lang.Object" or "FooBar" or "sun.tools.javac.Main" 2640 // Inner class names must be mangled, as ordinary '.' qualification 2641 // is used internally where the spec requires '$' separators. 2642 // String className = getName().toString(); 2643 String className = Type.mangleInnerType(getName()).toString(); 2644 2645 // Line number where class starts in the src file 2646 long startLine = getWhere() >> WHEREOFFSETBITS; 2647 2648 // Line number where class ends in the src file (not used yet) 2649 long endLine = getEndPosition() >> WHEREOFFSETBITS; 2650 2651 // First line looks like: 2652 // CLASS:src,startLine,endLine,className 2653 System.out.println( "CLASS:" 2654 + src + "," 2655 + startLine + "," 2656 + endLine + "," 2657 + className); 2658 2659 // For each class this class is dependent on: 2660 // CLDEP:className1,className2 2661 // where className1 is the name of the class we are in, and 2662 // classname2 is the name of the class className1 2663 // is dependent on. 2664 for(Enumeration<ClassDeclaration> e = deps.elements(); e.hasMoreElements(); ) { 2665 ClassDeclaration data = e.nextElement(); 2666 // Mangle name of class dependend on. 2667 String depName = 2668 Type.mangleInnerType(data.getName()).toString(); 2669 env.output("CLDEP:" + className + "," + depName); 2670 } 2671 } 2672 } 2673 } 2674