symcreat.pas 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219
  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 not (vardef is tarraydef) then
  1312. result:=vardef.fulltypename
  1313. else
  1314. begin
  1315. if (ado_isarrayofconst in arrdef.arrayoptions) then
  1316. begin
  1317. if asPointer then
  1318. Result:='Array of TVarRec'
  1319. else
  1320. result:='Array Of Const';
  1321. asPointer:=False;
  1322. isAnonymousArrayDef:=true;
  1323. end
  1324. else if (ado_OpenArray in arrdef.arrayoptions) then
  1325. begin
  1326. result:='Array of '+arrdef.elementdef.fulltypename;
  1327. asPointer:=False;
  1328. isAnonymousArrayDef:=true;
  1329. end
  1330. else
  1331. begin
  1332. result:=vardef.fulltypename;
  1333. end;
  1334. end;
  1335. // ansistring(0) -> ansistring
  1336. p:=pos('(',result);
  1337. if p=0 then
  1338. p:=pos('[',result);
  1339. if p>0 then
  1340. result:=copy(result,1,p-1);
  1341. if asPointer then
  1342. Result:='^'+Result;
  1343. end;
  1344. function get_method_paramtype(vardef : Tdef; asPointer : Boolean) : ansistring;
  1345. var
  1346. ad : boolean;
  1347. begin
  1348. result:=get_method_paramtype(vardef,aspointer,ad);
  1349. end;
  1350. function create_intf_method_args(p : tprocdef; out argcount: integer) : ansistring;
  1351. const
  1352. varspezprefixes : array[tvarspez] of shortstring =
  1353. ('','const','var','out','constref','final');
  1354. var
  1355. i : integer;
  1356. s : string;
  1357. para : tparavarsym;
  1358. begin
  1359. result:='';
  1360. argCount:=0;
  1361. for i:=0 to p.paras.Count-1 do
  1362. begin
  1363. para:=tparavarsym(p.paras[i]);
  1364. if vo_is_hidden_para in para.varoptions then
  1365. continue;
  1366. if Result<>'' then
  1367. Result:=Result+';';
  1368. inc(argCount);
  1369. result:=result+varspezprefixes[para.varspez]+' p'+tostr(argcount);
  1370. if Assigned(para.vardef) and not (para.vardef is tformaldef) then
  1371. result:=Result+' : '+get_method_paramtype(para.vardef,false);
  1372. end;
  1373. if Result<>'' then
  1374. Result:='('+Result+')';
  1375. end;
  1376. function generate_thunkclass_name(acount: Integer; objdef : tobjectdef) : shortstring;
  1377. var
  1378. cn : shortstring;
  1379. i : integer;
  1380. begin
  1381. cn:=ObjDef.GetTypeName;
  1382. for i:=0 to Length(cn) do
  1383. if cn[i]='.' then
  1384. cn[i]:='_';
  1385. result:='_t_hidden'+tostr(acount)+cn;
  1386. end;
  1387. function get_thunkclass_interface_vmtoffset(objdef : tobjectdef) : integer;
  1388. var
  1389. i,j,offs : integer;
  1390. sym : tsym;
  1391. proc : tprocsym absolute sym;
  1392. pd : tprocdef;
  1393. begin
  1394. offs:=maxint;
  1395. for I:=0 to objdef.symtable.symList.Count-1 do
  1396. begin
  1397. sym:=tsym(objdef.symtable.symList[i]);
  1398. if Not assigned(sym) then
  1399. continue;
  1400. if (Sym.typ<>procsym) then
  1401. continue;
  1402. for j:=0 to proc.ProcdefList.Count-1 do
  1403. begin
  1404. pd:=tprocdef(proc.ProcdefList[j]);
  1405. if pd.extnumber<offs then
  1406. offs:=pd.extnumber;
  1407. end;
  1408. end;
  1409. if offs=maxint then
  1410. offs:=0;
  1411. result:=offs;
  1412. end;
  1413. // return parent Interface def, but skip iunknown.
  1414. function getparent_interface_def(odef : tobjectdef) : tobjectdef;
  1415. begin
  1416. if (odef.getparentdef is tobjectdef) then
  1417. begin
  1418. result:=odef.getparentdef as tobjectdef;
  1419. if result=interface_iunknown then
  1420. result:=Nil;
  1421. end
  1422. else
  1423. result:=nil;
  1424. end;
  1425. procedure implement_interface_thunkclass_decl(cn : shortstring; objdef : tobjectdef);
  1426. var
  1427. parentname,str : ansistring;
  1428. sym : tsym;
  1429. proc : tprocsym absolute sym;
  1430. pd : tprocdef;
  1431. odef,def : tobjectdef;
  1432. offs,argcount,i,j : integer;
  1433. begin
  1434. str:='type '#10;
  1435. odef:=getparent_interface_def(objdef);
  1436. if (oDef=Nil) or (oDef.hiddenclassdef=Nil) then
  1437. parentname:='TInterfaceThunk'
  1438. else
  1439. parentname:=odef.hiddenclassdef.GetTypeName;
  1440. str:=str+cn+' = class('+parentname+','+objdef.GetTypeName+')'#10;
  1441. str:=str+' protected '#10;
  1442. for I:=0 to objdef.symtable.symList.Count-1 do
  1443. begin
  1444. sym:=tsym(objdef.symtable.symList[i]);
  1445. if Not assigned(sym) then
  1446. continue;
  1447. if (Sym.typ<>procsym) then
  1448. continue;
  1449. for j:=0 to proc.ProcdefList.Count-1 do
  1450. begin
  1451. pd:=tprocdef(proc.ProcdefList[j]);
  1452. if pd.returndef<>voidtype then
  1453. str:=str+'function '
  1454. else
  1455. str:=str+'procedure ';
  1456. str:=str+proc.RealName;
  1457. str:=str+create_intf_method_args(pd,argcount);
  1458. if pd.returndef<>voidtype then
  1459. str:=str+' : '+get_method_paramtype(pd.returndef,false);
  1460. str:=str+';'#10;
  1461. end;
  1462. end;
  1463. offs:=get_thunkclass_interface_vmtoffset(objdef);
  1464. if offs>0 then
  1465. begin
  1466. str:=str+'public '#10;
  1467. str:=str+' function InterfaceVMTOffset : word; override;'#10;
  1468. end;
  1469. str:=str+' end;'#10;
  1470. def:=str_parse_objecttypedef(cn,str);
  1471. if assigned(def) then
  1472. begin
  1473. def.created_in_current_module:=true;
  1474. if not def.typesym.is_registered then
  1475. def.typesym.register_sym;
  1476. def.buildderef;
  1477. include(def.objectoptions,oo_can_have_published);
  1478. end;
  1479. objdef.hiddenclassdef:=def;
  1480. end;
  1481. function str_parse_method(str: ansistring): tprocdef;
  1482. var
  1483. oldparse_only: boolean;
  1484. tmpstr: ansistring;
  1485. flags : tread_proc_flags;
  1486. begin
  1487. Message1(parser_d_internal_parser_string,str);
  1488. oldparse_only:=parse_only;
  1489. parse_only:=false;
  1490. { "const" starts a new kind of block and hence makes the scanner return }
  1491. str:=str+'const;';
  1492. block_type:=bt_none;
  1493. { inject the string in the scanner }
  1494. current_scanner.substitutemacro('hidden_interface_method',@str[1],length(str),current_scanner.line_no,current_scanner.inputfile.ref_index,true);
  1495. current_scanner.readtoken(false);
  1496. Result:=read_proc([],Nil);
  1497. parse_only:=oldparse_only;
  1498. { remove the temporary macro input file again }
  1499. current_scanner.closeinputfile;
  1500. current_scanner.nextfile;
  1501. current_scanner.tempopeninputfile;
  1502. end;
  1503. procedure implement_interface_thunkclass_impl_method(cn : shortstring; objdef : tobjectdef; proc : tprocsym; pd : tprocdef);
  1504. var
  1505. rest,str : ansistring;
  1506. pn,d : shortstring;
  1507. sym : tsym;
  1508. aArg,argcount,i : integer;
  1509. haveresult : boolean;
  1510. para : tparavarsym;
  1511. hasopenarray, washigh: Boolean;
  1512. begin
  1513. rest:='';
  1514. str:='';
  1515. if pd.returndef<>voidtype then
  1516. str:=str+'function '
  1517. else
  1518. str:=str+'procedure ';
  1519. pn:=proc.RealName;
  1520. str:=str+cn+'.'+pn;
  1521. str:=str+create_intf_method_args(pd,argcount);
  1522. haveresult:=pd.returndef<>voidtype;
  1523. if haveresult then
  1524. begin
  1525. rest:=get_method_paramtype(pd.returndef,false);
  1526. str:=str+' : '+rest;
  1527. end;
  1528. str:=str+';'#10;
  1529. str:=str+'var '#10;
  1530. str:=str+' data : array[0..'+tostr(argcount)+'] of System.TInterfaceThunk.TArgData;'#10;
  1531. if haveresult then
  1532. str:=str+' res : '+rest+';'#10;
  1533. str:=str+'begin'#10;
  1534. // initialize result.
  1535. if HaveResult then
  1536. begin
  1537. str:=Str+' data[0].addr:=@Res;'#10;
  1538. str:=Str+' data[0].info:=TypeInfo(Res);'#10;
  1539. end
  1540. else
  1541. begin
  1542. str:=Str+' data[0].addr:=nil;'#10;
  1543. str:=Str+' data[0].idx:=-1;'#10;
  1544. end;
  1545. str:=Str+' data[0].idx:=-1;'#10;
  1546. str:=Str+' data[0].ahigh:=-1;'#10;
  1547. // Fill rest of data
  1548. aArg:=0;
  1549. washigh:=false;
  1550. d:='0';
  1551. for i:=0 to pd.paras.Count-1 do
  1552. begin
  1553. para:=tparavarsym(pd.paras[i]);
  1554. // previous was open array. Record high
  1555. if (i>1) then
  1556. begin
  1557. WasHigh:=(vo_is_high_para in para.varoptions);
  1558. if Washigh then
  1559. // D is still value of previous (real) parameter
  1560. str:=str+' data['+d+'].ahigh:=High(p'+d+');'#10
  1561. else
  1562. str:=str+' data['+d+'].ahigh:=-1;'#10;
  1563. end;
  1564. if vo_is_hidden_para in para.varoptions then
  1565. continue;
  1566. inc(aArg);
  1567. d:=tostr(aArg);
  1568. Str:=Str+' data['+d+'].addr:=@p'+d+';'#10;
  1569. Str:=Str+' data['+d+'].idx:='+tostr(i)+';'#10;
  1570. if Assigned(para.vardef) and not (para.vardef is tformaldef) then
  1571. Str:=Str+' data['+d+'].info:=TypeInfo(p'+d+');'#10
  1572. else
  1573. Str:=Str+' data['+d+'].info:=Nil;'#10
  1574. end;
  1575. // if last was not high, set to sentinel.
  1576. if not WasHigh then
  1577. str:=str+' data['+d+'].ahigh:=-1;'#10;
  1578. str:=str+' Thunk('+tostr(pd.extnumber)+','+tostr(argcount)+',@Data);'#10;
  1579. if HaveResult then
  1580. str:=str+' Result:=res;'#10;
  1581. str:=str+'end;'#10;
  1582. pd:=str_parse_method(str);
  1583. end;
  1584. procedure implement_thunkclass_interfacevmtoffset(cn : shortstring; objdef : tobjectdef; offs : integer);
  1585. var
  1586. str : ansistring;
  1587. begin
  1588. str:='function '+cn+'.InterfaceVMTOffset : word;'#10;
  1589. str:=str+'begin'#10;
  1590. str:=str+' result:='+toStr(offs)+';'#10;
  1591. str:=str+'end;'#10;
  1592. str_parse_method(str);
  1593. end;
  1594. procedure implement_interface_thunkclass_impl(cn: shortstring; objdef : tobjectdef);
  1595. var
  1596. str : ansistring;
  1597. sym : tsym;
  1598. proc : tprocsym absolute sym;
  1599. pd : tprocdef;
  1600. offs,i,j : integer;
  1601. begin
  1602. offs:=get_thunkclass_interface_vmtoffset(objdef);
  1603. if offs>0 then
  1604. implement_thunkclass_interfacevmtoffset(cn,objdef,offs);
  1605. for I:=0 to objdef.symtable.symList.Count-1 do
  1606. begin
  1607. sym:=tsym(objdef.symtable.symList[i]);
  1608. if Not assigned(sym) then
  1609. continue;
  1610. if (Sym.typ<>procsym) then
  1611. continue;
  1612. for j:=0 to proc.ProcdefList.Count-1 do
  1613. begin
  1614. pd:=tprocdef(proc.ProcdefList[j]);
  1615. implement_interface_thunkclass_impl_method(cn,objdef,proc,pd);
  1616. end;
  1617. end;
  1618. end;
  1619. procedure add_synthetic_interface_classes_for_st(st : tsymtable; gen_intf, gen_impl : boolean);
  1620. var
  1621. i : longint;
  1622. def : tdef;
  1623. objdef : tobjectdef absolute def;
  1624. recdef : trecorddef absolute def;
  1625. sstate: tscannerstate;
  1626. cn : shortstring;
  1627. begin
  1628. { skip if any errors have occurred, since then this can only cause more
  1629. errors }
  1630. if ErrorCount<>0 then
  1631. exit;
  1632. replace_scanner('hiddenclass_impl',sstate);
  1633. for i:=0 to st.deflist.count-1 do
  1634. begin
  1635. def:=tdef(st.deflist[i]);
  1636. if (def.typ<>objectdef) then
  1637. continue;
  1638. if not (objdef.objecttype in objecttypes_with_thunk) then
  1639. continue;
  1640. if not (oo_can_have_published in objdef.objectoptions) then
  1641. continue;
  1642. // need to add here extended rtti check when it is available
  1643. cn:=generate_thunkclass_name(i,objdef);
  1644. if gen_intf then
  1645. implement_interface_thunkclass_decl(cn,objdef);
  1646. if gen_impl then
  1647. implement_interface_thunkclass_impl(cn,objdef);
  1648. end;
  1649. restore_scanner(sstate);
  1650. // Recurse for interfaces defined in a type section of a class/record.
  1651. for i:=0 to st.deflist.count-1 do
  1652. begin
  1653. def:=tdef(st.deflist[i]);
  1654. if (def.typ=objectdef) and (objdef.objecttype=odt_class) then
  1655. add_synthetic_interface_classes_for_st(objdef.symtable,gen_intf,gen_impl)
  1656. else if (def.typ=recorddef) and (m_advanced_records in current_settings.modeswitches) then
  1657. add_synthetic_interface_classes_for_st(recdef.symtable,gen_intf,gen_impl);
  1658. end;
  1659. end;
  1660. procedure add_synthetic_method_implementations(st: tsymtable);
  1661. var
  1662. i: longint;
  1663. def: tdef;
  1664. sstate: tscannerstate;
  1665. begin
  1666. { skip if any errors have occurred, since then this can only cause more
  1667. errors }
  1668. if ErrorCount<>0 then
  1669. exit;
  1670. replace_scanner('synthetic_impl',sstate);
  1671. add_synthetic_method_implementations_for_st(st);
  1672. for i:=0 to st.deflist.count-1 do
  1673. begin
  1674. def:=tdef(st.deflist[i]);
  1675. if (def.typ=procdef) and
  1676. assigned(tprocdef(def).localst) and
  1677. { not true for the "main" procedure, whose localsymtable is the staticsymtable }
  1678. (tprocdef(def).localst.symtabletype=localsymtable) then
  1679. add_synthetic_method_implementations(tprocdef(def).localst)
  1680. else if ((def.typ=objectdef) and
  1681. not(oo_is_external in tobjectdef(def).objectoptions)) or
  1682. (def.typ=recorddef) then
  1683. begin
  1684. { also complete nested types }
  1685. add_synthetic_method_implementations(tabstractrecorddef(def).symtable);
  1686. end;
  1687. end;
  1688. restore_scanner(sstate);
  1689. end;
  1690. function create_procdef_alias(pd: tprocdef; const newrealname: string; const newmangledname: TSymStr; newparentst: tsymtable; newstruct: tabstractrecorddef;
  1691. sk: tsynthetickind; skpara: pointer): tprocdef;
  1692. begin
  1693. { bare copy so we don't copy the aliasnames (specify prefix for
  1694. parameter names so we don't get issues in the body in case
  1695. we e.g. reference system.initialize and one of the parameters
  1696. is called "system") }
  1697. result:=tprocdef(pd.getcopyas(procdef,pc_bareproc,'__FPCW_',true));
  1698. { set the mangled name to the wrapper name }
  1699. result.setmangledname(newmangledname);
  1700. { finish creating the copy }
  1701. finish_copied_procdef(result,newrealname,newparentst,newstruct);
  1702. { insert hidden high parameters }
  1703. result.parast.SymList.ForEachCall(@insert_hidden_para,result);
  1704. { now insert self/vmt }
  1705. insert_self_and_vmt_para(result);
  1706. { and the function result }
  1707. insert_funcret_para(result);
  1708. { recalculate the parameters now that we've added the missing ones }
  1709. result.calcparas;
  1710. { set the info required to generate the implementation }
  1711. result.synthetickind:=sk;
  1712. result.skpara:=skpara;
  1713. end;
  1714. procedure finish_copied_procdef(var pd: tprocdef; const realname: string; newparentst: tsymtable; newstruct: tabstractrecorddef);
  1715. var
  1716. sym: tsym;
  1717. parasym: tparavarsym;
  1718. ps: tprocsym;
  1719. stname: string;
  1720. i: longint;
  1721. begin
  1722. { add generic flag if required }
  1723. if assigned(newstruct) and
  1724. (df_generic in newstruct.defoptions) then
  1725. include(pd.defoptions,df_generic);
  1726. { associate the procdef with a procsym in the owner }
  1727. if not(pd.proctypeoption in [potype_class_constructor,potype_class_destructor]) then
  1728. stname:=upper(realname)
  1729. else
  1730. stname:=lower(realname);
  1731. sym:=tsym(newparentst.find(stname));
  1732. if assigned(sym) then
  1733. begin
  1734. if sym.typ<>procsym then
  1735. internalerror(2011040601);
  1736. ps:=tprocsym(sym);
  1737. end
  1738. else
  1739. begin
  1740. ps:=cprocsym.create(realname);
  1741. newparentst.insertsym(ps);
  1742. end;
  1743. pd.procsym:=ps;
  1744. pd.struct:=newstruct;
  1745. { in case of methods, replace the special parameter types with new ones }
  1746. if assigned(newstruct) then
  1747. begin
  1748. symtablestack.push(pd.parast);
  1749. { may not be assigned in case we converted a procvar into a procdef }
  1750. if assigned(pd.paras) then
  1751. begin
  1752. for i:=0 to pd.paras.count-1 do
  1753. begin
  1754. parasym:=tparavarsym(pd.paras[i]);
  1755. if vo_is_self in parasym.varoptions then
  1756. begin
  1757. if parasym.vardef.typ=classrefdef then
  1758. parasym.vardef:=cclassrefdef.create(newstruct)
  1759. else
  1760. parasym.vardef:=newstruct;
  1761. end
  1762. end;
  1763. end;
  1764. { also fix returndef in case of a constructor }
  1765. if pd.proctypeoption=potype_constructor then
  1766. pd.returndef:=newstruct;
  1767. symtablestack.pop(pd.parast);
  1768. end;
  1769. pd.calcparas;
  1770. proc_add_definition(pd);
  1771. end;
  1772. function maybe_add_sym_to_parentfpstruct(pd: tprocdef; sym: tsym; vardef: tdef; addrparam: boolean): tsym;
  1773. var
  1774. fieldvardef,
  1775. nestedvarsdef: tdef;
  1776. nestedvarsst: tsymtable;
  1777. initcode: tnode;
  1778. old_filepos: tfileposinfo;
  1779. symname,
  1780. symrealname: TSymStr;
  1781. begin
  1782. nestedvarsdef:=tlocalvarsym(pd.parentfpstruct).vardef;
  1783. { redirect all aliases for the function result also to the function
  1784. result }
  1785. if vo_is_funcret in tabstractvarsym(sym).varoptions then
  1786. begin
  1787. symname:='result';
  1788. symrealname:='$result'
  1789. end
  1790. else
  1791. begin
  1792. symname:=sym.name;
  1793. symrealname:=sym.EscapedRealName;
  1794. end;
  1795. result:=search_struct_member(trecorddef(nestedvarsdef),symname);
  1796. if not assigned(result) then
  1797. begin
  1798. { mark that this symbol is mirrored in the parentfpstruct }
  1799. tabstractnormalvarsym(sym).inparentfpstruct:=true;
  1800. { add field to the struct holding all locals accessed
  1801. by nested routines }
  1802. nestedvarsst:=trecorddef(nestedvarsdef).symtable;
  1803. { indicate whether or not this is a var/out/constref/... parameter }
  1804. if addrparam then
  1805. fieldvardef:=cpointerdef.getreusable(vardef)
  1806. else
  1807. fieldvardef:=vardef;
  1808. result:=cfieldvarsym.create(symrealname,vs_value,fieldvardef,[]);
  1809. nestedvarsst.insertsym(result);
  1810. trecordsymtable(nestedvarsst).addfield(tfieldvarsym(result),vis_public);
  1811. { add initialization with original value if it's a parameter }
  1812. if (sym.typ=paravarsym) then
  1813. begin
  1814. old_filepos:=current_filepos;
  1815. fillchar(current_filepos,sizeof(current_filepos),0);
  1816. initcode:=cloadnode.create(sym,sym.owner);
  1817. { indicate that this load should not be transformed into a load
  1818. from the parentfpstruct, but instead should load the original
  1819. value }
  1820. include(initcode.flags,nf_internal);
  1821. { in case it's a var/out/constref parameter, store the address of the
  1822. parameter in the struct }
  1823. if addrparam then
  1824. begin
  1825. initcode:=caddrnode.create_internal(initcode);
  1826. include(taddrnode(initcode).addrnodeflags,anf_typedaddr);
  1827. end;
  1828. initcode:=cassignmentnode.create(
  1829. csubscriptnode.create(result,cloadnode.create(pd.parentfpstruct,pd.parentfpstruct.owner)),
  1830. initcode);
  1831. tblocknode(pd.parentfpinitblock).left:=cstatementnode.create
  1832. (initcode,tblocknode(pd.parentfpinitblock).left);
  1833. current_filepos:=old_filepos;
  1834. end;
  1835. end;
  1836. end;
  1837. procedure redirect_parentfpstruct_local_syms(pd: tprocdef);
  1838. var
  1839. nestedvarsdef: trecorddef;
  1840. sl: tpropaccesslist;
  1841. fsym,
  1842. lsym,
  1843. aliassym: tsym;
  1844. i: longint;
  1845. begin
  1846. nestedvarsdef:=trecorddef(tlocalvarsym(pd.parentfpstruct).vardef);
  1847. for i:=0 to nestedvarsdef.symtable.symlist.count-1 do
  1848. begin
  1849. fsym:=tsym(nestedvarsdef.symtable.symlist[i]);
  1850. if fsym.typ<>fieldvarsym then
  1851. continue;
  1852. lsym:=tsym(pd.localst.find(fsym.name));
  1853. if not assigned(lsym) then
  1854. lsym:=tsym(pd.parast.find(fsym.name));
  1855. if not assigned(lsym) then
  1856. internalerror(2011060408);
  1857. { add an absolute variable that redirects to the field }
  1858. sl:=tpropaccesslist.create;
  1859. sl.addsym(sl_load,pd.parentfpstruct);
  1860. sl.addsym(sl_subscript,tfieldvarsym(fsym));
  1861. aliassym:=cabsolutevarsym.create_ref(lsym.EscapedRealName,tfieldvarsym(fsym).vardef,sl);
  1862. { hide the original variable (can't delete, because there
  1863. may be other loadnodes that reference it)
  1864. -- only for locals; hiding parameters changes the
  1865. function signature }
  1866. if lsym.typ<>paravarsym then
  1867. hidesym(lsym);
  1868. { insert the absolute variable in the localst of the
  1869. routine; ignore duplicates, because this will also check the
  1870. parasymtable and we want to override parameters with our local
  1871. versions }
  1872. pd.localst.insertsym(aliassym,false);
  1873. end;
  1874. end;
  1875. function find_sym_in_parentfpstruct(pd: tprocdef; sym: tsym): tsym;
  1876. var
  1877. nestedvarsdef: tdef;
  1878. begin
  1879. nestedvarsdef:=tlocalvarsym(pd.parentfpstruct).vardef;
  1880. result:=search_struct_member(trecorddef(nestedvarsdef),sym.name);
  1881. end;
  1882. procedure finish_parentfpstruct(pd: tprocdef);
  1883. begin
  1884. trecordsymtable(trecorddef(tlocalvarsym(pd.parentfpstruct).vardef).symtable).addalignmentpadding;
  1885. end;
  1886. function make_field_static(recst: tsymtable; fieldvs: tfieldvarsym): tstaticvarsym;
  1887. var
  1888. static_name: string;
  1889. hstaticvs: tstaticvarsym;
  1890. tmp: tabsolutevarsym;
  1891. sl: tpropaccesslist;
  1892. begin
  1893. include(fieldvs.symoptions,sp_static);
  1894. { generate the symbol which reserves the space }
  1895. static_name:=lower(generate_nested_name(recst,'_'))+'_'+fieldvs.name;
  1896. hstaticvs:=cstaticvarsym.create_from_fieldvar(static_name,fieldvs);
  1897. {$ifdef jvm}
  1898. { for the JVM, static field accesses are name-based and
  1899. hence we have to keep the original name of the field.
  1900. Create a staticvarsym instead of a fieldvarsym so we can
  1901. nevertheless use a loadn instead of a subscriptn though,
  1902. since a subscriptn requires something to subscript and
  1903. there is nothing in this case (class+field name will be
  1904. encoded in the mangled symbol name) }
  1905. recst.insertsym(hstaticvs);
  1906. { only set the staticvarsym's basename (= field name, without any
  1907. mangling), because generating the fully mangled name right now can
  1908. result in a wrong string in case the field's type is a forward
  1909. declared class whose external name will change when the actual
  1910. definition is parsed }
  1911. if (vo_has_mangledname in fieldvs.varoptions) then
  1912. hstaticvs.set_mangledbasename(fieldvs.externalname^)
  1913. else
  1914. hstaticvs.set_mangledbasename(fieldvs.realname);
  1915. { for definition in class file }
  1916. hstaticvs.visibility:=fieldvs.visibility;
  1917. {$else jvm}
  1918. include(hstaticvs.symoptions,sp_internal);
  1919. if df_generic in tdef(recst.defowner).defoptions then
  1920. tabstractrecordsymtable(recst).insertsym(hstaticvs)
  1921. else
  1922. tdef(tabstractrecordsymtable(recst).defowner).get_top_level_symtable(false).insertsym(hstaticvs);
  1923. {$endif jvm}
  1924. { generate the symbol for the access }
  1925. sl:=tpropaccesslist.create;
  1926. sl.addsym(sl_load,hstaticvs);
  1927. { do *not* change the visibility of this absolutevarsym from vis_public
  1928. to anything else, because its visibility is used by visibility checks
  1929. after turning a class property referring to a class variable into a
  1930. load node (handle_staticfield_access -> searchsym_in_class ->
  1931. is_visible_for_object), which means that the load will fail if this
  1932. symbol is e.g. "strict private" while the property is public }
  1933. tmp:=cabsolutevarsym.create_ref('$'+static_name,fieldvs.vardef,sl);
  1934. recst.insertsym(tmp);
  1935. result:=hstaticvs;
  1936. end;
  1937. procedure call_through_new_name(orgpd: tprocdef; const newname: TSymStr);
  1938. var
  1939. newpd: tprocdef;
  1940. begin
  1941. { we have a forward declaration like
  1942. procedure test; (in the unit interface or "forward")
  1943. and then an implementation like
  1944. procedure test; external name 'something';
  1945. To solve this, we create a new external procdef for the
  1946. implementation, and then generate a procedure body for the original
  1947. one that calls through to the external procdef. This is necessary
  1948. because there may already be references to the mangled name for the
  1949. non-external "test".
  1950. }
  1951. { prefixing the parameters here is useless, because the new procdef will
  1952. just be an external declaration without a body }
  1953. newpd:=tprocdef(orgpd.getcopyas(procdef,pc_bareproc,'',true));
  1954. insert_funcret_para(newpd);
  1955. newpd.procoptions:=newpd.procoptions+orgpd.procoptions*[po_external,po_has_importname,po_has_importdll];
  1956. stringdispose(orgpd.import_name);
  1957. stringdispose(orgpd.import_dll);
  1958. orgpd.import_nr:=0;
  1959. newpd.setmangledname(newname);
  1960. finish_copied_procdef(newpd,'__FPC_IMPL_EXTERNAL_REDIRECT_'+newname,current_module.localsymtable,nil);
  1961. newpd.forwarddef:=false;
  1962. { ideally we would prefix the parameters of the original routine here, but since it
  1963. can be an interface definition, we cannot do that without risking to change the
  1964. interface crc }
  1965. orgpd.skpara:=newpd;
  1966. orgpd.synthetickind:=tsk_callthrough;
  1967. orgpd.procoptions:=orgpd.procoptions-[po_external,po_has_importname,po_has_importdll];
  1968. orgpd.forwarddef:=true;
  1969. end;
  1970. function generate_pkg_stub(pd:tprocdef):tnode;
  1971. begin
  1972. if target_info.system in systems_all_windows+systems_nativent then
  1973. begin
  1974. insert_funcret_local(pd);
  1975. result:=cassignmentnode.create(
  1976. cloadnode.create(pd.funcretsym,pd.localst),
  1977. cordconstnode.create(1,bool32type,false)
  1978. );
  1979. end
  1980. else
  1981. result:=cnothingnode.create;
  1982. end;
  1983. procedure generate_attr_constrs(attrs:tfpobjectlist);
  1984. var
  1985. ps : tprocsym;
  1986. pd : tprocdef;
  1987. pi : tcgprocinfo;
  1988. i : sizeint;
  1989. attr : trtti_attribute;
  1990. begin
  1991. if attrs.count=0 then
  1992. exit;
  1993. { if this isn't set then this unit shouldn't have any attributes }
  1994. if not assigned(class_tcustomattribute) then
  1995. internalerror(2019071003);
  1996. for i:=0 to attrs.count-1 do
  1997. begin
  1998. attr:=trtti_attribute(attrs[i]);
  1999. {Generate a procsym for main}
  2000. ps:=cprocsym.create('$rttiattrconstr$'+tostr(i));
  2001. { always register the symbol }
  2002. ps.register_sym;
  2003. { the RTTI always references this symbol }
  2004. inc(ps.refs);
  2005. current_module.localsymtable.insertsym(ps);
  2006. pd:=cprocdef.create(normal_function_level,true);
  2007. { always register the def }
  2008. pd.register_def;
  2009. pd.procsym:=ps;
  2010. ps.ProcdefList.Add(pd);
  2011. { set procdef options }
  2012. pd.proctypeoption:=potype_function;
  2013. pd.proccalloption:=pocall_default;
  2014. include(pd.procoptions,po_hascallingconvention);
  2015. pd.returndef:=class_tcustomattribute;
  2016. insert_funcret_para(pd);
  2017. pd.calcparas;
  2018. pd.forwarddef:=false;
  2019. pd.aliasnames.insert(pd.mangledname);
  2020. handle_calling_convention(pd,hcc_default_actions_impl);
  2021. { set procinfo and current_procinfo.procdef }
  2022. pi:=tcgprocinfo(cprocinfo.create(nil));
  2023. pi.procdef:=pd;
  2024. { we always do a call, namely to the constructor }
  2025. include(pi.flags,pi_do_call);
  2026. insert_funcret_local(pd);
  2027. pi.code:=cassignmentnode.create(
  2028. cloadnode.create(pd.funcretsym,pd.localst),
  2029. attr.constructorcall.getcopy
  2030. );
  2031. pi.generate_code;
  2032. attr.constructorpd:=pd;
  2033. end;
  2034. end;
  2035. end.