symcreat.pas 52 KB

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