pjvm.pas 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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_create_procvar_class(const name: TIDString; def: tdef);
  32. procedure jvm_wrap_virtual_class_methods(obj: tobjectdef);
  33. function jvm_add_typed_const_initializer(csym: tconstsym): tstaticvarsym;
  34. function jvm_wrap_method_with_vis(pd: tprocdef; vis: tvisibility): tprocdef;
  35. { when a private/protected field is exposed via a property with a higher
  36. visibility, then we have to create a getter and/or setter with that same
  37. higher visibility to make sure that using the property does not result
  38. in JVM verification errors }
  39. procedure jvm_create_getter_for_property(p: tpropertysym);
  40. procedure jvm_create_setter_for_property(p: tpropertysym);
  41. implementation
  42. uses
  43. cutils,cclasses,
  44. verbose,systems,
  45. fmodule,
  46. parabase,aasmdata,
  47. pdecsub,ngenutil,pparautl,
  48. symtable,symcreat,defcmp,jvmdef,nobj,
  49. defutil,paramgr;
  50. { the JVM specs require that you add a default parameterless
  51. constructor in case the programmer hasn't specified any }
  52. procedure maybe_add_public_default_java_constructor(obj: tabstractrecorddef);
  53. var
  54. sym: tsym;
  55. ps: tprocsym;
  56. pd: tprocdef;
  57. topowner: tdefentry;
  58. i: longint;
  59. sstate: tscannerstate;
  60. needclassconstructor: boolean;
  61. begin
  62. { if there is at least one constructor for a class, do nothing (for
  63. records, we'll always also need a parameterless constructor) }
  64. if not is_javaclass(obj) or
  65. not (oo_has_constructor in obj.objectoptions) then
  66. begin
  67. { check whether the parent has a parameterless constructor that we can
  68. call (in case of a class; all records will derive from
  69. java.lang.Object or a shim on top of that with a parameterless
  70. constructor) }
  71. if is_javaclass(obj) then
  72. begin
  73. pd:=nil;
  74. sym:=tsym(tobjectdef(obj).childof.symtable.find('CREATE'));
  75. if assigned(sym) and
  76. (sym.typ=procsym) then
  77. pd:=tprocsym(sym).find_bytype_parameterless(potype_constructor);
  78. if not assigned(pd) then
  79. begin
  80. Message(sym_e_no_matching_inherited_parameterless_constructor);
  81. exit
  82. end;
  83. end;
  84. { we call all constructors CREATE, because they don't have a name in
  85. Java and otherwise we can't determine whether multiple overloads
  86. are created with the same parameters }
  87. sym:=tsym(obj.symtable.find('CREATE'));
  88. if assigned(sym) then
  89. begin
  90. { does another, non-procsym, symbol already exist with that name? }
  91. if (sym.typ<>procsym) then
  92. begin
  93. Message1(sym_e_duplicate_id_create_java_constructor,sym.realname);
  94. exit;
  95. end;
  96. ps:=tprocsym(sym);
  97. { is there already a parameterless function/procedure create? }
  98. pd:=ps.find_bytype_parameterless(potype_function);
  99. if not assigned(pd) then
  100. pd:=ps.find_bytype_parameterless(potype_procedure);
  101. if assigned(pd) then
  102. begin
  103. Message1(sym_e_duplicate_id_create_java_constructor,pd.fullprocname(false));
  104. exit;
  105. end;
  106. end;
  107. if not assigned(sym) then
  108. begin
  109. ps:=tprocsym.create('Create');
  110. obj.symtable.insert(ps);
  111. end;
  112. { determine symtable level }
  113. topowner:=obj;
  114. while not(topowner.owner.symtabletype in [staticsymtable,globalsymtable]) do
  115. topowner:=topowner.owner.defowner;
  116. { create procdef }
  117. pd:=tprocdef.create(topowner.owner.symtablelevel+1);
  118. { method of this objectdef }
  119. pd.struct:=obj;
  120. { associated procsym }
  121. pd.procsym:=ps;
  122. { constructor }
  123. pd.proctypeoption:=potype_constructor;
  124. { needs to be exported }
  125. include(pd.procoptions,po_global);
  126. { by default do not include this routine when looking for overloads }
  127. include(pd.procoptions,po_ignore_for_overload_resolution);
  128. { generate anonymous inherited call in the implementation }
  129. pd.synthetickind:=tsk_anon_inherited;
  130. { public }
  131. pd.visibility:=vis_public;
  132. { result type }
  133. pd.returndef:=obj;
  134. { calling convention, self, ... }
  135. handle_calling_convention(pd);
  136. { register forward declaration with procsym }
  137. proc_add_definition(pd);
  138. end;
  139. { also add class constructor if class fields that need wrapping, and
  140. if none was defined }
  141. if obj.find_procdef_bytype(potype_class_constructor)=nil then
  142. begin
  143. needclassconstructor:=false;
  144. for i:=0 to obj.symtable.symlist.count-1 do
  145. begin
  146. if (tsym(obj.symtable.symlist[i]).typ=staticvarsym) and
  147. jvmimplicitpointertype(tstaticvarsym(obj.symtable.symlist[i]).vardef) then
  148. begin
  149. needclassconstructor:=true;
  150. break;
  151. end;
  152. end;
  153. if needclassconstructor then
  154. begin
  155. replace_scanner('custom_class_constructor',sstate);
  156. if str_parse_method_dec('constructor fpc_jvm_class_constructor;',potype_class_constructor,true,obj,pd) then
  157. pd.synthetickind:=tsk_empty
  158. else
  159. internalerror(2011040501);
  160. restore_scanner(sstate);
  161. end;
  162. end;
  163. end;
  164. procedure add_java_default_record_methods_intf(def: trecorddef);
  165. var
  166. sstate: tscannerstate;
  167. pd: tprocdef;
  168. sym: tsym;
  169. i: longint;
  170. begin
  171. maybe_add_public_default_java_constructor(def);
  172. replace_scanner('record_jvm_helpers',sstate);
  173. { no override, because not supported in records. Only required in case
  174. some of the fields require deep copies (otherwise the default
  175. shallow clone is fine) }
  176. for i:=0 to def.symtable.symlist.count-1 do
  177. begin
  178. sym:=tsym(def.symtable.symlist[i]);
  179. if (sym.typ=fieldvarsym) and
  180. jvmimplicitpointertype(tfieldvarsym(sym).vardef) then
  181. begin
  182. if str_parse_method_dec('function clone: JLObject;',potype_function,false,def,pd) then
  183. pd.synthetickind:=tsk_jvm_clone
  184. else
  185. internalerror(2011032806);
  186. break;
  187. end;
  188. end;
  189. { can't use def.typesym, not yet set at this point }
  190. if not assigned(def.symtable.realname) then
  191. internalerror(2011032803);
  192. if str_parse_method_dec('procedure fpcDeepCopy(result: FpcBaseRecordType);override;',potype_procedure,false,def,pd) then
  193. pd.synthetickind:=tsk_record_deepcopy
  194. else
  195. internalerror(2011032807);
  196. if def.needs_inittable then
  197. begin
  198. { 'var' instead of 'out' parameter, because 'out' would trigger
  199. calling the initialize method recursively }
  200. if str_parse_method_dec('procedure fpcInitializeRec;',potype_procedure,false,def,pd) then
  201. pd.synthetickind:=tsk_record_initialize
  202. else
  203. internalerror(2011071711);
  204. end;
  205. restore_scanner(sstate);
  206. end;
  207. procedure setup_for_new_class(const scannername: string; out sstate: tscannerstate; out islocal: boolean; out oldsymtablestack: TSymtablestack);
  208. begin
  209. replace_scanner(scannername,sstate);
  210. oldsymtablestack:=symtablestack;
  211. islocal:=symtablestack.top.symtablelevel>=normal_function_level;
  212. if islocal then
  213. begin
  214. { we cannot add a class local to a procedure -> insert it in the
  215. static symtable. This is not ideal because this means that it will
  216. be saved to the ppu file for no good reason, and loaded again
  217. even though it contains a reference to a type that was never
  218. saved to the ppu file (the locally defined enum type). Since this
  219. alias for the locally defined enumtype is only used while
  220. implementing the class' methods, this is however no problem. }
  221. symtablestack:=symtablestack.getcopyuntil(current_module.localsymtable);
  222. end;
  223. end;
  224. procedure restore_after_new_class(const sstate: tscannerstate; const islocal: boolean; const oldsymtablestack: TSymtablestack);
  225. begin
  226. if islocal then
  227. begin
  228. symtablestack.free;
  229. symtablestack:=oldsymtablestack;
  230. end;
  231. restore_scanner(sstate);
  232. end;
  233. procedure jvm_maybe_create_enum_class(const name: TIDString; def: tdef);
  234. var
  235. vmtbuilder: tvmtbuilder;
  236. arrdef: tarraydef;
  237. arrsym: ttypesym;
  238. juhashmap: tdef;
  239. enumclass: tobjectdef;
  240. pd: tprocdef;
  241. old_current_structdef: tabstractrecorddef;
  242. i: longint;
  243. sym,
  244. aliassym: tstaticvarsym;
  245. fsym: tfieldvarsym;
  246. sstate: tscannerstate;
  247. sl: tpropaccesslist;
  248. temptypesym: ttypesym;
  249. oldsymtablestack: tsymtablestack;
  250. islocal: boolean;
  251. begin
  252. { if it's a subrange type, don't create a new class }
  253. if assigned(tenumdef(def).basedef) then
  254. exit;
  255. setup_for_new_class('jvm_enum_class',sstate,islocal,oldsymtablestack);
  256. { create new class (different internal name than enum to prevent name
  257. clash; at unit level because we don't want its methods to be nested
  258. inside a function in case its a local type) }
  259. enumclass:=tobjectdef.create(odt_javaclass,'$'+current_module.realmodulename^+'$'+name+'$InternEnum$'+tostr(def.defid),java_jlenum);
  260. tenumdef(def).classdef:=enumclass;
  261. include(enumclass.objectoptions,oo_is_enum_class);
  262. include(enumclass.objectoptions,oo_is_sealed);
  263. { implement FpcEnumValueObtainable interface }
  264. enumclass.ImplementedInterfaces.add(TImplementedInterface.Create(tobjectdef(search_system_type('FPCENUMVALUEOBTAINABLE').typedef)));
  265. { create an alias for this type inside itself: this way we can choose a
  266. name that can be used in generated Pascal code without risking an
  267. identifier conflict (since it is local to this class; the global name
  268. is unique because it's an identifier that contains $-signs) }
  269. enumclass.symtable.insert(ttypesym.create('__FPC_TEnumClassAlias',enumclass));
  270. { also create an alias for the enum type so that we can iterate over
  271. all enum values when creating the body of the class constructor }
  272. temptypesym:=ttypesym.create('__FPC_TEnumAlias',nil);
  273. { don't pass def to the ttypesym constructor, because then it
  274. will replace the current (real) typesym of that def with the alias }
  275. temptypesym.typedef:=def;
  276. enumclass.symtable.insert(temptypesym);
  277. { but the name of the class as far as the JVM is concerned will match
  278. the enum's original name (the enum type itself won't be output in
  279. any class file, so no conflict there) }
  280. if not islocal then
  281. enumclass.objextname:=stringdup(name)
  282. else
  283. { for local types, use a unique name to prevent conflicts (since such
  284. types are not visible outside the routine anyway, it doesn't matter
  285. }
  286. begin
  287. enumclass.objextname:=stringdup(enumclass.objrealname^);
  288. { also mark it as private (not strict private, because the class
  289. is not a subclass of the unit in which it is declared, so then
  290. the unit's procedures would not be able to use it) }
  291. enumclass.typesym.visibility:=vis_private;
  292. end;
  293. { now add a bunch of extra things to the enum class }
  294. old_current_structdef:=current_structdef;
  295. current_structdef:=enumclass;
  296. symtablestack.push(enumclass.symtable);
  297. { create static fields representing all enums }
  298. for i:=0 to tenumdef(def).symtable.symlist.count-1 do
  299. begin
  300. fsym:=tfieldvarsym.create(tenumsym(tenumdef(def).symtable.symlist[i]).realname,vs_final,enumclass,[]);
  301. enumclass.symtable.insert(fsym);
  302. sym:=make_field_static(enumclass.symtable,fsym);
  303. { add alias for the field representing ordinal(0), for use in
  304. initialization code }
  305. if tenumsym(tenumdef(def).symtable.symlist[i]).value=0 then
  306. begin
  307. aliassym:=tstaticvarsym.create('__FPC_Zero_Initializer',vs_final,enumclass,[vo_is_external]);
  308. enumclass.symtable.insert(aliassym);
  309. aliassym.set_raw_mangledname(sym.mangledname);
  310. end;
  311. end;
  312. { create local "array of enumtype" type for the "values" functionality
  313. (used internally by the JDK) }
  314. arrdef:=tarraydef.create(0,tenumdef(def).symtable.symlist.count-1,s32inttype);
  315. arrdef.elementdef:=enumclass;
  316. arrsym:=ttypesym.create('__FPC_TEnumValues',arrdef);
  317. enumclass.symtable.insert(arrsym);
  318. { insert "public static values: array of enumclass" that returns $VALUES.clone()
  319. (rather than a dynamic array and using clone --which we don't support yet for arrays--
  320. simply use a fixed length array and copy it) }
  321. if not str_parse_method_dec('function values: __FPC_TEnumValues;static;',potype_function,true,enumclass,pd) then
  322. internalerror(2011062301);
  323. include(pd.procoptions,po_staticmethod);
  324. pd.synthetickind:=tsk_jvm_enum_values;
  325. { do we have to store the ordinal value separately? (if no jumps, we can
  326. just call the default ordinal() java.lang.Enum function) }
  327. if tenumdef(def).has_jumps then
  328. begin
  329. { add field for the value }
  330. fsym:=tfieldvarsym.create('__fpc_fenumval',vs_final,s32inttype,[]);
  331. enumclass.symtable.insert(fsym);
  332. tobjectsymtable(enumclass.symtable).addfield(fsym,vis_strictprivate);
  333. { add class field with hash table that maps from FPC-declared ordinal value -> enum instance }
  334. juhashmap:=search_system_type('JUHASHMAP').typedef;
  335. fsym:=tfieldvarsym.create('__fpc_ord2enum',vs_final,juhashmap,[]);
  336. enumclass.symtable.insert(fsym);
  337. make_field_static(enumclass.symtable,fsym);
  338. { add custom constructor }
  339. if not str_parse_method_dec('constructor Create(const __fpc_name: JLString; const __fpc_ord, __fpc_initenumval: longint);',potype_constructor,false,enumclass,pd) then
  340. internalerror(2011062401);
  341. pd.synthetickind:=tsk_jvm_enum_jumps_constr;
  342. pd.visibility:=vis_strictprivate;
  343. end
  344. else
  345. begin
  346. { insert "private constructor(string,int,int)" that calls inherited and
  347. initialises the FPC value field }
  348. add_missing_parent_constructors_intf(enumclass,false,vis_strictprivate);
  349. end;
  350. { add instance method to get the enum's value as declared in FPC }
  351. if not str_parse_method_dec('function FPCOrdinal: longint;',potype_function,false,enumclass,pd) then
  352. internalerror(2011062402);
  353. pd.synthetickind:=tsk_jvm_enum_fpcordinal;
  354. { add static class method to convert an ordinal to the corresponding enum }
  355. if not str_parse_method_dec('function FPCValueOf(__fpc_int: longint): __FPC_TEnumClassAlias; static;',potype_function,true,enumclass,pd) then
  356. internalerror(2011062402);
  357. pd.synthetickind:=tsk_jvm_enum_fpcvalueof;
  358. { similar (instance) function for use in set factories; implements FpcEnumValueObtainable interface }
  359. if not str_parse_method_dec('function fpcGenericValueOf(__fpc_int: longint): JLEnum;',potype_function,false,enumclass,pd) then
  360. internalerror(2011062402);
  361. pd.synthetickind:=tsk_jvm_enum_fpcvalueof;
  362. { insert "public static valueOf(string): tenumclass" that returns tenumclass(inherited valueOf(tenumclass,string)) }
  363. if not str_parse_method_dec('function valueOf(const __fpc_str: JLString): __FPC_TEnumClassAlias; static;',potype_function,true,enumclass,pd) then
  364. internalerror(2011062302);
  365. include(pd.procoptions,po_staticmethod);
  366. pd.synthetickind:=tsk_jvm_enum_valueof;
  367. { add instance method to convert an ordinal and an array into a set of
  368. (we always need/can use both in case of subrange types and/or array
  369. -> set type casts) }
  370. if not str_parse_method_dec('function fpcLongToEnumSet(__val: jlong; __setbase, __setsize: jint): JUEnumSet;',potype_function,true,enumclass,pd) then
  371. internalerror(2011070501);
  372. pd.synthetickind:=tsk_jvm_enum_long2set;
  373. if not str_parse_method_dec('function fpcBitSetToEnumSet(const __val: FpcBitSet; __fromsetbase, __tosetbase: jint): JUEnumSet; static;',potype_function,true,enumclass,pd) then
  374. internalerror(2011071004);
  375. pd.synthetickind:=tsk_jvm_enum_bitset2set;
  376. if not str_parse_method_dec('function fpcEnumSetToEnumSet(const __val: JUEnumSet; __fromsetbase, __tosetbase: jint): JUEnumSet; static;',potype_function,true,enumclass,pd) then
  377. internalerror(2011071005);
  378. pd.synthetickind:=tsk_jvm_enum_set2set;
  379. { create array called "$VALUES" that will contain a reference to all
  380. enum instances (JDK convention)
  381. Disable duplicate identifier checking when inserting, because it will
  382. check for a conflict with "VALUES" ($<id> normally means "check for
  383. <id> without uppercasing first"), which will conflict with the
  384. "Values" instance method -- that's also the reason why we insert the
  385. field only now, because we cannot disable duplicate identifier
  386. checking when creating the "Values" method }
  387. fsym:=tfieldvarsym.create('$VALUES',vs_final,arrdef,[]);
  388. fsym.visibility:=vis_strictprivate;
  389. enumclass.symtable.insert(fsym,false);
  390. sym:=make_field_static(enumclass.symtable,fsym);
  391. { alias for accessing the field in generated Pascal code }
  392. sl:=tpropaccesslist.create;
  393. sl.addsym(sl_load,sym);
  394. enumclass.symtable.insert(tabsolutevarsym.create_ref('__fpc_FVALUES',arrdef,sl));
  395. { add initialization of the static class fields created above }
  396. if not str_parse_method_dec('constructor fpc_enum_class_constructor;',potype_class_constructor,true,enumclass,pd) then
  397. internalerror(2011062303);
  398. pd.synthetickind:=tsk_jvm_enum_classconstr;
  399. symtablestack.pop(enumclass.symtable);
  400. vmtbuilder:=TVMTBuilder.Create(enumclass);
  401. vmtbuilder.generate_vmt;
  402. vmtbuilder.free;
  403. restore_after_new_class(sstate,islocal,oldsymtablestack);
  404. current_structdef:=old_current_structdef;
  405. end;
  406. procedure jvm_create_procvar_class(const name: TIDString; def: tdef);
  407. var
  408. vmtbuilder: tvmtbuilder;
  409. oldsymtablestack: tsymtablestack;
  410. pvclass: tobjectdef;
  411. temptypesym: ttypesym;
  412. sstate: tscannerstate;
  413. methoddef: tprocdef;
  414. islocal: boolean;
  415. begin
  416. { inlined definition of procvar -> generate name, derive from
  417. FpcBaseNestedProcVarType, pass nestedfpstruct to constructor and
  418. copy it }
  419. if name='' then
  420. internalerror(2011071901);
  421. setup_for_new_class('jvm_pvar_class',sstate,islocal,oldsymtablestack);
  422. { create new class (different internal name than pvar to prevent name
  423. clash; at unit level because we don't want its methods to be nested
  424. inside a function in case its a local type) }
  425. pvclass:=tobjectdef.create(odt_javaclass,'$'+current_module.realmodulename^+'$'+name+'$InternProcvar$'+tostr(def.defid),java_procvarbase);
  426. tprocvardef(def).classdef:=pvclass;
  427. include(pvclass.objectoptions,oo_is_sealed);
  428. { associate typesym }
  429. pvclass.symtable.insert(ttypesym.create('__FPC_TProcVarClassAlias',pvclass));
  430. { set external name to match procvar type name }
  431. if not islocal then
  432. pvclass.objextname:=stringdup(name)
  433. else
  434. pvclass.objextname:=stringdup(pvclass.objrealname^);
  435. symtablestack.push(pvclass.symtable);
  436. { inherit constructor and keep public }
  437. add_missing_parent_constructors_intf(pvclass,true,vis_public);
  438. { add a method to call the procvar using unwrapped arguments, which
  439. then wraps them and calls through to JLRMethod.invoke }
  440. methoddef:=tprocdef(tprocvardef(def).getcopyas(procdef,pc_bareproc));
  441. finish_copied_procdef(methoddef,'invoke',pvclass.symtable,pvclass);
  442. insert_self_and_vmt_para(methoddef);
  443. methoddef.synthetickind:=tsk_jvm_procvar_invoke;
  444. methoddef.calcparas;
  445. { add local alias for the procvartype that we can use when implementing
  446. the invoke method }
  447. temptypesym:=ttypesym.create('__FPC_ProcVarAlias',nil);
  448. { don't pass def to the ttypesym constructor, because then it
  449. will replace the current (real) typesym of that def with the alias }
  450. temptypesym.typedef:=def;
  451. pvclass.symtable.insert(temptypesym);
  452. symtablestack.pop(pvclass.symtable);
  453. vmtbuilder:=TVMTBuilder.Create(pvclass);
  454. vmtbuilder.generate_vmt;
  455. vmtbuilder.free;
  456. restore_after_new_class(sstate,islocal,oldsymtablestack);
  457. end;
  458. procedure jvm_wrap_virtual_class_method(pd: tprocdef);
  459. var
  460. wrapperpd: tprocdef;
  461. wrapperpv: tprocvardef;
  462. typ: ttypesym;
  463. wrappername: shortstring;
  464. begin
  465. if (po_external in pd.procoptions) or
  466. (oo_is_external in pd.struct.objectoptions) then
  467. exit;
  468. { the JVM does not support virtual class methods -> we generate
  469. wrappers with the original name so they can be called normally,
  470. and these wrappers will then perform a dynamic lookup. To enable
  471. calling the class method by its intended name from external Java code,
  472. we have to change its external name so that we give that original
  473. name to the wrapper function -> "switch" the external names around for
  474. the original and wrapper methods }
  475. { replace importname of original procdef }
  476. include(pd.procoptions,po_has_importname);
  477. if not assigned(pd.import_name) then
  478. wrappername:=pd.procsym.realname
  479. else
  480. wrappername:=pd.import_name^;
  481. stringdispose(pd.import_name);
  482. pd.import_name:=stringdup(wrappername+'__fpcvirtualclassmethod__');
  483. { wrapper is part of the same symtable as the original procdef }
  484. symtablestack.push(pd.owner);
  485. { get a copy of the virtual class method }
  486. wrapperpd:=tprocdef(pd.getcopy);
  487. { this one is not virtual nor override }
  488. exclude(wrapperpd.procoptions,po_virtualmethod);
  489. exclude(wrapperpd.procoptions,po_overridingmethod);
  490. { import/external name = name of original class method }
  491. stringdispose(wrapperpd.import_name);
  492. wrapperpd.import_name:=stringdup(wrappername);
  493. include(wrapperpd.procoptions,po_has_importname);
  494. { associate with wrapper procsym (Pascal-level name = wrapper name ->
  495. in callnodes, we will have to replace the calls to virtual class
  496. methods with calls to the wrappers) }
  497. finish_copied_procdef(wrapperpd,pd.import_name^,pd.owner,tabstractrecorddef(pd.owner.defowner));
  498. { we only have to generate the dispatching routine for non-overriding
  499. methods; the overriding ones can use the original one, but generate
  500. a skeleton for that anyway because the overriding one may still
  501. change the visibility (but we can just call the inherited routine
  502. in that case) }
  503. if po_overridingmethod in pd.procoptions then
  504. begin
  505. { by default do not include this routine when looking for overloads }
  506. include(wrapperpd.procoptions,po_ignore_for_overload_resolution);
  507. wrapperpd.synthetickind:=tsk_anon_inherited;
  508. symtablestack.pop(pd.owner);
  509. exit;
  510. end;
  511. { implementation }
  512. wrapperpd.synthetickind:=tsk_jvm_virtual_clmethod;
  513. wrapperpd.skpara:=pd;
  514. { also create procvar type that we can use in the implementation }
  515. wrapperpv:=tprocvardef(pd.getcopyas(procvardef,pc_normal));
  516. wrapperpv.calcparas;
  517. jvm_create_procvar_class('__fpc_virtualclassmethod_pv_t'+tostr(wrapperpd.defid),wrapperpv);
  518. { create alias for the procvar type so we can use it in generated
  519. Pascal code }
  520. typ:=ttypesym.create('__fpc_virtualclassmethod_pv_t'+tostr(wrapperpd.defid),wrapperpv);
  521. wrapperpv.classdef.typesym.visibility:=vis_strictprivate;
  522. symtablestack.top.insert(typ);
  523. symtablestack.pop(pd.owner);
  524. end;
  525. procedure jvm_wrap_virtual_constructor(pd: tprocdef);
  526. var
  527. wrapperpd: tprocdef;
  528. begin
  529. { to avoid having to implement procvar-like support for dynamically
  530. invoking constructors, call the constructors from virtual class
  531. methods and replace calls to the constructors with calls to the
  532. virtual class methods -> we can reuse lots of infrastructure }
  533. if (po_external in pd.procoptions) or
  534. (oo_is_external in pd.struct.objectoptions) then
  535. exit;
  536. { wrapper is part of the same symtable as the original procdef }
  537. symtablestack.push(pd.owner);
  538. { get a copy of the constructor }
  539. wrapperpd:=tprocdef(pd.getcopyas(procdef,pc_bareproc));
  540. { this one is is a class method rather than a constructor }
  541. include(wrapperpd.procoptions,po_classmethod);
  542. wrapperpd.proctypeoption:=potype_function;
  543. wrapperpd.returndef:=tobjectdef(pd.owner.defowner);
  544. { import/external name = name of original constructor (since
  545. constructors don't have names in Java, this won't conflict with the
  546. original constructor definition) }
  547. stringdispose(wrapperpd.import_name);
  548. wrapperpd.import_name:=stringdup(pd.procsym.realname);
  549. { associate with wrapper procsym (Pascal-level name = wrapper name ->
  550. in callnodes, we will have to replace the calls to virtual
  551. constructors with calls to the wrappers) }
  552. finish_copied_procdef(wrapperpd,pd.procsym.realname+'__fpcvirtconstrwrapper__',pd.owner,tabstractrecorddef(pd.owner.defowner));
  553. { since it was a bare copy, insert the self parameter (we can't just
  554. copy the vmt parameter from the constructor, that's different) }
  555. insert_self_and_vmt_para(wrapperpd);
  556. wrapperpd.calcparas;
  557. { implementation: call through to the constructor }
  558. wrapperpd.synthetickind:=tsk_callthrough;
  559. wrapperpd.skpara:=pd;
  560. symtablestack.pop(pd.owner);
  561. { and now wrap this generated virtual static method itself as well }
  562. jvm_wrap_virtual_class_method(wrapperpd);
  563. end;
  564. procedure jvm_wrap_virtual_class_methods(obj: tobjectdef);
  565. var
  566. i: longint;
  567. def: tdef;
  568. begin
  569. { new methods will be inserted while we do this, but since
  570. symtable.deflist.count is evaluated at the start of the loop that
  571. doesn't matter }
  572. for i:=0 to obj.symtable.deflist.count-1 do
  573. begin
  574. def:=tdef(obj.symtable.deflist[i]);
  575. if def.typ<>procdef then
  576. continue;
  577. if [po_classmethod,po_virtualmethod]<=tprocdef(def).procoptions then
  578. jvm_wrap_virtual_class_method(tprocdef(def))
  579. else if (tprocdef(def).proctypeoption=potype_constructor) and
  580. (po_virtualmethod in tprocdef(def).procoptions) then
  581. jvm_wrap_virtual_constructor(tprocdef(def));
  582. end;
  583. end;
  584. function jvm_add_typed_const_initializer(csym: tconstsym): tstaticvarsym;
  585. var
  586. ssym: tstaticvarsym;
  587. esym: tenumsym;
  588. i: longint;
  589. sstate: tscannerstate;
  590. elemdef: tdef;
  591. elemdefname,
  592. conststr: ansistring;
  593. first: boolean;
  594. begin
  595. case csym.constdef.typ of
  596. enumdef:
  597. begin
  598. replace_scanner('jvm_enum_const',sstate);
  599. { make sure we don't emit a definition for this field (we'll do
  600. that for the constsym already) -> mark as external }
  601. ssym:=tstaticvarsym.create(internal_static_field_name(csym.realname),vs_final,csym.constdef,[vo_is_external]);
  602. csym.owner.insert(ssym);
  603. { alias storage to the constsym }
  604. ssym.set_mangledname(csym.realname);
  605. for i:=0 to tenumdef(csym.constdef).symtable.symlist.count-1 do
  606. begin
  607. esym:=tenumsym(tenumdef(csym.constdef).symtable.symlist[i]);
  608. if esym.value=csym.value.valueord.svalue then
  609. break;
  610. esym:=nil;
  611. end;
  612. { can happen in case of explicit typecast from integer constant
  613. to enum type }
  614. if not assigned(esym) then
  615. begin
  616. MessagePos(csym.fileinfo,parser_e_range_check_error);
  617. exit;
  618. end;
  619. str_parse_typedconst(current_asmdata.asmlists[al_typedconsts],esym.name+';',ssym);
  620. restore_scanner(sstate);
  621. result:=ssym;
  622. end;
  623. setdef:
  624. begin
  625. replace_scanner('jvm_set_const',sstate);
  626. { make sure we don't emit a definition for this field (we'll do
  627. that for the constsym already) -> mark as external;
  628. on the other hand, we don't create instances for constsyms in
  629. (or external syms) the program/unit initialization code -> add
  630. vo_has_local_copy to indicate that this should be done after all
  631. (in thlcgjvm.allocate_implicit_structs_for_st_with_base_ref) }
  632. { the constant can be defined in the body of a function and its
  633. def can also belong to that -> will be freed when the function
  634. has been compiler -> insert a copy in the unit's staticsymtable
  635. }
  636. symtablestack.push(current_module.localsymtable);
  637. ssym:=tstaticvarsym.create(internal_static_field_name(csym.realname),vs_final,tsetdef(csym.constdef).getcopy,[vo_is_external,vo_has_local_copy]);
  638. symtablestack.top.insert(ssym);
  639. symtablestack.pop(current_module.localsymtable);
  640. { alias storage to the constsym }
  641. ssym.set_mangledname(csym.realname);
  642. { ensure that we allocate space for global symbols (won't actually
  643. allocate space for this one, since it's external, but for the
  644. constsym) }
  645. cnodeutils.insertbssdata(ssym);
  646. elemdef:=tsetdef(csym.constdef).elementdef;
  647. if not assigned(elemdef) then
  648. begin
  649. internalerror(2011070502);
  650. end
  651. else
  652. begin
  653. elemdefname:=elemdef.typename;
  654. conststr:='[';
  655. first:=true;
  656. for i:=0 to 255 do
  657. if i in pnormalset(csym.value.valueptr)^ then
  658. begin
  659. if not first then
  660. conststr:=conststr+',';
  661. first:=false;
  662. { instead of looking up all enum value names/boolean
  663. names, type cast integers to the required type }
  664. conststr:=conststr+elemdefname+'('+tostr(i)+')';
  665. end;
  666. conststr:=conststr+'];';
  667. end;
  668. str_parse_typedconst(current_asmdata.asmlists[al_typedconsts],conststr,ssym);
  669. restore_scanner(sstate);
  670. result:=ssym;
  671. end;
  672. else
  673. internalerror(2011062701);
  674. end;
  675. end;
  676. function jvm_wrap_method_with_vis(pd: tprocdef; vis: tvisibility): tprocdef;
  677. var
  678. obj: tabstractrecorddef;
  679. visname: string;
  680. begin
  681. obj:=current_structdef;
  682. { if someone gets the idea to add a property to an external class
  683. definition, don't try to wrap it since we cannot add methods to
  684. external classes }
  685. if oo_is_external in obj.objectoptions then
  686. begin
  687. result:=pd;
  688. exit
  689. end;
  690. symtablestack.push(obj.symtable);
  691. result:=tprocdef(pd.getcopy);
  692. result.visibility:=vis;
  693. visname:=visibilityName[vis];
  694. replace(visname,' ','_');
  695. { create a name that is unique amongst all units (start with '$unitname$$') and
  696. unique in this unit (result.defid) }
  697. finish_copied_procdef(result,'$'+current_module.realmodulename^+'$$'+tostr(result.defid)+pd.procsym.realname+'$'+visname,obj.symtable,obj);
  698. { in case the referred method is from an external class }
  699. exclude(result.procoptions,po_external);
  700. { not virtual/override/abstract/... }
  701. result.procoptions:=result.procoptions*[po_classmethod,po_staticmethod,po_varargs,po_public];
  702. result.synthetickind:=tsk_callthrough;
  703. { so we know the name of the routine to call through to }
  704. result.skpara:=pd;
  705. symtablestack.pop(obj.symtable);
  706. end;
  707. procedure jvm_create_getter_or_setter_for_property(p: tpropertysym; getter: boolean);
  708. var
  709. obj: tabstractrecorddef;
  710. ps: tprocsym;
  711. pvs: tparavarsym;
  712. pd: tprocdef;
  713. callthroughpropname,
  714. name: string;
  715. callthroughprop: tpropertysym;
  716. accesstyp: tpropaccesslisttypes;
  717. begin
  718. obj:=current_structdef;
  719. { if someone gets the idea to add a property to an external class
  720. definition, don't try to wrap it since we cannot add methods to
  721. external classes }
  722. if oo_is_external in obj.objectoptions then
  723. exit;
  724. symtablestack.push(obj.symtable);
  725. if getter then
  726. accesstyp:=palt_read
  727. else
  728. accesstyp:=palt_write;
  729. { create a property for the old symaccesslist with a new name, so that
  730. we can reuse it in the implementation (rather than having to
  731. translate the symaccesslist back to Pascal code) }
  732. callthroughpropname:='__fpc__'+p.realname;
  733. if getter then
  734. callthroughpropname:=callthroughpropname+'__getter_wrapper'
  735. else
  736. callthroughpropname:=callthroughpropname+'__setter_wrapper';
  737. callthroughprop:=tpropertysym.create(callthroughpropname);
  738. callthroughprop.visibility:=p.visibility;
  739. callthroughprop.default:=longint($80000000);
  740. if sp_static in p.symoptions then
  741. include(callthroughprop.symoptions, sp_static);
  742. { copy original property target to callthrough property }
  743. callthroughprop.propaccesslist[accesstyp]:=p.propaccesslist[accesstyp];
  744. p.propaccesslist[accesstyp]:=tpropaccesslist.create;
  745. p.owner.insert(callthroughprop);
  746. { we can't use str_parse_method_dec here because the type of the field
  747. may not be visible at the Pascal level }
  748. { create procdef }
  749. pd:=tprocdef.create(normal_function_level);
  750. { construct procsym name (unique for this access; reusing the same
  751. helper for multiple accesses to the same field is hard because the
  752. propacesslist can contain subscript nodes etc) }
  753. name:=visibilityName[p.visibility];
  754. replace(name,' ','_');
  755. if getter then
  756. name:=name+'$getter'
  757. else
  758. name:=name+'$setter';
  759. name:='$'+obj.symtable.realname^+'$'+p.realname+'$'+name+'$'+tostr(pd.defid);
  760. { new procsym }
  761. ps:=tprocsym.create(name);
  762. obj.symtable.insert(ps);
  763. { associate procsym with procdef}
  764. pd.procsym:=ps;
  765. { method of this objectdef }
  766. pd.struct:=obj;
  767. { visibility }
  768. pd.visibility:=p.visibility;
  769. { function/procedure }
  770. if getter then
  771. begin
  772. pd.proctypeoption:=potype_function;
  773. pd.synthetickind:=tsk_field_getter;
  774. { result type }
  775. pd.returndef:=p.propdef;
  776. end
  777. else
  778. begin
  779. pd.proctypeoption:=potype_procedure;
  780. pd.synthetickind:=tsk_field_setter;
  781. pd.returndef:=voidtype;
  782. { parameter with value to set }
  783. pvs:=tparavarsym.create('__fpc_newval__',10,vs_const,p.propdef,[]);
  784. pd.parast.insert(pvs);
  785. end;
  786. pd.skpara:=callthroughprop;
  787. { needs to be exported }
  788. include(pd.procoptions,po_global);
  789. { class property -> static class method }
  790. if sp_static in p.symoptions then
  791. pd.procoptions:=pd.procoptions+[po_classmethod,po_staticmethod];
  792. { calling convention, self, ... }
  793. handle_calling_convention(pd);
  794. { register forward declaration with procsym }
  795. proc_add_definition(pd);
  796. { make the property call this new function }
  797. p.propaccesslist[accesstyp].addsym(sl_call,ps);
  798. p.propaccesslist[accesstyp].procdef:=pd;
  799. symtablestack.pop(obj.symtable);
  800. end;
  801. procedure jvm_create_getter_for_property(p: tpropertysym);
  802. begin
  803. jvm_create_getter_or_setter_for_property(p,true);
  804. end;
  805. procedure jvm_create_setter_for_property(p: tpropertysym);
  806. begin
  807. jvm_create_getter_or_setter_for_property(p,false);
  808. end;
  809. end.