symcreat.pas 49 KB

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