symcreat.pas 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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_token: ttoken;
  29. old_c: char;
  30. old_orgpattern: string;
  31. old_modeswitches: tmodeswitches;
  32. valid: boolean;
  33. end;
  34. { save/restore the scanner state before/after injecting }
  35. procedure replace_scanner(const tempname: string; out sstate: tscannerstate);
  36. procedure restore_scanner(const sstate: tscannerstate);
  37. { parses a (class or regular) method/constructor/destructor declaration from
  38. str, as if it were declared in astruct's declaration body
  39. WARNING: save the scanner state before calling this routine, and restore
  40. when done. }
  41. function str_parse_method_dec(str: ansistring; potype: tproctypeoption; is_classdef: boolean; astruct: tabstractrecorddef; out pd: tprocdef): boolean;
  42. { parses a (class or regular) method/constructor/destructor implementation
  43. from str, as if it appeared in the current unit's implementation section
  44. WARNINGS:
  45. * save the scanner state before calling this routine, and restore when done.
  46. * the code *must* be written in objfpc style
  47. }
  48. function str_parse_method_impl(str: ansistring; usefwpd: tprocdef; is_classdef: boolean):boolean;
  49. { parses a typed constant assignment to ssym
  50. WARNINGS:
  51. * save the scanner state before calling this routine, and restore when done.
  52. * the code *must* be written in objfpc style
  53. }
  54. procedure str_parse_typedconst(list: TAsmList; str: ansistring; ssym: tstaticvarsym);
  55. { in the JVM, constructors are not automatically inherited (so you can hide
  56. them). To emulate the Pascal behaviour, we have to automatically add
  57. all parent constructors to the current class as well.}
  58. procedure add_missing_parent_constructors_intf(obj: tobjectdef; forcevis: tvisibility);
  59. { goes through all defs in st to add implementations for synthetic methods
  60. added earlier }
  61. procedure add_synthetic_method_implementations(st: tsymtable);
  62. procedure finish_copied_procdef(var pd: tprocdef; const realname: string; newparentst: tsymtable; newstruct: tabstractrecorddef);
  63. { create "parent frame pointer" record skeleton for procdef, in which local
  64. variables and parameters from pd accessed from nested routines can be
  65. stored }
  66. procedure build_parentfpstruct(pd: tprocdef);
  67. { checks whether sym (a local or para of pd) already has a counterpart in
  68. pd's parentfpstruct, and if not adds a new field to the struct with type
  69. "vardef" (can be different from sym's type in case it's a call-by-reference
  70. parameter, which is indicated by addrparam). If it already has a field in
  71. the parentfpstruct, this field is returned. }
  72. function maybe_add_sym_to_parentfpstruct(pd: tprocdef; sym: tsym; vardef: tdef; addrparam: boolean): tsym;
  73. { given a localvarsym or paravarsym of pd, returns the field of the
  74. parentfpstruct corresponding to this sym }
  75. function find_sym_in_parentfpstruct(pd: tprocdef; sym: tsym): tsym;
  76. { replaces all local and paravarsyms that have been mirrored in the
  77. parentfpstruct with aliasvarsyms that redirect to these fields (used to
  78. make sure that references to these syms in the owning procdef itself also
  79. use the ones in the parentfpstructs) }
  80. procedure redirect_parentfpstruct_local_syms(pd: tprocdef);
  81. { finalises the parentfpstruct (alignment padding, ...) }
  82. procedure finish_parentfpstruct(pd: tprocdef);
  83. procedure maybe_guarantee_record_typesym(var def: tdef; st: tsymtable);
  84. implementation
  85. uses
  86. cutils,cclasses,globals,verbose,systems,comphook,fmodule,
  87. symtable,defutil,
  88. pbase,pdecobj,pdecsub,psub,ptconst,
  89. {$ifdef jvm}
  90. pjvm,jvmdef,
  91. {$endif jvm}
  92. node,nbas,nld,nmem,
  93. defcmp,
  94. paramgr;
  95. procedure replace_scanner(const tempname: string; out sstate: tscannerstate);
  96. var
  97. old_block_type: tblock_type;
  98. begin
  99. { would require saving of idtoken, pattern etc }
  100. if (token=_ID) or
  101. (token=_CWCHAR) or
  102. (token=_CWSTRING) then
  103. internalerror(2011032201);
  104. sstate.old_scanner:=current_scanner;
  105. sstate.old_token:=token;
  106. sstate.old_c:=c;
  107. sstate.old_orgpattern:=orgpattern;
  108. sstate.old_modeswitches:=current_settings.modeswitches;
  109. sstate.valid:=true;
  110. { creating a new scanner resets the block type, while we want to continue
  111. in the current one }
  112. old_block_type:=block_type;
  113. current_scanner:=tscannerfile.Create('_Macro_.'+tempname);
  114. block_type:=old_block_type;
  115. { required for e.g. FpcDeepCopy record method (uses "out" parameter; field
  116. names are escaped via &, so should not cause conflicts }
  117. current_settings.modeswitches:=objfpcmodeswitches;
  118. end;
  119. procedure restore_scanner(const sstate: tscannerstate);
  120. begin
  121. if sstate.valid then
  122. begin
  123. current_scanner.free;
  124. current_scanner:=sstate.old_scanner;
  125. token:=sstate.old_token;
  126. current_settings.modeswitches:=sstate.old_modeswitches;
  127. c:=sstate.old_c;
  128. orgpattern:=sstate.old_orgpattern;
  129. pattern:=upper(sstate.old_orgpattern);
  130. end;
  131. end;
  132. function str_parse_method_dec(str: ansistring; potype: tproctypeoption; is_classdef: boolean; astruct: tabstractrecorddef; out pd: tprocdef): boolean;
  133. var
  134. oldparse_only: boolean;
  135. begin
  136. Message1(parser_d_internal_parser_string,str);
  137. oldparse_only:=parse_only;
  138. parse_only:=true;
  139. result:=false;
  140. { inject the string in the scanner }
  141. str:=str+'end;';
  142. current_scanner.substitutemacro('meth_head_macro',@str[1],length(str),current_scanner.line_no,current_scanner.inputfile.ref_index);
  143. current_scanner.readtoken(false);
  144. { and parse it... }
  145. case potype of
  146. potype_class_constructor:
  147. pd:=class_constructor_head(astruct);
  148. potype_class_destructor:
  149. pd:=class_destructor_head(astruct);
  150. potype_constructor:
  151. pd:=constructor_head;
  152. potype_destructor:
  153. pd:=destructor_head;
  154. else
  155. pd:=method_dec(astruct,is_classdef);
  156. end;
  157. if assigned(pd) then
  158. result:=true;
  159. parse_only:=oldparse_only;
  160. end;
  161. function str_parse_method_impl(str: ansistring; usefwpd: tprocdef; is_classdef: boolean):boolean;
  162. var
  163. oldparse_only: boolean;
  164. tmpstr: ansistring;
  165. begin
  166. if ((status.verbosity and v_debug)<>0) then
  167. begin
  168. if assigned(usefwpd) then
  169. Message1(parser_d_internal_parser_string,usefwpd.customprocname([pno_proctypeoption,pno_paranames,pno_noclassmarker,pno_noleadingdollar])+str)
  170. else
  171. begin
  172. if is_classdef then
  173. tmpstr:='class '
  174. else
  175. tmpstr:='';
  176. Message1(parser_d_internal_parser_string,tmpstr+str);
  177. end;
  178. end;
  179. oldparse_only:=parse_only;
  180. parse_only:=false;
  181. result:=false;
  182. { inject the string in the scanner }
  183. str:=str+'end;';
  184. current_scanner.substitutemacro('meth_impl_macro',@str[1],length(str),current_scanner.line_no,current_scanner.inputfile.ref_index);
  185. current_scanner.readtoken(false);
  186. { and parse it... }
  187. read_proc(is_classdef,usefwpd);
  188. parse_only:=oldparse_only;
  189. result:=true;
  190. end;
  191. procedure str_parse_typedconst(list: TAsmList; str: ansistring; ssym: tstaticvarsym);
  192. var
  193. old_block_type: tblock_type;
  194. old_parse_only: boolean;
  195. begin
  196. Message1(parser_d_internal_parser_string,str);
  197. { a string that will be interpreted as the start of a new section ->
  198. typed constant parsing will stop }
  199. str:=str+'type ';
  200. old_parse_only:=parse_only;
  201. old_block_type:=block_type;
  202. parse_only:=true;
  203. block_type:=bt_const;
  204. current_scanner.substitutemacro('typed_const_macro',@str[1],length(str),current_scanner.line_no,current_scanner.inputfile.ref_index);
  205. current_scanner.readtoken(false);
  206. read_typed_const(list,ssym,ssym.owner.symtabletype in [recordsymtable,objectsymtable]);
  207. parse_only:=old_parse_only;
  208. block_type:=old_block_type;
  209. end;
  210. procedure add_missing_parent_constructors_intf(obj: tobjectdef; forcevis: tvisibility);
  211. var
  212. parent: tobjectdef;
  213. def: tdef;
  214. parentpd,
  215. childpd: tprocdef;
  216. i: longint;
  217. srsym: tsym;
  218. srsymtable: tsymtable;
  219. begin
  220. if (oo_is_external in obj.objectoptions) or
  221. not assigned(obj.childof) then
  222. exit;
  223. parent:=obj.childof;
  224. { find all constructor in the parent }
  225. for i:=0 to tobjectsymtable(parent.symtable).deflist.count-1 do
  226. begin
  227. def:=tdef(tobjectsymtable(parent.symtable).deflist[i]);
  228. if (def.typ<>procdef) or
  229. (tprocdef(def).proctypeoption<>potype_constructor) or
  230. not is_visible_for_object(tprocdef(def),obj) then
  231. continue;
  232. parentpd:=tprocdef(def);
  233. { do we have this constructor too? (don't use
  234. search_struct_member/searchsym_in_class, since those will
  235. search parents too) }
  236. if searchsym_in_record(obj,parentpd.procsym.name,srsym,srsymtable) then
  237. begin
  238. { there's a symbol with the same name, is it a constructor
  239. with the same parameters? }
  240. if srsym.typ=procsym then
  241. begin
  242. childpd:=tprocsym(srsym).find_procdef_bytype_and_para(
  243. potype_constructor,parentpd.paras,nil,
  244. [cpo_ignorehidden,cpo_ignoreuniv,cpo_openequalisexact]);
  245. if assigned(childpd) then
  246. continue;
  247. end;
  248. end;
  249. { if we get here, we did not find it in the current objectdef ->
  250. add }
  251. childpd:=tprocdef(parentpd.getcopy);
  252. if forcevis<>vis_none then
  253. childpd.visibility:=forcevis;
  254. if po_virtualmethod in childpd.procoptions then
  255. include(childpd.procoptions,po_overridingmethod);
  256. finish_copied_procdef(childpd,parentpd.procsym.realname,obj.symtable,obj);
  257. exclude(childpd.procoptions,po_external);
  258. include(childpd.procoptions,po_overload);
  259. childpd.synthetickind:=tsk_anon_inherited;
  260. include(obj.objectoptions,oo_has_constructor);
  261. end;
  262. end;
  263. procedure implement_anon_inherited(pd: tprocdef);
  264. var
  265. str: ansistring;
  266. isclassmethod: boolean;
  267. begin
  268. isclassmethod:=
  269. (po_classmethod in pd.procoptions) and
  270. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  271. str:='begin inherited end;';
  272. str_parse_method_impl(str,pd,isclassmethod);
  273. end;
  274. procedure implement_jvm_clone(pd: tprocdef);
  275. var
  276. struct: tabstractrecorddef;
  277. str: ansistring;
  278. i: longint;
  279. sym: tsym;
  280. fsym: tfieldvarsym;
  281. begin
  282. if not(pd.struct.typ in [recorddef,objectdef]) then
  283. internalerror(2011032802);
  284. struct:=pd.struct;
  285. { anonymous record types must get an artificial name, so we can generate
  286. a typecast at the scanner level }
  287. if (struct.typ=recorddef) and
  288. not assigned(struct.typesym) then
  289. internalerror(2011032812);
  290. { the inherited clone will already copy all fields in a shallow way ->
  291. copy records/regular arrays in a regular way }
  292. str:='type _fpc_ptrt = ^'+struct.typesym.realname+'; begin clone:=inherited;';
  293. for i:=0 to struct.symtable.symlist.count-1 do
  294. begin
  295. sym:=tsym(struct.symtable.symlist[i]);
  296. if (sym.typ=fieldvarsym) then
  297. begin
  298. fsym:=tfieldvarsym(sym);
  299. if (fsym.vardef.typ=recorddef) or
  300. ((fsym.vardef.typ=arraydef) and
  301. not is_dynamic_array(fsym.vardef)) or
  302. ((fsym.vardef.typ=setdef) and
  303. not is_smallset(fsym.vardef)) then
  304. str:=str+'_fpc_ptrt(clone)^.&'+fsym.realname+':='+fsym.realname+';';
  305. end;
  306. end;
  307. str:=str+'end;';
  308. str_parse_method_impl(str,pd,false);
  309. end;
  310. procedure implement_record_deepcopy(pd: tprocdef);
  311. var
  312. struct: tabstractrecorddef;
  313. str: ansistring;
  314. i: longint;
  315. sym: tsym;
  316. fsym: tfieldvarsym;
  317. begin
  318. if not(pd.struct.typ in [recorddef,objectdef]) then
  319. internalerror(2011032810);
  320. struct:=pd.struct;
  321. { anonymous record types must get an artificial name, so we can generate
  322. a typecast at the scanner level }
  323. if (struct.typ=recorddef) and
  324. not assigned(struct.typesym) then
  325. internalerror(2011032811);
  326. { copy all fields }
  327. str:='begin ';
  328. for i:=0 to struct.symtable.symlist.count-1 do
  329. begin
  330. sym:=tsym(struct.symtable.symlist[i]);
  331. if (sym.typ=fieldvarsym) then
  332. begin
  333. fsym:=tfieldvarsym(sym);
  334. str:=str+'result.&'+fsym.realname+':=&'+fsym.realname+';';
  335. end;
  336. end;
  337. str:=str+'end;';
  338. str_parse_method_impl(str,pd,false);
  339. end;
  340. procedure implement_record_initialize(pd: tprocdef);
  341. var
  342. struct: tabstractrecorddef;
  343. str: ansistring;
  344. i: longint;
  345. sym: tsym;
  346. fsym: tfieldvarsym;
  347. begin
  348. if not(pd.struct.typ in [recorddef,objectdef]) then
  349. internalerror(2011071710);
  350. struct:=pd.struct;
  351. { anonymous record types must get an artificial name, so we can generate
  352. a typecast at the scanner level }
  353. if (struct.typ=recorddef) and
  354. not assigned(struct.typesym) then
  355. internalerror(2011032811);
  356. { walk over all fields that need initialization }
  357. str:='begin ';
  358. for i:=0 to struct.symtable.symlist.count-1 do
  359. begin
  360. sym:=tsym(struct.symtable.symlist[i]);
  361. if (sym.typ=fieldvarsym) then
  362. begin
  363. fsym:=tfieldvarsym(sym);
  364. if fsym.vardef.needs_inittable then
  365. str:=str+'system.initialize(&'+fsym.realname+');';
  366. end;
  367. end;
  368. str:=str+'end;';
  369. str_parse_method_impl(str,pd,false);
  370. end;
  371. procedure implement_empty(pd: tprocdef);
  372. var
  373. str: ansistring;
  374. isclassmethod: boolean;
  375. begin
  376. isclassmethod:=
  377. (po_classmethod in pd.procoptions) and
  378. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  379. str:='begin end;';
  380. str_parse_method_impl(str,pd,isclassmethod);
  381. end;
  382. procedure addvisibibleparameters(var str: ansistring; pd: tprocdef);
  383. var
  384. currpara: tparavarsym;
  385. i: longint;
  386. firstpara: boolean;
  387. begin
  388. firstpara:=true;
  389. for i:=0 to pd.paras.count-1 do
  390. begin
  391. currpara:=tparavarsym(pd.paras[i]);
  392. if not(vo_is_hidden_para in currpara.varoptions) then
  393. begin
  394. if not firstpara then
  395. str:=str+',';
  396. firstpara:=false;
  397. str:=str+currpara.realname;
  398. end;
  399. end;
  400. end;
  401. procedure implement_callthrough(pd: tprocdef);
  402. var
  403. str: ansistring;
  404. callpd: tprocdef;
  405. isclassmethod: boolean;
  406. begin
  407. isclassmethod:=
  408. (po_classmethod in pd.procoptions) and
  409. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  410. callpd:=tprocdef(pd.skpara);
  411. str:='begin ';
  412. if pd.returndef<>voidtype then
  413. str:=str+'result:=';
  414. str:=str+callpd.procsym.realname+'(';
  415. addvisibibleparameters(str,pd);
  416. str:=str+') end;';
  417. str_parse_method_impl(str,pd,isclassmethod);
  418. end;
  419. {$ifdef jvm}
  420. procedure implement_jvm_enum_values(pd: tprocdef);
  421. begin
  422. str_parse_method_impl('begin result:=__fpc_FVALUES end;',pd,true);
  423. end;
  424. procedure implement_jvm_enum_valuof(pd: tprocdef);
  425. begin
  426. str_parse_method_impl('begin result:=__FPC_TEnumClassAlias(inherited valueOf(JLClass(__FPC_TEnumClassAlias),__fpc_str)) end;',pd,true);
  427. end;
  428. procedure implement_jvm_enum_jumps_constr(pd: tprocdef);
  429. begin
  430. str_parse_method_impl('begin inherited create(__fpc_name,__fpc_ord); __fpc_fenumval:=__fpc_initenumval end;',pd,false);
  431. end;
  432. procedure implement_jvm_enum_fpcordinal(pd: tprocdef);
  433. var
  434. enumclass: tobjectdef;
  435. enumdef: tenumdef;
  436. begin
  437. enumclass:=tobjectdef(pd.owner.defowner);
  438. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  439. if not enumdef.has_jumps then
  440. str_parse_method_impl('begin result:=ordinal end;',pd,false)
  441. else
  442. str_parse_method_impl('begin result:=__fpc_fenumval end;',pd,false);
  443. end;
  444. procedure implement_jvm_enum_fpcvalueof(pd: tprocdef);
  445. var
  446. enumclass: tobjectdef;
  447. enumdef: tenumdef;
  448. isclassmethod: boolean;
  449. begin
  450. isclassmethod:=
  451. (po_classmethod in pd.procoptions) and
  452. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  453. enumclass:=tobjectdef(pd.owner.defowner);
  454. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  455. { convert integer to corresponding enum instance: in case of no jumps
  456. get it from the $VALUES array, otherwise from the __fpc_ord2enum
  457. hashmap }
  458. if not enumdef.has_jumps then
  459. str_parse_method_impl('begin result:=__fpc_FVALUES[__fpc_int] end;',pd,isclassmethod)
  460. else
  461. str_parse_method_impl('begin result:=__FPC_TEnumClassAlias(__fpc_ord2enum.get(JLInteger.valueOf(__fpc_int))) end;',pd,isclassmethod);
  462. end;
  463. function CompareEnumSyms(Item1, Item2: Pointer): Integer;
  464. var
  465. I1 : tenumsym absolute Item1;
  466. I2 : tenumsym absolute Item2;
  467. begin
  468. Result:=I1.value-I2.value;
  469. end;
  470. procedure implement_jvm_enum_classconstr(pd: tprocdef);
  471. var
  472. enumclass: tobjectdef;
  473. enumdef: tenumdef;
  474. str: ansistring;
  475. i: longint;
  476. enumsym: tenumsym;
  477. classfield: tstaticvarsym;
  478. orderedenums: tfpobjectlist;
  479. begin
  480. enumclass:=tobjectdef(pd.owner.defowner);
  481. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  482. if not assigned(enumdef) then
  483. internalerror(2011062305);
  484. str:='begin ';
  485. if enumdef.has_jumps then
  486. { init hashmap for ordinal -> enum instance mapping; don't let it grow,
  487. and set the capacity to the next prime following the total number of
  488. enum elements to minimise the number of collisions }
  489. str:=str+'__fpc_ord2enum:=JUHashMap.Create('+tostr(next_prime(enumdef.symtable.symlist.count))+',1.0);';
  490. { iterate over all enum elements and initialise the class fields, and
  491. store them in the values array. Since the java.lang.Enum doCompare
  492. method is final and hardcoded to compare based on declaration order
  493. (= java.lang.Enum.ordinal() value), we have to create them in order of
  494. ascending FPC ordinal values (which may not be the same as the FPC
  495. declaration order in case of jumps }
  496. orderedenums:=tfpobjectlist.create(false);
  497. for i:=0 to enumdef.symtable.symlist.count-1 do
  498. orderedenums.add(enumdef.symtable.symlist[i]);
  499. if enumdef.has_jumps then
  500. orderedenums.sort(@CompareEnumSyms);
  501. for i:=0 to orderedenums.count-1 do
  502. begin
  503. enumsym:=tenumsym(orderedenums[i]);
  504. classfield:=tstaticvarsym(search_struct_member(enumclass,enumsym.name));
  505. if not assigned(classfield) then
  506. internalerror(2011062306);
  507. str:=str+classfield.name+':=__FPC_TEnumClassAlias.Create('''+enumsym.realname+''','+tostr(i);
  508. if enumdef.has_jumps then
  509. str:=str+','+tostr(enumsym.value);
  510. str:=str+');';
  511. { alias for $VALUES array used internally by the JDK, and also by FPC
  512. in case of no jumps }
  513. str:=str+'__fpc_FVALUES['+tostr(i)+']:='+classfield.name+';';
  514. if enumdef.has_jumps then
  515. str:=str+'__fpc_ord2enum.put(JLInteger.valueOf('+tostr(enumsym.value)+'),'+classfield.name+');';
  516. end;
  517. orderedenums.free;
  518. str:=str+' end;';
  519. str_parse_method_impl(str,pd,true);
  520. end;
  521. procedure implement_jvm_enum_long2set(pd: tprocdef);
  522. begin
  523. str_parse_method_impl(
  524. 'var '+
  525. 'i, setval: jint;'+
  526. 'begin '+
  527. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  528. 'if __val<>0 then '+
  529. 'begin '+
  530. '__setsize:=__setsize*8;'+
  531. 'for i:=0 to __setsize-1 do '+
  532. // setsize-i because JVM = big endian
  533. 'if (__val and (jlong(1) shl (__setsize-i)))<>0 then '+
  534. 'result.add(fpcValueOf(i+__setbase));'+
  535. 'end '+
  536. 'end;',
  537. pd,true);
  538. end;
  539. procedure implement_jvm_enum_bitset2set(pd: tprocdef);
  540. begin
  541. str_parse_method_impl(
  542. 'var '+
  543. 'i, setval: jint;'+
  544. 'begin '+
  545. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  546. 'i:=__val.nextSetBit(0);'+
  547. 'while i>=0 do '+
  548. 'begin '+
  549. 'setval:=-__fromsetbase;'+
  550. 'result.add(fpcValueOf(setval+__tosetbase));'+
  551. 'i:=__val.nextSetBit(i+1);'+
  552. 'end '+
  553. 'end;',
  554. pd,true);
  555. end;
  556. procedure implement_jvm_enum_set2set(pd: tprocdef);
  557. begin
  558. str_parse_method_impl(
  559. 'var '+
  560. 'it: JUIterator;'+
  561. 'ele: FpcEnumValueObtainable;'+
  562. 'i: longint;'+
  563. 'begin '+
  564. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  565. 'it:=__val.iterator;'+
  566. 'while it.hasNext do '+
  567. 'begin '+
  568. 'ele:=FpcEnumValueObtainable(it.next);'+
  569. 'i:=ele.fpcOrdinal-__fromsetbase;'+
  570. 'result.add(fpcValueOf(i+__tosetbase));'+
  571. 'end '+
  572. 'end;',
  573. pd,true);
  574. end;
  575. procedure implement_jvm_procvar_invoke(pd: tprocdef);
  576. var
  577. pvclass: tobjectdef;
  578. procvar: tprocvardef;
  579. paraname,str,endstr: ansistring;
  580. pvs: tparavarsym;
  581. paradef,boxdef,boxargdef: tdef;
  582. i: longint;
  583. firstpara: boolean;
  584. begin
  585. pvclass:=tobjectdef(pd.owner.defowner);
  586. procvar:=tprocvardef(ttypesym(search_struct_member(pvclass,'__FPC_PROCVARALIAS')).typedef);
  587. { the procvar wrapper class has a tmethod member called "method", whose
  588. "code" field is a JLRMethod, and whose "data" field is the self pointer
  589. if any (if none is required, it's ignored by the JVM, so there's no
  590. problem with always passing it) }
  591. { force extended syntax to allow calling invokeObjectFunc() without using
  592. its result }
  593. str:='';
  594. endstr:='';
  595. { create local pointer to result type for typecasting in case of an
  596. implicit pointer type }
  597. if jvmimplicitpointertype(procvar.returndef) then
  598. str:=str+'type __FPC_returnptrtype = ^'+procvar.returndef.typename+';';
  599. str:=str+'begin ';
  600. { result handling }
  601. if not is_void(procvar.returndef) then
  602. begin
  603. str:=str+'invoke:=';
  604. if procvar.returndef.typ in [orddef,floatdef] then
  605. begin
  606. { primitivetype(boxtype(..).unboxmethod) }
  607. jvmgetboxtype(procvar.returndef,boxdef,boxargdef,false);
  608. str:=str+procvar.returndef.typename+'('+boxdef.typename+'(';
  609. endstr:=').'+jvmgetunboxmethod(procvar.returndef)+')';
  610. end
  611. else if jvmimplicitpointertype(procvar.returndef) then
  612. begin
  613. str:=str+'__FPC_returnptrtype(';
  614. { dereference }
  615. endstr:=')^';
  616. end
  617. else
  618. begin
  619. str:=str+procvar.returndef.typename+'(';
  620. endstr:=')';
  621. end;
  622. end;
  623. str:=str+'invokeObjectFunc([';
  624. { parameters are a constant array of jlobject }
  625. firstpara:=true;
  626. for i:=0 to procvar.paras.count-1 do
  627. begin
  628. { skip self/vmt/parentfp, passed separately }
  629. pvs:=tparavarsym(procvar.paras[i]);
  630. if ([vo_is_self,vo_is_vmt,vo_is_parentfp]*pvs.varoptions)<>[] then
  631. continue;
  632. if not firstpara then
  633. str:=str+',';
  634. firstpara:=false;
  635. paraname:=pvs.realname;
  636. paradef:=pvs.vardef;
  637. { Pascalize hidden high parameter }
  638. if vo_is_high_para in pvs.varoptions then
  639. paraname:='high('+tparavarsym(procvar.paras[i-1]).realname+')'
  640. else if vo_is_hidden_para in pvs.varoptions then
  641. begin
  642. if ([vo_is_range_check,vo_is_overflow_check]*pvs.varoptions)<>[] then
  643. { ok, simple boolean parameters }
  644. else
  645. internalerror(2011072403);
  646. end;
  647. { var/out/constref parameters -> pass address through (same for
  648. implicit pointer types) }
  649. if paramanager.push_addr_param(pvs.varspez,paradef,procvar.proccalloption) or
  650. jvmimplicitpointertype(paradef) then
  651. begin
  652. paraname:='@'+paraname;
  653. paradef:=java_jlobject;
  654. end;
  655. if paradef.typ in [orddef,floatdef] then
  656. begin
  657. { box primitive types; use valueOf() rather than create because it
  658. can give better performance }
  659. jvmgetboxtype(paradef,boxdef,boxargdef,false);
  660. str:=str+boxdef.typename+'.valueOf('+boxargdef.typename+'('+paraname+'))'
  661. end
  662. else
  663. str:=str+'JLObject('+paraname+')';
  664. end;
  665. str:=str+'])'+endstr+' end;';
  666. str_parse_method_impl(str,pd,false)
  667. end;
  668. procedure implement_jvm_virtual_clmethod(pd: tprocdef);
  669. var
  670. str: ansistring;
  671. callpd: tprocdef;
  672. begin
  673. callpd:=tprocdef(pd.skpara);
  674. str:='var pv: __fpc_virtualclassmethod_pv_t'+tostr(pd.defid)+'; begin '
  675. + 'pv:=@'+callpd.procsym.RealName+';';
  676. if (pd.proctypeoption<>potype_constructor) and
  677. not is_void(pd.returndef) then
  678. str:=str+'result:=';
  679. str:=str+'pv(';
  680. addvisibibleparameters(str,pd);
  681. str:=str+') end;';
  682. str_parse_method_impl(str,pd,true)
  683. end;
  684. {$endif jvm}
  685. procedure add_synthetic_method_implementations_for_struct(struct: tabstractrecorddef);
  686. var
  687. i : longint;
  688. def : tdef;
  689. pd : tprocdef;
  690. begin
  691. for i:=0 to struct.symtable.deflist.count-1 do
  692. begin
  693. def:=tdef(struct.symtable.deflist[i]);
  694. if (def.typ<>procdef) then
  695. continue;
  696. pd:=tprocdef(def);
  697. case pd.synthetickind of
  698. tsk_none:
  699. ;
  700. tsk_anon_inherited:
  701. implement_anon_inherited(pd);
  702. tsk_jvm_clone:
  703. implement_jvm_clone(pd);
  704. tsk_record_deepcopy:
  705. implement_record_deepcopy(pd);
  706. tsk_record_initialize:
  707. implement_record_initialize(pd);
  708. tsk_empty,
  709. { special handling for this one is done in tnodeutils.wrap_proc_body }
  710. tsk_tcinit:
  711. implement_empty(pd);
  712. tsk_callthrough:
  713. implement_callthrough(pd);
  714. {$ifdef jvm}
  715. tsk_jvm_enum_values:
  716. implement_jvm_enum_values(pd);
  717. tsk_jvm_enum_valueof:
  718. implement_jvm_enum_valuof(pd);
  719. tsk_jvm_enum_classconstr:
  720. implement_jvm_enum_classconstr(pd);
  721. tsk_jvm_enum_jumps_constr:
  722. implement_jvm_enum_jumps_constr(pd);
  723. tsk_jvm_enum_fpcordinal:
  724. implement_jvm_enum_fpcordinal(pd);
  725. tsk_jvm_enum_fpcvalueof:
  726. implement_jvm_enum_fpcvalueof(pd);
  727. tsk_jvm_enum_long2set:
  728. implement_jvm_enum_long2set(pd);
  729. tsk_jvm_enum_bitset2set:
  730. implement_jvm_enum_bitset2set(pd);
  731. tsk_jvm_enum_set2set:
  732. implement_jvm_enum_set2set(pd);
  733. tsk_jvm_procvar_invoke:
  734. implement_jvm_procvar_invoke(pd);
  735. tsk_jvm_virtual_clmethod:
  736. implement_jvm_virtual_clmethod(pd);
  737. {$endif jvm}
  738. else
  739. internalerror(2011032801);
  740. end;
  741. end;
  742. end;
  743. procedure add_synthetic_method_implementations(st: tsymtable);
  744. var
  745. i: longint;
  746. def: tdef;
  747. sstate: tscannerstate;
  748. begin
  749. { only necessary for the JVM target currently }
  750. if not (target_info.system in [system_jvm_java32]) then
  751. exit;
  752. sstate.valid:=false;
  753. for i:=0 to st.deflist.count-1 do
  754. begin
  755. def:=tdef(st.deflist[i]);
  756. if (def.typ=procdef) and
  757. assigned(tprocdef(def).localst) and
  758. { not true for the "main" procedure, whose localsymtable is the staticsymtable }
  759. (tprocdef(def).localst.symtabletype=localsymtable) then
  760. add_synthetic_method_implementations(tprocdef(def).localst)
  761. else if (is_javaclass(def) and
  762. not(oo_is_external in tobjectdef(def).objectoptions)) or
  763. (def.typ=recorddef) then
  764. begin
  765. if not sstate.valid then
  766. replace_scanner('synthetic_impl',sstate);
  767. add_synthetic_method_implementations_for_struct(tabstractrecorddef(def));
  768. { also complete nested types }
  769. add_synthetic_method_implementations(tabstractrecorddef(def).symtable);
  770. end;
  771. end;
  772. restore_scanner(sstate);
  773. end;
  774. procedure finish_copied_procdef(var pd: tprocdef; const realname: string; newparentst: tsymtable; newstruct: tabstractrecorddef);
  775. var
  776. sym: tsym;
  777. parasym: tparavarsym;
  778. ps: tprocsym;
  779. stname: string;
  780. i: longint;
  781. begin
  782. { associate the procdef with a procsym in the owner }
  783. if not(pd.proctypeoption in [potype_class_constructor,potype_class_destructor]) then
  784. stname:=upper(realname)
  785. else
  786. stname:=lower(realname);
  787. sym:=tsym(newparentst.find(stname));
  788. if assigned(sym) then
  789. begin
  790. if sym.typ<>procsym then
  791. internalerror(2011040601);
  792. ps:=tprocsym(sym);
  793. end
  794. else
  795. begin
  796. ps:=tprocsym.create(realname);
  797. newparentst.insert(ps);
  798. end;
  799. pd.procsym:=ps;
  800. pd.struct:=newstruct;
  801. { in case of methods, replace the special parameter types with new ones }
  802. if assigned(newstruct) then
  803. begin
  804. symtablestack.push(pd.parast);
  805. { may not be assigned in case we converted a procvar into a procdef }
  806. if assigned(pd.paras) then
  807. begin
  808. for i:=0 to pd.paras.count-1 do
  809. begin
  810. parasym:=tparavarsym(pd.paras[i]);
  811. if vo_is_self in parasym.varoptions then
  812. begin
  813. if parasym.vardef.typ=classrefdef then
  814. parasym.vardef:=tclassrefdef.create(newstruct)
  815. else
  816. parasym.vardef:=newstruct;
  817. end
  818. end;
  819. end;
  820. { also fix returndef in case of a constructor }
  821. if pd.proctypeoption=potype_constructor then
  822. pd.returndef:=newstruct;
  823. symtablestack.pop(pd.parast);
  824. end;
  825. pd.calcparas;
  826. proc_add_definition(pd);
  827. end;
  828. procedure build_parentfpstruct(pd: tprocdef);
  829. var
  830. nestedvars: tsym;
  831. nestedvarsst: tsymtable;
  832. pnestedvarsdef,
  833. nestedvarsdef: tdef;
  834. old_symtablestack: tsymtablestack;
  835. begin
  836. { make sure the defs are not registered in the current symtablestack,
  837. because they may be for a parent procdef (changeowner does remove a def
  838. from the symtable in which it was originally created, so that by itself
  839. is not enough) }
  840. old_symtablestack:=symtablestack;
  841. symtablestack:=old_symtablestack.getcopyuntil(current_module.localsymtable);
  842. { create struct to hold local variables and parameters that are
  843. accessed from within nested routines (start with extra dollar to prevent
  844. the JVM from thinking this is a nested class in the unit) }
  845. nestedvarsst:=trecordsymtable.create('$'+current_module.realmodulename^+'$$_fpc_nestedvars$'+tostr(pd.defid),current_settings.alignment.localalignmax);
  846. nestedvarsdef:=trecorddef.create(nestedvarsst.name^,nestedvarsst);
  847. {$ifdef jvm}
  848. maybe_guarantee_record_typesym(nestedvarsdef,nestedvarsdef.owner);
  849. { don't add clone/FpcDeepCopy, because the field names are not all
  850. representable in source form and we don't need them anyway }
  851. symtablestack.push(trecorddef(nestedvarsdef).symtable);
  852. maybe_add_public_default_java_constructor(trecorddef(nestedvarsdef));
  853. symtablestack.pop(trecorddef(nestedvarsdef).symtable);
  854. {$endif}
  855. symtablestack.free;
  856. symtablestack:=old_symtablestack.getcopyuntil(pd.localst);
  857. pnestedvarsdef:=getpointerdef(nestedvarsdef);
  858. nestedvars:=tlocalvarsym.create('$nestedvars',vs_var,nestedvarsdef,[]);
  859. pd.localst.insert(nestedvars);
  860. pd.parentfpstruct:=nestedvars;
  861. pd.parentfpstructptrtype:=pnestedvarsdef;
  862. pd.parentfpinitblock:=cblocknode.create(nil);
  863. symtablestack.free;
  864. symtablestack:=old_symtablestack;
  865. end;
  866. function maybe_add_sym_to_parentfpstruct(pd: tprocdef; sym: tsym; vardef: tdef; addrparam: boolean): tsym;
  867. var
  868. fieldvardef,
  869. nestedvarsdef: tdef;
  870. nestedvarsst: tsymtable;
  871. initcode: tnode;
  872. old_filepos: tfileposinfo;
  873. begin
  874. nestedvarsdef:=tlocalvarsym(pd.parentfpstruct).vardef;
  875. result:=search_struct_member(trecorddef(nestedvarsdef),sym.name);
  876. if not assigned(result) then
  877. begin
  878. { mark that this symbol is mirrored in the parentfpstruct }
  879. tabstractnormalvarsym(sym).inparentfpstruct:=true;
  880. { add field to the struct holding all locals accessed
  881. by nested routines }
  882. nestedvarsst:=trecorddef(nestedvarsdef).symtable;
  883. { indicate whether or not this is a var/out/constref/... parameter }
  884. if addrparam then
  885. fieldvardef:=getpointerdef(vardef)
  886. else
  887. fieldvardef:=vardef;
  888. result:=tfieldvarsym.create(sym.realname,vs_value,fieldvardef,[]);
  889. if nestedvarsst.symlist.count=0 then
  890. include(tfieldvarsym(result).varoptions,vo_is_first_field);
  891. nestedvarsst.insert(result);
  892. trecordsymtable(nestedvarsst).addfield(tfieldvarsym(result),vis_public);
  893. { add initialization with original value if it's a parameter }
  894. if (sym.typ=paravarsym) then
  895. begin
  896. old_filepos:=current_filepos;
  897. fillchar(current_filepos,sizeof(current_filepos),0);
  898. initcode:=cloadnode.create(sym,sym.owner);
  899. { indicate that this load should not be transformed into a load
  900. from the parentfpstruct, but instead should load the original
  901. value }
  902. include(initcode.flags,nf_internal);
  903. { in case it's a var/out/constref parameter, store the address of the
  904. parameter in the struct }
  905. if addrparam then
  906. begin
  907. initcode:=caddrnode.create_internal(initcode);
  908. include(initcode.flags,nf_typedaddr);
  909. end;
  910. initcode:=cassignmentnode.create(
  911. csubscriptnode.create(result,cloadnode.create(pd.parentfpstruct,pd.parentfpstruct.owner)),
  912. initcode);
  913. tblocknode(pd.parentfpinitblock).left:=cstatementnode.create
  914. (initcode,tblocknode(pd.parentfpinitblock).left);
  915. current_filepos:=old_filepos;
  916. end;
  917. end;
  918. end;
  919. procedure redirect_parentfpstruct_local_syms(pd: tprocdef);
  920. var
  921. nestedvarsdef: trecorddef;
  922. sl: tpropaccesslist;
  923. fsym,
  924. lsym,
  925. aliassym: tsym;
  926. i: longint;
  927. begin
  928. nestedvarsdef:=trecorddef(tlocalvarsym(pd.parentfpstruct).vardef);
  929. for i:=0 to nestedvarsdef.symtable.symlist.count-1 do
  930. begin
  931. fsym:=tsym(nestedvarsdef.symtable.symlist[i]);
  932. if fsym.typ<>fieldvarsym then
  933. continue;
  934. lsym:=tsym(pd.localst.find(fsym.name));
  935. if not assigned(lsym) then
  936. lsym:=tsym(pd.parast.find(fsym.name));
  937. if not assigned(lsym) then
  938. internalerror(2011060408);
  939. { add an absolute variable that redirects to the field }
  940. sl:=tpropaccesslist.create;
  941. sl.addsym(sl_load,pd.parentfpstruct);
  942. sl.addsym(sl_subscript,tfieldvarsym(fsym));
  943. aliassym:=tabsolutevarsym.create_ref(lsym.name,tfieldvarsym(fsym).vardef,sl);
  944. { hide the original variable (can't delete, because there
  945. may be other loadnodes that reference it)
  946. -- only for locals; hiding parameters changes the
  947. function signature }
  948. if lsym.typ<>paravarsym then
  949. hidesym(lsym);
  950. { insert the absolute variable in the localst of the
  951. routine; ignore duplicates, because this will also check the
  952. parasymtable and we want to override parameters with our local
  953. versions }
  954. pd.localst.insert(aliassym,false);
  955. end;
  956. end;
  957. function find_sym_in_parentfpstruct(pd: tprocdef; sym: tsym): tsym;
  958. var
  959. nestedvarsdef: tdef;
  960. begin
  961. nestedvarsdef:=tlocalvarsym(pd.parentfpstruct).vardef;
  962. result:=search_struct_member(trecorddef(nestedvarsdef),sym.name);
  963. end;
  964. procedure finish_parentfpstruct(pd: tprocdef);
  965. begin
  966. trecordsymtable(trecorddef(tlocalvarsym(pd.parentfpstruct).vardef).symtable).addalignmentpadding;
  967. end;
  968. procedure maybe_guarantee_record_typesym(var def: tdef; st: tsymtable);
  969. var
  970. ts: ttypesym;
  971. begin
  972. { create a dummy typesym for the JVM target, because the record
  973. has to be wrapped by a class }
  974. if (target_info.system=system_jvm_java32) and
  975. (def.typ=recorddef) and
  976. not assigned(def.typesym) then
  977. begin
  978. ts:=ttypesym.create(trecorddef(def).symtable.realname^,def);
  979. st.insert(ts);
  980. ts.visibility:=vis_strictprivate;
  981. { this typesym can't be used by any Pascal code, so make sure we don't
  982. print a hint about it being unused }
  983. addsymref(ts);
  984. end;
  985. end;
  986. end.