symcreat.pas 54 KB

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