symcreat.pas 76 KB

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