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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2006 Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later.
  9. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. */
  15. package javassist.compiler;
  16. import javassist.CtClass;
  17. import javassist.CtPrimitiveType;
  18. import javassist.CtMember;
  19. import javassist.CtField;
  20. import javassist.CtBehavior;
  21. import javassist.CtMethod;
  22. import javassist.CtConstructor;
  23. import javassist.CannotCompileException;
  24. import javassist.Modifier;
  25. import javassist.bytecode.Bytecode;
  26. import javassist.bytecode.CodeAttribute;
  27. import javassist.bytecode.LocalVariableAttribute;
  28. import javassist.bytecode.Opcode;
  29. import javassist.NotFoundException;
  30. import javassist.compiler.ast.*;
  31. public class Javac {
  32. JvstCodeGen gen;
  33. SymbolTable stable;
  34. private Bytecode bytecode;
  35. public static final String param0Name = "$0";
  36. public static final String resultVarName = "$_";
  37. public static final String proceedName = "$proceed";
  38. /**
  39. * Constructs a compiler.
  40. *
  41. * @param thisClass the class that a compiled method/field
  42. * belongs to.
  43. */
  44. public Javac(CtClass thisClass) {
  45. this(new Bytecode(thisClass.getClassFile2().getConstPool(), 0, 0),
  46. thisClass);
  47. }
  48. /**
  49. * Constructs a compiler.
  50. * The produced bytecode is stored in the <code>Bytecode</code> object
  51. * specified by <code>b</code>.
  52. *
  53. * @param thisClass the class that a compiled method/field
  54. * belongs to.
  55. */
  56. public Javac(Bytecode b, CtClass thisClass) {
  57. gen = new JvstCodeGen(b, thisClass, thisClass.getClassPool());
  58. stable = new SymbolTable();
  59. bytecode = b;
  60. }
  61. /**
  62. * Returns the produced bytecode.
  63. */
  64. public Bytecode getBytecode() { return bytecode; }
  65. /**
  66. * Compiles a method, constructor, or field declaration
  67. * to a class.
  68. * A field declaration can declare only one field.
  69. *
  70. * <p>In a method or constructor body, $0, $1, ... and $_
  71. * are not available.
  72. *
  73. * @return a <code>CtMethod</code>, <code>CtConstructor</code>,
  74. * or <code>CtField</code> object.
  75. * @see #recordProceed(String,String)
  76. */
  77. public CtMember compile(String src) throws CompileError {
  78. Parser p = new Parser(new Lex(src));
  79. ASTList mem = p.parseMember1(stable);
  80. try {
  81. if (mem instanceof FieldDecl)
  82. return compileField((FieldDecl)mem);
  83. else
  84. return compileMethod(p, (MethodDecl)mem);
  85. }
  86. catch (CannotCompileException e) {
  87. throw new CompileError(e.getMessage());
  88. }
  89. }
  90. public static class CtFieldWithInit extends CtField {
  91. private ASTree init;
  92. CtFieldWithInit(CtClass type, String name, CtClass declaring)
  93. throws CannotCompileException
  94. {
  95. super(type, name, declaring);
  96. init = null;
  97. }
  98. protected void setInit(ASTree i) { init = i; }
  99. protected ASTree getInitAST() {
  100. return init;
  101. }
  102. }
  103. private CtField compileField(FieldDecl fd)
  104. throws CompileError, CannotCompileException
  105. {
  106. CtFieldWithInit f;
  107. Declarator d = fd.getDeclarator();
  108. f = new CtFieldWithInit(gen.resolver.lookupClass(d),
  109. d.getVariable().get(), gen.getThisClass());
  110. f.setModifiers(MemberResolver.getModifiers(fd.getModifiers()));
  111. if (fd.getInit() != null)
  112. f.setInit(fd.getInit());
  113. return f;
  114. }
  115. private CtMember compileMethod(Parser p, MethodDecl md)
  116. throws CompileError
  117. {
  118. int mod = MemberResolver.getModifiers(md.getModifiers());
  119. CtClass[] plist = gen.makeParamList(md);
  120. CtClass[] tlist = gen.makeThrowsList(md);
  121. recordParams(plist, Modifier.isStatic(mod));
  122. md = p.parseMethod2(stable, md);
  123. try {
  124. if (md.isConstructor()) {
  125. CtConstructor cons = new CtConstructor(plist,
  126. gen.getThisClass());
  127. cons.setModifiers(mod);
  128. md.accept(gen);
  129. cons.getMethodInfo().setCodeAttribute(
  130. bytecode.toCodeAttribute());
  131. cons.setExceptionTypes(tlist);
  132. return cons;
  133. }
  134. else {
  135. Declarator r = md.getReturn();
  136. CtClass rtype = gen.resolver.lookupClass(r);
  137. recordReturnType(rtype, false);
  138. CtMethod method = new CtMethod(rtype, r.getVariable().get(),
  139. plist, gen.getThisClass());
  140. method.setModifiers(mod);
  141. gen.setThisMethod(method);
  142. md.accept(gen);
  143. if (md.getBody() != null)
  144. method.getMethodInfo().setCodeAttribute(
  145. bytecode.toCodeAttribute());
  146. else
  147. method.setModifiers(mod | Modifier.ABSTRACT);
  148. method.setExceptionTypes(tlist);
  149. return method;
  150. }
  151. }
  152. catch (NotFoundException e) {
  153. throw new CompileError(e.toString());
  154. }
  155. }
  156. /**
  157. * Compiles a method (or constructor) body.
  158. *
  159. * @src a single statement or a block.
  160. * If null, this method produces a body returning zero or null.
  161. */
  162. public Bytecode compileBody(CtBehavior method, String src)
  163. throws CompileError
  164. {
  165. try {
  166. int mod = method.getModifiers();
  167. recordParams(method.getParameterTypes(), Modifier.isStatic(mod));
  168. CtClass rtype;
  169. if (method instanceof CtMethod) {
  170. gen.setThisMethod((CtMethod)method);
  171. rtype = ((CtMethod)method).getReturnType();
  172. }
  173. else
  174. rtype = CtClass.voidType;
  175. recordReturnType(rtype, false);
  176. boolean isVoid = rtype == CtClass.voidType;
  177. if (src == null)
  178. makeDefaultBody(bytecode, rtype);
  179. else {
  180. Parser p = new Parser(new Lex(src));
  181. SymbolTable stb = new SymbolTable(stable);
  182. Stmnt s = p.parseStatement(stb);
  183. if (p.hasMore())
  184. throw new CompileError(
  185. "the method/constructor body must be surrounded by {}");
  186. boolean callSuper = false;
  187. if (method instanceof CtConstructor)
  188. callSuper = !((CtConstructor)method).isClassInitializer();
  189. gen.atMethodBody(s, callSuper, isVoid);
  190. }
  191. return bytecode;
  192. }
  193. catch (NotFoundException e) {
  194. throw new CompileError(e.toString());
  195. }
  196. }
  197. private static void makeDefaultBody(Bytecode b, CtClass type) {
  198. int op;
  199. int value;
  200. if (type instanceof CtPrimitiveType) {
  201. CtPrimitiveType pt = (CtPrimitiveType)type;
  202. op = pt.getReturnOp();
  203. if (op == Opcode.DRETURN)
  204. value = Opcode.DCONST_0;
  205. else if (op == Opcode.FRETURN)
  206. value = Opcode.FCONST_0;
  207. else if (op == Opcode.LRETURN)
  208. value = Opcode.LCONST_0;
  209. else if (op == Opcode.RETURN)
  210. value = Opcode.NOP;
  211. else
  212. value = Opcode.ICONST_0;
  213. }
  214. else {
  215. op = Opcode.ARETURN;
  216. value = Opcode.ACONST_NULL;
  217. }
  218. if (value != Opcode.NOP)
  219. b.addOpcode(value);
  220. b.addOpcode(op);
  221. }
  222. /**
  223. * Records local variables available at the specified program counter.
  224. * If the LocalVariableAttribute is not available, this method does not
  225. * record any local variable. It only returns false.
  226. *
  227. * @param pc program counter (&gt;= 0)
  228. * @return false if the CodeAttribute does not include a
  229. * LocalVariableAttribute.
  230. */
  231. public boolean recordLocalVariables(CodeAttribute ca, int pc)
  232. throws CompileError
  233. {
  234. LocalVariableAttribute va
  235. = (LocalVariableAttribute)
  236. ca.getAttribute(LocalVariableAttribute.tag);
  237. if (va == null)
  238. return false;
  239. int n = va.tableLength();
  240. for (int i = 0; i < n; ++i) {
  241. int start = va.startPc(i);
  242. int len = va.codeLength(i);
  243. if (start <= pc && pc < start + len)
  244. gen.recordVariable(va.descriptor(i), va.variableName(i),
  245. va.index(i), stable);
  246. }
  247. return true;
  248. }
  249. /**
  250. * Records parameter names if the LocalVariableAttribute is available.
  251. * It returns false unless the LocalVariableAttribute is available.
  252. *
  253. * @param numOfLocalVars the number of local variables used
  254. * for storing the parameters.
  255. * @return false if the CodeAttribute does not include a
  256. * LocalVariableAttribute.
  257. */
  258. public boolean recordParamNames(CodeAttribute ca, int numOfLocalVars)
  259. throws CompileError
  260. {
  261. LocalVariableAttribute va
  262. = (LocalVariableAttribute)
  263. ca.getAttribute(LocalVariableAttribute.tag);
  264. if (va == null)
  265. return false;
  266. int n = va.tableLength();
  267. for (int i = 0; i < n; ++i) {
  268. int index = va.index(i);
  269. if (index < numOfLocalVars)
  270. gen.recordVariable(va.descriptor(i), va.variableName(i),
  271. index, stable);
  272. }
  273. return true;
  274. }
  275. /**
  276. * Makes variables $0 (this), $1, $2, ..., and $args represent method
  277. * parameters. $args represents an array of all the parameters.
  278. * It also makes $$ available as a parameter list of method call.
  279. *
  280. * <p>This must be called before calling <code>compileStmnt()</code> and
  281. * <code>compileExpr()</code>. The correct value of
  282. * <code>isStatic</code> must be recorded before compilation.
  283. * <code>maxLocals</code> is updated to include $0,...
  284. */
  285. public int recordParams(CtClass[] params, boolean isStatic)
  286. throws CompileError
  287. {
  288. return gen.recordParams(params, isStatic, "$", "$args", "$$", stable);
  289. }
  290. /**
  291. * Makes variables $0, $1, $2, ..., and $args represent method
  292. * parameters. $args represents an array of all the parameters.
  293. * It also makes $$ available as a parameter list of method call.
  294. * $0 can represent a local variable other than THIS (variable 0).
  295. * $class is also made available.
  296. *
  297. * <p>This must be called before calling <code>compileStmnt()</code> and
  298. * <code>compileExpr()</code>. The correct value of
  299. * <code>isStatic</code> must be recorded before compilation.
  300. * <code>maxLocals</code> is updated to include $0,...
  301. *
  302. * @paaram use0 true if $0 is used.
  303. * @param varNo the register number of $0 (use0 is true)
  304. * or $1 (otherwise).
  305. * @param target the type of $0 (it can be null if use0 is false).
  306. * It is used as the name of the type represented
  307. * by $class.
  308. * @param isStatic true if the method in which the compiled bytecode
  309. * is embedded is static.
  310. */
  311. public int recordParams(String target, CtClass[] params,
  312. boolean use0, int varNo, boolean isStatic)
  313. throws CompileError
  314. {
  315. return gen.recordParams(params, isStatic, "$", "$args", "$$",
  316. use0, varNo, target, stable);
  317. }
  318. /**
  319. * Sets <code>maxLocals</code> to <code>max</code>.
  320. * This method tells the compiler the local variables that have been
  321. * allocated for the rest of the code. When the compiler needs
  322. * new local variables, the local variables at the index <code>max</code>,
  323. * <code>max + 1</code>, ... are assigned.
  324. *
  325. * <p>This method is indirectly called by <code>recordParams</code>.
  326. */
  327. public void setMaxLocals(int max) {
  328. gen.setMaxLocals(max);
  329. }
  330. /**
  331. * Prepares to use cast $r, $w, $_, and $type.
  332. * $type is made to represent the specified return type.
  333. * It also enables to write a return statement with a return value
  334. * for void method.
  335. *
  336. * <p>If the return type is void, ($r) does nothing.
  337. * The type of $_ is java.lang.Object.
  338. *
  339. * @param type the return type.
  340. * @param useResultVar true if $_ is used.
  341. * @return -1 or the variable index assigned to $_.
  342. * @see #recordType(CtClass)
  343. */
  344. public int recordReturnType(CtClass type, boolean useResultVar)
  345. throws CompileError
  346. {
  347. gen.recordType(type);
  348. return gen.recordReturnType(type, "$r",
  349. (useResultVar ? resultVarName : null), stable);
  350. }
  351. /**
  352. * Prepares to use $type. Note that recordReturnType() overwrites
  353. * the value of $type.
  354. *
  355. * @param t the type represented by $type.
  356. */
  357. public void recordType(CtClass t) {
  358. gen.recordType(t);
  359. }
  360. /**
  361. * Makes the given variable available.
  362. *
  363. * @param type variable type
  364. * @param name variable name
  365. */
  366. public int recordVariable(CtClass type, String name)
  367. throws CompileError
  368. {
  369. return gen.recordVariable(type, name, stable);
  370. }
  371. /**
  372. * Prepares to use $proceed().
  373. * If the return type of $proceed() is void, null is pushed on the
  374. * stack.
  375. *
  376. * @param target an expression specifying the target object.
  377. * if null, "this" is the target.
  378. * @param method the method name.
  379. */
  380. public void recordProceed(String target, String method)
  381. throws CompileError
  382. {
  383. Parser p = new Parser(new Lex(target));
  384. final ASTree texpr = p.parseExpression(stable);
  385. final String m = method;
  386. ProceedHandler h = new ProceedHandler() {
  387. public void doit(JvstCodeGen gen, Bytecode b, ASTList args)
  388. throws CompileError
  389. {
  390. ASTree expr = new Member(m);
  391. if (texpr != null)
  392. expr = Expr.make('.', texpr, expr);
  393. expr = CallExpr.makeCall(expr, args);
  394. gen.compileExpr(expr);
  395. gen.addNullIfVoid();
  396. }
  397. public void setReturnType(JvstTypeChecker check, ASTList args)
  398. throws CompileError
  399. {
  400. ASTree expr = new Member(m);
  401. if (texpr != null)
  402. expr = Expr.make('.', texpr, expr);
  403. expr = CallExpr.makeCall(expr, args);
  404. expr.accept(check);
  405. check.addNullIfVoid();
  406. }
  407. };
  408. gen.setProceedHandler(h, proceedName);
  409. }
  410. /**
  411. * Prepares to use $proceed() representing a static method.
  412. * If the return type of $proceed() is void, null is pushed on the
  413. * stack.
  414. *
  415. * @param targetClass the fully-qualified dot-separated name
  416. * of the class declaring the method.
  417. * @param method the method name.
  418. */
  419. public void recordStaticProceed(String targetClass, String method)
  420. throws CompileError
  421. {
  422. final String c = targetClass;
  423. final String m = method;
  424. ProceedHandler h = new ProceedHandler() {
  425. public void doit(JvstCodeGen gen, Bytecode b, ASTList args)
  426. throws CompileError
  427. {
  428. Expr expr = Expr.make(TokenId.MEMBER,
  429. new Symbol(c), new Member(m));
  430. expr = CallExpr.makeCall(expr, args);
  431. gen.compileExpr(expr);
  432. gen.addNullIfVoid();
  433. }
  434. public void setReturnType(JvstTypeChecker check, ASTList args)
  435. throws CompileError
  436. {
  437. Expr expr = Expr.make(TokenId.MEMBER,
  438. new Symbol(c), new Member(m));
  439. expr = CallExpr.makeCall(expr, args);
  440. expr.accept(check);
  441. check.addNullIfVoid();
  442. }
  443. };
  444. gen.setProceedHandler(h, proceedName);
  445. }
  446. /**
  447. * Prepares to use $proceed() representing a private/super's method.
  448. * If the return type of $proceed() is void, null is pushed on the
  449. * stack. This method is for methods invoked by INVOKESPECIAL.
  450. *
  451. * @param target an expression specifying the target object.
  452. * if null, "this" is the target.
  453. * @param classname the class name declaring the method.
  454. * @param methodname the method name.
  455. * @param descriptor the method descriptor.
  456. */
  457. public void recordSpecialProceed(String target, String classname,
  458. String methodname, String descriptor)
  459. throws CompileError
  460. {
  461. Parser p = new Parser(new Lex(target));
  462. final ASTree texpr = p.parseExpression(stable);
  463. final String cname = classname;
  464. final String method = methodname;
  465. final String desc = descriptor;
  466. ProceedHandler h = new ProceedHandler() {
  467. public void doit(JvstCodeGen gen, Bytecode b, ASTList args)
  468. throws CompileError
  469. {
  470. gen.compileInvokeSpecial(texpr, cname, method, desc, args);
  471. }
  472. public void setReturnType(JvstTypeChecker c, ASTList args)
  473. throws CompileError
  474. {
  475. c.compileInvokeSpecial(texpr, cname, method, desc, args);
  476. }
  477. };
  478. gen.setProceedHandler(h, proceedName);
  479. }
  480. /**
  481. * Prepares to use $proceed().
  482. */
  483. public void recordProceed(ProceedHandler h) {
  484. gen.setProceedHandler(h, proceedName);
  485. }
  486. /**
  487. * Compiles a statement (or a block).
  488. * <code>recordParams()</code> must be called before invoking
  489. * this method.
  490. *
  491. * <p>Local variables that are not declared
  492. * in the compiled source text might not be accessible within that
  493. * source text. Fields and method parameters ($0, $1, ..) are available.
  494. */
  495. public void compileStmnt(String src) throws CompileError {
  496. Parser p = new Parser(new Lex(src));
  497. SymbolTable stb = new SymbolTable(stable);
  498. while (p.hasMore()) {
  499. Stmnt s = p.parseStatement(stb);
  500. if (s != null)
  501. s.accept(gen);
  502. }
  503. }
  504. /**
  505. * Compiles an exression. <code>recordParams()</code> must be
  506. * called before invoking this method.
  507. *
  508. * <p>Local variables are not accessible
  509. * within the compiled source text. Fields and method parameters
  510. * ($0, $1, ..) are available if <code>recordParams()</code>
  511. * have been invoked.
  512. */
  513. public void compileExpr(String src) throws CompileError {
  514. ASTree e = parseExpr(src, stable);
  515. compileExpr(e);
  516. }
  517. /**
  518. * Parsers an expression.
  519. */
  520. public static ASTree parseExpr(String src, SymbolTable st)
  521. throws CompileError
  522. {
  523. Parser p = new Parser(new Lex(src));
  524. return p.parseExpression(st);
  525. }
  526. /**
  527. * Compiles an exression. <code>recordParams()</code> must be
  528. * called before invoking this method.
  529. *
  530. * <p>Local variables are not accessible
  531. * within the compiled source text. Fields and method parameters
  532. * ($0, $1, ..) are available if <code>recordParams()</code>
  533. * have been invoked.
  534. */
  535. public void compileExpr(ASTree e) throws CompileError {
  536. if (e != null)
  537. gen.compileExpr(e);
  538. }
  539. }