1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
|
/*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999-2003 Shigeru Chiba. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/
package javassist.compiler;
import javassist.*;
import javassist.bytecode.*;
import javassist.compiler.ast.*;
/* Code generator methods depending on javassist.* classes.
*/
public class MemberCodeGen extends CodeGen {
protected MemberResolver resolver;
protected CtClass thisClass;
protected MethodInfo thisMethod;
protected boolean resultStatic;
public MemberCodeGen(Bytecode b, CtClass cc, ClassPool cp)
{
super(b);
resolver = new MemberResolver(cp);
thisClass = cc;
thisMethod = null;
}
/**
* Records the currently compiled method.
*/
public void setThisMethod(CtMethod m) {
thisMethod = m.getMethodInfo2();
if (typeChecker != null)
typeChecker.setThisMethod(thisMethod);
}
public CtClass getThisClass() { return thisClass; }
/**
* Returns the JVM-internal representation of this class name.
*/
protected String getThisName() {
return MemberResolver.javaToJvmName(thisClass.getName());
}
/**
* Returns the JVM-internal representation of this super class name.
*/
protected String getSuperName() throws CompileError {
return MemberResolver.javaToJvmName(
MemberResolver.getSuperclass(thisClass).getName());
}
protected void insertDefaultSuperCall() throws CompileError {
bytecode.addAload(0);
bytecode.addInvokespecial(MemberResolver.getSuperclass(thisClass),
"<init>", "()V");
}
protected void atTryStmnt(Stmnt st) throws CompileError {
Stmnt body = (Stmnt)st.getLeft();
if (body == null)
return;
int start = bytecode.currentPc();
body.accept(this);
int end = bytecode.currentPc();
if (start == end)
throw new CompileError("empty try block");
bytecode.addOpcode(Opcode.GOTO);
int pc = bytecode.currentPc();
bytecode.addIndex(0); // correct later
int var = getMaxLocals();
incMaxLocals(1);
ASTList catchList = (ASTList)st.getRight().getLeft();
while (catchList != null) {
Pair p = (Pair)catchList.head();
catchList = catchList.tail();
Declarator decl = (Declarator)p.getLeft();
Stmnt block = (Stmnt)p.getRight();
decl.setLocalVar(var);
CtClass type = resolver.lookupClassByJvmName(decl.getClassName());
decl.setClassName(MemberResolver.javaToJvmName(type.getName()));
bytecode.addExceptionHandler(start, end, bytecode.currentPc(),
type);
bytecode.growStack(1);
bytecode.addAstore(var);
if (block != null)
block.accept(this);
bytecode.addOpcode(Opcode.GOTO);
bytecode.addIndex(pc - bytecode.currentPc());
}
Stmnt finallyBlock = (Stmnt)st.getRight().getRight().getLeft();
if (finallyBlock != null)
throw new CompileError(
"sorry, finally has not been supported yet");
bytecode.write16bit(pc, bytecode.currentPc() - pc + 1);
hasReturned = false;
}
public void atNewExpr(NewExpr expr) throws CompileError {
if (expr.isArray())
atNewArrayExpr(expr);
else {
CtClass clazz = resolver.lookupClassByName(expr.getClassName());
String cname = clazz.getName();
ASTList args = expr.getArguments();
bytecode.addNew(cname);
bytecode.addOpcode(DUP);
atMethodCallCore(clazz, MethodInfo.nameInit, args,
false, true, -1, null);
exprType = CLASS;
arrayDim = 0;
className = MemberResolver.javaToJvmName(cname);
}
}
public void atNewArrayExpr(NewExpr expr) throws CompileError {
if (expr.getInitializer() != null)
throw new CompileError("array initializer is not supported");
int type = expr.getArrayType();
ASTList size = expr.getArraySize();
ASTList classname = expr.getClassName();
if (size.length() > 1) {
atMultiNewArray(type, classname, size);
return;
}
size.head().accept(this);
exprType = type;
arrayDim = 1;
if (type == CLASS) {
className = resolveClassName(classname);
bytecode.addAnewarray(MemberResolver.jvmToJavaName(className));
}
else {
className = null;
int atype = 0;
switch (type) {
case BOOLEAN :
atype = T_BOOLEAN;
break;
case CHAR :
atype = T_CHAR;
break;
case FLOAT :
atype = T_FLOAT;
break;
case DOUBLE :
atype = T_DOUBLE;
break;
case BYTE :
atype = T_BYTE;
break;
case SHORT :
atype = T_SHORT;
break;
case INT :
atype = T_INT;
break;
case LONG :
atype = T_LONG;
break;
default :
badNewExpr();
break;
}
bytecode.addOpcode(NEWARRAY);
bytecode.add(atype);
}
}
private static void badNewExpr() throws CompileError {
throw new CompileError("bad new expression");
}
protected void atMultiNewArray(int type, ASTList classname, ASTList size)
throws CompileError
{
int count, dim;
dim = size.length();
for (count = 0; size != null; size = size.tail()) {
ASTree s = size.head();
if (s == null)
break; // int[][][] a = new int[3][4][];
++count;
s.accept(this);
if (exprType != INT)
throw new CompileError("bad type for array size");
}
String desc;
exprType = type;
arrayDim = dim;
if (type == CLASS) {
className = resolveClassName(classname);
desc = toJvmArrayName(className, dim);
}
else
desc = toJvmTypeName(type, dim);
bytecode.addMultiNewarray(desc, count);
}
public void atCallExpr(CallExpr expr) throws CompileError {
String mname = null;
CtClass targetClass = null;
ASTree method = expr.oprand1();
ASTList args = (ASTList)expr.oprand2();
boolean isStatic = false;
boolean isSpecial = false;
int aload0pos = -1;
MemberResolver.Method cached = expr.getMethod();
if (method instanceof Member) {
mname = ((Member)method).get();
targetClass = thisClass;
if (inStaticMethod || (cached != null && cached.isStatic()))
isStatic = true; // should be static
else {
aload0pos = bytecode.currentPc();
bytecode.addAload(0); // this
}
}
else if (method instanceof Keyword) { // constructor
isSpecial = true;
mname = MethodInfo.nameInit; // <init>
targetClass = thisClass;
if (inStaticMethod)
throw new CompileError("a constructor cannot be static");
else
bytecode.addAload(0); // this
if (((Keyword)method).get() == SUPER)
targetClass = MemberResolver.getSuperclass(targetClass);
}
else if (method instanceof Expr) {
Expr e = (Expr)method;
mname = ((Symbol)e.oprand2()).get();
int op = e.getOperator();
if (op == MEMBER) { // static method
targetClass
= resolver.lookupClass(((Symbol)e.oprand1()).get(), false);
isStatic = true;
}
else if (op == '.') {
ASTree target = e.oprand1();
if (target instanceof Keyword)
if (((Keyword)target).get() == SUPER)
isSpecial = true;
try {
target.accept(this);
}
catch (NoFieldException nfe) {
if (nfe.getExpr() != target)
throw nfe;
// it should be a static method.
exprType = CLASS;
arrayDim = 0;
className = nfe.getField(); // JVM-internal
isStatic = true;
}
if (arrayDim > 0)
targetClass = resolver.lookupClass(javaLangObject, true);
else if (exprType == CLASS /* && arrayDim == 0 */)
targetClass = resolver.lookupClassByJvmName(className);
else
badMethod();
}
else
badMethod();
}
else
fatal();
atMethodCallCore(targetClass, mname, args, isStatic, isSpecial,
aload0pos, cached);
}
private static void badMethod() throws CompileError {
throw new CompileError("bad method");
}
// atMethodCallCore() is also called by doit() in NewExpr.ProceedForNew
public void atMethodCallCore(CtClass targetClass, String mname,
ASTList args, boolean isStatic, boolean isSpecial,
int aload0pos, MemberResolver.Method found)
throws CompileError
{
int nargs = getMethodArgsLength(args);
int[] types = new int[nargs];
int[] dims = new int[nargs];
String[] cnames = new String[nargs];
if (!isStatic && found != null && found.isStatic()) {
bytecode.addOpcode(POP);
isStatic = true;
}
int stack = bytecode.getStackDepth();
atMethodArgs(args, types, dims, cnames);
// used by invokeinterface
int count = bytecode.getStackDepth() - stack + 1;
if (found == null)
found = resolver.lookupMethod(targetClass, thisMethod, mname,
types, dims, cnames, false);
if (found == null) {
String msg;
if (mname.equals(MethodInfo.nameInit))
msg = "constructor not found";
else
msg = "Method " + mname + " not found in "
+ targetClass.getName();
throw new CompileError(msg);
}
CtClass declClass = found.declaring;
MethodInfo minfo = found.info;
String desc = minfo.getDescriptor();
int acc = minfo.getAccessFlags();
if (mname.equals(MethodInfo.nameInit)) {
isSpecial = true;
if (declClass != targetClass)
throw new CompileError("no such a constructor");
}
else if ((acc & AccessFlag.PRIVATE) != 0) {
isSpecial = true;
if (declClass != targetClass)
throw new CompileError("Method " + mname + "is private");
}
boolean popTarget = false;
if ((acc & AccessFlag.STATIC) != 0) {
if (!isStatic) {
/* this method is static but the target object is
on stack. It must be popped out. If aload0pos >= 0,
then the target object was pushed by aload_0. It is
overwritten by NOP.
*/
isStatic = true;
if (aload0pos >= 0)
bytecode.write(aload0pos, NOP);
else
popTarget = true;
}
bytecode.addInvokestatic(declClass, mname, desc);
}
else if (isSpecial)
bytecode.addInvokespecial(declClass, mname, desc);
else if (declClass.isInterface())
bytecode.addInvokeinterface(declClass, mname, desc, count);
else
if (isStatic)
throw new CompileError(mname + " is not static");
else
bytecode.addInvokevirtual(declClass, mname, desc);
setReturnType(desc, isStatic, popTarget);
}
public int getMethodArgsLength(ASTList args) {
return ASTList.length(args);
}
public void atMethodArgs(ASTList args, int[] types, int[] dims,
String[] cnames) throws CompileError {
int i = 0;
while (args != null) {
ASTree a = args.head();
a.accept(this);
types[i] = exprType;
dims[i] = arrayDim;
cnames[i] = className;
++i;
args = args.tail();
}
}
void setReturnType(String desc, boolean isStatic, boolean popTarget)
throws CompileError
{
int i = desc.indexOf(')');
if (i < 0)
badMethod();
char c = desc.charAt(++i);
int dim = 0;
while (c == '[') {
++dim;
c = desc.charAt(++i);
}
arrayDim = dim;
if (c == 'L') {
int j = desc.indexOf(';', i + 1);
if (j < 0)
badMethod();
exprType = CLASS;
className = desc.substring(i + 1, j);
}
else {
exprType = MemberResolver.descToType(c);
className = null;
}
int etype = exprType;
if (isStatic) {
if (popTarget) {
if (is2word(etype, dim)) {
bytecode.addOpcode(DUP2_X1);
bytecode.addOpcode(POP2);
bytecode.addOpcode(POP);
}
else if (etype == VOID)
bytecode.addOpcode(POP);
else {
bytecode.addOpcode(SWAP);
bytecode.addOpcode(POP);
}
}
}
}
protected void atFieldAssign(Expr expr, int op, ASTree left,
ASTree right, boolean doDup) throws CompileError
{
CtField f = fieldAccess(left);
boolean is_static = resultStatic;
if (op != '=' && !is_static)
bytecode.addOpcode(DUP);
int fi = atFieldRead(f, is_static, op == '=');
int fType = exprType;
int fDim = arrayDim;
String cname = className;
atAssignCore(expr, op, right, fType, fDim, cname);
boolean is2w = is2word(fType, fDim);
if (doDup) {
int dup_code;
if (is_static)
dup_code = (is2w ? DUP2 : DUP);
else
dup_code = (is2w ? DUP2_X1 : DUP_X1);
bytecode.addOpcode(dup_code);
}
if (is_static) {
bytecode.add(PUTSTATIC);
bytecode.growStack(is2w ? -2 : -1);
}
else {
bytecode.add(PUTFIELD);
bytecode.growStack(is2w ? -3 : -2);
}
bytecode.addIndex(fi);
exprType = fType;
arrayDim = fDim;
className = cname;
}
/* overwritten in JvstCodeGen.
*/
public void atMember(Member mem) throws CompileError {
atFieldRead(mem);
}
protected void atFieldRead(ASTree expr) throws CompileError
{
CtField f = fieldAccess(expr);
boolean is_static = resultStatic;
atFieldRead(f, is_static, false);
}
private int atFieldRead(CtField f, boolean isStatic, boolean noRead)
throws CompileError
{
FieldInfo finfo = f.getFieldInfo2();
String type = finfo.getDescriptor();
int fi = addFieldrefInfo(f, finfo, type);
int i = 0;
int dim = 0;
char c = type.charAt(i);
while (c == '[') {
++dim;
c = type.charAt(++i);
}
arrayDim = dim;
boolean is2byte = (c == 'J' || c == 'D');
exprType = MemberResolver.descToType(c);
if (c == 'L')
className = type.substring(i + 1, type.indexOf(';', i + 1));
else
className = null;
if (noRead)
return fi;
if (isStatic) {
bytecode.add(GETSTATIC);
bytecode.growStack(is2byte ? 2 : 1);
}
else {
bytecode.add(GETFIELD);
bytecode.growStack(is2byte ? 1 : 0);
}
bytecode.addIndex(fi);
return fi;
}
protected int addFieldrefInfo(CtField f, FieldInfo finfo, String type) {
ConstPool cp = bytecode.getConstPool();
String cname = f.getDeclaringClass().getName();
int ci = cp.addClassInfo(cname);
String name = finfo.getName();
return cp.addFieldrefInfo(ci, name, type);
}
protected void atFieldPlusPlus(int token, boolean isPost,
ASTree oprand, Expr expr, boolean doDup)
throws CompileError
{
CtField f = fieldAccess(oprand);
boolean is_static = resultStatic;
if (!is_static)
bytecode.addOpcode(DUP);
int fi = atFieldRead(f, is_static, false);
int t = exprType;
boolean is2w = is2word(t, arrayDim);
int dup_code;
if (is_static)
dup_code = (is2w ? DUP2 : DUP);
else
dup_code = (is2w ? DUP2_X1 : DUP_X1);
atPlusPlusCore(dup_code, doDup, token, isPost, expr);
if (is_static) {
bytecode.add(PUTSTATIC);
bytecode.growStack(is2w ? -2 : -1);
}
else {
bytecode.add(PUTFIELD);
bytecode.growStack(is2w ? -3 : -2);
}
bytecode.addIndex(fi);
}
/* This method also returns a value in resultStatic.
*/
protected CtField fieldAccess(ASTree expr) throws CompileError {
CtField f = null;
boolean is_static = false;
if (expr instanceof Member) {
String name = ((Member)expr).get();
try {
f = thisClass.getField(name);
}
catch (NotFoundException e) {
// EXPR might be part of a static member access?
throw new NoFieldException(name, expr);
}
is_static = Modifier.isStatic(f.getModifiers());
if (!is_static)
if (inStaticMethod)
throw new CompileError(
"not available in a static method: " + name);
else
bytecode.addAload(0); // this
}
else if (expr instanceof Expr) {
Expr e = (Expr)expr;
int op = e.getOperator();
if (op == MEMBER) {
// static member by # (extension by Javassist)
f = resolver.lookupField(((Symbol)e.oprand1()).get(),
(Symbol)e.oprand2());
is_static = true;
}
else if (op == '.') {
try {
e.oprand1().accept(this);
if (exprType == CLASS && arrayDim == 0)
f = resolver.lookupFieldByJvmName(className,
(Symbol)e.oprand2());
else
badLvalue();
is_static = Modifier.isStatic(f.getModifiers());
if (is_static)
bytecode.addOpcode(POP);
}
catch (NoFieldException nfe) {
if (nfe.getExpr() != e.oprand1())
throw nfe;
/* EXPR should be a static field.
* If EXPR might be part of a qualified class name,
* lookupFieldByJvmName2() throws NoFieldException.
*/
Symbol fname = (Symbol)e.oprand2();
f = resolver.lookupFieldByJvmName2(nfe.getField(),
fname, expr);
is_static = true;
}
}
else
badLvalue();
}
else
badLvalue();
resultStatic = is_static;
return f;
}
private static void badLvalue() throws CompileError {
throw new CompileError("bad l-value");
}
public CtClass[] makeParamList(MethodDecl md) throws CompileError {
CtClass[] params;
ASTList plist = md.getParams();
if (plist == null)
params = new CtClass[0];
else {
int i = 0;
params = new CtClass[plist.length()];
while (plist != null) {
params[i++] = resolver.lookupClass((Declarator)plist.head());
plist = plist.tail();
}
}
return params;
}
public CtClass[] makeThrowsList(MethodDecl md) throws CompileError {
CtClass[] clist;
ASTList list = md.getThrows();
if (list == null)
return null;
else {
int i = 0;
clist = new CtClass[list.length()];
while (list != null) {
clist[i++] = resolver.lookupClassByName((ASTList)list.head());
list = list.tail();
}
return clist;
}
}
/* Converts a class name into a JVM-internal representation.
*
* It may also expand a simple class name to java.lang.*.
* For example, this converts Object into java/lang/Object.
*/
protected String resolveClassName(ASTList name) throws CompileError {
return resolver.resolveClassName(name);
}
/* Expands a simple class name to java.lang.*.
* For example, this converts Object into java/lang/Object.
*/
protected String resolveClassName(String jvmName) throws CompileError {
return resolver.resolveJvmClassName(jvmName);
}
}
|