symcreat.pas 73 KB

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