pjvm.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. {
  2. Copyright (c) 2011 by Jonas Maebe
  3. This unit implements some JVM parser helper routines.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. {$i fpcdefs.inc}
  18. unit pjvm;
  19. interface
  20. uses
  21. globtype,
  22. symtype,symbase,symdef;
  23. { the JVM specs require that you add a default parameterless
  24. constructor in case the programmer hasn't specified any }
  25. procedure maybe_add_public_default_java_constructor(obj: tabstractrecorddef);
  26. { records are emulated via Java classes. They require a default constructor
  27. to initialise temps, a deep copy helper for assignments, and clone()
  28. to initialse dynamic arrays }
  29. procedure add_java_default_record_methods_intf(def: trecorddef);
  30. procedure jvm_maybe_create_enum_class(const name: TIDString; def: tdef);
  31. implementation
  32. uses
  33. cutils,cclasses,
  34. verbose,systems,
  35. fmodule,
  36. parabase,
  37. pdecsub,
  38. symtable,symconst,symsym,symcreat,defcmp,jvmdef,
  39. defutil,paramgr;
  40. { the JVM specs require that you add a default parameterless
  41. constructor in case the programmer hasn't specified any }
  42. procedure maybe_add_public_default_java_constructor(obj: tabstractrecorddef);
  43. var
  44. sym: tsym;
  45. ps: tprocsym;
  46. pd: tprocdef;
  47. topowner: tdefentry;
  48. i: longint;
  49. sstate: symcreat.tscannerstate;
  50. needclassconstructor: boolean;
  51. begin
  52. { if there is at least one constructor for a class, do nothing (for
  53. records, we'll always also need a parameterless constructor) }
  54. if not is_javaclass(obj) or
  55. not (oo_has_constructor in obj.objectoptions) then
  56. begin
  57. { check whether the parent has a parameterless constructor that we can
  58. call (in case of a class; all records will derive from
  59. java.lang.Object or a shim on top of that with a parameterless
  60. constructor) }
  61. if is_javaclass(obj) then
  62. begin
  63. pd:=nil;
  64. sym:=tsym(tobjectdef(obj).childof.symtable.find('CREATE'));
  65. if assigned(sym) and
  66. (sym.typ=procsym) then
  67. pd:=tprocsym(sym).find_bytype_parameterless(potype_constructor);
  68. if not assigned(pd) then
  69. begin
  70. Message(sym_e_no_matching_inherited_parameterless_constructor);
  71. exit
  72. end;
  73. end;
  74. { we call all constructors CREATE, because they don't have a name in
  75. Java and otherwise we can't determine whether multiple overloads
  76. are created with the same parameters }
  77. sym:=tsym(obj.symtable.find('CREATE'));
  78. if assigned(sym) then
  79. begin
  80. { does another, non-procsym, symbol already exist with that name? }
  81. if (sym.typ<>procsym) then
  82. begin
  83. Message1(sym_e_duplicate_id_create_java_constructor,sym.realname);
  84. exit;
  85. end;
  86. ps:=tprocsym(sym);
  87. { is there already a parameterless function/procedure create? }
  88. pd:=ps.find_bytype_parameterless(potype_function);
  89. if not assigned(pd) then
  90. pd:=ps.find_bytype_parameterless(potype_procedure);
  91. if assigned(pd) then
  92. begin
  93. Message1(sym_e_duplicate_id_create_java_constructor,pd.fullprocname(false));
  94. exit;
  95. end;
  96. end;
  97. if not assigned(sym) then
  98. begin
  99. ps:=tprocsym.create('Create');
  100. obj.symtable.insert(ps);
  101. end;
  102. { determine symtable level }
  103. topowner:=obj;
  104. while not(topowner.owner.symtabletype in [staticsymtable,globalsymtable]) do
  105. topowner:=topowner.owner.defowner;
  106. { create procdef }
  107. pd:=tprocdef.create(topowner.owner.symtablelevel+1);
  108. { method of this objectdef }
  109. pd.struct:=obj;
  110. { associated procsym }
  111. pd.procsym:=ps;
  112. { constructor }
  113. pd.proctypeoption:=potype_constructor;
  114. { needs to be exported }
  115. include(pd.procoptions,po_global);
  116. { for Delphi mode }
  117. include(pd.procoptions,po_overload);
  118. { generate anonymous inherited call in the implementation }
  119. pd.synthetickind:=tsk_anon_inherited;
  120. { public }
  121. pd.visibility:=vis_public;
  122. { result type }
  123. pd.returndef:=obj;
  124. { calling convention, self, ... }
  125. handle_calling_convention(pd);
  126. { register forward declaration with procsym }
  127. proc_add_definition(pd);
  128. end;
  129. { also add class constructor if class fields that need wrapping, and
  130. if none was defined }
  131. if obj.find_procdef_bytype(potype_class_constructor)=nil then
  132. begin
  133. needclassconstructor:=false;
  134. for i:=0 to obj.symtable.symlist.count-1 do
  135. begin
  136. if (tsym(obj.symtable.symlist[i]).typ=staticvarsym) and
  137. jvmimplicitpointertype(tstaticvarsym(obj.symtable.symlist[i]).vardef) then
  138. begin
  139. needclassconstructor:=true;
  140. break;
  141. end;
  142. end;
  143. if needclassconstructor then
  144. begin
  145. replace_scanner('custom_class_constructor',sstate);
  146. if str_parse_method_dec('constructor fpc_jvm_class_constructor;',potype_class_constructor,true,obj,pd) then
  147. pd.synthetickind:=tsk_empty
  148. else
  149. internalerror(2011040501);
  150. restore_scanner(sstate);
  151. end;
  152. end;
  153. end;
  154. procedure add_java_default_record_methods_intf(def: trecorddef);
  155. var
  156. sstate: tscannerstate;
  157. pd: tprocdef;
  158. begin
  159. maybe_add_public_default_java_constructor(def);
  160. replace_scanner('record_jvm_helpers',sstate);
  161. { no override, because not supported in records; the parser will still
  162. accept "inherited" though }
  163. if str_parse_method_dec('function clone: JLObject;',potype_function,false,def,pd) then
  164. pd.synthetickind:=tsk_jvm_clone
  165. else
  166. internalerror(2011032806);
  167. { can't use def.typesym, not yet set at this point }
  168. if not assigned(def.symtable.realname) then
  169. internalerror(2011032803);
  170. if str_parse_method_dec('procedure fpcDeepCopy(out result:'+def.symtable.realname^+');',potype_procedure,false,def,pd) then
  171. pd.synthetickind:=tsk_record_deepcopy
  172. else
  173. internalerror(2011032807);
  174. restore_scanner(sstate);
  175. end;
  176. procedure jvm_maybe_create_enum_class(const name: TIDString; def: tdef);
  177. var
  178. arrdef: tarraydef;
  179. arrsym: ttypesym;
  180. juhashmap: tdef;
  181. enumclass: tobjectdef;
  182. pd: tprocdef;
  183. old_current_structdef: tabstractrecorddef;
  184. i: longint;
  185. sym: tstaticvarsym;
  186. fsym: tfieldvarsym;
  187. sstate: symcreat.tscannerstate;
  188. sl: tpropaccesslist;
  189. begin
  190. { if it's a subrange type, don't create a new class }
  191. if assigned(tenumdef(def).basedef) then
  192. exit;
  193. replace_scanner('jvm_enum_class',sstate);
  194. { create new class (different internal name than enum to prevent name clash) }
  195. enumclass:=tobjectdef.create(odt_javaclass,'$'+name+'$InternEnum',java_jlenum);
  196. tenumdef(def).classdef:=enumclass;
  197. include(enumclass.objectoptions,oo_is_enum_class);
  198. include(enumclass.objectoptions,oo_is_sealed);
  199. { create an alias for this type inside itself: this way we can choose a
  200. name that can be used in generated Pascal code without risking an
  201. identifier conflict (since it is local to this class; the global name
  202. is unique because it's an identifier that contains $-signs) }
  203. enumclass.symtable.insert(ttypesym.create('__FPC_TEnumClassAlias',enumclass));
  204. { also create an alias for the enum type so that we can iterate over
  205. all enum values when creating the body of the class constructor }
  206. enumclass.symtable.insert(ttypesym.create('__FPC_TEnumAlias',def));
  207. { but the name of the class as far as the JVM is concerned will match
  208. the enum's original name (the enum type itself won't be output in
  209. any class file, so no conflict there) }
  210. enumclass.objextname:=stringdup(name);
  211. { now add a bunch of extra things to the enum class }
  212. old_current_structdef:=current_structdef;
  213. current_structdef:=enumclass;
  214. symtablestack.push(enumclass.symtable);
  215. { create static fields representing all enums }
  216. for i:=0 to tenumdef(def).symtable.symlist.count-1 do
  217. begin
  218. sym:=tstaticvarsym.create(tenumsym(tenumdef(def).symtable.symlist[i]).realname,vs_final,enumclass,[]);
  219. enumclass.symtable.insert(sym);
  220. { alias for consistency with parsed staticvarsyms }
  221. sl:=tpropaccesslist.create;
  222. sl.addsym(sl_load,sym);
  223. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),enumclass,sl));
  224. end;
  225. { create local "array of enumtype" type for the "values" functionality
  226. (used internally by the JDK) }
  227. arrdef:=tarraydef.create(0,tenumdef(def).symtable.symlist.count-1,s32inttype);
  228. arrdef.elementdef:=enumclass;
  229. arrsym:=ttypesym.create('__FPC_TEnumValues',arrdef);
  230. enumclass.symtable.insert(arrsym);
  231. { insert "public static values: array of enumclass" that returns $VALUES.clone()
  232. (rather than a dynamic array and using clone --which we don't support yet for arrays--
  233. simply use a fixed length array and copy it) }
  234. if not str_parse_method_dec('function values: __FPC_TEnumValues;',potype_function,true,enumclass,pd) then
  235. internalerror(2011062301);
  236. include(pd.procoptions,po_staticmethod);
  237. pd.synthetickind:=tsk_jvm_enum_values;
  238. { do we have to store the ordinal value separately? (if no jumps, we can
  239. just call the default ordinal() java.lang.Enum function) }
  240. if tenumdef(def).has_jumps then
  241. begin
  242. { add field for the value }
  243. fsym:=tfieldvarsym.create('__fpc_fenumval',vs_final,s32inttype,[]);
  244. enumclass.symtable.insert(fsym);
  245. tobjectsymtable(enumclass.symtable).addfield(fsym,vis_strictprivate);
  246. { add class field with hash table that maps from FPC-declared ordinal value -> enum instance }
  247. juhashmap:=search_system_type('JUHASHMAP').typedef;
  248. sym:=tstaticvarsym.create('__fpc_ord2enum',vs_final,juhashmap,[]);
  249. enumclass.symtable.insert(sym);
  250. { alias for consistency with parsed staticvarsyms }
  251. sl:=tpropaccesslist.create;
  252. sl.addsym(sl_load,sym);
  253. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),enumclass,sl));
  254. { add custom constructor }
  255. if not str_parse_method_dec('constructor Create(const __fpc_name: JLString; const __fpc_ord, __fpc_initenumval: longint);',potype_constructor,false,enumclass,pd) then
  256. internalerror(2011062401);
  257. pd.synthetickind:=tsk_jvm_enum_jumps_constr;
  258. pd.visibility:=vis_strictprivate;
  259. end
  260. else
  261. begin
  262. { insert "private constructor(string,int,int)" that calls inherited and
  263. initialises the FPC value field }
  264. add_missing_parent_constructors_intf(enumclass,vis_strictprivate);
  265. end;
  266. { add instance method to get the enum's value as declared in FPC }
  267. if not str_parse_method_dec('function FPCOrdinal: longint;',potype_function,false,enumclass,pd) then
  268. internalerror(2011062402);
  269. pd.synthetickind:=tsk_jvm_enum_fpcordinal;
  270. { add static class method to convert an ordinal to the corresponding enum }
  271. if not str_parse_method_dec('function FPCValueOf(__fpc_int: longint): __FPC_TEnumClassAlias; static;',potype_function,true,enumclass,pd) then
  272. internalerror(2011062402);
  273. pd.synthetickind:=tsk_jvm_enum_fpcvalueof;
  274. { insert "public static valueOf(string): tenumclass" that returns tenumclass(inherited valueOf(tenumclass,string)) }
  275. if not str_parse_method_dec('function valueOf(const __fpc_str: JLString): __FPC_TEnumClassAlias; static;',potype_function,true,enumclass,pd) then
  276. internalerror(2011062302);
  277. include(pd.procoptions,po_staticmethod);
  278. pd.synthetickind:=tsk_jvm_enum_valueof;
  279. { create array called "$VALUES" that will contain a reference to all
  280. enum instances (JDK convention)
  281. Disable duplicate identifier checking when inserting, because it will
  282. check for a conflict with "VALUES" ($<id> normally means "check for
  283. <id> without uppercasing first"), which will conflict with the
  284. "Values" instance method -- that's also the reason why we insert the
  285. field only now, because we cannot disable duplicate identifier
  286. checking when creating the "Values" method }
  287. sym:=tstaticvarsym.create('$VALUES',vs_final,arrdef,[]);
  288. sym.visibility:=vis_strictprivate;
  289. enumclass.symtable.insert(sym,false);
  290. { alias for consistency with parsed staticvarsyms }
  291. sl:=tpropaccesslist.create;
  292. sl.addsym(sl_load,sym);
  293. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),arrdef,sl));
  294. { alias for accessing the field in generated Pascal code }
  295. sl:=tpropaccesslist.create;
  296. sl.addsym(sl_load,sym);
  297. enumclass.symtable.insert(tabsolutevarsym.create_ref('__fpc_FVALUES',arrdef,sl));
  298. { add initialization of the static class fields created above }
  299. if not str_parse_method_dec('constructor fpc_enum_class_constructor;',potype_class_constructor,true,enumclass,pd) then
  300. internalerror(2011062303);
  301. pd.synthetickind:=tsk_jvm_enum_classconstr;
  302. symtablestack.pop(enumclass.symtable);
  303. current_structdef:=old_current_structdef;
  304. restore_scanner(sstate);
  305. end;
  306. end.