pjvm.pas 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. symconst,symtype,symbase,symdef,symsym;
  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. procedure jvm_add_typed_const_initializer(csym: tconstsym);
  32. function jvm_wrap_method_with_vis(pd: tprocdef; vis: tvisibility): tprocdef;
  33. implementation
  34. uses
  35. cutils,cclasses,
  36. verbose,systems,
  37. fmodule,
  38. parabase,aasmdata,
  39. pdecsub,
  40. symtable,symcreat,defcmp,jvmdef,
  41. defutil,paramgr;
  42. { the JVM specs require that you add a default parameterless
  43. constructor in case the programmer hasn't specified any }
  44. procedure maybe_add_public_default_java_constructor(obj: tabstractrecorddef);
  45. var
  46. sym: tsym;
  47. ps: tprocsym;
  48. pd: tprocdef;
  49. topowner: tdefentry;
  50. i: longint;
  51. sstate: tscannerstate;
  52. needclassconstructor: boolean;
  53. begin
  54. { if there is at least one constructor for a class, do nothing (for
  55. records, we'll always also need a parameterless constructor) }
  56. if not is_javaclass(obj) or
  57. not (oo_has_constructor in obj.objectoptions) then
  58. begin
  59. { check whether the parent has a parameterless constructor that we can
  60. call (in case of a class; all records will derive from
  61. java.lang.Object or a shim on top of that with a parameterless
  62. constructor) }
  63. if is_javaclass(obj) then
  64. begin
  65. pd:=nil;
  66. sym:=tsym(tobjectdef(obj).childof.symtable.find('CREATE'));
  67. if assigned(sym) and
  68. (sym.typ=procsym) then
  69. pd:=tprocsym(sym).find_bytype_parameterless(potype_constructor);
  70. if not assigned(pd) then
  71. begin
  72. Message(sym_e_no_matching_inherited_parameterless_constructor);
  73. exit
  74. end;
  75. end;
  76. { we call all constructors CREATE, because they don't have a name in
  77. Java and otherwise we can't determine whether multiple overloads
  78. are created with the same parameters }
  79. sym:=tsym(obj.symtable.find('CREATE'));
  80. if assigned(sym) then
  81. begin
  82. { does another, non-procsym, symbol already exist with that name? }
  83. if (sym.typ<>procsym) then
  84. begin
  85. Message1(sym_e_duplicate_id_create_java_constructor,sym.realname);
  86. exit;
  87. end;
  88. ps:=tprocsym(sym);
  89. { is there already a parameterless function/procedure create? }
  90. pd:=ps.find_bytype_parameterless(potype_function);
  91. if not assigned(pd) then
  92. pd:=ps.find_bytype_parameterless(potype_procedure);
  93. if assigned(pd) then
  94. begin
  95. Message1(sym_e_duplicate_id_create_java_constructor,pd.fullprocname(false));
  96. exit;
  97. end;
  98. end;
  99. if not assigned(sym) then
  100. begin
  101. ps:=tprocsym.create('Create');
  102. obj.symtable.insert(ps);
  103. end;
  104. { determine symtable level }
  105. topowner:=obj;
  106. while not(topowner.owner.symtabletype in [staticsymtable,globalsymtable]) do
  107. topowner:=topowner.owner.defowner;
  108. { create procdef }
  109. pd:=tprocdef.create(topowner.owner.symtablelevel+1);
  110. { method of this objectdef }
  111. pd.struct:=obj;
  112. { associated procsym }
  113. pd.procsym:=ps;
  114. { constructor }
  115. pd.proctypeoption:=potype_constructor;
  116. { needs to be exported }
  117. include(pd.procoptions,po_global);
  118. { for Delphi mode }
  119. include(pd.procoptions,po_overload);
  120. { generate anonymous inherited call in the implementation }
  121. pd.synthetickind:=tsk_anon_inherited;
  122. { public }
  123. pd.visibility:=vis_public;
  124. { result type }
  125. pd.returndef:=obj;
  126. { calling convention, self, ... }
  127. handle_calling_convention(pd);
  128. { register forward declaration with procsym }
  129. proc_add_definition(pd);
  130. end;
  131. { also add class constructor if class fields that need wrapping, and
  132. if none was defined }
  133. if obj.find_procdef_bytype(potype_class_constructor)=nil then
  134. begin
  135. needclassconstructor:=false;
  136. for i:=0 to obj.symtable.symlist.count-1 do
  137. begin
  138. if (tsym(obj.symtable.symlist[i]).typ=staticvarsym) and
  139. jvmimplicitpointertype(tstaticvarsym(obj.symtable.symlist[i]).vardef) then
  140. begin
  141. needclassconstructor:=true;
  142. break;
  143. end;
  144. end;
  145. if needclassconstructor then
  146. begin
  147. replace_scanner('custom_class_constructor',sstate);
  148. if str_parse_method_dec('constructor fpc_jvm_class_constructor;',potype_class_constructor,true,obj,pd) then
  149. pd.synthetickind:=tsk_empty
  150. else
  151. internalerror(2011040501);
  152. restore_scanner(sstate);
  153. end;
  154. end;
  155. end;
  156. procedure add_java_default_record_methods_intf(def: trecorddef);
  157. var
  158. sstate: tscannerstate;
  159. pd: tprocdef;
  160. begin
  161. maybe_add_public_default_java_constructor(def);
  162. replace_scanner('record_jvm_helpers',sstate);
  163. { no override, because not supported in records; the parser will still
  164. accept "inherited" though }
  165. if str_parse_method_dec('function clone: JLObject;',potype_function,false,def,pd) then
  166. pd.synthetickind:=tsk_jvm_clone
  167. else
  168. internalerror(2011032806);
  169. { can't use def.typesym, not yet set at this point }
  170. if not assigned(def.symtable.realname) then
  171. internalerror(2011032803);
  172. if str_parse_method_dec('procedure fpcDeepCopy(out result:'+def.symtable.realname^+');',potype_procedure,false,def,pd) then
  173. pd.synthetickind:=tsk_record_deepcopy
  174. else
  175. internalerror(2011032807);
  176. restore_scanner(sstate);
  177. end;
  178. procedure jvm_maybe_create_enum_class(const name: TIDString; def: tdef);
  179. var
  180. arrdef: tarraydef;
  181. arrsym: ttypesym;
  182. juhashmap: tdef;
  183. enumclass: tobjectdef;
  184. pd: tprocdef;
  185. old_current_structdef: tabstractrecorddef;
  186. i: longint;
  187. sym: tstaticvarsym;
  188. fsym: tfieldvarsym;
  189. sstate: tscannerstate;
  190. sl: tpropaccesslist;
  191. begin
  192. { if it's a subrange type, don't create a new class }
  193. if assigned(tenumdef(def).basedef) then
  194. exit;
  195. replace_scanner('jvm_enum_class',sstate);
  196. { create new class (different internal name than enum to prevent name clash) }
  197. enumclass:=tobjectdef.create(odt_javaclass,'$'+name+'$InternEnum',java_jlenum);
  198. tenumdef(def).classdef:=enumclass;
  199. include(enumclass.objectoptions,oo_is_enum_class);
  200. include(enumclass.objectoptions,oo_is_sealed);
  201. { create an alias for this type inside itself: this way we can choose a
  202. name that can be used in generated Pascal code without risking an
  203. identifier conflict (since it is local to this class; the global name
  204. is unique because it's an identifier that contains $-signs) }
  205. enumclass.symtable.insert(ttypesym.create('__FPC_TEnumClassAlias',enumclass));
  206. { also create an alias for the enum type so that we can iterate over
  207. all enum values when creating the body of the class constructor }
  208. enumclass.symtable.insert(ttypesym.create('__FPC_TEnumAlias',def));
  209. { but the name of the class as far as the JVM is concerned will match
  210. the enum's original name (the enum type itself won't be output in
  211. any class file, so no conflict there) }
  212. enumclass.objextname:=stringdup(name);
  213. { now add a bunch of extra things to the enum class }
  214. old_current_structdef:=current_structdef;
  215. current_structdef:=enumclass;
  216. symtablestack.push(enumclass.symtable);
  217. { create static fields representing all enums }
  218. for i:=0 to tenumdef(def).symtable.symlist.count-1 do
  219. begin
  220. sym:=tstaticvarsym.create(tenumsym(tenumdef(def).symtable.symlist[i]).realname,vs_final,enumclass,[]);
  221. enumclass.symtable.insert(sym);
  222. { alias for consistency with parsed staticvarsyms }
  223. sl:=tpropaccesslist.create;
  224. sl.addsym(sl_load,sym);
  225. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),enumclass,sl));
  226. end;
  227. { create local "array of enumtype" type for the "values" functionality
  228. (used internally by the JDK) }
  229. arrdef:=tarraydef.create(0,tenumdef(def).symtable.symlist.count-1,s32inttype);
  230. arrdef.elementdef:=enumclass;
  231. arrsym:=ttypesym.create('__FPC_TEnumValues',arrdef);
  232. enumclass.symtable.insert(arrsym);
  233. { insert "public static values: array of enumclass" that returns $VALUES.clone()
  234. (rather than a dynamic array and using clone --which we don't support yet for arrays--
  235. simply use a fixed length array and copy it) }
  236. if not str_parse_method_dec('function values: __FPC_TEnumValues;',potype_function,true,enumclass,pd) then
  237. internalerror(2011062301);
  238. include(pd.procoptions,po_staticmethod);
  239. pd.synthetickind:=tsk_jvm_enum_values;
  240. { do we have to store the ordinal value separately? (if no jumps, we can
  241. just call the default ordinal() java.lang.Enum function) }
  242. if tenumdef(def).has_jumps then
  243. begin
  244. { add field for the value }
  245. fsym:=tfieldvarsym.create('__fpc_fenumval',vs_final,s32inttype,[]);
  246. enumclass.symtable.insert(fsym);
  247. tobjectsymtable(enumclass.symtable).addfield(fsym,vis_strictprivate);
  248. { add class field with hash table that maps from FPC-declared ordinal value -> enum instance }
  249. juhashmap:=search_system_type('JUHASHMAP').typedef;
  250. sym:=tstaticvarsym.create('__fpc_ord2enum',vs_final,juhashmap,[]);
  251. enumclass.symtable.insert(sym);
  252. { alias for consistency with parsed staticvarsyms }
  253. sl:=tpropaccesslist.create;
  254. sl.addsym(sl_load,sym);
  255. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),enumclass,sl));
  256. { add custom constructor }
  257. if not str_parse_method_dec('constructor Create(const __fpc_name: JLString; const __fpc_ord, __fpc_initenumval: longint);',potype_constructor,false,enumclass,pd) then
  258. internalerror(2011062401);
  259. pd.synthetickind:=tsk_jvm_enum_jumps_constr;
  260. pd.visibility:=vis_strictprivate;
  261. end
  262. else
  263. begin
  264. { insert "private constructor(string,int,int)" that calls inherited and
  265. initialises the FPC value field }
  266. add_missing_parent_constructors_intf(enumclass,vis_strictprivate);
  267. end;
  268. { add instance method to get the enum's value as declared in FPC }
  269. if not str_parse_method_dec('function FPCOrdinal: longint;',potype_function,false,enumclass,pd) then
  270. internalerror(2011062402);
  271. pd.synthetickind:=tsk_jvm_enum_fpcordinal;
  272. { add static class method to convert an ordinal to the corresponding enum }
  273. if not str_parse_method_dec('function FPCValueOf(__fpc_int: longint): __FPC_TEnumClassAlias; static;',potype_function,true,enumclass,pd) then
  274. internalerror(2011062402);
  275. pd.synthetickind:=tsk_jvm_enum_fpcvalueof;
  276. { insert "public static valueOf(string): tenumclass" that returns tenumclass(inherited valueOf(tenumclass,string)) }
  277. if not str_parse_method_dec('function valueOf(const __fpc_str: JLString): __FPC_TEnumClassAlias; static;',potype_function,true,enumclass,pd) then
  278. internalerror(2011062302);
  279. include(pd.procoptions,po_staticmethod);
  280. pd.synthetickind:=tsk_jvm_enum_valueof;
  281. { create array called "$VALUES" that will contain a reference to all
  282. enum instances (JDK convention)
  283. Disable duplicate identifier checking when inserting, because it will
  284. check for a conflict with "VALUES" ($<id> normally means "check for
  285. <id> without uppercasing first"), which will conflict with the
  286. "Values" instance method -- that's also the reason why we insert the
  287. field only now, because we cannot disable duplicate identifier
  288. checking when creating the "Values" method }
  289. sym:=tstaticvarsym.create('$VALUES',vs_final,arrdef,[]);
  290. sym.visibility:=vis_strictprivate;
  291. enumclass.symtable.insert(sym,false);
  292. { alias for consistency with parsed staticvarsyms }
  293. sl:=tpropaccesslist.create;
  294. sl.addsym(sl_load,sym);
  295. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),arrdef,sl));
  296. { alias for accessing the field in generated Pascal code }
  297. sl:=tpropaccesslist.create;
  298. sl.addsym(sl_load,sym);
  299. enumclass.symtable.insert(tabsolutevarsym.create_ref('__fpc_FVALUES',arrdef,sl));
  300. { add initialization of the static class fields created above }
  301. if not str_parse_method_dec('constructor fpc_enum_class_constructor;',potype_class_constructor,true,enumclass,pd) then
  302. internalerror(2011062303);
  303. pd.synthetickind:=tsk_jvm_enum_classconstr;
  304. symtablestack.pop(enumclass.symtable);
  305. current_structdef:=old_current_structdef;
  306. restore_scanner(sstate);
  307. end;
  308. procedure jvm_add_typed_const_initializer(csym: tconstsym);
  309. var
  310. ssym: tstaticvarsym;
  311. esym: tenumsym;
  312. i: longint;
  313. sstate: tscannerstate;
  314. begin
  315. case csym.constdef.typ of
  316. enumdef:
  317. begin
  318. replace_scanner('jvm_enum_const',sstate);
  319. { make sure we don't emit a definition for this field (we'll do
  320. that for the constsym already) -> mark as external }
  321. ssym:=tstaticvarsym.create(internal_static_field_name(csym.realname),vs_final,csym.constdef,[vo_is_external]);
  322. csym.owner.insert(ssym);
  323. { alias storage to the constsym }
  324. ssym.set_mangledname(csym.realname);
  325. for i:=0 to tenumdef(csym.constdef).symtable.symlist.count-1 do
  326. begin
  327. esym:=tenumsym(tenumdef(csym.constdef).symtable.symlist[i]);
  328. if esym.value=csym.value.valueord.svalue then
  329. break;
  330. esym:=nil;
  331. end;
  332. { can happen in case of explicit typecast from integer constant
  333. to enum type }
  334. if not assigned(esym) then
  335. begin
  336. MessagePos(csym.fileinfo,parser_e_range_check_error);
  337. exit;
  338. end;
  339. str_parse_typedconst(current_asmdata.asmlists[al_typedconsts],esym.name+';',ssym);
  340. restore_scanner(sstate);
  341. end
  342. else
  343. internalerror(2011062701);
  344. end;
  345. end;
  346. function jvm_wrap_method_with_vis(pd: tprocdef; vis: tvisibility): tprocdef;
  347. var
  348. obj: tabstractrecorddef;
  349. visname: string;
  350. begin
  351. obj:=current_structdef;
  352. { if someone gets the idea to add a property to an external class
  353. definition, don't try to wrap it since we cannot add methods to
  354. external classes }
  355. if oo_is_external in obj.objectoptions then
  356. begin
  357. result:=pd;
  358. exit
  359. end;
  360. result:=tprocdef(pd.getcopy);
  361. result.visibility:=vis;
  362. visname:=visibilityName[vis];
  363. replace(visname,' ','_');
  364. { create a name that is unique amongst all units (start with '$unitname$$') and
  365. unique in this unit (result.defid) }
  366. finish_copied_procdef(result,'$'+current_module.realmodulename^+'$$'+tostr(result.defid)+pd.procsym.realname+'$'+visname,obj.symtable,obj);
  367. { in case the referred method is from an external class }
  368. exclude(result.procoptions,po_external);
  369. { not virtual/override/abstract/... }
  370. result.procoptions:=result.procoptions*[po_classmethod,po_staticmethod,po_java,po_varargs,po_public];
  371. result.synthetickind:=tsk_callthrough;
  372. { so we know the name of the routine to call through to }
  373. result.skpara:=pd;
  374. end;
  375. end.