You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CodeGen.java 58KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2006 Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later.
  9. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. */
  15. package javassist.compiler;
  16. import java.util.ArrayList;
  17. import java.util.Arrays;
  18. import javassist.compiler.ast.*;
  19. import javassist.bytecode.*;
  20. /* The code generator is implemeted by three files:
  21. * CodeGen.java, MemberCodeGen.java, and JvstCodeGen.
  22. * I just wanted to split a big file into three smaller ones.
  23. */
  24. public abstract class CodeGen extends Visitor implements Opcode, TokenId {
  25. static final String javaLangObject = "java.lang.Object";
  26. static final String jvmJavaLangObject = "java/lang/Object";
  27. static final String javaLangString = "java.lang.String";
  28. static final String jvmJavaLangString = "java/lang/String";
  29. protected Bytecode bytecode;
  30. private int tempVar;
  31. TypeChecker typeChecker;
  32. /**
  33. * true if the last visited node is a return statement.
  34. */
  35. protected boolean hasReturned;
  36. /**
  37. * Must be true if compilation is for a static method.
  38. */
  39. public boolean inStaticMethod;
  40. protected ArrayList breakList, continueList;
  41. /**
  42. * doit() in ReturnHook is called from atReturn().
  43. */
  44. protected static abstract class ReturnHook {
  45. ReturnHook next;
  46. protected abstract void doit(Bytecode b, int opcode);
  47. protected ReturnHook(CodeGen gen) {
  48. next = gen.returnHooks;
  49. gen.returnHooks = this;
  50. }
  51. protected void remove(CodeGen gen) {
  52. gen.returnHooks = next;
  53. }
  54. }
  55. protected ReturnHook returnHooks;
  56. /* The following fields are used by atXXX() methods
  57. * for returning the type of the compiled expression.
  58. */
  59. protected int exprType; // VOID, NULL, CLASS, BOOLEAN, INT, ...
  60. protected int arrayDim;
  61. protected String className; // JVM-internal representation
  62. public CodeGen(Bytecode b) {
  63. bytecode = b;
  64. tempVar = -1;
  65. typeChecker = null;
  66. hasReturned = false;
  67. inStaticMethod = false;
  68. breakList = null;
  69. continueList = null;
  70. returnHooks = null;
  71. }
  72. public void setTypeChecker(TypeChecker checker) {
  73. typeChecker = checker;
  74. }
  75. protected static void fatal() throws CompileError {
  76. throw new CompileError("fatal");
  77. }
  78. public static boolean is2word(int type, int dim) {
  79. return dim == 0 && (type == DOUBLE || type == LONG);
  80. }
  81. public int getMaxLocals() { return bytecode.getMaxLocals(); }
  82. public void setMaxLocals(int n) {
  83. bytecode.setMaxLocals(n);
  84. }
  85. protected void incMaxLocals(int size) {
  86. bytecode.incMaxLocals(size);
  87. }
  88. /**
  89. * Returns a local variable that single or double words can be
  90. * stored in.
  91. */
  92. protected int getTempVar() {
  93. if (tempVar < 0) {
  94. tempVar = getMaxLocals();
  95. incMaxLocals(2);
  96. }
  97. return tempVar;
  98. }
  99. protected int getLocalVar(Declarator d) {
  100. int v = d.getLocalVar();
  101. if (v < 0) {
  102. v = getMaxLocals(); // delayed variable allocation.
  103. d.setLocalVar(v);
  104. incMaxLocals(1);
  105. }
  106. return v;
  107. }
  108. /**
  109. * Returns the JVM-internal representation of this class name.
  110. */
  111. protected abstract String getThisName();
  112. /**
  113. * Returns the JVM-internal representation of this super class name.
  114. */
  115. protected abstract String getSuperName() throws CompileError;
  116. /* Converts a class name into a JVM-internal representation.
  117. *
  118. * It may also expand a simple class name to java.lang.*.
  119. * For example, this converts Object into java/lang/Object.
  120. */
  121. protected abstract String resolveClassName(ASTList name)
  122. throws CompileError;
  123. /* Expands a simple class name to java.lang.*.
  124. * For example, this converts Object into java/lang/Object.
  125. */
  126. protected abstract String resolveClassName(String jvmClassName)
  127. throws CompileError;
  128. /**
  129. * @param name the JVM-internal representation.
  130. * name is not exapnded to java.lang.*.
  131. */
  132. protected static String toJvmArrayName(String name, int dim) {
  133. if (name == null)
  134. return null;
  135. if (dim == 0)
  136. return name;
  137. else {
  138. StringBuffer sbuf = new StringBuffer();
  139. int d = dim;
  140. while (d-- > 0)
  141. sbuf.append('[');
  142. sbuf.append('L');
  143. sbuf.append(name);
  144. sbuf.append(';');
  145. return sbuf.toString();
  146. }
  147. }
  148. protected static String toJvmTypeName(int type, int dim) {
  149. char c = 'I';
  150. switch(type) {
  151. case BOOLEAN :
  152. c = 'Z';
  153. break;
  154. case BYTE :
  155. c = 'B';
  156. break;
  157. case CHAR :
  158. c = 'C';
  159. break;
  160. case SHORT :
  161. c = 'S';
  162. break;
  163. case INT :
  164. c = 'I';
  165. break;
  166. case LONG :
  167. c = 'J';
  168. break;
  169. case FLOAT :
  170. c = 'F';
  171. break;
  172. case DOUBLE :
  173. c = 'D';
  174. break;
  175. case VOID :
  176. c = 'V';
  177. break;
  178. }
  179. StringBuffer sbuf = new StringBuffer();
  180. while (dim-- > 0)
  181. sbuf.append('[');
  182. sbuf.append(c);
  183. return sbuf.toString();
  184. }
  185. public void compileExpr(ASTree expr) throws CompileError {
  186. doTypeCheck(expr);
  187. expr.accept(this);
  188. }
  189. public boolean compileBooleanExpr(boolean branchIf, ASTree expr)
  190. throws CompileError
  191. {
  192. doTypeCheck(expr);
  193. return booleanExpr(branchIf, expr);
  194. }
  195. public void doTypeCheck(ASTree expr) throws CompileError {
  196. if (typeChecker != null)
  197. expr.accept(typeChecker);
  198. }
  199. public void atASTList(ASTList n) throws CompileError { fatal(); }
  200. public void atPair(Pair n) throws CompileError { fatal(); }
  201. public void atSymbol(Symbol n) throws CompileError { fatal(); }
  202. public void atFieldDecl(FieldDecl field) throws CompileError {
  203. field.getInit().accept(this);
  204. }
  205. public void atMethodDecl(MethodDecl method) throws CompileError {
  206. ASTList mods = method.getModifiers();
  207. setMaxLocals(1);
  208. while (mods != null) {
  209. Keyword k = (Keyword)mods.head();
  210. mods = mods.tail();
  211. if (k.get() == STATIC) {
  212. setMaxLocals(0);
  213. inStaticMethod = true;
  214. }
  215. }
  216. ASTList params = method.getParams();
  217. while (params != null) {
  218. atDeclarator((Declarator)params.head());
  219. params = params.tail();
  220. }
  221. Stmnt s = method.getBody();
  222. atMethodBody(s, method.isConstructor(),
  223. method.getReturn().getType() == VOID);
  224. }
  225. /**
  226. * @param isCons true if super() must be called.
  227. * false if the method is a class initializer.
  228. */
  229. public void atMethodBody(Stmnt s, boolean isCons, boolean isVoid)
  230. throws CompileError
  231. {
  232. if (s == null)
  233. return;
  234. if (isCons && needsSuperCall(s))
  235. insertDefaultSuperCall();
  236. hasReturned = false;
  237. s.accept(this);
  238. if (!hasReturned)
  239. if (isVoid) {
  240. bytecode.addOpcode(Opcode.RETURN);
  241. hasReturned = true;
  242. }
  243. else
  244. throw new CompileError("no return statement");
  245. }
  246. private boolean needsSuperCall(Stmnt body) throws CompileError {
  247. if (body.getOperator() == BLOCK)
  248. body = (Stmnt)body.head();
  249. if (body != null && body.getOperator() == EXPR) {
  250. ASTree expr = body.head();
  251. if (expr != null && expr instanceof Expr
  252. && ((Expr)expr).getOperator() == CALL) {
  253. ASTree target = ((Expr)expr).head();
  254. if (target instanceof Keyword) {
  255. int token = ((Keyword)target).get();
  256. return token != THIS && token != SUPER;
  257. }
  258. }
  259. }
  260. return true;
  261. }
  262. protected abstract void insertDefaultSuperCall() throws CompileError;
  263. public void atStmnt(Stmnt st) throws CompileError {
  264. if (st == null)
  265. return; // empty
  266. int op = st.getOperator();
  267. if (op == EXPR) {
  268. ASTree expr = st.getLeft();
  269. doTypeCheck(expr);
  270. if (expr instanceof AssignExpr)
  271. atAssignExpr((AssignExpr)expr, false);
  272. else if (isPlusPlusExpr(expr)) {
  273. Expr e = (Expr)expr;
  274. atPlusPlus(e.getOperator(), e.oprand1(), e, false);
  275. }
  276. else {
  277. expr.accept(this);
  278. if (is2word(exprType, arrayDim))
  279. bytecode.addOpcode(POP2);
  280. else if (exprType != VOID)
  281. bytecode.addOpcode(POP);
  282. }
  283. }
  284. else if (op == DECL || op == BLOCK) {
  285. ASTList list = st;
  286. while (list != null) {
  287. ASTree h = list.head();
  288. list = list.tail();
  289. if (h != null)
  290. h.accept(this);
  291. }
  292. }
  293. else if (op == IF)
  294. atIfStmnt(st);
  295. else if (op == WHILE || op == DO)
  296. atWhileStmnt(st, op == WHILE);
  297. else if (op == FOR)
  298. atForStmnt(st);
  299. else if (op == BREAK || op == CONTINUE)
  300. atBreakStmnt(st, op == BREAK);
  301. else if (op == TokenId.RETURN)
  302. atReturnStmnt(st);
  303. else if (op == THROW)
  304. atThrowStmnt(st);
  305. else if (op == TRY)
  306. atTryStmnt(st);
  307. else if (op == SWITCH)
  308. atSwitchStmnt(st);
  309. else if (op == SYNCHRONIZED)
  310. atSyncStmnt(st);
  311. else {
  312. // LABEL, SWITCH label stament might be null?.
  313. hasReturned = false;
  314. throw new CompileError(
  315. "sorry, not supported statement: TokenId " + op);
  316. }
  317. }
  318. private void atIfStmnt(Stmnt st) throws CompileError {
  319. ASTree expr = st.head();
  320. Stmnt thenp = (Stmnt)st.tail().head();
  321. Stmnt elsep = (Stmnt)st.tail().tail().head();
  322. compileBooleanExpr(false, expr);
  323. int pc = bytecode.currentPc();
  324. int pc2 = 0;
  325. bytecode.addIndex(0); // correct later
  326. hasReturned = false;
  327. if (thenp != null)
  328. thenp.accept(this);
  329. boolean thenHasReturned = hasReturned;
  330. hasReturned = false;
  331. if (elsep != null && !thenHasReturned) {
  332. bytecode.addOpcode(Opcode.GOTO);
  333. pc2 = bytecode.currentPc();
  334. bytecode.addIndex(0);
  335. }
  336. bytecode.write16bit(pc, bytecode.currentPc() - pc + 1);
  337. if (elsep != null) {
  338. elsep.accept(this);
  339. if (!thenHasReturned)
  340. bytecode.write16bit(pc2, bytecode.currentPc() - pc2 + 1);
  341. hasReturned = thenHasReturned && hasReturned;
  342. }
  343. }
  344. private void atWhileStmnt(Stmnt st, boolean notDo) throws CompileError {
  345. ArrayList prevBreakList = breakList;
  346. ArrayList prevContList = continueList;
  347. breakList = new ArrayList();
  348. continueList = new ArrayList();
  349. ASTree expr = st.head();
  350. Stmnt body = (Stmnt)st.tail();
  351. int pc = 0;
  352. if (notDo) {
  353. bytecode.addOpcode(Opcode.GOTO);
  354. pc = bytecode.currentPc();
  355. bytecode.addIndex(0);
  356. }
  357. int pc2 = bytecode.currentPc();
  358. if (body != null)
  359. body.accept(this);
  360. int pc3 = bytecode.currentPc();
  361. if (notDo)
  362. bytecode.write16bit(pc, pc3 - pc + 1);
  363. boolean alwaysBranch = compileBooleanExpr(true, expr);
  364. bytecode.addIndex(pc2 - bytecode.currentPc() + 1);
  365. patchGoto(breakList, bytecode.currentPc());
  366. patchGoto(continueList, pc3);
  367. continueList = prevContList;
  368. breakList = prevBreakList;
  369. hasReturned = alwaysBranch;
  370. }
  371. protected void patchGoto(ArrayList list, int targetPc) {
  372. int n = list.size();
  373. for (int i = 0; i < n; ++i) {
  374. int pc = ((Integer)list.get(i)).intValue();
  375. bytecode.write16bit(pc, targetPc - pc + 1);
  376. }
  377. }
  378. private void atForStmnt(Stmnt st) throws CompileError {
  379. ArrayList prevBreakList = breakList;
  380. ArrayList prevContList = continueList;
  381. breakList = new ArrayList();
  382. continueList = new ArrayList();
  383. Stmnt init = (Stmnt)st.head();
  384. ASTList p = st.tail();
  385. ASTree expr = p.head();
  386. p = p.tail();
  387. Stmnt update = (Stmnt)p.head();
  388. Stmnt body = (Stmnt)p.tail();
  389. if (init != null)
  390. init.accept(this);
  391. int pc = bytecode.currentPc();
  392. int pc2 = 0;
  393. if (expr != null) {
  394. compileBooleanExpr(false, expr);
  395. pc2 = bytecode.currentPc();
  396. bytecode.addIndex(0);
  397. }
  398. if (body != null)
  399. body.accept(this);
  400. int pc3 = bytecode.currentPc();
  401. if (update != null)
  402. update.accept(this);
  403. bytecode.addOpcode(Opcode.GOTO);
  404. bytecode.addIndex(pc - bytecode.currentPc() + 1);
  405. int pc4 = bytecode.currentPc();
  406. if (expr != null)
  407. bytecode.write16bit(pc2, pc4 - pc2 + 1);
  408. patchGoto(breakList, pc4);
  409. patchGoto(continueList, pc3);
  410. continueList = prevContList;
  411. breakList = prevBreakList;
  412. hasReturned = false;
  413. }
  414. private void atSwitchStmnt(Stmnt st) throws CompileError {
  415. compileExpr(st.head());
  416. ArrayList prevBreakList = breakList;
  417. breakList = new ArrayList();
  418. int opcodePc = bytecode.currentPc();
  419. bytecode.addOpcode(LOOKUPSWITCH);
  420. int npads = 3 - (opcodePc & 3);
  421. while (npads-- > 0)
  422. bytecode.add(0);
  423. Stmnt body = (Stmnt)st.tail();
  424. int npairs = 0;
  425. for (ASTList list = body; list != null; list = list.tail())
  426. if (((Stmnt)list.head()).getOperator() == CASE)
  427. ++npairs;
  428. // opcodePc2 is the position at which the default jump offset is.
  429. int opcodePc2 = bytecode.currentPc();
  430. bytecode.addGap(4);
  431. bytecode.add32bit(npairs);
  432. bytecode.addGap(npairs * 8);
  433. long[] pairs = new long[npairs];
  434. int ipairs = 0;
  435. int defaultPc = -1;
  436. for (ASTList list = body; list != null; list = list.tail()) {
  437. Stmnt label = (Stmnt)list.head();
  438. int op = label.getOperator();
  439. if (op == DEFAULT)
  440. defaultPc = bytecode.currentPc();
  441. else if (op != CASE)
  442. fatal();
  443. else {
  444. pairs[ipairs++]
  445. = ((long)computeLabel(label.head()) << 32) +
  446. ((long)(bytecode.currentPc() - opcodePc) & 0xffffffff);
  447. }
  448. hasReturned = false;
  449. ((Stmnt)label.tail()).accept(this);
  450. }
  451. Arrays.sort(pairs);
  452. int pc = opcodePc2 + 8;
  453. for (int i = 0; i < npairs; ++i) {
  454. bytecode.write32bit(pc, (int)(pairs[i] >>> 32));
  455. bytecode.write32bit(pc + 4, (int)pairs[i]);
  456. pc += 8;
  457. }
  458. if (defaultPc < 0 || breakList.size() > 0)
  459. hasReturned = false;
  460. int endPc = bytecode.currentPc();
  461. if (defaultPc < 0)
  462. defaultPc = endPc;
  463. bytecode.write32bit(opcodePc2, defaultPc - opcodePc);
  464. patchGoto(breakList, endPc);
  465. breakList = prevBreakList;
  466. }
  467. private int computeLabel(ASTree expr) throws CompileError {
  468. doTypeCheck(expr);
  469. expr = TypeChecker.stripPlusExpr(expr);
  470. if (expr instanceof IntConst)
  471. return (int)((IntConst)expr).get();
  472. else
  473. throw new CompileError("bad case label");
  474. }
  475. private void atBreakStmnt(Stmnt st, boolean notCont)
  476. throws CompileError
  477. {
  478. if (st.head() != null)
  479. throw new CompileError(
  480. "sorry, not support labeled break or continue");
  481. bytecode.addOpcode(Opcode.GOTO);
  482. Integer pc = new Integer(bytecode.currentPc());
  483. bytecode.addIndex(0);
  484. if (notCont)
  485. breakList.add(pc);
  486. else
  487. continueList.add(pc);
  488. }
  489. protected void atReturnStmnt(Stmnt st) throws CompileError {
  490. atReturnStmnt2(st.getLeft());
  491. }
  492. protected final void atReturnStmnt2(ASTree result) throws CompileError {
  493. int op;
  494. if (result == null)
  495. op = Opcode.RETURN;
  496. else {
  497. compileExpr(result);
  498. if (arrayDim > 0)
  499. op = ARETURN;
  500. else {
  501. int type = exprType;
  502. if (type == DOUBLE)
  503. op = DRETURN;
  504. else if (type == FLOAT)
  505. op = FRETURN;
  506. else if (type == LONG)
  507. op = LRETURN;
  508. else if (isRefType(type))
  509. op = ARETURN;
  510. else
  511. op = IRETURN;
  512. }
  513. }
  514. for (ReturnHook har = returnHooks; har != null; har = har.next)
  515. har.doit(bytecode, op);
  516. bytecode.addOpcode(op);
  517. hasReturned = true;
  518. }
  519. private void atThrowStmnt(Stmnt st) throws CompileError {
  520. ASTree e = st.getLeft();
  521. compileExpr(e);
  522. if (exprType != CLASS || arrayDim > 0)
  523. throw new CompileError("bad throw statement");
  524. bytecode.addOpcode(ATHROW);
  525. hasReturned = true;
  526. }
  527. /* overridden in MemberCodeGen
  528. */
  529. protected void atTryStmnt(Stmnt st) throws CompileError {
  530. hasReturned = false;
  531. }
  532. private void atSyncStmnt(Stmnt st) throws CompileError {
  533. int nbreaks = getListSize(breakList);
  534. int ncontinues = getListSize(continueList);
  535. compileExpr(st.head());
  536. if (exprType != CLASS && arrayDim == 0)
  537. throw new CompileError("bad type expr for synchronized block");
  538. Bytecode bc = bytecode;
  539. final int var = bc.getMaxLocals();
  540. bc.incMaxLocals(1);
  541. bc.addOpcode(DUP);
  542. bc.addAstore(var);
  543. bc.addOpcode(MONITORENTER);
  544. ReturnHook rh = new ReturnHook(this) {
  545. protected void doit(Bytecode b, int opcode) {
  546. b.addAload(var);
  547. b.addOpcode(MONITOREXIT);
  548. }
  549. };
  550. int pc = bc.currentPc();
  551. Stmnt body = (Stmnt)st.tail();
  552. if (body != null)
  553. body.accept(this);
  554. int pc2 = bc.currentPc();
  555. int pc3 = 0;
  556. if (!hasReturned) {
  557. rh.doit(bc, 0); // the 2nd arg is ignored.
  558. bc.addOpcode(Opcode.GOTO);
  559. pc3 = bc.currentPc();
  560. bc.addIndex(0);
  561. }
  562. int pc4 = bc.currentPc();
  563. rh.doit(bc, 0); // the 2nd arg is ignored.
  564. bc.addOpcode(ATHROW);
  565. bc.addExceptionHandler(pc, pc2, pc4, 0);
  566. if (!hasReturned)
  567. bc.write16bit(pc3, bc.currentPc() - pc3 + 1);
  568. rh.remove(this);
  569. if (getListSize(breakList) != nbreaks
  570. || getListSize(continueList) != ncontinues)
  571. throw new CompileError(
  572. "sorry, cannot break/continue in synchronized block");
  573. }
  574. private static int getListSize(ArrayList list) {
  575. return list == null ? 0 : list.size();
  576. }
  577. private static boolean isPlusPlusExpr(ASTree expr) {
  578. if (expr instanceof Expr) {
  579. int op = ((Expr)expr).getOperator();
  580. return op == PLUSPLUS || op == MINUSMINUS;
  581. }
  582. return false;
  583. }
  584. public void atDeclarator(Declarator d) throws CompileError {
  585. d.setLocalVar(getMaxLocals());
  586. d.setClassName(resolveClassName(d.getClassName()));
  587. int size;
  588. if (is2word(d.getType(), d.getArrayDim()))
  589. size = 2;
  590. else
  591. size = 1;
  592. incMaxLocals(size);
  593. /* NOTE: Array initializers has not been supported.
  594. */
  595. ASTree init = d.getInitializer();
  596. if (init != null) {
  597. doTypeCheck(init);
  598. atVariableAssign(null, '=', null, d, init, false);
  599. }
  600. }
  601. public abstract void atNewExpr(NewExpr n) throws CompileError;
  602. public abstract void atArrayInit(ArrayInit init) throws CompileError;
  603. public void atAssignExpr(AssignExpr expr) throws CompileError {
  604. atAssignExpr(expr, true);
  605. }
  606. protected void atAssignExpr(AssignExpr expr, boolean doDup)
  607. throws CompileError
  608. {
  609. // =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, >>>=
  610. int op = expr.getOperator();
  611. ASTree left = expr.oprand1();
  612. ASTree right = expr.oprand2();
  613. if (left instanceof Variable)
  614. atVariableAssign(expr, op, (Variable)left,
  615. ((Variable)left).getDeclarator(),
  616. right, doDup);
  617. else {
  618. if (left instanceof Expr) {
  619. Expr e = (Expr)left;
  620. if (e.getOperator() == ARRAY) {
  621. atArrayAssign(expr, op, (Expr)left, right, doDup);
  622. return;
  623. }
  624. }
  625. atFieldAssign(expr, op, left, right, doDup);
  626. }
  627. }
  628. protected static void badAssign(Expr expr) throws CompileError {
  629. String msg;
  630. if (expr == null)
  631. msg = "incompatible type for assignment";
  632. else
  633. msg = "incompatible type for " + expr.getName();
  634. throw new CompileError(msg);
  635. }
  636. /* op is either =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, or >>>=.
  637. *
  638. * expr and var can be null.
  639. */
  640. private void atVariableAssign(Expr expr, int op, Variable var,
  641. Declarator d, ASTree right,
  642. boolean doDup) throws CompileError
  643. {
  644. int varType = d.getType();
  645. int varArray = d.getArrayDim();
  646. String varClass = d.getClassName();
  647. int varNo = getLocalVar(d);
  648. if (op != '=')
  649. atVariable(var);
  650. // expr is null if the caller is atDeclarator().
  651. if (expr == null && right instanceof ArrayInit)
  652. atArrayVariableAssign((ArrayInit)right, varType, varArray, varClass);
  653. else
  654. atAssignCore(expr, op, right, varType, varArray, varClass);
  655. if (doDup)
  656. if (is2word(varType, varArray))
  657. bytecode.addOpcode(DUP2);
  658. else
  659. bytecode.addOpcode(DUP);
  660. if (varArray > 0)
  661. bytecode.addAstore(varNo);
  662. else if (varType == DOUBLE)
  663. bytecode.addDstore(varNo);
  664. else if (varType == FLOAT)
  665. bytecode.addFstore(varNo);
  666. else if (varType == LONG)
  667. bytecode.addLstore(varNo);
  668. else if (isRefType(varType))
  669. bytecode.addAstore(varNo);
  670. else
  671. bytecode.addIstore(varNo);
  672. exprType = varType;
  673. arrayDim = varArray;
  674. className = varClass;
  675. }
  676. protected abstract void atArrayVariableAssign(ArrayInit init,
  677. int varType, int varArray, String varClass) throws CompileError;
  678. private void atArrayAssign(Expr expr, int op, Expr array,
  679. ASTree right, boolean doDup) throws CompileError
  680. {
  681. arrayAccess(array.oprand1(), array.oprand2());
  682. if (op != '=') {
  683. bytecode.addOpcode(DUP2);
  684. bytecode.addOpcode(getArrayReadOp(exprType, arrayDim));
  685. }
  686. int aType = exprType;
  687. int aDim = arrayDim;
  688. String cname = className;
  689. atAssignCore(expr, op, right, aType, aDim, cname);
  690. if (doDup)
  691. if (is2word(aType, aDim))
  692. bytecode.addOpcode(DUP2_X2);
  693. else
  694. bytecode.addOpcode(DUP_X2);
  695. bytecode.addOpcode(getArrayWriteOp(aType, aDim));
  696. exprType = aType;
  697. arrayDim = aDim;
  698. className = cname;
  699. }
  700. protected abstract void atFieldAssign(Expr expr, int op, ASTree left,
  701. ASTree right, boolean doDup) throws CompileError;
  702. protected void atAssignCore(Expr expr, int op, ASTree right,
  703. int type, int dim, String cname)
  704. throws CompileError
  705. {
  706. if (op == PLUS_E && dim == 0 && type == CLASS)
  707. atStringPlusEq(expr, type, dim, cname, right);
  708. else {
  709. right.accept(this);
  710. if (invalidDim(exprType, arrayDim, className, type, dim, cname,
  711. false) || (op != '=' && dim > 0))
  712. badAssign(expr);
  713. if (op != '=') {
  714. int token = assignOps[op - MOD_E];
  715. int k = lookupBinOp(token);
  716. if (k < 0)
  717. fatal();
  718. atArithBinExpr(expr, token, k, type);
  719. }
  720. }
  721. if (op != '=' || (dim == 0 && !isRefType(type)))
  722. atNumCastExpr(exprType, type);
  723. // type check should be done here.
  724. }
  725. private void atStringPlusEq(Expr expr, int type, int dim, String cname,
  726. ASTree right)
  727. throws CompileError
  728. {
  729. if (!jvmJavaLangString.equals(cname))
  730. badAssign(expr);
  731. convToString(type, dim); // the value might be null.
  732. right.accept(this);
  733. convToString(exprType, arrayDim);
  734. bytecode.addInvokevirtual(javaLangString, "concat",
  735. "(Ljava/lang/String;)Ljava/lang/String;");
  736. exprType = CLASS;
  737. arrayDim = 0;
  738. className = jvmJavaLangString;
  739. }
  740. private boolean invalidDim(int srcType, int srcDim, String srcClass,
  741. int destType, int destDim, String destClass,
  742. boolean isCast)
  743. {
  744. if (srcDim != destDim)
  745. if (srcType == NULL)
  746. return false;
  747. else if (destDim == 0 && destType == CLASS
  748. && jvmJavaLangObject.equals(destClass))
  749. return false;
  750. else if (isCast && srcDim == 0 && srcType == CLASS
  751. && jvmJavaLangObject.equals(srcClass))
  752. return false;
  753. else
  754. return true;
  755. return false;
  756. }
  757. public void atCondExpr(CondExpr expr) throws CompileError {
  758. booleanExpr(false, expr.condExpr());
  759. int pc = bytecode.currentPc();
  760. bytecode.addIndex(0); // correct later
  761. expr.thenExpr().accept(this);
  762. int dim1 = arrayDim;
  763. bytecode.addOpcode(Opcode.GOTO);
  764. int pc2 = bytecode.currentPc();
  765. bytecode.addIndex(0);
  766. bytecode.write16bit(pc, bytecode.currentPc() - pc + 1);
  767. expr.elseExpr().accept(this);
  768. if (dim1 != arrayDim)
  769. throw new CompileError("type mismatch in ?:");
  770. bytecode.write16bit(pc2, bytecode.currentPc() - pc2 + 1);
  771. }
  772. static final int[] binOp = {
  773. '+', DADD, FADD, LADD, IADD,
  774. '-', DSUB, FSUB, LSUB, ISUB,
  775. '*', DMUL, FMUL, LMUL, IMUL,
  776. '/', DDIV, FDIV, LDIV, IDIV,
  777. '%', DREM, FREM, LREM, IREM,
  778. '|', NOP, NOP, LOR, IOR,
  779. '^', NOP, NOP, LXOR, IXOR,
  780. '&', NOP, NOP, LAND, IAND,
  781. LSHIFT, NOP, NOP, LSHL, ISHL,
  782. RSHIFT, NOP, NOP, LSHR, ISHR,
  783. ARSHIFT, NOP, NOP, LUSHR, IUSHR };
  784. static int lookupBinOp(int token) {
  785. int[] code = binOp;
  786. int s = code.length;
  787. for (int k = 0; k < s; k = k + 5)
  788. if (code[k] == token)
  789. return k;
  790. return -1;
  791. }
  792. public void atBinExpr(BinExpr expr) throws CompileError {
  793. int token = expr.getOperator();
  794. /* arithmetic operators: +, -, *, /, %, |, ^, &, <<, >>, >>>
  795. */
  796. int k = lookupBinOp(token);
  797. if (k >= 0) {
  798. expr.oprand1().accept(this);
  799. ASTree right = expr.oprand2();
  800. if (right == null)
  801. return; // see TypeChecker.atBinExpr().
  802. int type1 = exprType;
  803. int dim1 = arrayDim;
  804. String cname1 = className;
  805. right.accept(this);
  806. if (dim1 != arrayDim)
  807. throw new CompileError("incompatible array types");
  808. if (token == '+' && dim1 == 0
  809. && (type1 == CLASS || exprType == CLASS))
  810. atStringConcatExpr(expr, type1, dim1, cname1);
  811. else
  812. atArithBinExpr(expr, token, k, type1);
  813. }
  814. else {
  815. /* equation: &&, ||, ==, !=, <=, >=, <, >
  816. */
  817. booleanExpr(true, expr);
  818. bytecode.addIndex(7);
  819. bytecode.addIconst(0); // false
  820. bytecode.addOpcode(Opcode.GOTO);
  821. bytecode.addIndex(4);
  822. bytecode.addIconst(1); // true
  823. }
  824. }
  825. /* arrayDim values of the two oprands must be equal.
  826. * If an oprand type is not a numeric type, this method
  827. * throws an exception.
  828. */
  829. private void atArithBinExpr(Expr expr, int token,
  830. int index, int type1) throws CompileError
  831. {
  832. if (arrayDim != 0)
  833. badTypes(expr);
  834. int type2 = exprType;
  835. if (token == LSHIFT || token == RSHIFT || token == ARSHIFT)
  836. if (type2 == INT || type2 == SHORT
  837. || type2 == CHAR || type2 == BYTE)
  838. exprType = type1;
  839. else
  840. badTypes(expr);
  841. else
  842. convertOprandTypes(type1, type2, expr);
  843. int p = typePrecedence(exprType);
  844. if (p >= 0) {
  845. int op = binOp[index + p + 1];
  846. if (op != NOP) {
  847. if (p == P_INT && exprType != BOOLEAN)
  848. exprType = INT; // type1 may be BYTE, ...
  849. bytecode.addOpcode(op);
  850. return;
  851. }
  852. }
  853. badTypes(expr);
  854. }
  855. private void atStringConcatExpr(Expr expr, int type1, int dim1,
  856. String cname1) throws CompileError
  857. {
  858. int type2 = exprType;
  859. int dim2 = arrayDim;
  860. boolean type2Is2 = is2word(type2, dim2);
  861. boolean type2IsString
  862. = (type2 == CLASS && jvmJavaLangString.equals(className));
  863. if (type2Is2)
  864. convToString(type2, dim2);
  865. if (is2word(type1, dim1)) {
  866. bytecode.addOpcode(DUP_X2);
  867. bytecode.addOpcode(POP);
  868. }
  869. else
  870. bytecode.addOpcode(SWAP);
  871. // even if type1 is String, the left operand might be null.
  872. convToString(type1, dim1);
  873. bytecode.addOpcode(SWAP);
  874. if (!type2Is2 && !type2IsString)
  875. convToString(type2, dim2);
  876. bytecode.addInvokevirtual(javaLangString, "concat",
  877. "(Ljava/lang/String;)Ljava/lang/String;");
  878. exprType = CLASS;
  879. arrayDim = 0;
  880. className = jvmJavaLangString;
  881. }
  882. private void convToString(int type, int dim) throws CompileError {
  883. final String method = "valueOf";
  884. if (isRefType(type) || dim > 0)
  885. bytecode.addInvokestatic(javaLangString, method,
  886. "(Ljava/lang/Object;)Ljava/lang/String;");
  887. else if (type == DOUBLE)
  888. bytecode.addInvokestatic(javaLangString, method,
  889. "(D)Ljava/lang/String;");
  890. else if (type == FLOAT)
  891. bytecode.addInvokestatic(javaLangString, method,
  892. "(F)Ljava/lang/String;");
  893. else if (type == LONG)
  894. bytecode.addInvokestatic(javaLangString, method,
  895. "(J)Ljava/lang/String;");
  896. else if (type == BOOLEAN)
  897. bytecode.addInvokestatic(javaLangString, method,
  898. "(Z)Ljava/lang/String;");
  899. else if (type == CHAR)
  900. bytecode.addInvokestatic(javaLangString, method,
  901. "(C)Ljava/lang/String;");
  902. else if (type == VOID)
  903. throw new CompileError("void type expression");
  904. else /* INT, BYTE, SHORT */
  905. bytecode.addInvokestatic(javaLangString, method,
  906. "(I)Ljava/lang/String;");
  907. }
  908. /* Produces the opcode to branch if the condition is true.
  909. * The oprand is not produced.
  910. *
  911. * @return true if the compiled code is GOTO (always branch).
  912. */
  913. private boolean booleanExpr(boolean branchIf, ASTree expr)
  914. throws CompileError
  915. {
  916. boolean isAndAnd;
  917. int op = getCompOperator(expr);
  918. if (op == EQ) { // ==, !=, ...
  919. BinExpr bexpr = (BinExpr)expr;
  920. int type1 = compileOprands(bexpr);
  921. // here, arrayDim might represent the array dim. of the left oprand
  922. // if the right oprand is NULL.
  923. compareExpr(branchIf, bexpr.getOperator(), type1, bexpr);
  924. }
  925. else if (op == '!')
  926. booleanExpr(!branchIf, ((Expr)expr).oprand1());
  927. else if ((isAndAnd = (op == ANDAND)) || op == OROR) {
  928. BinExpr bexpr = (BinExpr)expr;
  929. booleanExpr(!isAndAnd, bexpr.oprand1());
  930. int pc = bytecode.currentPc();
  931. bytecode.addIndex(0); // correct later
  932. booleanExpr(isAndAnd, bexpr.oprand2());
  933. bytecode.write16bit(pc, bytecode.currentPc() - pc + 3);
  934. if (branchIf != isAndAnd) {
  935. bytecode.addIndex(6); // skip GOTO instruction
  936. bytecode.addOpcode(Opcode.GOTO);
  937. }
  938. }
  939. else if (isAlwaysBranch(expr, branchIf)) {
  940. bytecode.addOpcode(Opcode.GOTO);
  941. return true; // always branch
  942. }
  943. else { // others
  944. expr.accept(this);
  945. if (exprType != BOOLEAN || arrayDim != 0)
  946. throw new CompileError("boolean expr is required");
  947. bytecode.addOpcode(branchIf ? IFNE : IFEQ);
  948. }
  949. exprType = BOOLEAN;
  950. arrayDim = 0;
  951. return false;
  952. }
  953. private static boolean isAlwaysBranch(ASTree expr, boolean branchIf) {
  954. if (expr instanceof Keyword) {
  955. int t = ((Keyword)expr).get();
  956. return branchIf ? t == TRUE : t == FALSE;
  957. }
  958. return false;
  959. }
  960. static int getCompOperator(ASTree expr) throws CompileError {
  961. if (expr instanceof Expr) {
  962. Expr bexpr = (Expr)expr;
  963. int token = bexpr.getOperator();
  964. if (token == '!')
  965. return '!';
  966. else if ((bexpr instanceof BinExpr)
  967. && token != OROR && token != ANDAND
  968. && token != '&' && token != '|')
  969. return EQ; // ==, !=, ...
  970. else
  971. return token;
  972. }
  973. return ' '; // others
  974. }
  975. private int compileOprands(BinExpr expr) throws CompileError {
  976. expr.oprand1().accept(this);
  977. int type1 = exprType;
  978. int dim1 = arrayDim;
  979. expr.oprand2().accept(this);
  980. if (dim1 != arrayDim)
  981. if (type1 != NULL && exprType != NULL)
  982. throw new CompileError("incompatible array types");
  983. else if (exprType == NULL)
  984. arrayDim = dim1;
  985. if (type1 == NULL)
  986. return exprType;
  987. else
  988. return type1;
  989. }
  990. private static final int ifOp[] = { EQ, IF_ICMPEQ, IF_ICMPNE,
  991. NEQ, IF_ICMPNE, IF_ICMPEQ,
  992. LE, IF_ICMPLE, IF_ICMPGT,
  993. GE, IF_ICMPGE, IF_ICMPLT,
  994. '<', IF_ICMPLT, IF_ICMPGE,
  995. '>', IF_ICMPGT, IF_ICMPLE };
  996. private static final int ifOp2[] = { EQ, IFEQ, IFNE,
  997. NEQ, IFNE, IFEQ,
  998. LE, IFLE, IFGT,
  999. GE, IFGE, IFLT,
  1000. '<', IFLT, IFGE,
  1001. '>', IFGT, IFLE };
  1002. /* Produces the opcode to branch if the condition is true.
  1003. * The oprands are not produced.
  1004. *
  1005. * Parameter expr - compare expression ==, !=, <=, >=, <, >
  1006. */
  1007. private void compareExpr(boolean branchIf,
  1008. int token, int type1, BinExpr expr)
  1009. throws CompileError
  1010. {
  1011. if (arrayDim == 0)
  1012. convertOprandTypes(type1, exprType, expr);
  1013. int p = typePrecedence(exprType);
  1014. if (p == P_OTHER || arrayDim > 0)
  1015. if (token == EQ)
  1016. bytecode.addOpcode(branchIf ? IF_ACMPEQ : IF_ACMPNE);
  1017. else if (token == NEQ)
  1018. bytecode.addOpcode(branchIf ? IF_ACMPNE : IF_ACMPEQ);
  1019. else
  1020. badTypes(expr);
  1021. else
  1022. if (p == P_INT) {
  1023. int op[] = ifOp;
  1024. for (int i = 0; i < op.length; i += 3)
  1025. if (op[i] == token) {
  1026. bytecode.addOpcode(op[i + (branchIf ? 1 : 2)]);
  1027. return;
  1028. }
  1029. badTypes(expr);
  1030. }
  1031. else {
  1032. if (p == P_DOUBLE)
  1033. if (token == '<' || token == LE)
  1034. bytecode.addOpcode(DCMPG);
  1035. else
  1036. bytecode.addOpcode(DCMPL);
  1037. else if (p == P_FLOAT)
  1038. if (token == '<' || token == LE)
  1039. bytecode.addOpcode(FCMPG);
  1040. else
  1041. bytecode.addOpcode(FCMPL);
  1042. else if (p == P_LONG)
  1043. bytecode.addOpcode(LCMP); // 1: >, 0: =, -1: <
  1044. else
  1045. fatal();
  1046. int[] op = ifOp2;
  1047. for (int i = 0; i < op.length; i += 3)
  1048. if (op[i] == token) {
  1049. bytecode.addOpcode(op[i + (branchIf ? 1 : 2)]);
  1050. return;
  1051. }
  1052. badTypes(expr);
  1053. }
  1054. }
  1055. protected static void badTypes(Expr expr) throws CompileError {
  1056. throw new CompileError("invalid types for " + expr.getName());
  1057. }
  1058. private static final int P_DOUBLE = 0;
  1059. private static final int P_FLOAT = 1;
  1060. private static final int P_LONG = 2;
  1061. private static final int P_INT = 3;
  1062. private static final int P_OTHER = -1;
  1063. protected static boolean isRefType(int type) {
  1064. return type == CLASS || type == NULL;
  1065. }
  1066. private static int typePrecedence(int type) {
  1067. if (type == DOUBLE)
  1068. return P_DOUBLE;
  1069. else if (type == FLOAT)
  1070. return P_FLOAT;
  1071. else if (type == LONG)
  1072. return P_LONG;
  1073. else if (isRefType(type))
  1074. return P_OTHER;
  1075. else if (type == VOID)
  1076. return P_OTHER; // this is wrong, but ...
  1077. else
  1078. return P_INT; // BOOLEAN, BYTE, CHAR, SHORT, INT
  1079. }
  1080. // used in TypeChecker.
  1081. static boolean isP_INT(int type) {
  1082. return typePrecedence(type) == P_INT;
  1083. }
  1084. // used in TypeChecker.
  1085. static boolean rightIsStrong(int type1, int type2) {
  1086. int type1_p = typePrecedence(type1);
  1087. int type2_p = typePrecedence(type2);
  1088. return type1_p >= 0 && type2_p >= 0 && type1_p > type2_p;
  1089. }
  1090. private static final int[] castOp = {
  1091. /* D F L I */
  1092. /* double */ NOP, D2F, D2L, D2I,
  1093. /* float */ F2D, NOP, F2L, F2I,
  1094. /* long */ L2D, L2F, NOP, L2I,
  1095. /* other */ I2D, I2F, I2L, NOP };
  1096. /* do implicit type conversion.
  1097. * arrayDim values of the two oprands must be zero.
  1098. */
  1099. private void convertOprandTypes(int type1, int type2, Expr expr)
  1100. throws CompileError
  1101. {
  1102. boolean rightStrong;
  1103. int type1_p = typePrecedence(type1);
  1104. int type2_p = typePrecedence(type2);
  1105. if (type2_p < 0 && type1_p < 0) // not primitive types
  1106. return;
  1107. if (type2_p < 0 || type1_p < 0) // either is not a primitive type
  1108. badTypes(expr);
  1109. int op, result_type;
  1110. if (type1_p <= type2_p) {
  1111. rightStrong = false;
  1112. exprType = type1;
  1113. op = castOp[type2_p * 4 + type1_p];
  1114. result_type = type1_p;
  1115. }
  1116. else {
  1117. rightStrong = true;
  1118. op = castOp[type1_p * 4 + type2_p];
  1119. result_type = type2_p;
  1120. }
  1121. if (rightStrong) {
  1122. if (result_type == P_DOUBLE || result_type == P_LONG) {
  1123. if (type1_p == P_DOUBLE || type1_p == P_LONG)
  1124. bytecode.addOpcode(DUP2_X2);
  1125. else
  1126. bytecode.addOpcode(DUP2_X1);
  1127. bytecode.addOpcode(POP2);
  1128. bytecode.addOpcode(op);
  1129. bytecode.addOpcode(DUP2_X2);
  1130. bytecode.addOpcode(POP2);
  1131. }
  1132. else if (result_type == P_FLOAT) {
  1133. if (type1_p == P_LONG) {
  1134. bytecode.addOpcode(DUP_X2);
  1135. bytecode.addOpcode(POP);
  1136. }
  1137. else
  1138. bytecode.addOpcode(SWAP);
  1139. bytecode.addOpcode(op);
  1140. bytecode.addOpcode(SWAP);
  1141. }
  1142. else
  1143. fatal();
  1144. }
  1145. else if (op != NOP)
  1146. bytecode.addOpcode(op);
  1147. }
  1148. public void atCastExpr(CastExpr expr) throws CompileError {
  1149. String cname = resolveClassName(expr.getClassName());
  1150. String toClass = checkCastExpr(expr, cname);
  1151. int srcType = exprType;
  1152. exprType = expr.getType();
  1153. arrayDim = expr.getArrayDim();
  1154. className = cname;
  1155. if (toClass == null)
  1156. atNumCastExpr(srcType, exprType); // built-in type
  1157. else
  1158. bytecode.addCheckcast(toClass);
  1159. }
  1160. public void atInstanceOfExpr(InstanceOfExpr expr) throws CompileError {
  1161. String cname = resolveClassName(expr.getClassName());
  1162. String toClass = checkCastExpr(expr, cname);
  1163. bytecode.addInstanceof(toClass);
  1164. exprType = BOOLEAN;
  1165. arrayDim = 0;
  1166. }
  1167. private String checkCastExpr(CastExpr expr, String name)
  1168. throws CompileError
  1169. {
  1170. final String msg = "invalid cast";
  1171. ASTree oprand = expr.getOprand();
  1172. int dim = expr.getArrayDim();
  1173. int type = expr.getType();
  1174. oprand.accept(this);
  1175. int srcType = exprType;
  1176. if (invalidDim(srcType, arrayDim, className, type, dim, name, true)
  1177. || srcType == VOID || type == VOID)
  1178. throw new CompileError(msg);
  1179. if (type == CLASS) {
  1180. if (!isRefType(srcType))
  1181. throw new CompileError(msg);
  1182. return toJvmArrayName(name, dim);
  1183. }
  1184. else
  1185. if (dim > 0)
  1186. return toJvmTypeName(type, dim);
  1187. else
  1188. return null; // built-in type
  1189. }
  1190. void atNumCastExpr(int srcType, int destType)
  1191. throws CompileError
  1192. {
  1193. if (srcType == destType)
  1194. return;
  1195. int op, op2;
  1196. int stype = typePrecedence(srcType);
  1197. int dtype = typePrecedence(destType);
  1198. if (0 <= stype && stype < 3)
  1199. op = castOp[stype * 4 + dtype];
  1200. else
  1201. op = NOP;
  1202. if (destType == DOUBLE)
  1203. op2 = I2D;
  1204. else if (destType == FLOAT)
  1205. op2 = I2F;
  1206. else if (destType == LONG)
  1207. op2 = I2L;
  1208. else if (destType == SHORT)
  1209. op2 = I2S;
  1210. else if (destType == CHAR)
  1211. op2 = I2C;
  1212. else if (destType == BYTE)
  1213. op2 = I2B;
  1214. else
  1215. op2 = NOP;
  1216. if (op != NOP)
  1217. bytecode.addOpcode(op);
  1218. if (op == NOP || op == L2I || op == F2I || op == D2I)
  1219. if (op2 != NOP)
  1220. bytecode.addOpcode(op2);
  1221. }
  1222. public void atExpr(Expr expr) throws CompileError {
  1223. // array access, member access,
  1224. // (unary) +, (unary) -, ++, --, !, ~
  1225. int token = expr.getOperator();
  1226. ASTree oprand = expr.oprand1();
  1227. if (token == '.') {
  1228. String member = ((Symbol)expr.oprand2()).get();
  1229. if (member.equals("class"))
  1230. atClassObject(expr); // .class
  1231. else
  1232. atFieldRead(expr);
  1233. }
  1234. else if (token == MEMBER) { // field read
  1235. /* MEMBER ('#') is an extension by Javassist.
  1236. * The compiler internally uses # for compiling .class
  1237. * expressions such as "int.class".
  1238. */
  1239. atFieldRead(expr);
  1240. }
  1241. else if (token == ARRAY)
  1242. atArrayRead(oprand, expr.oprand2());
  1243. else if (token == PLUSPLUS || token == MINUSMINUS)
  1244. atPlusPlus(token, oprand, expr, true);
  1245. else if (token == '!') {
  1246. booleanExpr(false, expr);
  1247. bytecode.addIndex(7);
  1248. bytecode.addIconst(1);
  1249. bytecode.addOpcode(Opcode.GOTO);
  1250. bytecode.addIndex(4);
  1251. bytecode.addIconst(0);
  1252. }
  1253. else if (token == CALL) // method call
  1254. fatal();
  1255. else {
  1256. expr.oprand1().accept(this);
  1257. int type = typePrecedence(exprType);
  1258. if (arrayDim > 0)
  1259. badType(expr);
  1260. if (token == '-') {
  1261. if (type == P_DOUBLE)
  1262. bytecode.addOpcode(DNEG);
  1263. else if (type == P_FLOAT)
  1264. bytecode.addOpcode(FNEG);
  1265. else if (type == P_LONG)
  1266. bytecode.addOpcode(LNEG);
  1267. else if (type == P_INT) {
  1268. bytecode.addOpcode(INEG);
  1269. exprType = INT; // type may be BYTE, ...
  1270. }
  1271. else
  1272. badType(expr);
  1273. }
  1274. else if (token == '~') {
  1275. if (type == P_INT) {
  1276. bytecode.addIconst(-1);
  1277. bytecode.addOpcode(IXOR);
  1278. exprType = INT; // type may be BYTE. ...
  1279. }
  1280. else if (type == P_LONG) {
  1281. bytecode.addLconst(-1);
  1282. bytecode.addOpcode(LXOR);
  1283. }
  1284. else
  1285. badType(expr);
  1286. }
  1287. else if (token == '+') {
  1288. if (type == P_OTHER)
  1289. badType(expr);
  1290. // do nothing. ignore.
  1291. }
  1292. else
  1293. fatal();
  1294. }
  1295. }
  1296. protected static void badType(Expr expr) throws CompileError {
  1297. throw new CompileError("invalid type for " + expr.getName());
  1298. }
  1299. public abstract void atCallExpr(CallExpr expr) throws CompileError;
  1300. protected abstract void atFieldRead(ASTree expr) throws CompileError;
  1301. public void atClassObject(Expr expr) throws CompileError {
  1302. ASTree op1 = expr.oprand1();
  1303. if (!(op1 instanceof Symbol))
  1304. throw new CompileError("fatal error: badly parsed .class expr");
  1305. String cname = ((Symbol)op1).get();
  1306. if (cname.startsWith("[")) {
  1307. int i = cname.indexOf("[L");
  1308. if (i >= 0) {
  1309. String name = cname.substring(i + 2, cname.length() - 1);
  1310. String name2 = resolveClassName(name);
  1311. if (!name.equals(name2)) {
  1312. /* For example, to obtain String[].class,
  1313. * "[Ljava.lang.String;" (not "[Ljava/lang/String"!)
  1314. * must be passed to Class.forName().
  1315. */
  1316. name2 = MemberResolver.jvmToJavaName(name2);
  1317. StringBuffer sbuf = new StringBuffer();
  1318. while (i-- >= 0)
  1319. sbuf.append('[');
  1320. sbuf.append('L').append(name2).append(';');
  1321. cname = sbuf.toString();
  1322. }
  1323. }
  1324. }
  1325. else {
  1326. cname = resolveClassName(MemberResolver.javaToJvmName(cname));
  1327. cname = MemberResolver.jvmToJavaName(cname);
  1328. }
  1329. int start = bytecode.currentPc();
  1330. bytecode.addLdc(cname);
  1331. bytecode.addInvokestatic("java.lang.Class", "forName",
  1332. "(Ljava/lang/String;)Ljava/lang/Class;");
  1333. int end = bytecode.currentPc();
  1334. bytecode.addOpcode(Opcode.GOTO);
  1335. int pc = bytecode.currentPc();
  1336. bytecode.addIndex(0); // correct later
  1337. bytecode.addExceptionHandler(start, end, bytecode.currentPc(),
  1338. "java.lang.ClassNotFoundException");
  1339. /* -- the following code is for inlining a call to DotClass.fail().
  1340. int var = getMaxLocals();
  1341. incMaxLocals(1);
  1342. bytecode.growStack(1);
  1343. bytecode.addAstore(var);
  1344. bytecode.addNew("java.lang.NoClassDefFoundError");
  1345. bytecode.addOpcode(DUP);
  1346. bytecode.addAload(var);
  1347. bytecode.addInvokevirtual("java.lang.ClassNotFoundException",
  1348. "getMessage", "()Ljava/lang/String;");
  1349. bytecode.addInvokespecial("java.lang.NoClassDefFoundError", "<init>",
  1350. "(Ljava/lang/String;)V");
  1351. */
  1352. bytecode.growStack(1);
  1353. bytecode.addInvokestatic("javassist.runtime.DotClass", "fail",
  1354. "(Ljava/lang/ClassNotFoundException;)"
  1355. + "Ljava/lang/NoClassDefFoundError;");
  1356. bytecode.addOpcode(ATHROW);
  1357. bytecode.write16bit(pc, bytecode.currentPc() - pc + 1);
  1358. exprType = CLASS;
  1359. arrayDim = 0;
  1360. className = "java/lang/Class";
  1361. }
  1362. public void atArrayRead(ASTree array, ASTree index)
  1363. throws CompileError
  1364. {
  1365. arrayAccess(array, index);
  1366. bytecode.addOpcode(getArrayReadOp(exprType, arrayDim));
  1367. }
  1368. protected void arrayAccess(ASTree array, ASTree index)
  1369. throws CompileError
  1370. {
  1371. array.accept(this);
  1372. int type = exprType;
  1373. int dim = arrayDim;
  1374. if (dim == 0)
  1375. throw new CompileError("bad array access");
  1376. String cname = className;
  1377. index.accept(this);
  1378. if (typePrecedence(exprType) != P_INT || arrayDim > 0)
  1379. throw new CompileError("bad array index");
  1380. exprType = type;
  1381. arrayDim = dim - 1;
  1382. className = cname;
  1383. }
  1384. protected static int getArrayReadOp(int type, int dim) {
  1385. if (dim > 0)
  1386. return AALOAD;
  1387. switch (type) {
  1388. case DOUBLE :
  1389. return DALOAD;
  1390. case FLOAT :
  1391. return FALOAD;
  1392. case LONG :
  1393. return LALOAD;
  1394. case INT :
  1395. return IALOAD;
  1396. case SHORT :
  1397. return SALOAD;
  1398. case CHAR :
  1399. return CALOAD;
  1400. case BYTE :
  1401. case BOOLEAN :
  1402. return BALOAD;
  1403. default :
  1404. return AALOAD;
  1405. }
  1406. }
  1407. protected static int getArrayWriteOp(int type, int dim) {
  1408. if (dim > 0)
  1409. return AASTORE;
  1410. switch (type) {
  1411. case DOUBLE :
  1412. return DASTORE;
  1413. case FLOAT :
  1414. return FASTORE;
  1415. case LONG :
  1416. return LASTORE;
  1417. case INT :
  1418. return IASTORE;
  1419. case CHAR :
  1420. return CASTORE;
  1421. case BYTE :
  1422. case BOOLEAN :
  1423. return BASTORE;
  1424. default :
  1425. return AASTORE;
  1426. }
  1427. }
  1428. private void atPlusPlus(int token, ASTree oprand, Expr expr,
  1429. boolean doDup) throws CompileError
  1430. {
  1431. boolean isPost = oprand == null; // ++i or i++?
  1432. if (isPost)
  1433. oprand = expr.oprand2();
  1434. if (oprand instanceof Variable) {
  1435. Declarator d = ((Variable)oprand).getDeclarator();
  1436. int t = exprType = d.getType();
  1437. arrayDim = d.getArrayDim();
  1438. int var = getLocalVar(d);
  1439. if (arrayDim > 0)
  1440. badType(expr);
  1441. if (t == DOUBLE) {
  1442. bytecode.addDload(var);
  1443. if (doDup && isPost)
  1444. bytecode.addOpcode(DUP2);
  1445. bytecode.addDconst(1.0);
  1446. bytecode.addOpcode(token == PLUSPLUS ? DADD : DSUB);
  1447. if (doDup && !isPost)
  1448. bytecode.addOpcode(DUP2);
  1449. bytecode.addDstore(var);
  1450. }
  1451. else if (t == LONG) {
  1452. bytecode.addLload(var);
  1453. if (doDup && isPost)
  1454. bytecode.addOpcode(DUP2);
  1455. bytecode.addLconst((long)1);
  1456. bytecode.addOpcode(token == PLUSPLUS ? LADD : LSUB);
  1457. if (doDup && !isPost)
  1458. bytecode.addOpcode(DUP2);
  1459. bytecode.addLstore(var);
  1460. }
  1461. else if (t == FLOAT) {
  1462. bytecode.addFload(var);
  1463. if (doDup && isPost)
  1464. bytecode.addOpcode(DUP);
  1465. bytecode.addFconst(1.0f);
  1466. bytecode.addOpcode(token == PLUSPLUS ? FADD : FSUB);
  1467. if (doDup && !isPost)
  1468. bytecode.addOpcode(DUP);
  1469. bytecode.addFstore(var);
  1470. }
  1471. else if (t == BYTE || t == CHAR || t == SHORT || t == INT) {
  1472. if (doDup && isPost)
  1473. bytecode.addIload(var);
  1474. bytecode.addOpcode(IINC);
  1475. bytecode.add(var);
  1476. bytecode.add(token == PLUSPLUS ? 1 : -1);
  1477. if (doDup && !isPost)
  1478. bytecode.addIload(var);
  1479. }
  1480. else
  1481. badType(expr);
  1482. }
  1483. else {
  1484. if (oprand instanceof Expr) {
  1485. Expr e = (Expr)oprand;
  1486. if (e.getOperator() == ARRAY) {
  1487. atArrayPlusPlus(token, isPost, e, doDup);
  1488. return;
  1489. }
  1490. }
  1491. atFieldPlusPlus(token, isPost, oprand, expr, doDup);
  1492. }
  1493. }
  1494. public void atArrayPlusPlus(int token, boolean isPost,
  1495. Expr expr, boolean doDup) throws CompileError
  1496. {
  1497. arrayAccess(expr.oprand1(), expr.oprand2());
  1498. int t = exprType;
  1499. int dim = arrayDim;
  1500. if (dim > 0)
  1501. badType(expr);
  1502. bytecode.addOpcode(DUP2);
  1503. bytecode.addOpcode(getArrayReadOp(t, arrayDim));
  1504. int dup_code = is2word(t, dim) ? DUP2_X2 : DUP_X2;
  1505. atPlusPlusCore(dup_code, doDup, token, isPost, expr);
  1506. bytecode.addOpcode(getArrayWriteOp(t, dim));
  1507. }
  1508. protected void atPlusPlusCore(int dup_code, boolean doDup,
  1509. int token, boolean isPost,
  1510. Expr expr) throws CompileError
  1511. {
  1512. int t = exprType;
  1513. if (doDup && isPost)
  1514. bytecode.addOpcode(dup_code);
  1515. if (t == INT || t == BYTE || t == CHAR || t == SHORT) {
  1516. bytecode.addIconst(1);
  1517. bytecode.addOpcode(token == PLUSPLUS ? IADD : ISUB);
  1518. exprType = INT;
  1519. }
  1520. else if (t == LONG) {
  1521. bytecode.addLconst((long)1);
  1522. bytecode.addOpcode(token == PLUSPLUS ? LADD : LSUB);
  1523. }
  1524. else if (t == FLOAT) {
  1525. bytecode.addFconst(1.0f);
  1526. bytecode.addOpcode(token == PLUSPLUS ? FADD : FSUB);
  1527. }
  1528. else if (t == DOUBLE) {
  1529. bytecode.addDconst(1.0);
  1530. bytecode.addOpcode(token == PLUSPLUS ? DADD : DSUB);
  1531. }
  1532. else
  1533. badType(expr);
  1534. if (doDup && !isPost)
  1535. bytecode.addOpcode(dup_code);
  1536. }
  1537. protected abstract void atFieldPlusPlus(int token, boolean isPost,
  1538. ASTree oprand, Expr expr, boolean doDup) throws CompileError;
  1539. public abstract void atMember(Member n) throws CompileError;
  1540. public void atVariable(Variable v) throws CompileError {
  1541. Declarator d = v.getDeclarator();
  1542. exprType = d.getType();
  1543. arrayDim = d.getArrayDim();
  1544. className = d.getClassName();
  1545. int var = getLocalVar(d);
  1546. if (arrayDim > 0)
  1547. bytecode.addAload(var);
  1548. else
  1549. switch (exprType) {
  1550. case CLASS :
  1551. bytecode.addAload(var);
  1552. break;
  1553. case LONG :
  1554. bytecode.addLload(var);
  1555. break;
  1556. case FLOAT :
  1557. bytecode.addFload(var);
  1558. break;
  1559. case DOUBLE :
  1560. bytecode.addDload(var);
  1561. break;
  1562. default : // BOOLEAN, BYTE, CHAR, SHORT, INT
  1563. bytecode.addIload(var);
  1564. break;
  1565. }
  1566. }
  1567. public void atKeyword(Keyword k) throws CompileError {
  1568. arrayDim = 0;
  1569. int token = k.get();
  1570. switch (token) {
  1571. case TRUE :
  1572. bytecode.addIconst(1);
  1573. exprType = BOOLEAN;
  1574. break;
  1575. case FALSE :
  1576. bytecode.addIconst(0);
  1577. exprType = BOOLEAN;
  1578. break;
  1579. case NULL :
  1580. bytecode.addOpcode(ACONST_NULL);
  1581. exprType = NULL;
  1582. break;
  1583. case THIS :
  1584. case SUPER :
  1585. if (inStaticMethod)
  1586. throw new CompileError("not-available: "
  1587. + (token == THIS ? "this" : "super"));
  1588. bytecode.addAload(0);
  1589. exprType = CLASS;
  1590. if (token == THIS)
  1591. className = getThisName();
  1592. else
  1593. className = getSuperName();
  1594. break;
  1595. default :
  1596. fatal();
  1597. }
  1598. }
  1599. public void atStringL(StringL s) throws CompileError {
  1600. exprType = CLASS;
  1601. arrayDim = 0;
  1602. className = jvmJavaLangString;
  1603. bytecode.addLdc(s.get());
  1604. }
  1605. public void atIntConst(IntConst i) throws CompileError {
  1606. arrayDim = 0;
  1607. long value = i.get();
  1608. int type = i.getType();
  1609. if (type == IntConstant || type == CharConstant) {
  1610. exprType = (type == IntConstant ? INT : CHAR);
  1611. bytecode.addIconst((int)value);
  1612. }
  1613. else {
  1614. exprType = LONG;
  1615. bytecode.addLconst(value);
  1616. }
  1617. }
  1618. public void atDoubleConst(DoubleConst d) throws CompileError {
  1619. arrayDim = 0;
  1620. if (d.getType() == DoubleConstant) {
  1621. exprType = DOUBLE;
  1622. bytecode.addDconst(d.get());
  1623. }
  1624. else {
  1625. exprType = FLOAT;
  1626. bytecode.addFconst((float)d.get());
  1627. }
  1628. }
  1629. }