pjvm.pas 39 KB

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