symcreat.pas 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. {
  2. Copyright (c) 2011 by Jonas Maebe
  3. This unit provides helpers for creating new syms/defs based on string
  4. representations.
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. {$i fpcdefs.inc}
  19. unit symcreat;
  20. interface
  21. uses
  22. finput,tokens,scanner,globtype,
  23. aasmdata,
  24. symconst,symbase,symtype,symdef,symsym,
  25. node;
  26. type
  27. tscannerstate = record
  28. old_scanner: tscannerfile;
  29. old_filepos: tfileposinfo;
  30. old_token: ttoken;
  31. old_c: char;
  32. old_orgpattern: string;
  33. old_modeswitches: tmodeswitches;
  34. old_idtoken: ttoken;
  35. valid: boolean;
  36. end;
  37. { save/restore the scanner state before/after injecting }
  38. procedure replace_scanner(const tempname: string; out sstate: tscannerstate);
  39. procedure restore_scanner(const sstate: tscannerstate);
  40. { parses a (class or regular) method/constructor/destructor declaration from
  41. str, as if it were declared in astruct's declaration body
  42. WARNING: save the scanner state before calling this routine, and restore
  43. when done. }
  44. function str_parse_method_dec(str: ansistring; potype: tproctypeoption; is_classdef: boolean; astruct: tabstractrecorddef; out pd: tprocdef): boolean;
  45. { parses a (class or regular) method/constructor/destructor implementation
  46. from str, as if it appeared in the current unit's implementation section
  47. WARNINGS:
  48. * save the scanner state before calling this routine, and restore when done.
  49. * the code *must* be written in objfpc style
  50. }
  51. function str_parse_method_impl(const str: ansistring; usefwpd: tprocdef; is_classdef: boolean):boolean;
  52. { parses a typed constant assignment to ssym
  53. WARNINGS:
  54. * save the scanner state before calling this routine, and restore when done.
  55. * the code *must* be written in objfpc style
  56. }
  57. procedure str_parse_typedconst(list: TAsmList; str: ansistring; ssym: tstaticvarsym);
  58. { in the JVM, constructors are not automatically inherited (so you can hide
  59. them). To emulate the Pascal behaviour, we have to automatically add
  60. all parent constructors to the current class as well. We also have to do
  61. the same for the (emulated) virtual class methods }
  62. procedure add_missing_parent_constructors_intf(obj: tobjectdef; addvirtclassmeth: boolean; forcevis: tvisibility);
  63. { goes through all defs in st to add implementations for synthetic methods
  64. added earlier }
  65. procedure add_synthetic_method_implementations(st: tsymtable);
  66. { create an alias for a procdef with Pascal name "newrealname",
  67. mangledname "newmangledname", in symtable newparentst, part of the
  68. record/class/.. "newstruct" (nil if none), and with synthetickind "sk" and
  69. synthetic kind para "skpara" to create the implementation (tsk_none and nil
  70. in case not necessary). Returns the new procdef; finish_copied_procdef() is
  71. not required/must not be called for the result. }
  72. function create_procdef_alias(pd: tprocdef; const newrealname: string; const newmangledname: TSymStr; newparentst: tsymtable; newstruct: tabstractrecorddef; sk: tsynthetickind; skpara: pointer): tprocdef;
  73. { finalize a procdef that has been copied with
  74. tprocdef.getcopyas(procdef,pc_bareproc) }
  75. procedure finish_copied_procdef(var pd: tprocdef; const realname: string; newparentst: tsymtable; newstruct: tabstractrecorddef);
  76. { create "parent frame pointer" record skeleton for procdef, in which local
  77. variables and parameters from pd accessed from nested routines can be
  78. stored }
  79. procedure build_parentfpstruct(pd: tprocdef);
  80. { checks whether sym (a local or para of pd) already has a counterpart in
  81. pd's parentfpstruct, and if not adds a new field to the struct with type
  82. "vardef" (can be different from sym's type in case it's a call-by-reference
  83. parameter, which is indicated by addrparam). If it already has a field in
  84. the parentfpstruct, this field is returned. }
  85. function maybe_add_sym_to_parentfpstruct(pd: tprocdef; sym: tsym; vardef: tdef; addrparam: boolean): tsym;
  86. { given a localvarsym or paravarsym of pd, returns the field of the
  87. parentfpstruct corresponding to this sym }
  88. function find_sym_in_parentfpstruct(pd: tprocdef; sym: tsym): tsym;
  89. { replaces all local and paravarsyms that have been mirrored in the
  90. parentfpstruct with aliasvarsyms that redirect to these fields (used to
  91. make sure that references to these syms in the owning procdef itself also
  92. use the ones in the parentfpstructs) }
  93. procedure redirect_parentfpstruct_local_syms(pd: tprocdef);
  94. { finalises the parentfpstruct (alignment padding, ...) }
  95. procedure finish_parentfpstruct(pd: tprocdef);
  96. procedure maybe_guarantee_record_typesym(var def: tdef; st: tsymtable);
  97. { turns a fieldvarsym into a class/static field definition, and returns the
  98. created staticvarsym that is responsible for allocating the global storage }
  99. function make_field_static(recst: tsymtable; fieldvs: tfieldvarsym): tstaticvarsym;
  100. { create a new procdef with the signature of orgpd and (mangled) name
  101. newname, and change the implementation of orgpd so that it calls through
  102. to this new procedure }
  103. procedure call_through_new_name(orgpd: tprocdef; const newname: TSymStr);
  104. function generate_pkg_stub(pd:tprocdef):tnode;
  105. implementation
  106. uses
  107. cutils,cclasses,globals,verbose,systems,comphook,fmodule,constexp,
  108. symtable,defutil,
  109. pbase,pdecobj,pdecsub,psub,ptconst,pparautl,
  110. {$ifdef jvm}
  111. pjvm,jvmdef,
  112. {$endif jvm}
  113. nbas,nld,nmem,ncon,
  114. defcmp,
  115. paramgr;
  116. procedure replace_scanner(const tempname: string; out sstate: tscannerstate);
  117. var
  118. old_block_type: tblock_type;
  119. begin
  120. { would require saving of cstringpattern, patternw }
  121. if (token=_CSTRING) or
  122. (token=_CWCHAR) or
  123. (token=_CWSTRING) then
  124. internalerror(2011032201);
  125. sstate.old_scanner:=current_scanner;
  126. sstate.old_filepos:=current_filepos;
  127. sstate.old_token:=token;
  128. sstate.old_c:=c;
  129. sstate.old_orgpattern:=orgpattern;
  130. sstate.old_modeswitches:=current_settings.modeswitches;
  131. sstate.old_idtoken:=idtoken;
  132. sstate.valid:=true;
  133. { creating a new scanner resets the block type, while we want to continue
  134. in the current one }
  135. old_block_type:=block_type;
  136. current_scanner:=tscannerfile.Create('_Macro_.'+tempname,true);
  137. block_type:=old_block_type;
  138. { required for e.g. FpcDeepCopy record method (uses "out" parameter; field
  139. names are escaped via &, so should not cause conflicts }
  140. current_settings.modeswitches:=objfpcmodeswitches;
  141. end;
  142. procedure restore_scanner(const sstate: tscannerstate);
  143. begin
  144. if sstate.valid then
  145. begin
  146. current_scanner.free;
  147. current_scanner:=sstate.old_scanner;
  148. current_filepos:=sstate.old_filepos;
  149. token:=sstate.old_token;
  150. current_settings.modeswitches:=sstate.old_modeswitches;
  151. c:=sstate.old_c;
  152. orgpattern:=sstate.old_orgpattern;
  153. pattern:=upper(sstate.old_orgpattern);
  154. idtoken:=sstate.old_idtoken;
  155. end;
  156. end;
  157. function str_parse_method_dec(str: ansistring; potype: tproctypeoption; is_classdef: boolean; astruct: tabstractrecorddef; out pd: tprocdef): boolean;
  158. var
  159. oldparse_only: boolean;
  160. begin
  161. Message1(parser_d_internal_parser_string,str);
  162. oldparse_only:=parse_only;
  163. parse_only:=true;
  164. result:=false;
  165. { in case multiple strings are injected, make sure to always close the
  166. previous macro inputfile to prevent memory leaks }
  167. if assigned(current_scanner.inputfile) and
  168. not(current_scanner.inputfile.closed) then
  169. current_scanner.closeinputfile;
  170. { inject the string in the scanner }
  171. str:=str+'end;';
  172. current_scanner.substitutemacro('meth_head_macro',@str[1],length(str),current_scanner.line_no,current_scanner.inputfile.ref_index);
  173. current_scanner.readtoken(false);
  174. { and parse it... }
  175. case potype of
  176. potype_class_constructor:
  177. pd:=class_constructor_head(astruct);
  178. potype_class_destructor:
  179. pd:=class_destructor_head(astruct);
  180. potype_constructor:
  181. pd:=constructor_head;
  182. potype_destructor:
  183. pd:=destructor_head;
  184. else if assigned(astruct) and
  185. (astruct.typ=recorddef) then
  186. pd:=parse_record_method_dec(astruct,is_classdef,false)
  187. else
  188. pd:=method_dec(astruct,is_classdef,false);
  189. end;
  190. if assigned(pd) then
  191. result:=true;
  192. parse_only:=oldparse_only;
  193. { remove the temporary macro input file again }
  194. current_scanner.closeinputfile;
  195. current_scanner.nextfile;
  196. current_scanner.tempopeninputfile;
  197. end;
  198. function str_parse_method_impl_with_fileinfo(str: ansistring; usefwpd: tprocdef; fileno, lineno: longint; is_classdef: boolean):boolean;
  199. var
  200. oldparse_only: boolean;
  201. tmpstr: ansistring;
  202. begin
  203. if ((status.verbosity and v_debug)<>0) then
  204. begin
  205. if assigned(usefwpd) then
  206. Message1(parser_d_internal_parser_string,usefwpd.customprocname([pno_proctypeoption,pno_paranames,pno_ownername,pno_noclassmarker,pno_noleadingdollar])+str)
  207. else
  208. begin
  209. if is_classdef then
  210. tmpstr:='class '
  211. else
  212. tmpstr:='';
  213. Message1(parser_d_internal_parser_string,tmpstr+str);
  214. end;
  215. end;
  216. oldparse_only:=parse_only;
  217. parse_only:=false;
  218. result:=false;
  219. { "const" starts a new kind of block and hence makes the scanner return }
  220. str:=str+'const;';
  221. { inject the string in the scanner }
  222. current_scanner.substitutemacro('meth_impl_macro',@str[1],length(str),lineno,fileno);
  223. current_scanner.readtoken(false);
  224. { and parse it... }
  225. read_proc(is_classdef,usefwpd,false);
  226. parse_only:=oldparse_only;
  227. { remove the temporary macro input file again }
  228. current_scanner.closeinputfile;
  229. current_scanner.nextfile;
  230. current_scanner.tempopeninputfile;
  231. result:=true;
  232. end;
  233. function str_parse_method_impl(const str: ansistring; usefwpd: tprocdef; is_classdef: boolean):boolean;
  234. begin
  235. result:=str_parse_method_impl_with_fileinfo(str, usefwpd, current_scanner.inputfile.ref_index, current_scanner.line_no, is_classdef);
  236. end;
  237. procedure str_parse_typedconst(list: TAsmList; str: ansistring; ssym: tstaticvarsym);
  238. var
  239. old_block_type: tblock_type;
  240. old_parse_only: boolean;
  241. begin
  242. Message1(parser_d_internal_parser_string,str);
  243. { a string that will be interpreted as the start of a new section ->
  244. typed constant parsing will stop }
  245. str:=str+'type ';
  246. old_parse_only:=parse_only;
  247. old_block_type:=block_type;
  248. parse_only:=true;
  249. block_type:=bt_const;
  250. current_scanner.substitutemacro('typed_const_macro',@str[1],length(str),current_scanner.line_no,current_scanner.inputfile.ref_index);
  251. current_scanner.readtoken(false);
  252. read_typed_const(list,ssym,ssym.owner.symtabletype in [recordsymtable,objectsymtable]);
  253. parse_only:=old_parse_only;
  254. block_type:=old_block_type;
  255. { remove the temporary macro input file again }
  256. current_scanner.closeinputfile;
  257. current_scanner.nextfile;
  258. current_scanner.tempopeninputfile;
  259. end;
  260. function def_unit_name_prefix_if_toplevel(def: tdef): TSymStr;
  261. begin
  262. result:='';
  263. { if the routine is a global routine in a unit, explicitly use this unit
  264. name to avoid accidentally calling other same-named routines that may be
  265. in scope }
  266. if not assigned(def.owner.defowner) and
  267. assigned(def.owner.realname) and
  268. (def.owner.moduleid<>0) then
  269. result:=def.owner.realname^+'.';
  270. end;
  271. procedure add_missing_parent_constructors_intf(obj: tobjectdef; addvirtclassmeth: boolean; forcevis: tvisibility);
  272. var
  273. parent: tobjectdef;
  274. def: tdef;
  275. parentpd,
  276. childpd: tprocdef;
  277. i: longint;
  278. srsym: tsym;
  279. srsymtable: tsymtable;
  280. begin
  281. if (oo_is_external in obj.objectoptions) or
  282. not assigned(obj.childof) then
  283. exit;
  284. parent:=obj.childof;
  285. { find all constructor in the parent }
  286. for i:=0 to tobjectsymtable(parent.symtable).deflist.count-1 do
  287. begin
  288. def:=tdef(tobjectsymtable(parent.symtable).deflist[i]);
  289. if (def.typ<>procdef) or
  290. ((tprocdef(def).proctypeoption<>potype_constructor) and
  291. (not addvirtclassmeth or
  292. not([po_classmethod,po_virtualmethod]<=tprocdef(def).procoptions))) or
  293. not is_visible_for_object(tprocdef(def),obj) then
  294. continue;
  295. parentpd:=tprocdef(def);
  296. { do we have this constructor too? (don't use
  297. search_struct_member/searchsym_in_class, since those will
  298. search parents too) }
  299. if searchsym_in_record(obj,parentpd.procsym.name,srsym,srsymtable) then
  300. begin
  301. { there's a symbol with the same name, is it a routine of the
  302. same type with the same parameters? }
  303. if srsym.typ=procsym then
  304. begin
  305. childpd:=tprocsym(srsym).find_procdef_bytype_and_para(
  306. tprocdef(def).proctypeoption,parentpd.paras,nil,
  307. [cpo_ignorehidden,cpo_ignoreuniv,cpo_openequalisexact]);
  308. if assigned(childpd) then
  309. continue;
  310. end;
  311. end;
  312. { if we get here, we did not find it in the current objectdef ->
  313. add }
  314. childpd:=tprocdef(parentpd.getcopy);
  315. { get rid of the import name for inherited virtual class methods,
  316. it has to be regenerated rather than amended }
  317. if [po_classmethod,po_virtualmethod]<=childpd.procoptions then
  318. begin
  319. stringdispose(childpd.import_name);
  320. exclude(childpd.procoptions,po_has_importname);
  321. end;
  322. if forcevis<>vis_none then
  323. childpd.visibility:=forcevis;
  324. if po_virtualmethod in childpd.procoptions then
  325. include(childpd.procoptions,po_overridingmethod);
  326. { ignore this artificially added procdef when looking for overloads }
  327. include(childpd.procoptions,po_ignore_for_overload_resolution);
  328. finish_copied_procdef(childpd,parentpd.procsym.realname,obj.symtable,obj);
  329. exclude(childpd.procoptions,po_external);
  330. childpd.synthetickind:=tsk_anon_inherited;
  331. include(obj.objectoptions,oo_has_constructor);
  332. end;
  333. end;
  334. procedure implement_anon_inherited(pd: tprocdef);
  335. var
  336. str: ansistring;
  337. isclassmethod: boolean;
  338. begin
  339. isclassmethod:=
  340. (po_classmethod in pd.procoptions) and
  341. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  342. str:='begin ';
  343. if (pd.proctypeoption<>potype_constructor) and
  344. not is_void(pd.returndef) then
  345. str:=str+'result:=';
  346. str:=str+'inherited end;';
  347. str_parse_method_impl(str,pd,isclassmethod);
  348. end;
  349. procedure implement_jvm_clone(pd: tprocdef);
  350. var
  351. struct: tabstractrecorddef;
  352. str: ansistring;
  353. i: longint;
  354. sym: tsym;
  355. fsym: tfieldvarsym;
  356. begin
  357. if not(pd.struct.typ in [recorddef,objectdef]) then
  358. internalerror(2011032802);
  359. struct:=pd.struct;
  360. { anonymous record types must get an artificial name, so we can generate
  361. a typecast at the scanner level }
  362. if (struct.typ=recorddef) and
  363. not assigned(struct.typesym) then
  364. internalerror(2011032812);
  365. { We cannot easily use the inherited clone in case we have to create a
  366. deep copy of certain fields. The reason is that e.g. sets are pointers
  367. at the JVM level, but not in Pascal. So the JVM clone routine will copy
  368. the pointer to the set from the old record (= class instance) to the new
  369. one, but we have no way to change this pointer itself from inside Pascal
  370. code.
  371. We solve this by relying on the fact that the JVM is garbage collected:
  372. we simply declare a temporary instance on the stack, which will be
  373. allocated/initialized by the temp generator. We return its address as
  374. the result of the clone routine, so it remains live. }
  375. str:='var __fpc_newcopy:'+ struct.typesym.realname+'; begin clone:=JLObject(@__fpc_newcopy);';
  376. { copy all field contents }
  377. for i:=0 to struct.symtable.symlist.count-1 do
  378. begin
  379. sym:=tsym(struct.symtable.symlist[i]);
  380. if (sym.typ=fieldvarsym) then
  381. begin
  382. fsym:=tfieldvarsym(sym);
  383. str:=str+'__fpc_newcopy.&'+fsym.realname+':=&'+fsym.realname+';';
  384. end;
  385. end;
  386. str:=str+'end;';
  387. str_parse_method_impl(str,pd,false);
  388. end;
  389. procedure implement_record_deepcopy(pd: tprocdef);
  390. var
  391. struct: tabstractrecorddef;
  392. str: ansistring;
  393. i: longint;
  394. sym: tsym;
  395. fsym: tfieldvarsym;
  396. begin
  397. if not(pd.struct.typ in [recorddef,objectdef]) then
  398. internalerror(2011032810);
  399. struct:=pd.struct;
  400. { anonymous record types must get an artificial name, so we can generate
  401. a typecast at the scanner level }
  402. if (struct.typ=recorddef) and
  403. not assigned(struct.typesym) then
  404. internalerror(2011032811);
  405. { copy all fields }
  406. str:='type _fpc_ptrt = ^'+struct.typesym.realname+'; var res: _fpc_ptrt; begin res:=_fpc_ptrt(result);';
  407. for i:=0 to struct.symtable.symlist.count-1 do
  408. begin
  409. sym:=tsym(struct.symtable.symlist[i]);
  410. if (sym.typ=fieldvarsym) then
  411. begin
  412. fsym:=tfieldvarsym(sym);
  413. str:=str+'res^.&'+fsym.realname+':=&'+fsym.realname+';';
  414. end;
  415. end;
  416. str:=str+'end;';
  417. str_parse_method_impl(str,pd,false);
  418. end;
  419. procedure implement_record_initialize(pd: tprocdef);
  420. var
  421. struct: tabstractrecorddef;
  422. str: ansistring;
  423. i: longint;
  424. sym: tsym;
  425. fsym: tfieldvarsym;
  426. begin
  427. if not(pd.struct.typ in [recorddef,objectdef]) then
  428. internalerror(2011071710);
  429. struct:=pd.struct;
  430. { anonymous record types must get an artificial name, so we can generate
  431. a typecast at the scanner level }
  432. if (struct.typ=recorddef) and
  433. not assigned(struct.typesym) then
  434. internalerror(2011032811);
  435. { walk over all fields that need initialization }
  436. str:='begin ';
  437. for i:=0 to struct.symtable.symlist.count-1 do
  438. begin
  439. sym:=tsym(struct.symtable.symlist[i]);
  440. if (sym.typ=fieldvarsym) then
  441. begin
  442. fsym:=tfieldvarsym(sym);
  443. if fsym.vardef.needs_inittable then
  444. str:=str+'system.initialize(&'+fsym.realname+');';
  445. end;
  446. end;
  447. str:=str+'end;';
  448. str_parse_method_impl(str,pd,false);
  449. end;
  450. procedure implement_empty(pd: tprocdef);
  451. var
  452. str: ansistring;
  453. isclassmethod: boolean;
  454. begin
  455. isclassmethod:=
  456. (po_classmethod in pd.procoptions) and
  457. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  458. str:='begin end;';
  459. str_parse_method_impl(str,pd,isclassmethod);
  460. end;
  461. procedure addvisibibleparameters(var str: ansistring; pd: tprocdef);
  462. var
  463. currpara: tparavarsym;
  464. i: longint;
  465. firstpara: boolean;
  466. begin
  467. firstpara:=true;
  468. for i:=0 to pd.paras.count-1 do
  469. begin
  470. currpara:=tparavarsym(pd.paras[i]);
  471. if not(vo_is_hidden_para in currpara.varoptions) then
  472. begin
  473. if not firstpara then
  474. str:=str+',';
  475. firstpara:=false;
  476. str:=str+currpara.realname;
  477. end;
  478. end;
  479. end;
  480. procedure implement_callthrough(pd: tprocdef);
  481. var
  482. str: ansistring;
  483. callpd: tprocdef;
  484. isclassmethod: boolean;
  485. begin
  486. isclassmethod:=
  487. (po_classmethod in pd.procoptions) and
  488. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  489. callpd:=tprocdef(pd.skpara);
  490. str:='begin ';
  491. if pd.returndef<>voidtype then
  492. str:=str+'result:=';
  493. { if the routine is a global routine in a unit/program, explicitly
  494. mnetion this program/unit name to avoid accidentally calling other
  495. same-named routines that may be in scope }
  496. str:=str+def_unit_name_prefix_if_toplevel(callpd)+callpd.procsym.realname+'(';
  497. addvisibibleparameters(str,pd);
  498. str:=str+') end;';
  499. str_parse_method_impl(str,pd,isclassmethod);
  500. end;
  501. {$ifdef jvm}
  502. procedure implement_jvm_enum_values(pd: tprocdef);
  503. begin
  504. str_parse_method_impl('begin result:=__fpc_FVALUES end;',pd,true);
  505. end;
  506. procedure implement_jvm_enum_valuof(pd: tprocdef);
  507. begin
  508. str_parse_method_impl('begin result:=__FPC_TEnumClassAlias(inherited valueOf(JLClass(__FPC_TEnumClassAlias),__fpc_str)) end;',pd,true);
  509. end;
  510. procedure implement_jvm_enum_jumps_constr(pd: tprocdef);
  511. begin
  512. str_parse_method_impl('begin inherited create(__fpc_name,__fpc_ord); __fpc_fenumval:=__fpc_initenumval end;',pd,false);
  513. end;
  514. procedure implement_jvm_enum_fpcordinal(pd: tprocdef);
  515. var
  516. enumclass: tobjectdef;
  517. enumdef: tenumdef;
  518. begin
  519. enumclass:=tobjectdef(pd.owner.defowner);
  520. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  521. if not enumdef.has_jumps then
  522. str_parse_method_impl('begin result:=ordinal end;',pd,false)
  523. else
  524. str_parse_method_impl('begin result:=__fpc_fenumval end;',pd,false);
  525. end;
  526. procedure implement_jvm_enum_fpcvalueof(pd: tprocdef);
  527. var
  528. enumclass: tobjectdef;
  529. enumdef: tenumdef;
  530. isclassmethod: boolean;
  531. begin
  532. isclassmethod:=
  533. (po_classmethod in pd.procoptions) and
  534. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  535. enumclass:=tobjectdef(pd.owner.defowner);
  536. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  537. { convert integer to corresponding enum instance: in case of no jumps
  538. get it from the $VALUES array, otherwise from the __fpc_ord2enum
  539. hashmap }
  540. if not enumdef.has_jumps then
  541. str_parse_method_impl('begin result:=__fpc_FVALUES[__fpc_int] end;',pd,isclassmethod)
  542. else
  543. str_parse_method_impl('begin result:=__FPC_TEnumClassAlias(__fpc_ord2enum.get(JLInteger.valueOf(__fpc_int))) end;',pd,isclassmethod);
  544. end;
  545. function CompareEnumSyms(Item1, Item2: Pointer): Integer;
  546. var
  547. I1 : tenumsym absolute Item1;
  548. I2 : tenumsym absolute Item2;
  549. begin
  550. Result:=I1.value-I2.value;
  551. end;
  552. procedure implement_jvm_enum_classconstr(pd: tprocdef);
  553. var
  554. enumclass: tobjectdef;
  555. enumdef: tenumdef;
  556. enumname,
  557. str: ansistring;
  558. i: longint;
  559. enumsym: tenumsym;
  560. orderedenums: tfpobjectlist;
  561. begin
  562. enumclass:=tobjectdef(pd.owner.defowner);
  563. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  564. if not assigned(enumdef) then
  565. internalerror(2011062305);
  566. str:='begin ';
  567. if enumdef.has_jumps then
  568. { init hashmap for ordinal -> enum instance mapping; don't let it grow,
  569. and set the capacity to the next prime following the total number of
  570. enum elements to minimise the number of collisions }
  571. str:=str+'__fpc_ord2enum:=JUHashMap.Create('+tostr(next_prime(enumdef.symtable.symlist.count))+',1.0);';
  572. { iterate over all enum elements and initialise the class fields, and
  573. store them in the values array. Since the java.lang.Enum doCompare
  574. method is final and hardcoded to compare based on declaration order
  575. (= java.lang.Enum.ordinal() value), we have to create them in order of
  576. ascending FPC ordinal values (which may not be the same as the FPC
  577. declaration order in case of jumps }
  578. orderedenums:=tfpobjectlist.create(false);
  579. for i:=0 to enumdef.symtable.symlist.count-1 do
  580. orderedenums.add(enumdef.symtable.symlist[i]);
  581. if enumdef.has_jumps then
  582. orderedenums.sort(@CompareEnumSyms);
  583. for i:=0 to orderedenums.count-1 do
  584. begin
  585. enumsym:=tenumsym(orderedenums[i]);
  586. enumname:=enumsym.realname;
  587. str:=str+enumsym.name+':=__FPC_TEnumClassAlias.Create('''+enumname+''','+tostr(i);
  588. if enumdef.has_jumps then
  589. str:=str+','+tostr(enumsym.value);
  590. str:=str+');';
  591. { alias for $VALUES array used internally by the JDK, and also by FPC
  592. in case of no jumps }
  593. str:=str+'__fpc_FVALUES['+tostr(i)+']:='+enumname+';';
  594. if enumdef.has_jumps then
  595. str:=str+'__fpc_ord2enum.put(JLInteger.valueOf('+tostr(enumsym.value)+'),'+enumname+');';
  596. end;
  597. orderedenums.free;
  598. str:=str+' end;';
  599. str_parse_method_impl(str,pd,true);
  600. end;
  601. procedure implement_jvm_enum_long2set(pd: tprocdef);
  602. begin
  603. str_parse_method_impl(
  604. 'var '+
  605. 'i, setval: jint;'+
  606. 'begin '+
  607. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  608. 'if __val<>0 then '+
  609. 'begin '+
  610. '__setsize:=__setsize*8;'+
  611. 'for i:=0 to __setsize-1 do '+
  612. // setsize-i because JVM = big endian
  613. 'if (__val and (jlong(1) shl (__setsize-i)))<>0 then '+
  614. 'result.add(fpcValueOf(i+__setbase));'+
  615. 'end '+
  616. 'end;',
  617. pd,true);
  618. end;
  619. procedure implement_jvm_enum_bitset2set(pd: tprocdef);
  620. begin
  621. str_parse_method_impl(
  622. 'var '+
  623. 'i, setval: jint;'+
  624. 'begin '+
  625. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  626. 'i:=__val.nextSetBit(0);'+
  627. 'while i>=0 do '+
  628. 'begin '+
  629. 'setval:=-__fromsetbase;'+
  630. 'result.add(fpcValueOf(setval+__tosetbase));'+
  631. 'i:=__val.nextSetBit(i+1);'+
  632. 'end '+
  633. 'end;',
  634. pd,true);
  635. end;
  636. procedure implement_jvm_enum_set2set(pd: tprocdef);
  637. begin
  638. str_parse_method_impl(
  639. 'var '+
  640. 'it: JUIterator;'+
  641. 'ele: FpcEnumValueObtainable;'+
  642. 'i: longint;'+
  643. 'begin '+
  644. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  645. 'it:=__val.iterator;'+
  646. 'while it.hasNext do '+
  647. 'begin '+
  648. 'ele:=FpcEnumValueObtainable(it.next);'+
  649. 'i:=ele.fpcOrdinal-__fromsetbase;'+
  650. 'result.add(fpcValueOf(i+__tosetbase));'+
  651. 'end '+
  652. 'end;',
  653. pd,true);
  654. end;
  655. procedure implement_jvm_procvar_invoke(pd: tprocdef);
  656. var
  657. pvclass: tobjectdef;
  658. procvar: tprocvardef;
  659. paraname,str,endstr: ansistring;
  660. pvs: tparavarsym;
  661. paradef,boxdef,boxargdef: tdef;
  662. i: longint;
  663. firstpara: boolean;
  664. begin
  665. pvclass:=tobjectdef(pd.owner.defowner);
  666. procvar:=tprocvardef(ttypesym(search_struct_member(pvclass,'__FPC_PROCVARALIAS')).typedef);
  667. { the procvar wrapper class has a tmethod member called "method", whose
  668. "code" field is a JLRMethod, and whose "data" field is the self pointer
  669. if any (if none is required, it's ignored by the JVM, so there's no
  670. problem with always passing it) }
  671. { force extended syntax to allow calling invokeObjectFunc() without using
  672. its result }
  673. str:='';
  674. endstr:='';
  675. { create local pointer to result type for typecasting in case of an
  676. implicit pointer type }
  677. if jvmimplicitpointertype(procvar.returndef) then
  678. str:=str+'type __FPC_returnptrtype = ^'+procvar.returndef.typename+';';
  679. str:=str+'begin ';
  680. { result handling (skip for generic definitions, we'll generate a new
  681. version for the specialized definition) ) }
  682. if not is_void(procvar.returndef) and
  683. (procvar.returndef.typ<>undefineddef) then
  684. begin
  685. str:=str+'invoke:=';
  686. if procvar.returndef.typ in [orddef,floatdef] then
  687. begin
  688. { primitivetype(boxtype(..).unboxmethod) }
  689. jvmgetboxtype(procvar.returndef,boxdef,boxargdef,false);
  690. str:=str+procvar.returndef.typename+'('+boxdef.typename+'(';
  691. endstr:=').'+jvmgetunboxmethod(procvar.returndef)+')';
  692. end
  693. else if jvmimplicitpointertype(procvar.returndef) then
  694. begin
  695. str:=str+'__FPC_returnptrtype(';
  696. { dereference }
  697. endstr:=')^';
  698. end
  699. else
  700. begin
  701. str:=str+procvar.returndef.typename+'(';
  702. endstr:=')';
  703. end;
  704. end;
  705. str:=str+'invokeObjectFunc([';
  706. { parameters are a constant array of jlobject }
  707. firstpara:=true;
  708. for i:=0 to procvar.paras.count-1 do
  709. begin
  710. { skip self/vmt/parentfp, passed separately }
  711. pvs:=tparavarsym(procvar.paras[i]);
  712. if ([vo_is_self,vo_is_vmt,vo_is_parentfp]*pvs.varoptions)<>[] then
  713. continue;
  714. if not firstpara then
  715. str:=str+',';
  716. firstpara:=false;
  717. paraname:=pvs.realname;
  718. paradef:=pvs.vardef;
  719. { Pascalize hidden high parameter }
  720. if vo_is_high_para in pvs.varoptions then
  721. paraname:='high('+tparavarsym(procvar.paras[i-1]).realname+')'
  722. else if vo_is_hidden_para in pvs.varoptions then
  723. begin
  724. if ([vo_is_range_check,vo_is_overflow_check]*pvs.varoptions)<>[] then
  725. { ok, simple boolean parameters }
  726. else
  727. internalerror(2011072403);
  728. end;
  729. { var/out/constref parameters -> pass address through (same for
  730. implicit pointer types) }
  731. if paramanager.push_copyout_param(pvs.varspez,paradef,procvar.proccalloption) or
  732. jvmimplicitpointertype(paradef) then
  733. begin
  734. paraname:='@'+paraname;
  735. paradef:=java_jlobject;
  736. end;
  737. if paradef.typ in [orddef,floatdef] then
  738. begin
  739. { box primitive types; use valueOf() rather than create because it
  740. can give better performance }
  741. jvmgetboxtype(paradef,boxdef,boxargdef,false);
  742. str:=str+boxdef.typename+'.valueOf('+boxargdef.typename+'('+paraname+'))'
  743. end
  744. else
  745. str:=str+'JLObject('+paraname+')';
  746. end;
  747. str:=str+'])'+endstr+' end;';
  748. str_parse_method_impl(str,pd,false)
  749. end;
  750. procedure implement_jvm_procvar_intconstr(pd: tprocdef);
  751. var
  752. pvdef: tprocvardef;
  753. begin
  754. { ideal, and most performant, would be to keep the interface instance
  755. passed to the constructor around and always call its method directly
  756. rather than working via reflection. Unfortunately, the procvar semantics
  757. that allow directly modifying the procvar via typecasting it to a
  758. tmethod make this very hard.
  759. So for now we simply take the address of the interface instance's
  760. method and assign it to the tmethod of this procvar }
  761. pvdef:=tprocvardef(pd.skpara);
  762. str_parse_method_impl('begin method:=System.TMethod(@__intf.'+pvdef.typesym.RealName+'Callback) end;',pd,false);
  763. end;
  764. procedure implement_jvm_virtual_clmethod(pd: tprocdef);
  765. var
  766. str: ansistring;
  767. callpd: tprocdef;
  768. begin
  769. callpd:=tprocdef(pd.skpara);
  770. str:='var pv: __fpc_virtualclassmethod_pv_t'+pd.unique_id_str+'; begin '
  771. + 'pv:=@'+callpd.procsym.RealName+';';
  772. if (pd.proctypeoption<>potype_constructor) and
  773. not is_void(pd.returndef) then
  774. str:=str+'result:=';
  775. str:=str+'pv(';
  776. addvisibibleparameters(str,pd);
  777. str:=str+') end;';
  778. str_parse_method_impl(str,pd,true)
  779. end;
  780. {$endif jvm}
  781. procedure implement_field_getter(pd: tprocdef);
  782. var
  783. i: longint;
  784. pvs: tparavarsym;
  785. str: ansistring;
  786. callthroughprop: tpropertysym;
  787. propaccesslist: tpropaccesslist;
  788. lastparanr: longint;
  789. firstpara: boolean;
  790. begin
  791. callthroughprop:=tpropertysym(pd.skpara);
  792. str:='begin result:='+callthroughprop.realname;
  793. if ppo_hasparameters in callthroughprop.propoptions then
  794. begin
  795. if not callthroughprop.getpropaccesslist(palt_read,propaccesslist) then
  796. internalerror(2012100701);
  797. str:=str+'[';
  798. firstpara:=true;
  799. lastparanr:=tprocdef(propaccesslist.procdef).paras.count-1;
  800. if ppo_indexed in callthroughprop.propoptions then
  801. dec(lastparanr);
  802. for i:=0 to lastparanr do
  803. begin
  804. { skip self/vmt/parentfp, passed implicitly }
  805. pvs:=tparavarsym(tprocdef(propaccesslist.procdef).paras[i]);
  806. if ([vo_is_self,vo_is_vmt,vo_is_parentfp]*pvs.varoptions)<>[] then
  807. continue;
  808. if not firstpara then
  809. str:=str+',';
  810. firstpara:=false;
  811. str:=str+pvs.realname;
  812. end;
  813. str:=str+']';
  814. end;
  815. str:=str+'; end;';
  816. str_parse_method_impl(str,pd,po_classmethod in pd.procoptions)
  817. end;
  818. procedure implement_field_setter(pd: tprocdef);
  819. var
  820. i, lastparaindex: longint;
  821. pvs: tparavarsym;
  822. paraname, str: ansistring;
  823. callthroughprop: tpropertysym;
  824. propaccesslist: tpropaccesslist;
  825. firstpara: boolean;
  826. begin
  827. callthroughprop:=tpropertysym(pd.skpara);
  828. str:='begin '+callthroughprop.realname;
  829. if not callthroughprop.getpropaccesslist(palt_write,propaccesslist) then
  830. internalerror(2012100702);
  831. if ppo_hasparameters in callthroughprop.propoptions then
  832. begin
  833. str:=str+'[';
  834. firstpara:=true;
  835. { last parameter is the value to be set, skip (only add index
  836. parameters here) }
  837. lastparaindex:=tprocdef(propaccesslist.procdef).paras.count-2;
  838. if ppo_indexed in callthroughprop.propoptions then
  839. dec(lastparaindex);
  840. for i:=0 to lastparaindex do
  841. begin
  842. { skip self/vmt/parentfp/index, passed implicitly }
  843. pvs:=tparavarsym(tprocdef(propaccesslist.procdef).paras[i]);
  844. if ([vo_is_self,vo_is_vmt,vo_is_parentfp]*pvs.varoptions)<>[] then
  845. continue;
  846. if not firstpara then
  847. str:=str+',';
  848. firstpara:=false;
  849. str:=str+pvs.realname;
  850. end;
  851. str:=str+']';
  852. end;
  853. { the value-to-be-set }
  854. if assigned(propaccesslist.procdef) then
  855. begin
  856. pvs:=tparavarsym(tprocdef(propaccesslist.procdef).paras[tprocdef(propaccesslist.procdef).paras.count-1]);
  857. paraname:=pvs.realname;
  858. end
  859. else
  860. paraname:='__fpc_newval__';
  861. str:=str+':='+paraname+'; end;';
  862. str_parse_method_impl(str,pd,po_classmethod in pd.procoptions)
  863. end;
  864. procedure implement_block_invoke_procvar(pd: tprocdef);
  865. var
  866. str: ansistring;
  867. begin
  868. str:='';
  869. str:='begin ';
  870. if pd.returndef<>voidtype then
  871. str:=str+'result:=';
  872. str:=str+'__FPC_BLOCK_INVOKE_PV_TYPE(PFPC_Block_literal_complex_procvar(FPC_Block_Self)^.pv)(';
  873. addvisibibleparameters(str,pd);
  874. str:=str+') end;';
  875. str_parse_method_impl(str,pd,false);
  876. end;
  877. procedure implement_interface_wrapper(pd: tprocdef);
  878. var
  879. wrapperinfo: pskpara_interface_wrapper;
  880. callthroughpd: tprocdef;
  881. str: ansistring;
  882. fileinfo: tfileposinfo;
  883. begin
  884. wrapperinfo:=pskpara_interface_wrapper(pd.skpara);
  885. if not assigned(wrapperinfo) then
  886. internalerror(2015090801);
  887. callthroughpd:=tprocdef(wrapperinfo^.pd);
  888. str:='begin ';
  889. { self right now points to the VMT of interface inside the instance ->
  890. adjust so it points to the start of the instance }
  891. str:=str+'pointer(self):=pointer(self) - '+tostr(wrapperinfo^.offset)+';';
  892. { now call through to the actual method }
  893. if pd.returndef<>voidtype then
  894. str:=str+'result:=';
  895. str:=str+callthroughpd.procsym.realname+'(';
  896. addvisibibleparameters(str,callthroughpd);
  897. str:=str+') end;';
  898. { add dummy file info so we can step in/through it }
  899. if pd.owner.iscurrentunit then
  900. fileinfo:=pd.fileinfo
  901. else
  902. begin
  903. fileinfo.moduleindex:=current_module.moduleid;
  904. fileinfo.fileindex:=1;
  905. fileinfo.line:=1;
  906. fileinfo.column:=1;
  907. end;
  908. str_parse_method_impl_with_fileinfo(str,pd,fileinfo.fileindex,fileinfo.line,false);
  909. dispose(wrapperinfo);
  910. pd.skpara:=nil;
  911. end;
  912. procedure implement_call_no_parameters(pd: tprocdef);
  913. var
  914. callpd: tprocdef;
  915. str: ansistring;
  916. warningson,
  917. isclassmethod: boolean;
  918. begin
  919. { avoid warnings about unset function results in these abstract wrappers }
  920. warningson:=(status.verbosity and V_Warning)<>0;
  921. setverbosity('W-');
  922. str:='begin ';
  923. callpd:=tprocdef(pd.skpara);
  924. str:=str+def_unit_name_prefix_if_toplevel(callpd)+callpd.procsym.realname+'; end;';
  925. isclassmethod:=
  926. (po_classmethod in pd.procoptions) and
  927. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  928. str_parse_method_impl(str,pd,isclassmethod);
  929. if warningson then
  930. setverbosity('W+');
  931. end;
  932. procedure add_synthetic_method_implementations_for_st(st: tsymtable);
  933. var
  934. i : longint;
  935. def : tdef;
  936. pd : tprocdef;
  937. begin
  938. for i:=0 to st.deflist.count-1 do
  939. begin
  940. def:=tdef(st.deflist[i]);
  941. if (def.typ<>procdef) then
  942. continue;
  943. { skip methods when processing unit symtable }
  944. if def.owner<>st then
  945. continue;
  946. pd:=tprocdef(def);
  947. case pd.synthetickind of
  948. tsk_none:
  949. ;
  950. tsk_anon_inherited:
  951. implement_anon_inherited(pd);
  952. tsk_jvm_clone:
  953. implement_jvm_clone(pd);
  954. tsk_record_deepcopy:
  955. implement_record_deepcopy(pd);
  956. tsk_record_initialize:
  957. implement_record_initialize(pd);
  958. tsk_empty,
  959. { special handling for this one is done in tnodeutils.wrap_proc_body }
  960. tsk_tcinit:
  961. implement_empty(pd);
  962. tsk_callthrough:
  963. implement_callthrough(pd);
  964. tsk_callthrough_nonabstract:
  965. begin
  966. if (pd.owner.defowner.typ<>objectdef) or
  967. (tobjectdef(pd.owner.defowner).abstractcnt=0) then
  968. implement_callthrough(pd)
  969. else
  970. implement_empty(pd);
  971. end;
  972. {$ifdef jvm}
  973. tsk_jvm_enum_values:
  974. implement_jvm_enum_values(pd);
  975. tsk_jvm_enum_valueof:
  976. implement_jvm_enum_valuof(pd);
  977. tsk_jvm_enum_classconstr:
  978. implement_jvm_enum_classconstr(pd);
  979. tsk_jvm_enum_jumps_constr:
  980. implement_jvm_enum_jumps_constr(pd);
  981. tsk_jvm_enum_fpcordinal:
  982. implement_jvm_enum_fpcordinal(pd);
  983. tsk_jvm_enum_fpcvalueof:
  984. implement_jvm_enum_fpcvalueof(pd);
  985. tsk_jvm_enum_long2set:
  986. implement_jvm_enum_long2set(pd);
  987. tsk_jvm_enum_bitset2set:
  988. implement_jvm_enum_bitset2set(pd);
  989. tsk_jvm_enum_set2set:
  990. implement_jvm_enum_set2set(pd);
  991. tsk_jvm_procvar_invoke:
  992. implement_jvm_procvar_invoke(pd);
  993. tsk_jvm_procvar_intconstr:
  994. implement_jvm_procvar_intconstr(pd);
  995. tsk_jvm_virtual_clmethod:
  996. implement_jvm_virtual_clmethod(pd);
  997. {$endif jvm}
  998. tsk_field_getter:
  999. implement_field_getter(pd);
  1000. tsk_field_setter:
  1001. implement_field_setter(pd);
  1002. tsk_block_invoke_procvar:
  1003. implement_block_invoke_procvar(pd);
  1004. tsk_interface_wrapper:
  1005. implement_interface_wrapper(pd);
  1006. tsk_call_no_parameters:
  1007. implement_call_no_parameters(pd);
  1008. else
  1009. internalerror(2011032801);
  1010. end;
  1011. end;
  1012. end;
  1013. procedure add_synthetic_method_implementations(st: tsymtable);
  1014. var
  1015. i: longint;
  1016. def: tdef;
  1017. sstate: tscannerstate;
  1018. begin
  1019. { skip if any errors have occurred, since then this can only cause more
  1020. errors }
  1021. if ErrorCount<>0 then
  1022. exit;
  1023. replace_scanner('synthetic_impl',sstate);
  1024. add_synthetic_method_implementations_for_st(st);
  1025. for i:=0 to st.deflist.count-1 do
  1026. begin
  1027. def:=tdef(st.deflist[i]);
  1028. if (def.typ=procdef) and
  1029. assigned(tprocdef(def).localst) and
  1030. { not true for the "main" procedure, whose localsymtable is the staticsymtable }
  1031. (tprocdef(def).localst.symtabletype=localsymtable) then
  1032. add_synthetic_method_implementations(tprocdef(def).localst)
  1033. else if ((def.typ=objectdef) and
  1034. not(oo_is_external in tobjectdef(def).objectoptions)) or
  1035. (def.typ=recorddef) then
  1036. begin
  1037. { also complete nested types }
  1038. add_synthetic_method_implementations(tabstractrecorddef(def).symtable);
  1039. end;
  1040. end;
  1041. restore_scanner(sstate);
  1042. end;
  1043. function create_procdef_alias(pd: tprocdef; const newrealname: string; const newmangledname: TSymStr; newparentst: tsymtable; newstruct: tabstractrecorddef;
  1044. sk: tsynthetickind; skpara: pointer): tprocdef;
  1045. begin
  1046. { bare copy so we don't copy the aliasnames }
  1047. result:=tprocdef(pd.getcopyas(procdef,pc_bareproc));
  1048. { set the mangled name to the wrapper name }
  1049. result.setmangledname(newmangledname);
  1050. { finish creating the copy }
  1051. finish_copied_procdef(result,newrealname,newparentst,newstruct);
  1052. { now insert self/vmt }
  1053. insert_self_and_vmt_para(result);
  1054. { and the function result }
  1055. insert_funcret_para(result);
  1056. { recalculate the parameters now that we've added the missing ones }
  1057. result.calcparas;
  1058. { set the info required to generate the implementation }
  1059. result.synthetickind:=sk;
  1060. result.skpara:=skpara;
  1061. end;
  1062. procedure finish_copied_procdef(var pd: tprocdef; const realname: string; newparentst: tsymtable; newstruct: tabstractrecorddef);
  1063. var
  1064. sym: tsym;
  1065. parasym: tparavarsym;
  1066. ps: tprocsym;
  1067. stname: string;
  1068. i: longint;
  1069. begin
  1070. { add generic flag if required }
  1071. if assigned(newstruct) and
  1072. (df_generic in newstruct.defoptions) then
  1073. include(pd.defoptions,df_generic);
  1074. { associate the procdef with a procsym in the owner }
  1075. if not(pd.proctypeoption in [potype_class_constructor,potype_class_destructor]) then
  1076. stname:=upper(realname)
  1077. else
  1078. stname:=lower(realname);
  1079. sym:=tsym(newparentst.find(stname));
  1080. if assigned(sym) then
  1081. begin
  1082. if sym.typ<>procsym then
  1083. internalerror(2011040601);
  1084. ps:=tprocsym(sym);
  1085. end
  1086. else
  1087. begin
  1088. ps:=cprocsym.create(realname);
  1089. newparentst.insert(ps);
  1090. end;
  1091. pd.procsym:=ps;
  1092. pd.struct:=newstruct;
  1093. { in case of methods, replace the special parameter types with new ones }
  1094. if assigned(newstruct) then
  1095. begin
  1096. symtablestack.push(pd.parast);
  1097. { may not be assigned in case we converted a procvar into a procdef }
  1098. if assigned(pd.paras) then
  1099. begin
  1100. for i:=0 to pd.paras.count-1 do
  1101. begin
  1102. parasym:=tparavarsym(pd.paras[i]);
  1103. if vo_is_self in parasym.varoptions then
  1104. begin
  1105. if parasym.vardef.typ=classrefdef then
  1106. parasym.vardef:=cclassrefdef.create(newstruct)
  1107. else
  1108. parasym.vardef:=newstruct;
  1109. end
  1110. end;
  1111. end;
  1112. { also fix returndef in case of a constructor }
  1113. if pd.proctypeoption=potype_constructor then
  1114. pd.returndef:=newstruct;
  1115. symtablestack.pop(pd.parast);
  1116. end;
  1117. pd.calcparas;
  1118. proc_add_definition(pd);
  1119. end;
  1120. procedure build_parentfpstruct(pd: tprocdef);
  1121. var
  1122. nestedvars: tsym;
  1123. nestedvarsst: tsymtable;
  1124. pnestedvarsdef,
  1125. nestedvarsdef: tdef;
  1126. old_symtablestack: tsymtablestack;
  1127. begin
  1128. { make sure the defs are not registered in the current symtablestack,
  1129. because they may be for a parent procdef (changeowner does remove a def
  1130. from the symtable in which it was originally created, so that by itself
  1131. is not enough) }
  1132. old_symtablestack:=symtablestack;
  1133. symtablestack:=old_symtablestack.getcopyuntil(current_module.localsymtable);
  1134. { create struct to hold local variables and parameters that are
  1135. accessed from within nested routines (start with extra dollar to prevent
  1136. the JVM from thinking this is a nested class in the unit) }
  1137. nestedvarsst:=trecordsymtable.create('$'+current_module.realmodulename^+'$$_fpc_nestedvars$'+pd.unique_id_str,
  1138. current_settings.alignment.localalignmax,current_settings.alignment.localalignmin,current_settings.alignment.maxCrecordalign);
  1139. nestedvarsdef:=crecorddef.create(nestedvarsst.name^,nestedvarsst);
  1140. {$ifdef jvm}
  1141. maybe_guarantee_record_typesym(nestedvarsdef,nestedvarsdef.owner);
  1142. { don't add clone/FpcDeepCopy, because the field names are not all
  1143. representable in source form and we don't need them anyway }
  1144. symtablestack.push(trecorddef(nestedvarsdef).symtable);
  1145. maybe_add_public_default_java_constructor(trecorddef(nestedvarsdef));
  1146. insert_record_hidden_paras(trecorddef(nestedvarsdef));
  1147. symtablestack.pop(trecorddef(nestedvarsdef).symtable);
  1148. {$endif}
  1149. symtablestack.free;
  1150. symtablestack:=old_symtablestack.getcopyuntil(pd.localst);
  1151. pnestedvarsdef:=cpointerdef.getreusable(nestedvarsdef);
  1152. if not(po_assembler in pd.procoptions) then
  1153. begin
  1154. nestedvars:=clocalvarsym.create('$nestedvars',vs_var,nestedvarsdef,[],true);
  1155. pd.localst.insert(nestedvars);
  1156. pd.parentfpstruct:=nestedvars;
  1157. pd.parentfpinitblock:=cblocknode.create(nil);
  1158. end;
  1159. symtablestack.free;
  1160. pd.parentfpstructptrtype:=pnestedvarsdef;
  1161. symtablestack:=old_symtablestack;
  1162. end;
  1163. function maybe_add_sym_to_parentfpstruct(pd: tprocdef; sym: tsym; vardef: tdef; addrparam: boolean): tsym;
  1164. var
  1165. fieldvardef,
  1166. nestedvarsdef: tdef;
  1167. nestedvarsst: tsymtable;
  1168. initcode: tnode;
  1169. old_filepos: tfileposinfo;
  1170. symname,
  1171. symrealname: TSymStr;
  1172. begin
  1173. nestedvarsdef:=tlocalvarsym(pd.parentfpstruct).vardef;
  1174. { redirect all aliases for the function result also to the function
  1175. result }
  1176. if vo_is_funcret in tabstractvarsym(sym).varoptions then
  1177. begin
  1178. symname:='result';
  1179. symrealname:='$result'
  1180. end
  1181. else
  1182. begin
  1183. symname:=sym.name;
  1184. symrealname:=sym.realname;
  1185. end;
  1186. result:=search_struct_member(trecorddef(nestedvarsdef),symname);
  1187. if not assigned(result) then
  1188. begin
  1189. { mark that this symbol is mirrored in the parentfpstruct }
  1190. tabstractnormalvarsym(sym).inparentfpstruct:=true;
  1191. { add field to the struct holding all locals accessed
  1192. by nested routines }
  1193. nestedvarsst:=trecorddef(nestedvarsdef).symtable;
  1194. { indicate whether or not this is a var/out/constref/... parameter }
  1195. if addrparam then
  1196. fieldvardef:=cpointerdef.getreusable(vardef)
  1197. else
  1198. fieldvardef:=vardef;
  1199. result:=cfieldvarsym.create(symrealname,vs_value,fieldvardef,[],true);
  1200. if nestedvarsst.symlist.count=0 then
  1201. include(tfieldvarsym(result).varoptions,vo_is_first_field);
  1202. nestedvarsst.insert(result);
  1203. trecordsymtable(nestedvarsst).addfield(tfieldvarsym(result),vis_public);
  1204. { add initialization with original value if it's a parameter }
  1205. if (sym.typ=paravarsym) then
  1206. begin
  1207. old_filepos:=current_filepos;
  1208. fillchar(current_filepos,sizeof(current_filepos),0);
  1209. initcode:=cloadnode.create(sym,sym.owner);
  1210. { indicate that this load should not be transformed into a load
  1211. from the parentfpstruct, but instead should load the original
  1212. value }
  1213. include(initcode.flags,nf_internal);
  1214. { in case it's a var/out/constref parameter, store the address of the
  1215. parameter in the struct }
  1216. if addrparam then
  1217. begin
  1218. initcode:=caddrnode.create_internal(initcode);
  1219. include(initcode.flags,nf_typedaddr);
  1220. end;
  1221. initcode:=cassignmentnode.create(
  1222. csubscriptnode.create(result,cloadnode.create(pd.parentfpstruct,pd.parentfpstruct.owner)),
  1223. initcode);
  1224. tblocknode(pd.parentfpinitblock).left:=cstatementnode.create
  1225. (initcode,tblocknode(pd.parentfpinitblock).left);
  1226. current_filepos:=old_filepos;
  1227. end;
  1228. end;
  1229. end;
  1230. procedure redirect_parentfpstruct_local_syms(pd: tprocdef);
  1231. var
  1232. nestedvarsdef: trecorddef;
  1233. sl: tpropaccesslist;
  1234. fsym,
  1235. lsym,
  1236. aliassym: tsym;
  1237. i: longint;
  1238. begin
  1239. nestedvarsdef:=trecorddef(tlocalvarsym(pd.parentfpstruct).vardef);
  1240. for i:=0 to nestedvarsdef.symtable.symlist.count-1 do
  1241. begin
  1242. fsym:=tsym(nestedvarsdef.symtable.symlist[i]);
  1243. if fsym.typ<>fieldvarsym then
  1244. continue;
  1245. lsym:=tsym(pd.localst.find(fsym.name));
  1246. if not assigned(lsym) then
  1247. lsym:=tsym(pd.parast.find(fsym.name));
  1248. if not assigned(lsym) then
  1249. internalerror(2011060408);
  1250. { add an absolute variable that redirects to the field }
  1251. sl:=tpropaccesslist.create;
  1252. sl.addsym(sl_load,pd.parentfpstruct);
  1253. sl.addsym(sl_subscript,tfieldvarsym(fsym));
  1254. aliassym:=cabsolutevarsym.create_ref(lsym.name,tfieldvarsym(fsym).vardef,sl);
  1255. { hide the original variable (can't delete, because there
  1256. may be other loadnodes that reference it)
  1257. -- only for locals; hiding parameters changes the
  1258. function signature }
  1259. if lsym.typ<>paravarsym then
  1260. hidesym(lsym);
  1261. { insert the absolute variable in the localst of the
  1262. routine; ignore duplicates, because this will also check the
  1263. parasymtable and we want to override parameters with our local
  1264. versions }
  1265. pd.localst.insert(aliassym,false);
  1266. end;
  1267. end;
  1268. function find_sym_in_parentfpstruct(pd: tprocdef; sym: tsym): tsym;
  1269. var
  1270. nestedvarsdef: tdef;
  1271. begin
  1272. nestedvarsdef:=tlocalvarsym(pd.parentfpstruct).vardef;
  1273. result:=search_struct_member(trecorddef(nestedvarsdef),sym.name);
  1274. end;
  1275. procedure finish_parentfpstruct(pd: tprocdef);
  1276. begin
  1277. trecordsymtable(trecorddef(tlocalvarsym(pd.parentfpstruct).vardef).symtable).addalignmentpadding;
  1278. end;
  1279. procedure maybe_guarantee_record_typesym(var def: tdef; st: tsymtable);
  1280. var
  1281. ts: ttypesym;
  1282. begin
  1283. { create a dummy typesym for the JVM target, because the record
  1284. has to be wrapped by a class }
  1285. if (target_info.system in systems_jvm) and
  1286. (def.typ=recorddef) and
  1287. not assigned(def.typesym) then
  1288. begin
  1289. ts:=ctypesym.create(trecorddef(def).symtable.realname^,def,true);
  1290. st.insert(ts);
  1291. ts.visibility:=vis_strictprivate;
  1292. { this typesym can't be used by any Pascal code, so make sure we don't
  1293. print a hint about it being unused }
  1294. addsymref(ts);
  1295. end;
  1296. end;
  1297. function make_field_static(recst: tsymtable; fieldvs: tfieldvarsym): tstaticvarsym;
  1298. var
  1299. static_name: string;
  1300. hstaticvs: tstaticvarsym;
  1301. tmp: tabsolutevarsym;
  1302. sl: tpropaccesslist;
  1303. begin
  1304. include(fieldvs.symoptions,sp_static);
  1305. { generate the symbol which reserves the space }
  1306. static_name:=lower(generate_nested_name(recst,'_'))+'_'+fieldvs.name;
  1307. hstaticvs:=cstaticvarsym.create_from_fieldvar(static_name,fieldvs);
  1308. {$ifdef jvm}
  1309. { for the JVM, static field accesses are name-based and
  1310. hence we have to keep the original name of the field.
  1311. Create a staticvarsym instead of a fieldvarsym so we can
  1312. nevertheless use a loadn instead of a subscriptn though,
  1313. since a subscriptn requires something to subscript and
  1314. there is nothing in this case (class+field name will be
  1315. encoded in the mangled symbol name) }
  1316. recst.insert(hstaticvs);
  1317. { only set the staticvarsym's basename (= field name, without any
  1318. mangling), because generating the fully mangled name right now can
  1319. result in a wrong string in case the field's type is a forward
  1320. declared class whose external name will change when the actual
  1321. definition is parsed }
  1322. if (vo_has_mangledname in fieldvs.varoptions) then
  1323. hstaticvs.set_mangledbasename(fieldvs.externalname^)
  1324. else
  1325. hstaticvs.set_mangledbasename(fieldvs.realname);
  1326. { for definition in class file }
  1327. hstaticvs.visibility:=fieldvs.visibility;
  1328. {$else jvm}
  1329. include(hstaticvs.symoptions,sp_internal);
  1330. tabstractrecordsymtable(recst).get_unit_symtable.insert(hstaticvs);
  1331. {$endif jvm}
  1332. { generate the symbol for the access }
  1333. sl:=tpropaccesslist.create;
  1334. sl.addsym(sl_load,hstaticvs);
  1335. { do *not* change the visibility of this absolutevarsym from vis_public
  1336. to anything else, because its visibility is used by visibility checks
  1337. after turning a class property referring to a class variable into a
  1338. load node (handle_staticfield_access -> searchsym_in_class ->
  1339. is_visible_for_object), which means that the load will fail if this
  1340. symbol is e.g. "strict private" while the property is public }
  1341. tmp:=cabsolutevarsym.create_ref('$'+static_name,fieldvs.vardef,sl);
  1342. recst.insert(tmp);
  1343. result:=hstaticvs;
  1344. end;
  1345. procedure call_through_new_name(orgpd: tprocdef; const newname: TSymStr);
  1346. var
  1347. newpd: tprocdef;
  1348. begin
  1349. { we have a forward declaration like
  1350. procedure test; (in the unit interface or "forward")
  1351. and then an implementation like
  1352. procedure test; external name 'something';
  1353. To solve this, we create a new external procdef for the
  1354. implementation, and then generate a procedure body for the original
  1355. one that calls through to the external procdef. This is necessary
  1356. because there may already be references to the mangled name for the
  1357. non-external "test".
  1358. }
  1359. newpd:=tprocdef(orgpd.getcopyas(procdef,pc_bareproc));
  1360. insert_funcret_para(newpd);
  1361. newpd.procoptions:=newpd.procoptions+orgpd.procoptions*[po_external,po_has_importname,po_has_importdll];
  1362. newpd.import_name:=orgpd.import_name;
  1363. orgpd.import_name:=nil;
  1364. newpd.import_dll:=orgpd.import_dll;
  1365. orgpd.import_dll:=nil;
  1366. newpd.import_nr:=orgpd.import_nr;
  1367. orgpd.import_nr:=0;
  1368. newpd.setmangledname(newname);
  1369. finish_copied_procdef(newpd,'__FPC_IMPL_EXTERNAL_REDIRECT_'+newname,current_module.localsymtable,nil);
  1370. newpd.forwarddef:=false;
  1371. orgpd.skpara:=newpd;
  1372. orgpd.synthetickind:=tsk_callthrough;
  1373. orgpd.procoptions:=orgpd.procoptions-[po_external,po_has_importname,po_has_importdll];
  1374. orgpd.forwarddef:=true;
  1375. end;
  1376. function generate_pkg_stub(pd:tprocdef):tnode;
  1377. begin
  1378. if target_info.system in systems_all_windows+systems_nativent then
  1379. begin
  1380. insert_funcret_local(pd);
  1381. result:=cassignmentnode.create(
  1382. cloadnode.create(pd.funcretsym,pd.localst),
  1383. cordconstnode.create(1,bool32type,false)
  1384. );
  1385. end
  1386. else
  1387. result:=cnothingnode.create;
  1388. end;
  1389. end.