symcreat.pas 61 KB

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