symcreat.pas 77 KB

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