symcreat.pas 79 KB

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