Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

SignatureAttribute.java 37KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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.bytecode;
  17. import java.io.DataInputStream;
  18. import java.io.IOException;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import javassist.CtClass;
  25. /**
  26. * <code>Signature_attribute</code>.
  27. */
  28. public class SignatureAttribute extends AttributeInfo {
  29. /**
  30. * The name of this attribute <code>"Signature"</code>.
  31. */
  32. public static final String tag = "Signature";
  33. SignatureAttribute(ConstPool cp, int n, DataInputStream in)
  34. throws IOException
  35. {
  36. super(cp, n, in);
  37. }
  38. /**
  39. * Constructs a <code>Signature</code> attribute.
  40. *
  41. * @param cp a constant pool table.
  42. * @param signature the signature represented by this attribute.
  43. */
  44. public SignatureAttribute(ConstPool cp, String signature) {
  45. super(cp, tag);
  46. int index = cp.addUtf8Info(signature);
  47. byte[] bvalue = new byte[2];
  48. bvalue[0] = (byte)(index >>> 8);
  49. bvalue[1] = (byte)index;
  50. set(bvalue);
  51. }
  52. /**
  53. * Returns the generic signature indicated by <code>signature_index</code>.
  54. *
  55. * @see #toClassSignature(String)
  56. * @see #toMethodSignature(String)
  57. * @see #toFieldSignature(String)
  58. */
  59. public String getSignature() {
  60. return getConstPool().getUtf8Info(ByteArray.readU16bit(get(), 0));
  61. }
  62. /**
  63. * Sets <code>signature_index</code> to the index of the given generic signature,
  64. * which is added to a constant pool.
  65. *
  66. * @param sig new signature.
  67. * @since 3.11
  68. */
  69. public void setSignature(String sig) {
  70. int index = getConstPool().addUtf8Info(sig);
  71. ByteArray.write16bit(index, info, 0);
  72. }
  73. /**
  74. * Makes a copy. Class names are replaced according to the
  75. * given <code>Map</code> object.
  76. *
  77. * @param newCp the constant pool table used by the new copy.
  78. * @param classnames pairs of replaced and substituted
  79. * class names.
  80. */
  81. @Override
  82. public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) {
  83. return new SignatureAttribute(newCp, getSignature());
  84. }
  85. @Override
  86. void renameClass(String oldname, String newname) {
  87. String sig = renameClass(getSignature(), oldname, newname);
  88. setSignature(sig);
  89. }
  90. @Override
  91. void renameClass(Map<String,String> classnames) {
  92. String sig = renameClass(getSignature(), classnames);
  93. setSignature(sig);
  94. }
  95. static String renameClass(String desc, String oldname, String newname) {
  96. Map<String,String> map = new HashMap<String,String>();
  97. map.put(oldname, newname);
  98. return renameClass(desc, map);
  99. }
  100. static String renameClass(String desc, Map<String,String> map) {
  101. if (map == null || map.isEmpty())
  102. return desc;
  103. StringBuilder newdesc = new StringBuilder();
  104. int head = 0;
  105. int i = 0;
  106. for (;;) {
  107. final int j = desc.indexOf('L', i);
  108. if (j < 0)
  109. break;
  110. StringBuilder nameBuf = new StringBuilder();
  111. StringBuilder genericParamBuf = new StringBuilder();
  112. final ArrayList<StringBuilder> nameBufs = new ArrayList<>();
  113. final ArrayList<StringBuilder> genericParamBufs = new ArrayList<>();
  114. int k = j;
  115. char c;
  116. try {
  117. while ((c = desc.charAt(++k)) != ';') {
  118. if (c == '<') {
  119. genericParamBuf.append(c);
  120. int level = 1;
  121. while (level > 0) {
  122. c = desc.charAt(++k);
  123. genericParamBuf.append(c);
  124. if (c == '<') ++level;
  125. else if (c == '>') --level;
  126. }
  127. } else if (c == '.') {
  128. nameBufs.add(nameBuf);
  129. genericParamBufs.add(genericParamBuf);
  130. nameBuf = new StringBuilder();
  131. genericParamBuf = new StringBuilder();
  132. } else {
  133. nameBuf.append(c);
  134. }
  135. }
  136. }
  137. catch (IndexOutOfBoundsException e) { break; }
  138. nameBufs.add(nameBuf);
  139. genericParamBufs.add(genericParamBuf);
  140. i = k + 1;
  141. String name = String.join("$", nameBufs.toArray(new StringBuilder[0]));
  142. String newname = map.get(name);
  143. if (newname != null) {
  144. final String[] nameSplit = name.split("\\$");
  145. final String[] newnameSplit = newname.split("\\$");
  146. if (nameSplit.length == newnameSplit.length) {
  147. final String[] newnames = new String[nameBufs.size()];
  148. for (int start = 0, z = 0; z < nameBufs.size(); ++z) {
  149. final int toAggregate = (int) nameBufs.get(z).chars().filter(ch -> ch == '$').count() + 1;
  150. String s = String.join("$", Arrays.copyOfRange(newnameSplit, start, start + toAggregate));
  151. start += toAggregate;
  152. newnames[z] = s;
  153. }
  154. newdesc.append(desc.substring(head, j));
  155. newdesc.append('L');
  156. for (int z = 0; z < newnames.length; ++z) {
  157. if (z > 0) {
  158. newdesc.append('.');
  159. }
  160. newdesc.append(newnames[z]);
  161. final String newgenericParam;
  162. final StringBuilder genericParamBufCurrent = genericParamBufs.get(z);
  163. if (genericParamBufCurrent.length() > 0) {
  164. newgenericParam = "<" + renameClass(genericParamBufCurrent.substring(1, genericParamBufCurrent.length() - 1), map) + ">";
  165. } else {
  166. newgenericParam = genericParamBufCurrent.toString(); //empty string
  167. }
  168. newdesc.append(newgenericParam);
  169. }
  170. newdesc.append(c); //the final semicolon
  171. head = i;
  172. }
  173. }
  174. }
  175. if (head == 0)
  176. return desc;
  177. int len = desc.length();
  178. if (head < len)
  179. newdesc.append(desc.substring(head, len));
  180. return newdesc.toString();
  181. }
  182. @SuppressWarnings("unused")
  183. private static boolean isNamePart(int c) {
  184. return c != ';' && c != '<';
  185. }
  186. static private class Cursor {
  187. int position = 0;
  188. int indexOf(String s, int ch) throws BadBytecode {
  189. int i = s.indexOf(ch, position);
  190. if (i < 0)
  191. throw error(s);
  192. position = i + 1;
  193. return i;
  194. }
  195. }
  196. /**
  197. * Class signature.
  198. */
  199. public static class ClassSignature {
  200. TypeParameter[] params;
  201. ClassType superClass;
  202. ClassType[] interfaces;
  203. /**
  204. * Constructs a class signature.
  205. *
  206. * @param params type parameters.
  207. * @param superClass the super class.
  208. * @param interfaces the interface types.
  209. */
  210. public ClassSignature(TypeParameter[] params, ClassType superClass, ClassType[] interfaces) {
  211. this.params = params == null ? new TypeParameter[0] : params;
  212. this.superClass = superClass == null ? ClassType.OBJECT : superClass;
  213. this.interfaces = interfaces == null ? new ClassType[0] : interfaces;
  214. }
  215. /**
  216. * Constructs a class signature.
  217. *
  218. * @param p type parameters.
  219. */
  220. public ClassSignature(TypeParameter[] p) {
  221. this(p, null, null);
  222. }
  223. /**
  224. * Returns the type parameters.
  225. *
  226. * @return a zero-length array if the type parameters are not specified.
  227. */
  228. public TypeParameter[] getParameters() {
  229. return params;
  230. }
  231. /**
  232. * Returns the super class.
  233. */
  234. public ClassType getSuperClass() { return superClass; }
  235. /**
  236. * Returns the super interfaces.
  237. *
  238. * @return a zero-length array if the super interfaces are not specified.
  239. */
  240. public ClassType[] getInterfaces() { return interfaces; }
  241. /**
  242. * Returns the string representation.
  243. */
  244. @Override
  245. public String toString() {
  246. StringBuffer sbuf = new StringBuffer();
  247. TypeParameter.toString(sbuf, params);
  248. sbuf.append(" extends ").append(superClass);
  249. if (interfaces.length > 0) {
  250. sbuf.append(" implements ");
  251. Type.toString(sbuf, interfaces);
  252. }
  253. return sbuf.toString();
  254. }
  255. /**
  256. * Returns the encoded string representing the method type signature.
  257. */
  258. public String encode() {
  259. StringBuffer sbuf = new StringBuffer();
  260. if (params.length > 0) {
  261. sbuf.append('<');
  262. for (int i = 0; i < params.length; i++)
  263. params[i].encode(sbuf);
  264. sbuf.append('>');
  265. }
  266. superClass.encode(sbuf);
  267. for (int i = 0; i < interfaces.length; i++)
  268. interfaces[i].encode(sbuf);
  269. return sbuf.toString();
  270. }
  271. }
  272. /**
  273. * Method type signature.
  274. */
  275. public static class MethodSignature {
  276. TypeParameter[] typeParams;
  277. Type[] params;
  278. Type retType;
  279. ObjectType[] exceptions;
  280. /**
  281. * Constructs a method type signature. Any parameter can be null
  282. * to represent <code>void</code> or nothing.
  283. *
  284. * @param tp type parameters.
  285. * @param params parameter types.
  286. * @param ret a return type, or null if the return type is <code>void</code>.
  287. * @param ex exception types.
  288. */
  289. public MethodSignature(TypeParameter[] tp, Type[] params, Type ret, ObjectType[] ex) {
  290. typeParams = tp == null ? new TypeParameter[0] : tp;
  291. this.params = params == null ? new Type[0] : params;
  292. retType = ret == null ? new BaseType("void") : ret;
  293. exceptions = ex == null ? new ObjectType[0] : ex;
  294. }
  295. /**
  296. * Returns the formal type parameters.
  297. *
  298. * @return a zero-length array if the type parameters are not specified.
  299. */
  300. public TypeParameter[] getTypeParameters() { return typeParams; }
  301. /**
  302. * Returns the types of the formal parameters.
  303. *
  304. * @return a zero-length array if no formal parameter is taken.
  305. */
  306. public Type[] getParameterTypes() { return params; }
  307. /**
  308. * Returns the type of the returned value.
  309. */
  310. public Type getReturnType() { return retType; }
  311. /**
  312. * Returns the types of the exceptions that may be thrown.
  313. *
  314. * @return a zero-length array if exceptions are never thrown or
  315. * the exception types are not parameterized types or type variables.
  316. */
  317. public ObjectType[] getExceptionTypes() { return exceptions; }
  318. /**
  319. * Returns the string representation.
  320. */
  321. @Override
  322. public String toString() {
  323. StringBuffer sbuf = new StringBuffer();
  324. TypeParameter.toString(sbuf, typeParams);
  325. sbuf.append(" (");
  326. Type.toString(sbuf, params);
  327. sbuf.append(") ");
  328. sbuf.append(retType);
  329. if (exceptions.length > 0) {
  330. sbuf.append(" throws ");
  331. Type.toString(sbuf, exceptions);
  332. }
  333. return sbuf.toString();
  334. }
  335. /**
  336. * Returns the encoded string representing the method type signature.
  337. */
  338. public String encode() {
  339. StringBuffer sbuf = new StringBuffer();
  340. if (typeParams.length > 0) {
  341. sbuf.append('<');
  342. for (int i = 0; i < typeParams.length; i++)
  343. typeParams[i].encode(sbuf);
  344. sbuf.append('>');
  345. }
  346. sbuf.append('(');
  347. for (int i = 0; i < params.length; i++)
  348. params[i].encode(sbuf);
  349. sbuf.append(')');
  350. retType.encode(sbuf);
  351. if (exceptions.length > 0)
  352. for (int i = 0; i < exceptions.length; i++) {
  353. sbuf.append('^');
  354. exceptions[i].encode(sbuf);
  355. }
  356. return sbuf.toString();
  357. }
  358. }
  359. /**
  360. * Formal type parameters.
  361. *
  362. * @see TypeArgument
  363. */
  364. public static class TypeParameter {
  365. String name;
  366. ObjectType superClass;
  367. ObjectType[] superInterfaces;
  368. TypeParameter(String sig, int nb, int ne, ObjectType sc, ObjectType[] si) {
  369. name = sig.substring(nb, ne);
  370. superClass = sc;
  371. superInterfaces = si;
  372. }
  373. /**
  374. * Constructs a <code>TypeParameter</code> representing a type parametre
  375. * like <code>&lt;T extends ... &gt;</code>.
  376. *
  377. * @param name parameter name.
  378. * @param superClass an upper bound class-type (or null).
  379. * @param superInterfaces an upper bound interface-type (or null).
  380. */
  381. public TypeParameter(String name, ObjectType superClass, ObjectType[] superInterfaces) {
  382. this.name = name;
  383. this.superClass = superClass;
  384. if (superInterfaces == null)
  385. this.superInterfaces = new ObjectType[0];
  386. else
  387. this.superInterfaces = superInterfaces;
  388. }
  389. /**
  390. * Constructs a <code>TypeParameter</code> representing a type parameter
  391. * like <code>&lt;T&gt;</code>.
  392. *
  393. * @param name parameter name.
  394. */
  395. public TypeParameter(String name) {
  396. this(name, null, null);
  397. }
  398. /**
  399. * Returns the name of the type parameter.
  400. */
  401. public String getName() {
  402. return name;
  403. }
  404. /**
  405. * Returns the class bound of this parameter.
  406. */
  407. public ObjectType getClassBound() { return superClass; }
  408. /**
  409. * Returns the interface bound of this parameter.
  410. *
  411. * @return a zero-length array if the interface bound is not specified.
  412. */
  413. public ObjectType[] getInterfaceBound() { return superInterfaces; }
  414. /**
  415. * Returns the string representation.
  416. */
  417. @Override
  418. public String toString() {
  419. StringBuffer sbuf = new StringBuffer(getName());
  420. if (superClass != null)
  421. sbuf.append(" extends ").append(superClass.toString());
  422. int len = superInterfaces.length;
  423. if (len > 0) {
  424. for (int i = 0; i < len; i++) {
  425. if (i > 0 || superClass != null)
  426. sbuf.append(" & ");
  427. else
  428. sbuf.append(" extends ");
  429. sbuf.append(superInterfaces[i].toString());
  430. }
  431. }
  432. return sbuf.toString();
  433. }
  434. static void toString(StringBuffer sbuf, TypeParameter[] tp) {
  435. sbuf.append('<');
  436. for (int i = 0; i < tp.length; i++) {
  437. if (i > 0)
  438. sbuf.append(", ");
  439. sbuf.append(tp[i]);
  440. }
  441. sbuf.append('>');
  442. }
  443. void encode(StringBuffer sb) {
  444. sb.append(name);
  445. if (superClass == null)
  446. sb.append(":Ljava/lang/Object;");
  447. else {
  448. sb.append(':');
  449. superClass.encode(sb);
  450. }
  451. for (int i = 0; i < superInterfaces.length; i++) {
  452. sb.append(':');
  453. superInterfaces[i].encode(sb);
  454. }
  455. }
  456. }
  457. /**
  458. * Type argument.
  459. *
  460. * @see TypeParameter
  461. */
  462. public static class TypeArgument {
  463. ObjectType arg;
  464. char wildcard;
  465. TypeArgument(ObjectType a, char w) {
  466. arg = a;
  467. wildcard = w;
  468. }
  469. /**
  470. * Constructs a <code>TypeArgument</code>.
  471. * A type argument is <code>&lt;String&gt;</code>, <code>&lt;int[]&gt;</code>,
  472. * or a type variable <code>&lt;T&gt;</code>, etc.
  473. *
  474. * @param t a class type, an array type, or a type variable.
  475. */
  476. public TypeArgument(ObjectType t) {
  477. this(t, ' ');
  478. }
  479. /**
  480. * Constructs a <code>TypeArgument</code> representing <code>&lt;?&gt;</code>.
  481. */
  482. public TypeArgument() {
  483. this(null, '*');
  484. }
  485. /**
  486. * A factory method constructing a <code>TypeArgument</code> with an upper bound.
  487. * It represents <code>&lt;? extends ... &gt;</code>
  488. *
  489. * @param t an upper bound type.
  490. */
  491. public static TypeArgument subclassOf(ObjectType t) {
  492. return new TypeArgument(t, '+');
  493. }
  494. /**
  495. * A factory method constructing a <code>TypeArgument</code> with an lower bound.
  496. * It represents <code>&lt;? super ... &gt;</code>
  497. *
  498. * @param t an lower bbound type.
  499. */
  500. public static TypeArgument superOf(ObjectType t) {
  501. return new TypeArgument(t, '-');
  502. }
  503. /**
  504. * Returns the kind of this type argument.
  505. *
  506. * @return <code>' '</code> (not-wildcard), <code>'*'</code> (wildcard), <code>'+'</code> (wildcard with
  507. * upper bound), or <code>'-'</code> (wildcard with lower bound).
  508. */
  509. public char getKind() { return wildcard; }
  510. /**
  511. * Returns true if this type argument is a wildcard type
  512. * such as <code>?</code>, <code>? extends String</code>, or <code>? super Integer</code>.
  513. */
  514. public boolean isWildcard() { return wildcard != ' '; }
  515. /**
  516. * Returns the type represented by this argument
  517. * if the argument is not a wildcard type. Otherwise, this method
  518. * returns the upper bound (if the kind is '+'),
  519. * the lower bound (if the kind is '-'), or null (if the upper or lower
  520. * bound is not specified).
  521. */
  522. public ObjectType getType() { return arg; }
  523. /**
  524. * Returns the string representation.
  525. */
  526. @Override
  527. public String toString() {
  528. if (wildcard == '*')
  529. return "?";
  530. String type = arg.toString();
  531. if (wildcard == ' ')
  532. return type;
  533. else if (wildcard == '+')
  534. return "? extends " + type;
  535. else
  536. return "? super " + type;
  537. }
  538. static void encode(StringBuffer sb, TypeArgument[] args) {
  539. sb.append('<');
  540. for (int i = 0; i < args.length; i++) {
  541. TypeArgument ta = args[i];
  542. if (ta.isWildcard())
  543. sb.append(ta.wildcard);
  544. if (ta.getType() != null)
  545. ta.getType().encode(sb);
  546. }
  547. sb.append('>');
  548. }
  549. }
  550. /**
  551. * Primitive types and object types.
  552. */
  553. public static abstract class Type {
  554. abstract void encode(StringBuffer sb);
  555. static void toString(StringBuffer sbuf, Type[] ts) {
  556. for (int i = 0; i < ts.length; i++) {
  557. if (i > 0)
  558. sbuf.append(", ");
  559. sbuf.append(ts[i]);
  560. }
  561. }
  562. /**
  563. * Returns the type name in the JVM internal style.
  564. * For example, if the type is a nested class {@code foo.Bar.Baz},
  565. * then {@code foo.Bar$Baz} is returned.
  566. */
  567. public String jvmTypeName() { return toString(); }
  568. }
  569. /**
  570. * Primitive types.
  571. */
  572. public static class BaseType extends Type {
  573. char descriptor;
  574. BaseType(char c) { descriptor = c; }
  575. /**
  576. * Constructs a <code>BaseType</code>.
  577. *
  578. * @param typeName <code>void</code>, <code>int</code>, ...
  579. */
  580. public BaseType(String typeName) {
  581. this(Descriptor.of(typeName).charAt(0));
  582. }
  583. /**
  584. * Returns the descriptor representing this primitive type.
  585. *
  586. * @see javassist.bytecode.Descriptor
  587. */
  588. public char getDescriptor() { return descriptor; }
  589. /**
  590. * Returns the <code>CtClass</code> representing this
  591. * primitive type.
  592. */
  593. public CtClass getCtlass() {
  594. return Descriptor.toPrimitiveClass(descriptor);
  595. }
  596. /**
  597. * Returns the string representation.
  598. */
  599. @Override
  600. public String toString() {
  601. return Descriptor.toClassName(Character.toString(descriptor));
  602. }
  603. @Override
  604. void encode(StringBuffer sb) {
  605. sb.append(descriptor);
  606. }
  607. }
  608. /**
  609. * Class types, array types, and type variables.
  610. * This class is also used for representing a field type.
  611. */
  612. public static abstract class ObjectType extends Type {
  613. /**
  614. * Returns the encoded string representing the object type signature.
  615. */
  616. public String encode() {
  617. StringBuffer sb = new StringBuffer();
  618. encode(sb);
  619. return sb.toString();
  620. }
  621. }
  622. /**
  623. * Class types.
  624. */
  625. public static class ClassType extends ObjectType {
  626. String name;
  627. TypeArgument[] arguments;
  628. static ClassType make(String s, int b, int e,
  629. TypeArgument[] targs, ClassType parent) {
  630. if (parent == null)
  631. return new ClassType(s, b, e, targs);
  632. return new NestedClassType(s, b, e, targs, parent);
  633. }
  634. ClassType(String signature, int begin, int end, TypeArgument[] targs) {
  635. name = signature.substring(begin, end).replace('/', '.');
  636. arguments = targs;
  637. }
  638. /**
  639. * A class type representing <code>java.lang.Object</code>.
  640. */
  641. public static ClassType OBJECT = new ClassType("java.lang.Object", null);
  642. /**
  643. * Constructs a <code>ClassType</code>. It represents
  644. * the name of a non-nested class.
  645. *
  646. * @param className a fully qualified class name.
  647. * @param args type arguments or null.
  648. */
  649. public ClassType(String className, TypeArgument[] args) {
  650. name = className;
  651. arguments = args;
  652. }
  653. /**
  654. * Constructs a <code>ClassType</code>. It represents
  655. * the name of a non-nested class.
  656. *
  657. * @param className a fully qualified class name.
  658. */
  659. public ClassType(String className) {
  660. this(className, null);
  661. }
  662. /**
  663. * Returns the class name.
  664. */
  665. public String getName() {
  666. return name;
  667. }
  668. /**
  669. * Returns the type arguments.
  670. *
  671. * @return null if no type arguments are given to this class.
  672. */
  673. public TypeArgument[] getTypeArguments() { return arguments; }
  674. /**
  675. * If this class is a member of another class, returns the
  676. * class in which this class is declared.
  677. *
  678. * @return null if this class is not a member of another class.
  679. */
  680. public ClassType getDeclaringClass() { return null; }
  681. /**
  682. * Returns the string representation.
  683. */
  684. @Override
  685. public String toString() {
  686. StringBuffer sbuf = new StringBuffer();
  687. ClassType parent = getDeclaringClass();
  688. if (parent != null)
  689. sbuf.append(parent.toString()).append('.');
  690. return toString2(sbuf);
  691. }
  692. private String toString2(StringBuffer sbuf) {
  693. sbuf.append(name);
  694. if (arguments != null) {
  695. sbuf.append('<');
  696. int n = arguments.length;
  697. for (int i = 0; i < n; i++) {
  698. if (i > 0)
  699. sbuf.append(", ");
  700. sbuf.append(arguments[i].toString());
  701. }
  702. sbuf.append('>');
  703. }
  704. return sbuf.toString();
  705. }
  706. /**
  707. * Returns the type name in the JVM internal style.
  708. * For example, if the type is a nested class {@code foo.Bar.Baz},
  709. * then {@code foo.Bar$Baz} is returned.
  710. */
  711. @Override
  712. public String jvmTypeName() {
  713. StringBuffer sbuf = new StringBuffer();
  714. ClassType parent = getDeclaringClass();
  715. if (parent != null)
  716. sbuf.append(parent.jvmTypeName()).append('$');
  717. return toString2(sbuf);
  718. }
  719. @Override
  720. void encode(StringBuffer sb) {
  721. sb.append('L');
  722. encode2(sb);
  723. sb.append(';');
  724. }
  725. void encode2(StringBuffer sb) {
  726. ClassType parent = getDeclaringClass();
  727. if (parent != null) {
  728. parent.encode2(sb);
  729. sb.append('$');
  730. }
  731. sb.append(name.replace('.', '/'));
  732. if (arguments != null)
  733. TypeArgument.encode(sb, arguments);
  734. }
  735. }
  736. /**
  737. * Nested class types.
  738. */
  739. public static class NestedClassType extends ClassType {
  740. ClassType parent;
  741. NestedClassType(String s, int b, int e,
  742. TypeArgument[] targs, ClassType p) {
  743. super(s, b, e, targs);
  744. parent = p;
  745. }
  746. /**
  747. * Constructs a <code>NestedClassType</code>.
  748. *
  749. * @param parent the class surrounding this class type.
  750. * @param className a simple class name. It does not include
  751. * a package name or a parent's class name.
  752. * @param args type parameters or null.
  753. */
  754. public NestedClassType(ClassType parent, String className, TypeArgument[] args) {
  755. super(className, args);
  756. this.parent = parent;
  757. }
  758. /**
  759. * Returns the class that declares this nested class.
  760. * This nested class is a member of that declaring class.
  761. */
  762. @Override
  763. public ClassType getDeclaringClass() { return parent; }
  764. }
  765. /**
  766. * Array types.
  767. */
  768. public static class ArrayType extends ObjectType {
  769. int dim;
  770. Type componentType;
  771. /**
  772. * Constructs an <code>ArrayType</code>.
  773. *
  774. * @param d dimension.
  775. * @param comp the component type.
  776. */
  777. public ArrayType(int d, Type comp) {
  778. dim = d;
  779. componentType = comp;
  780. }
  781. /**
  782. * Returns the dimension of the array.
  783. */
  784. public int getDimension() { return dim; }
  785. /**
  786. * Returns the component type.
  787. */
  788. public Type getComponentType() {
  789. return componentType;
  790. }
  791. /**
  792. * Returns the string representation.
  793. */
  794. @Override
  795. public String toString() {
  796. StringBuffer sbuf = new StringBuffer(componentType.toString());
  797. for (int i = 0; i < dim; i++)
  798. sbuf.append("[]");
  799. return sbuf.toString();
  800. }
  801. @Override
  802. void encode(StringBuffer sb) {
  803. for (int i = 0; i < dim; i++)
  804. sb.append('[');
  805. componentType.encode(sb);
  806. }
  807. }
  808. /**
  809. * Type variables.
  810. */
  811. public static class TypeVariable extends ObjectType {
  812. String name;
  813. TypeVariable(String sig, int begin, int end) {
  814. name = sig.substring(begin, end);
  815. }
  816. /**
  817. * Constructs a <code>TypeVariable</code>.
  818. *
  819. * @param name the name of a type variable.
  820. */
  821. public TypeVariable(String name) {
  822. this.name = name;
  823. }
  824. /**
  825. * Returns the variable name.
  826. */
  827. public String getName() {
  828. return name;
  829. }
  830. /**
  831. * Returns the string representation.
  832. */
  833. @Override
  834. public String toString() {
  835. return name;
  836. }
  837. @Override
  838. void encode(StringBuffer sb) {
  839. sb.append('T').append(name).append(';');
  840. }
  841. }
  842. /**
  843. * Parses the given signature string as a class signature.
  844. *
  845. * @param sig the signature obtained from the <code>SignatureAttribute</code>
  846. * of a <code>ClassFile</code>.
  847. * @return a tree-like data structure representing a class signature. It provides
  848. * convenient accessor methods.
  849. * @throws BadBytecode thrown when a syntactical error is found.
  850. * @see #getSignature()
  851. * @since 3.5
  852. */
  853. public static ClassSignature toClassSignature(String sig) throws BadBytecode {
  854. try {
  855. return parseSig(sig);
  856. }
  857. catch (IndexOutOfBoundsException e) {
  858. throw error(sig);
  859. }
  860. }
  861. /**
  862. * Parses the given signature string as a method type signature.
  863. *
  864. * @param sig the signature obtained from the <code>SignatureAttribute</code>
  865. * of a <code>MethodInfo</code>.
  866. * @return @return a tree-like data structure representing a method signature. It provides
  867. * convenient accessor methods.
  868. * @throws BadBytecode thrown when a syntactical error is found.
  869. * @see #getSignature()
  870. * @since 3.5
  871. */
  872. public static MethodSignature toMethodSignature(String sig) throws BadBytecode {
  873. try {
  874. return parseMethodSig(sig);
  875. }
  876. catch (IndexOutOfBoundsException e) {
  877. throw error(sig);
  878. }
  879. }
  880. /**
  881. * Parses the given signature string as a field type signature.
  882. *
  883. * @param sig the signature string obtained from the <code>SignatureAttribute</code>
  884. * of a <code>FieldInfo</code>.
  885. * @return the field type signature.
  886. * @throws BadBytecode thrown when a syntactical error is found.
  887. * @see #getSignature()
  888. * @since 3.5
  889. */
  890. public static ObjectType toFieldSignature(String sig) throws BadBytecode {
  891. try {
  892. return parseObjectType(sig, new Cursor(), false);
  893. }
  894. catch (IndexOutOfBoundsException e) {
  895. throw error(sig);
  896. }
  897. }
  898. /**
  899. * Parses the given signature string as a type signature.
  900. * The type signature is either the field type signature or a base type
  901. * descriptor including <code>void</code> type.
  902. *
  903. * @throws BadBytecode thrown when a syntactical error is found.
  904. * @since 3.18
  905. */
  906. public static Type toTypeSignature(String sig) throws BadBytecode {
  907. try {
  908. return parseType(sig, new Cursor());
  909. }
  910. catch (IndexOutOfBoundsException e) {
  911. throw error(sig);
  912. }
  913. }
  914. private static ClassSignature parseSig(String sig)
  915. throws BadBytecode, IndexOutOfBoundsException
  916. {
  917. Cursor cur = new Cursor();
  918. TypeParameter[] tp = parseTypeParams(sig, cur);
  919. ClassType superClass = parseClassType(sig, cur);
  920. int sigLen = sig.length();
  921. List<ClassType> ifArray = new ArrayList<ClassType>();
  922. while (cur.position < sigLen && sig.charAt(cur.position) == 'L')
  923. ifArray.add(parseClassType(sig, cur));
  924. ClassType[] ifs
  925. = ifArray.toArray(new ClassType[ifArray.size()]);
  926. return new ClassSignature(tp, superClass, ifs);
  927. }
  928. private static MethodSignature parseMethodSig(String sig)
  929. throws BadBytecode
  930. {
  931. Cursor cur = new Cursor();
  932. TypeParameter[] tp = parseTypeParams(sig, cur);
  933. if (sig.charAt(cur.position++) != '(')
  934. throw error(sig);
  935. List<Type> params = new ArrayList<Type>();
  936. while (sig.charAt(cur.position) != ')') {
  937. Type t = parseType(sig, cur);
  938. params.add(t);
  939. }
  940. cur.position++;
  941. Type ret = parseType(sig, cur);
  942. int sigLen = sig.length();
  943. List<ObjectType> exceptions = new ArrayList<ObjectType>();
  944. while (cur.position < sigLen && sig.charAt(cur.position) == '^') {
  945. cur.position++;
  946. ObjectType t = parseObjectType(sig, cur, false);
  947. if (t instanceof ArrayType)
  948. throw error(sig);
  949. exceptions.add(t);
  950. }
  951. Type[] p = params.toArray(new Type[params.size()]);
  952. ObjectType[] ex = exceptions.toArray(new ObjectType[exceptions.size()]);
  953. return new MethodSignature(tp, p, ret, ex);
  954. }
  955. private static TypeParameter[] parseTypeParams(String sig, Cursor cur)
  956. throws BadBytecode
  957. {
  958. List<TypeParameter> typeParam = new ArrayList<TypeParameter>();
  959. if (sig.charAt(cur.position) == '<') {
  960. cur.position++;
  961. while (sig.charAt(cur.position) != '>') {
  962. int nameBegin = cur.position;
  963. int nameEnd = cur.indexOf(sig, ':');
  964. ObjectType classBound = parseObjectType(sig, cur, true);
  965. List<ObjectType> ifBound = new ArrayList<ObjectType>();
  966. while (sig.charAt(cur.position) == ':') {
  967. cur.position++;
  968. ObjectType t = parseObjectType(sig, cur, false);
  969. ifBound.add(t);
  970. }
  971. TypeParameter p = new TypeParameter(sig, nameBegin, nameEnd,
  972. classBound, ifBound.toArray(new ObjectType[ifBound.size()]));
  973. typeParam.add(p);
  974. }
  975. cur.position++;
  976. }
  977. return typeParam.toArray(new TypeParameter[typeParam.size()]);
  978. }
  979. private static ObjectType parseObjectType(String sig, Cursor c, boolean dontThrow)
  980. throws BadBytecode
  981. {
  982. int i;
  983. int begin = c.position;
  984. switch (sig.charAt(begin)) {
  985. case 'L' :
  986. return parseClassType2(sig, c, null);
  987. case 'T' :
  988. i = c.indexOf(sig, ';');
  989. return new TypeVariable(sig, begin + 1, i);
  990. case '[' :
  991. return parseArray(sig, c);
  992. default :
  993. if (dontThrow)
  994. return null;
  995. throw error(sig);
  996. }
  997. }
  998. private static ClassType parseClassType(String sig, Cursor c)
  999. throws BadBytecode
  1000. {
  1001. if (sig.charAt(c.position) == 'L')
  1002. return parseClassType2(sig, c, null);
  1003. throw error(sig);
  1004. }
  1005. private static ClassType parseClassType2(String sig, Cursor c, ClassType parent)
  1006. throws BadBytecode
  1007. {
  1008. int start = ++c.position;
  1009. char t;
  1010. do {
  1011. t = sig.charAt(c.position++);
  1012. } while (t != '$' && t != '<' && t != ';');
  1013. int end = c.position - 1;
  1014. TypeArgument[] targs;
  1015. if (t == '<') {
  1016. targs = parseTypeArgs(sig, c);
  1017. t = sig.charAt(c.position++);
  1018. }
  1019. else
  1020. targs = null;
  1021. ClassType thisClass = ClassType.make(sig, start, end, targs, parent);
  1022. if (t == '$' || t == '.') {
  1023. c.position--;
  1024. return parseClassType2(sig, c, thisClass);
  1025. }
  1026. return thisClass;
  1027. }
  1028. private static TypeArgument[] parseTypeArgs(String sig, Cursor c) throws BadBytecode {
  1029. List<TypeArgument> args = new ArrayList<TypeArgument>();
  1030. char t;
  1031. while ((t = sig.charAt(c.position++)) != '>') {
  1032. TypeArgument ta;
  1033. if (t == '*' )
  1034. ta = new TypeArgument(null, '*');
  1035. else {
  1036. if (t != '+' && t != '-') {
  1037. t = ' ';
  1038. c.position--;
  1039. }
  1040. ta = new TypeArgument(parseObjectType(sig, c, false), t);
  1041. }
  1042. args.add(ta);
  1043. }
  1044. return args.toArray(new TypeArgument[args.size()]);
  1045. }
  1046. private static ObjectType parseArray(String sig, Cursor c) throws BadBytecode {
  1047. int dim = 1;
  1048. while (sig.charAt(++c.position) == '[')
  1049. dim++;
  1050. return new ArrayType(dim, parseType(sig, c));
  1051. }
  1052. private static Type parseType(String sig, Cursor c) throws BadBytecode {
  1053. Type t = parseObjectType(sig, c, true);
  1054. if (t == null)
  1055. t = new BaseType(sig.charAt(c.position++));
  1056. return t;
  1057. }
  1058. private static BadBytecode error(String sig) {
  1059. return new BadBytecode("bad signature: " + sig);
  1060. }
  1061. }