symcreat.pas 56 KB

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