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 59KB

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