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

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