symcreat.pas 55 KB

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