pjvm.pas 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. temptypesym: ttypesym;
  192. oldsymtablestack: tsymtablestack;
  193. islocal: boolean;
  194. begin
  195. { if it's a subrange type, don't create a new class }
  196. if assigned(tenumdef(def).basedef) then
  197. exit;
  198. replace_scanner('jvm_enum_class',sstate);
  199. oldsymtablestack:=symtablestack;
  200. islocal:=symtablestack.top.symtablelevel>=normal_function_level;
  201. if islocal then
  202. begin
  203. { we cannot add a class local to a procedure -> insert it in the
  204. static symtable. This is not ideal because this means that it will
  205. be saved to the ppu file for no good reason, and loaded again
  206. even though it contains a reference to a type that was never
  207. saved to the ppu file (the locally defined enum type). Since this
  208. alias for the locally defined enumtype is only used while
  209. implementing the class' methods, this is however no problem. }
  210. symtablestack:=symtablestack.getcopyuntil(current_module.localsymtable);
  211. end;
  212. { create new class (different internal name than enum to prevent name
  213. clash; at unit level because we don't want its methods to be nested
  214. inside a function in case its a local type) }
  215. enumclass:=tobjectdef.create(odt_javaclass,'$'+current_module.realmodulename^+'$'+name+'$InternEnum$'+tostr(def.defid),java_jlenum);
  216. tenumdef(def).classdef:=enumclass;
  217. include(enumclass.objectoptions,oo_is_enum_class);
  218. include(enumclass.objectoptions,oo_is_sealed);
  219. { create an alias for this type inside itself: this way we can choose a
  220. name that can be used in generated Pascal code without risking an
  221. identifier conflict (since it is local to this class; the global name
  222. is unique because it's an identifier that contains $-signs) }
  223. enumclass.symtable.insert(ttypesym.create('__FPC_TEnumClassAlias',enumclass));
  224. { also create an alias for the enum type so that we can iterate over
  225. all enum values when creating the body of the class constructor }
  226. temptypesym:=ttypesym.create('__FPC_TEnumAlias',nil);
  227. { don't pass def to the ttypesym constructor, because then it
  228. will replace the current (real) typesym of that def with the alias }
  229. temptypesym.typedef:=def;
  230. enumclass.symtable.insert(temptypesym);
  231. { but the name of the class as far as the JVM is concerned will match
  232. the enum's original name (the enum type itself won't be output in
  233. any class file, so no conflict there) }
  234. if not islocal then
  235. enumclass.objextname:=stringdup(name)
  236. else
  237. { for local types, use a unique name to prevent conflicts (since such
  238. types are not visible outside the routine anyway, it doesn't matter
  239. }
  240. begin
  241. enumclass.objextname:=stringdup(enumclass.objrealname^);
  242. { also mark it as private (not strict private, because the class
  243. is not a subclass of the unit in which it is declared, so then
  244. the unit's procedures would not be able to use it) }
  245. enumclass.typesym.visibility:=vis_private;
  246. end;
  247. { now add a bunch of extra things to the enum class }
  248. old_current_structdef:=current_structdef;
  249. current_structdef:=enumclass;
  250. symtablestack.push(enumclass.symtable);
  251. { create static fields representing all enums }
  252. for i:=0 to tenumdef(def).symtable.symlist.count-1 do
  253. begin
  254. sym:=tstaticvarsym.create(tenumsym(tenumdef(def).symtable.symlist[i]).realname,vs_final,enumclass,[]);
  255. enumclass.symtable.insert(sym);
  256. { alias for consistency with parsed staticvarsyms }
  257. sl:=tpropaccesslist.create;
  258. sl.addsym(sl_load,sym);
  259. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),enumclass,sl));
  260. end;
  261. { create local "array of enumtype" type for the "values" functionality
  262. (used internally by the JDK) }
  263. arrdef:=tarraydef.create(0,tenumdef(def).symtable.symlist.count-1,s32inttype);
  264. arrdef.elementdef:=enumclass;
  265. arrsym:=ttypesym.create('__FPC_TEnumValues',arrdef);
  266. enumclass.symtable.insert(arrsym);
  267. { insert "public static values: array of enumclass" that returns $VALUES.clone()
  268. (rather than a dynamic array and using clone --which we don't support yet for arrays--
  269. simply use a fixed length array and copy it) }
  270. if not str_parse_method_dec('function values: __FPC_TEnumValues;',potype_function,true,enumclass,pd) then
  271. internalerror(2011062301);
  272. include(pd.procoptions,po_staticmethod);
  273. pd.synthetickind:=tsk_jvm_enum_values;
  274. { do we have to store the ordinal value separately? (if no jumps, we can
  275. just call the default ordinal() java.lang.Enum function) }
  276. if tenumdef(def).has_jumps then
  277. begin
  278. { add field for the value }
  279. fsym:=tfieldvarsym.create('__fpc_fenumval',vs_final,s32inttype,[]);
  280. enumclass.symtable.insert(fsym);
  281. tobjectsymtable(enumclass.symtable).addfield(fsym,vis_strictprivate);
  282. { add class field with hash table that maps from FPC-declared ordinal value -> enum instance }
  283. juhashmap:=search_system_type('JUHASHMAP').typedef;
  284. sym:=tstaticvarsym.create('__fpc_ord2enum',vs_final,juhashmap,[]);
  285. enumclass.symtable.insert(sym);
  286. { alias for consistency with parsed staticvarsyms }
  287. sl:=tpropaccesslist.create;
  288. sl.addsym(sl_load,sym);
  289. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),enumclass,sl));
  290. { add custom constructor }
  291. if not str_parse_method_dec('constructor Create(const __fpc_name: JLString; const __fpc_ord, __fpc_initenumval: longint);',potype_constructor,false,enumclass,pd) then
  292. internalerror(2011062401);
  293. pd.synthetickind:=tsk_jvm_enum_jumps_constr;
  294. pd.visibility:=vis_strictprivate;
  295. end
  296. else
  297. begin
  298. { insert "private constructor(string,int,int)" that calls inherited and
  299. initialises the FPC value field }
  300. add_missing_parent_constructors_intf(enumclass,vis_strictprivate);
  301. end;
  302. { add instance method to get the enum's value as declared in FPC }
  303. if not str_parse_method_dec('function FPCOrdinal: longint;',potype_function,false,enumclass,pd) then
  304. internalerror(2011062402);
  305. pd.synthetickind:=tsk_jvm_enum_fpcordinal;
  306. { add static class method to convert an ordinal to the corresponding enum }
  307. if not str_parse_method_dec('function FPCValueOf(__fpc_int: longint): __FPC_TEnumClassAlias; static;',potype_function,true,enumclass,pd) then
  308. internalerror(2011062402);
  309. pd.synthetickind:=tsk_jvm_enum_fpcvalueof;
  310. { insert "public static valueOf(string): tenumclass" that returns tenumclass(inherited valueOf(tenumclass,string)) }
  311. if not str_parse_method_dec('function valueOf(const __fpc_str: JLString): __FPC_TEnumClassAlias; static;',potype_function,true,enumclass,pd) then
  312. internalerror(2011062302);
  313. include(pd.procoptions,po_staticmethod);
  314. pd.synthetickind:=tsk_jvm_enum_valueof;
  315. { create array called "$VALUES" that will contain a reference to all
  316. enum instances (JDK convention)
  317. Disable duplicate identifier checking when inserting, because it will
  318. check for a conflict with "VALUES" ($<id> normally means "check for
  319. <id> without uppercasing first"), which will conflict with the
  320. "Values" instance method -- that's also the reason why we insert the
  321. field only now, because we cannot disable duplicate identifier
  322. checking when creating the "Values" method }
  323. sym:=tstaticvarsym.create('$VALUES',vs_final,arrdef,[]);
  324. sym.visibility:=vis_strictprivate;
  325. enumclass.symtable.insert(sym,false);
  326. { alias for consistency with parsed staticvarsyms }
  327. sl:=tpropaccesslist.create;
  328. sl.addsym(sl_load,sym);
  329. enumclass.symtable.insert(tabsolutevarsym.create_ref('$'+internal_static_field_name(sym.name),arrdef,sl));
  330. { alias for accessing the field in generated Pascal code }
  331. sl:=tpropaccesslist.create;
  332. sl.addsym(sl_load,sym);
  333. enumclass.symtable.insert(tabsolutevarsym.create_ref('__fpc_FVALUES',arrdef,sl));
  334. { add initialization of the static class fields created above }
  335. if not str_parse_method_dec('constructor fpc_enum_class_constructor;',potype_class_constructor,true,enumclass,pd) then
  336. internalerror(2011062303);
  337. pd.synthetickind:=tsk_jvm_enum_classconstr;
  338. symtablestack.pop(enumclass.symtable);
  339. if islocal then
  340. begin
  341. symtablestack.free;
  342. symtablestack:=oldsymtablestack;
  343. end;
  344. current_structdef:=old_current_structdef;
  345. restore_scanner(sstate);
  346. end;
  347. procedure jvm_add_typed_const_initializer(csym: tconstsym);
  348. var
  349. ssym: tstaticvarsym;
  350. esym: tenumsym;
  351. i: longint;
  352. sstate: tscannerstate;
  353. begin
  354. case csym.constdef.typ of
  355. enumdef:
  356. begin
  357. replace_scanner('jvm_enum_const',sstate);
  358. { make sure we don't emit a definition for this field (we'll do
  359. that for the constsym already) -> mark as external }
  360. ssym:=tstaticvarsym.create(internal_static_field_name(csym.realname),vs_final,csym.constdef,[vo_is_external]);
  361. csym.owner.insert(ssym);
  362. { alias storage to the constsym }
  363. ssym.set_mangledname(csym.realname);
  364. for i:=0 to tenumdef(csym.constdef).symtable.symlist.count-1 do
  365. begin
  366. esym:=tenumsym(tenumdef(csym.constdef).symtable.symlist[i]);
  367. if esym.value=csym.value.valueord.svalue then
  368. break;
  369. esym:=nil;
  370. end;
  371. { can happen in case of explicit typecast from integer constant
  372. to enum type }
  373. if not assigned(esym) then
  374. begin
  375. MessagePos(csym.fileinfo,parser_e_range_check_error);
  376. exit;
  377. end;
  378. str_parse_typedconst(current_asmdata.asmlists[al_typedconsts],esym.name+';',ssym);
  379. restore_scanner(sstate);
  380. end
  381. else
  382. internalerror(2011062701);
  383. end;
  384. end;
  385. function jvm_wrap_method_with_vis(pd: tprocdef; vis: tvisibility): tprocdef;
  386. var
  387. obj: tabstractrecorddef;
  388. visname: string;
  389. begin
  390. obj:=current_structdef;
  391. { if someone gets the idea to add a property to an external class
  392. definition, don't try to wrap it since we cannot add methods to
  393. external classes }
  394. if oo_is_external in obj.objectoptions then
  395. begin
  396. result:=pd;
  397. exit
  398. end;
  399. result:=tprocdef(pd.getcopy);
  400. result.visibility:=vis;
  401. visname:=visibilityName[vis];
  402. replace(visname,' ','_');
  403. { create a name that is unique amongst all units (start with '$unitname$$') and
  404. unique in this unit (result.defid) }
  405. finish_copied_procdef(result,'$'+current_module.realmodulename^+'$$'+tostr(result.defid)+pd.procsym.realname+'$'+visname,obj.symtable,obj);
  406. { in case the referred method is from an external class }
  407. exclude(result.procoptions,po_external);
  408. { not virtual/override/abstract/... }
  409. result.procoptions:=result.procoptions*[po_classmethod,po_staticmethod,po_java,po_varargs,po_public];
  410. result.synthetickind:=tsk_callthrough;
  411. { so we know the name of the routine to call through to }
  412. result.skpara:=pd;
  413. end;
  414. end.