symcreat.pas 59 KB

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