pjvm.pas 43 KB

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