symcreat.pas 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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 ';
  272. if (pd.proctypeoption<>potype_constructor) and
  273. not is_void(pd.returndef) then
  274. str:=str+'result:=';
  275. str:=str+'inherited end;';
  276. str_parse_method_impl(str,pd,isclassmethod);
  277. end;
  278. procedure implement_jvm_clone(pd: tprocdef);
  279. var
  280. struct: tabstractrecorddef;
  281. str: ansistring;
  282. i: longint;
  283. sym: tsym;
  284. fsym: tfieldvarsym;
  285. begin
  286. if not(pd.struct.typ in [recorddef,objectdef]) then
  287. internalerror(2011032802);
  288. struct:=pd.struct;
  289. { anonymous record types must get an artificial name, so we can generate
  290. a typecast at the scanner level }
  291. if (struct.typ=recorddef) and
  292. not assigned(struct.typesym) then
  293. internalerror(2011032812);
  294. { the inherited clone will already copy all fields in a shallow way ->
  295. copy records/regular arrays in a regular way }
  296. str:='type _fpc_ptrt = ^'+struct.typesym.realname+'; begin clone:=inherited;';
  297. for i:=0 to struct.symtable.symlist.count-1 do
  298. begin
  299. sym:=tsym(struct.symtable.symlist[i]);
  300. if (sym.typ=fieldvarsym) then
  301. begin
  302. fsym:=tfieldvarsym(sym);
  303. if (fsym.vardef.typ=recorddef) or
  304. ((fsym.vardef.typ=arraydef) and
  305. not is_dynamic_array(fsym.vardef)) or
  306. ((fsym.vardef.typ=setdef) and
  307. not is_smallset(fsym.vardef)) then
  308. str:=str+'_fpc_ptrt(clone)^.&'+fsym.realname+':='+fsym.realname+';';
  309. end;
  310. end;
  311. str:=str+'end;';
  312. str_parse_method_impl(str,pd,false);
  313. end;
  314. procedure implement_record_deepcopy(pd: tprocdef);
  315. var
  316. struct: tabstractrecorddef;
  317. str: ansistring;
  318. i: longint;
  319. sym: tsym;
  320. fsym: tfieldvarsym;
  321. begin
  322. if not(pd.struct.typ in [recorddef,objectdef]) then
  323. internalerror(2011032810);
  324. struct:=pd.struct;
  325. { anonymous record types must get an artificial name, so we can generate
  326. a typecast at the scanner level }
  327. if (struct.typ=recorddef) and
  328. not assigned(struct.typesym) then
  329. internalerror(2011032811);
  330. { copy all fields }
  331. str:='begin ';
  332. for i:=0 to struct.symtable.symlist.count-1 do
  333. begin
  334. sym:=tsym(struct.symtable.symlist[i]);
  335. if (sym.typ=fieldvarsym) then
  336. begin
  337. fsym:=tfieldvarsym(sym);
  338. str:=str+'result.&'+fsym.realname+':=&'+fsym.realname+';';
  339. end;
  340. end;
  341. str:=str+'end;';
  342. str_parse_method_impl(str,pd,false);
  343. end;
  344. procedure implement_record_initialize(pd: tprocdef);
  345. var
  346. struct: tabstractrecorddef;
  347. str: ansistring;
  348. i: longint;
  349. sym: tsym;
  350. fsym: tfieldvarsym;
  351. begin
  352. if not(pd.struct.typ in [recorddef,objectdef]) then
  353. internalerror(2011071710);
  354. struct:=pd.struct;
  355. { anonymous record types must get an artificial name, so we can generate
  356. a typecast at the scanner level }
  357. if (struct.typ=recorddef) and
  358. not assigned(struct.typesym) then
  359. internalerror(2011032811);
  360. { walk over all fields that need initialization }
  361. str:='begin ';
  362. for i:=0 to struct.symtable.symlist.count-1 do
  363. begin
  364. sym:=tsym(struct.symtable.symlist[i]);
  365. if (sym.typ=fieldvarsym) then
  366. begin
  367. fsym:=tfieldvarsym(sym);
  368. if fsym.vardef.needs_inittable then
  369. str:=str+'system.initialize(&'+fsym.realname+');';
  370. end;
  371. end;
  372. str:=str+'end;';
  373. str_parse_method_impl(str,pd,false);
  374. end;
  375. procedure implement_empty(pd: tprocdef);
  376. var
  377. str: ansistring;
  378. isclassmethod: boolean;
  379. begin
  380. isclassmethod:=
  381. (po_classmethod in pd.procoptions) and
  382. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  383. str:='begin end;';
  384. str_parse_method_impl(str,pd,isclassmethod);
  385. end;
  386. procedure addvisibibleparameters(var str: ansistring; pd: tprocdef);
  387. var
  388. currpara: tparavarsym;
  389. i: longint;
  390. firstpara: boolean;
  391. begin
  392. firstpara:=true;
  393. for i:=0 to pd.paras.count-1 do
  394. begin
  395. currpara:=tparavarsym(pd.paras[i]);
  396. if not(vo_is_hidden_para in currpara.varoptions) then
  397. begin
  398. if not firstpara then
  399. str:=str+',';
  400. firstpara:=false;
  401. str:=str+currpara.realname;
  402. end;
  403. end;
  404. end;
  405. procedure implement_callthrough(pd: tprocdef);
  406. var
  407. str: ansistring;
  408. callpd: tprocdef;
  409. isclassmethod: boolean;
  410. begin
  411. isclassmethod:=
  412. (po_classmethod in pd.procoptions) and
  413. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  414. callpd:=tprocdef(pd.skpara);
  415. str:='begin ';
  416. if pd.returndef<>voidtype then
  417. str:=str+'result:=';
  418. str:=str+callpd.procsym.realname+'(';
  419. addvisibibleparameters(str,pd);
  420. str:=str+') end;';
  421. str_parse_method_impl(str,pd,isclassmethod);
  422. end;
  423. {$ifdef jvm}
  424. procedure implement_jvm_enum_values(pd: tprocdef);
  425. begin
  426. str_parse_method_impl('begin result:=__fpc_FVALUES end;',pd,true);
  427. end;
  428. procedure implement_jvm_enum_valuof(pd: tprocdef);
  429. begin
  430. str_parse_method_impl('begin result:=__FPC_TEnumClassAlias(inherited valueOf(JLClass(__FPC_TEnumClassAlias),__fpc_str)) end;',pd,true);
  431. end;
  432. procedure implement_jvm_enum_jumps_constr(pd: tprocdef);
  433. begin
  434. str_parse_method_impl('begin inherited create(__fpc_name,__fpc_ord); __fpc_fenumval:=__fpc_initenumval end;',pd,false);
  435. end;
  436. procedure implement_jvm_enum_fpcordinal(pd: tprocdef);
  437. var
  438. enumclass: tobjectdef;
  439. enumdef: tenumdef;
  440. begin
  441. enumclass:=tobjectdef(pd.owner.defowner);
  442. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  443. if not enumdef.has_jumps then
  444. str_parse_method_impl('begin result:=ordinal end;',pd,false)
  445. else
  446. str_parse_method_impl('begin result:=__fpc_fenumval end;',pd,false);
  447. end;
  448. procedure implement_jvm_enum_fpcvalueof(pd: tprocdef);
  449. var
  450. enumclass: tobjectdef;
  451. enumdef: tenumdef;
  452. isclassmethod: boolean;
  453. begin
  454. isclassmethod:=
  455. (po_classmethod in pd.procoptions) and
  456. not(pd.proctypeoption in [potype_constructor,potype_destructor]);
  457. enumclass:=tobjectdef(pd.owner.defowner);
  458. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  459. { convert integer to corresponding enum instance: in case of no jumps
  460. get it from the $VALUES array, otherwise from the __fpc_ord2enum
  461. hashmap }
  462. if not enumdef.has_jumps then
  463. str_parse_method_impl('begin result:=__fpc_FVALUES[__fpc_int] end;',pd,isclassmethod)
  464. else
  465. str_parse_method_impl('begin result:=__FPC_TEnumClassAlias(__fpc_ord2enum.get(JLInteger.valueOf(__fpc_int))) end;',pd,isclassmethod);
  466. end;
  467. function CompareEnumSyms(Item1, Item2: Pointer): Integer;
  468. var
  469. I1 : tenumsym absolute Item1;
  470. I2 : tenumsym absolute Item2;
  471. begin
  472. Result:=I1.value-I2.value;
  473. end;
  474. procedure implement_jvm_enum_classconstr(pd: tprocdef);
  475. var
  476. enumclass: tobjectdef;
  477. enumdef: tenumdef;
  478. str: ansistring;
  479. i: longint;
  480. enumsym: tenumsym;
  481. classfield: tstaticvarsym;
  482. orderedenums: tfpobjectlist;
  483. begin
  484. enumclass:=tobjectdef(pd.owner.defowner);
  485. enumdef:=tenumdef(ttypesym(search_struct_member(enumclass,'__FPC_TENUMALIAS')).typedef);
  486. if not assigned(enumdef) then
  487. internalerror(2011062305);
  488. str:='begin ';
  489. if enumdef.has_jumps then
  490. { init hashmap for ordinal -> enum instance mapping; don't let it grow,
  491. and set the capacity to the next prime following the total number of
  492. enum elements to minimise the number of collisions }
  493. str:=str+'__fpc_ord2enum:=JUHashMap.Create('+tostr(next_prime(enumdef.symtable.symlist.count))+',1.0);';
  494. { iterate over all enum elements and initialise the class fields, and
  495. store them in the values array. Since the java.lang.Enum doCompare
  496. method is final and hardcoded to compare based on declaration order
  497. (= java.lang.Enum.ordinal() value), we have to create them in order of
  498. ascending FPC ordinal values (which may not be the same as the FPC
  499. declaration order in case of jumps }
  500. orderedenums:=tfpobjectlist.create(false);
  501. for i:=0 to enumdef.symtable.symlist.count-1 do
  502. orderedenums.add(enumdef.symtable.symlist[i]);
  503. if enumdef.has_jumps then
  504. orderedenums.sort(@CompareEnumSyms);
  505. for i:=0 to orderedenums.count-1 do
  506. begin
  507. enumsym:=tenumsym(orderedenums[i]);
  508. classfield:=tstaticvarsym(search_struct_member(enumclass,enumsym.name));
  509. if not assigned(classfield) then
  510. internalerror(2011062306);
  511. str:=str+classfield.name+':=__FPC_TEnumClassAlias.Create('''+enumsym.realname+''','+tostr(i);
  512. if enumdef.has_jumps then
  513. str:=str+','+tostr(enumsym.value);
  514. str:=str+');';
  515. { alias for $VALUES array used internally by the JDK, and also by FPC
  516. in case of no jumps }
  517. str:=str+'__fpc_FVALUES['+tostr(i)+']:='+classfield.name+';';
  518. if enumdef.has_jumps then
  519. str:=str+'__fpc_ord2enum.put(JLInteger.valueOf('+tostr(enumsym.value)+'),'+classfield.name+');';
  520. end;
  521. orderedenums.free;
  522. str:=str+' end;';
  523. str_parse_method_impl(str,pd,true);
  524. end;
  525. procedure implement_jvm_enum_long2set(pd: tprocdef);
  526. begin
  527. str_parse_method_impl(
  528. 'var '+
  529. 'i, setval: jint;'+
  530. 'begin '+
  531. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  532. 'if __val<>0 then '+
  533. 'begin '+
  534. '__setsize:=__setsize*8;'+
  535. 'for i:=0 to __setsize-1 do '+
  536. // setsize-i because JVM = big endian
  537. 'if (__val and (jlong(1) shl (__setsize-i)))<>0 then '+
  538. 'result.add(fpcValueOf(i+__setbase));'+
  539. 'end '+
  540. 'end;',
  541. pd,true);
  542. end;
  543. procedure implement_jvm_enum_bitset2set(pd: tprocdef);
  544. begin
  545. str_parse_method_impl(
  546. 'var '+
  547. 'i, setval: jint;'+
  548. 'begin '+
  549. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  550. 'i:=__val.nextSetBit(0);'+
  551. 'while i>=0 do '+
  552. 'begin '+
  553. 'setval:=-__fromsetbase;'+
  554. 'result.add(fpcValueOf(setval+__tosetbase));'+
  555. 'i:=__val.nextSetBit(i+1);'+
  556. 'end '+
  557. 'end;',
  558. pd,true);
  559. end;
  560. procedure implement_jvm_enum_set2set(pd: tprocdef);
  561. begin
  562. str_parse_method_impl(
  563. 'var '+
  564. 'it: JUIterator;'+
  565. 'ele: FpcEnumValueObtainable;'+
  566. 'i: longint;'+
  567. 'begin '+
  568. 'result:=JUEnumSet.noneOf(JLClass(__FPC_TEnumClassAlias));'+
  569. 'it:=__val.iterator;'+
  570. 'while it.hasNext do '+
  571. 'begin '+
  572. 'ele:=FpcEnumValueObtainable(it.next);'+
  573. 'i:=ele.fpcOrdinal-__fromsetbase;'+
  574. 'result.add(fpcValueOf(i+__tosetbase));'+
  575. 'end '+
  576. 'end;',
  577. pd,true);
  578. end;
  579. procedure implement_jvm_procvar_invoke(pd: tprocdef);
  580. var
  581. pvclass: tobjectdef;
  582. procvar: tprocvardef;
  583. paraname,str,endstr: ansistring;
  584. pvs: tparavarsym;
  585. paradef,boxdef,boxargdef: tdef;
  586. i: longint;
  587. firstpara: boolean;
  588. begin
  589. pvclass:=tobjectdef(pd.owner.defowner);
  590. procvar:=tprocvardef(ttypesym(search_struct_member(pvclass,'__FPC_PROCVARALIAS')).typedef);
  591. { the procvar wrapper class has a tmethod member called "method", whose
  592. "code" field is a JLRMethod, and whose "data" field is the self pointer
  593. if any (if none is required, it's ignored by the JVM, so there's no
  594. problem with always passing it) }
  595. { force extended syntax to allow calling invokeObjectFunc() without using
  596. its result }
  597. str:='';
  598. endstr:='';
  599. { create local pointer to result type for typecasting in case of an
  600. implicit pointer type }
  601. if jvmimplicitpointertype(procvar.returndef) then
  602. str:=str+'type __FPC_returnptrtype = ^'+procvar.returndef.typename+';';
  603. str:=str+'begin ';
  604. { result handling }
  605. if not is_void(procvar.returndef) then
  606. begin
  607. str:=str+'invoke:=';
  608. if procvar.returndef.typ in [orddef,floatdef] then
  609. begin
  610. { primitivetype(boxtype(..).unboxmethod) }
  611. jvmgetboxtype(procvar.returndef,boxdef,boxargdef,false);
  612. str:=str+procvar.returndef.typename+'('+boxdef.typename+'(';
  613. endstr:=').'+jvmgetunboxmethod(procvar.returndef)+')';
  614. end
  615. else if jvmimplicitpointertype(procvar.returndef) then
  616. begin
  617. str:=str+'__FPC_returnptrtype(';
  618. { dereference }
  619. endstr:=')^';
  620. end
  621. else
  622. begin
  623. str:=str+procvar.returndef.typename+'(';
  624. endstr:=')';
  625. end;
  626. end;
  627. str:=str+'invokeObjectFunc([';
  628. { parameters are a constant array of jlobject }
  629. firstpara:=true;
  630. for i:=0 to procvar.paras.count-1 do
  631. begin
  632. { skip self/vmt/parentfp, passed separately }
  633. pvs:=tparavarsym(procvar.paras[i]);
  634. if ([vo_is_self,vo_is_vmt,vo_is_parentfp]*pvs.varoptions)<>[] then
  635. continue;
  636. if not firstpara then
  637. str:=str+',';
  638. firstpara:=false;
  639. paraname:=pvs.realname;
  640. paradef:=pvs.vardef;
  641. { Pascalize hidden high parameter }
  642. if vo_is_high_para in pvs.varoptions then
  643. paraname:='high('+tparavarsym(procvar.paras[i-1]).realname+')'
  644. else if vo_is_hidden_para in pvs.varoptions then
  645. begin
  646. if ([vo_is_range_check,vo_is_overflow_check]*pvs.varoptions)<>[] then
  647. { ok, simple boolean parameters }
  648. else
  649. internalerror(2011072403);
  650. end;
  651. { var/out/constref parameters -> pass address through (same for
  652. implicit pointer types) }
  653. if paramanager.push_addr_param(pvs.varspez,paradef,procvar.proccalloption) or
  654. jvmimplicitpointertype(paradef) then
  655. begin
  656. paraname:='@'+paraname;
  657. paradef:=java_jlobject;
  658. end;
  659. if paradef.typ in [orddef,floatdef] then
  660. begin
  661. { box primitive types; use valueOf() rather than create because it
  662. can give better performance }
  663. jvmgetboxtype(paradef,boxdef,boxargdef,false);
  664. str:=str+boxdef.typename+'.valueOf('+boxargdef.typename+'('+paraname+'))'
  665. end
  666. else
  667. str:=str+'JLObject('+paraname+')';
  668. end;
  669. str:=str+'])'+endstr+' end;';
  670. str_parse_method_impl(str,pd,false)
  671. end;
  672. procedure implement_jvm_virtual_clmethod(pd: tprocdef);
  673. var
  674. str: ansistring;
  675. callpd: tprocdef;
  676. begin
  677. callpd:=tprocdef(pd.skpara);
  678. str:='var pv: __fpc_virtualclassmethod_pv_t'+tostr(pd.defid)+'; begin '
  679. + 'pv:=@'+callpd.procsym.RealName+';';
  680. if (pd.proctypeoption<>potype_constructor) and
  681. not is_void(pd.returndef) then
  682. str:=str+'result:=';
  683. str:=str+'pv(';
  684. addvisibibleparameters(str,pd);
  685. str:=str+') end;';
  686. str_parse_method_impl(str,pd,true)
  687. end;
  688. {$endif jvm}
  689. procedure add_synthetic_method_implementations_for_struct(struct: tabstractrecorddef);
  690. var
  691. i : longint;
  692. def : tdef;
  693. pd : tprocdef;
  694. begin
  695. for i:=0 to struct.symtable.deflist.count-1 do
  696. begin
  697. def:=tdef(struct.symtable.deflist[i]);
  698. if (def.typ<>procdef) then
  699. continue;
  700. pd:=tprocdef(def);
  701. case pd.synthetickind of
  702. tsk_none:
  703. ;
  704. tsk_anon_inherited:
  705. implement_anon_inherited(pd);
  706. tsk_jvm_clone:
  707. implement_jvm_clone(pd);
  708. tsk_record_deepcopy:
  709. implement_record_deepcopy(pd);
  710. tsk_record_initialize:
  711. implement_record_initialize(pd);
  712. tsk_empty,
  713. { special handling for this one is done in tnodeutils.wrap_proc_body }
  714. tsk_tcinit:
  715. implement_empty(pd);
  716. tsk_callthrough:
  717. implement_callthrough(pd);
  718. {$ifdef jvm}
  719. tsk_jvm_enum_values:
  720. implement_jvm_enum_values(pd);
  721. tsk_jvm_enum_valueof:
  722. implement_jvm_enum_valuof(pd);
  723. tsk_jvm_enum_classconstr:
  724. implement_jvm_enum_classconstr(pd);
  725. tsk_jvm_enum_jumps_constr:
  726. implement_jvm_enum_jumps_constr(pd);
  727. tsk_jvm_enum_fpcordinal:
  728. implement_jvm_enum_fpcordinal(pd);
  729. tsk_jvm_enum_fpcvalueof:
  730. implement_jvm_enum_fpcvalueof(pd);
  731. tsk_jvm_enum_long2set:
  732. implement_jvm_enum_long2set(pd);
  733. tsk_jvm_enum_bitset2set:
  734. implement_jvm_enum_bitset2set(pd);
  735. tsk_jvm_enum_set2set:
  736. implement_jvm_enum_set2set(pd);
  737. tsk_jvm_procvar_invoke:
  738. implement_jvm_procvar_invoke(pd);
  739. tsk_jvm_virtual_clmethod:
  740. implement_jvm_virtual_clmethod(pd);
  741. {$endif jvm}
  742. else
  743. internalerror(2011032801);
  744. end;
  745. end;
  746. end;
  747. procedure add_synthetic_method_implementations(st: tsymtable);
  748. var
  749. i: longint;
  750. def: tdef;
  751. sstate: tscannerstate;
  752. begin
  753. { only necessary for the JVM target currently }
  754. if not (target_info.system in [system_jvm_java32]) then
  755. exit;
  756. sstate.valid:=false;
  757. for i:=0 to st.deflist.count-1 do
  758. begin
  759. def:=tdef(st.deflist[i]);
  760. if (def.typ=procdef) and
  761. assigned(tprocdef(def).localst) and
  762. { not true for the "main" procedure, whose localsymtable is the staticsymtable }
  763. (tprocdef(def).localst.symtabletype=localsymtable) then
  764. add_synthetic_method_implementations(tprocdef(def).localst)
  765. else if (is_javaclass(def) and
  766. not(oo_is_external in tobjectdef(def).objectoptions)) or
  767. (def.typ=recorddef) then
  768. begin
  769. if not sstate.valid then
  770. replace_scanner('synthetic_impl',sstate);
  771. add_synthetic_method_implementations_for_struct(tabstractrecorddef(def));
  772. { also complete nested types }
  773. add_synthetic_method_implementations(tabstractrecorddef(def).symtable);
  774. end;
  775. end;
  776. restore_scanner(sstate);
  777. end;
  778. procedure finish_copied_procdef(var pd: tprocdef; const realname: string; newparentst: tsymtable; newstruct: tabstractrecorddef);
  779. var
  780. sym: tsym;
  781. parasym: tparavarsym;
  782. ps: tprocsym;
  783. stname: string;
  784. i: longint;
  785. begin
  786. { associate the procdef with a procsym in the owner }
  787. if not(pd.proctypeoption in [potype_class_constructor,potype_class_destructor]) then
  788. stname:=upper(realname)
  789. else
  790. stname:=lower(realname);
  791. sym:=tsym(newparentst.find(stname));
  792. if assigned(sym) then
  793. begin
  794. if sym.typ<>procsym then
  795. internalerror(2011040601);
  796. ps:=tprocsym(sym);
  797. end
  798. else
  799. begin
  800. ps:=tprocsym.create(realname);
  801. newparentst.insert(ps);
  802. end;
  803. pd.procsym:=ps;
  804. pd.struct:=newstruct;
  805. { in case of methods, replace the special parameter types with new ones }
  806. if assigned(newstruct) then
  807. begin
  808. symtablestack.push(pd.parast);
  809. { may not be assigned in case we converted a procvar into a procdef }
  810. if assigned(pd.paras) then
  811. begin
  812. for i:=0 to pd.paras.count-1 do
  813. begin
  814. parasym:=tparavarsym(pd.paras[i]);
  815. if vo_is_self in parasym.varoptions then
  816. begin
  817. if parasym.vardef.typ=classrefdef then
  818. parasym.vardef:=tclassrefdef.create(newstruct)
  819. else
  820. parasym.vardef:=newstruct;
  821. end
  822. end;
  823. end;
  824. { also fix returndef in case of a constructor }
  825. if pd.proctypeoption=potype_constructor then
  826. pd.returndef:=newstruct;
  827. symtablestack.pop(pd.parast);
  828. end;
  829. pd.calcparas;
  830. proc_add_definition(pd);
  831. end;
  832. procedure build_parentfpstruct(pd: tprocdef);
  833. var
  834. nestedvars: tsym;
  835. nestedvarsst: tsymtable;
  836. pnestedvarsdef,
  837. nestedvarsdef: tdef;
  838. old_symtablestack: tsymtablestack;
  839. begin
  840. { make sure the defs are not registered in the current symtablestack,
  841. because they may be for a parent procdef (changeowner does remove a def
  842. from the symtable in which it was originally created, so that by itself
  843. is not enough) }
  844. old_symtablestack:=symtablestack;
  845. symtablestack:=old_symtablestack.getcopyuntil(current_module.localsymtable);
  846. { create struct to hold local variables and parameters that are
  847. accessed from within nested routines (start with extra dollar to prevent
  848. the JVM from thinking this is a nested class in the unit) }
  849. nestedvarsst:=trecordsymtable.create('$'+current_module.realmodulename^+'$$_fpc_nestedvars$'+tostr(pd.defid),current_settings.alignment.localalignmax);
  850. nestedvarsdef:=trecorddef.create(nestedvarsst.name^,nestedvarsst);
  851. {$ifdef jvm}
  852. maybe_guarantee_record_typesym(nestedvarsdef,nestedvarsdef.owner);
  853. { don't add clone/FpcDeepCopy, because the field names are not all
  854. representable in source form and we don't need them anyway }
  855. symtablestack.push(trecorddef(nestedvarsdef).symtable);
  856. maybe_add_public_default_java_constructor(trecorddef(nestedvarsdef));
  857. symtablestack.pop(trecorddef(nestedvarsdef).symtable);
  858. {$endif}
  859. symtablestack.free;
  860. symtablestack:=old_symtablestack.getcopyuntil(pd.localst);
  861. pnestedvarsdef:=getpointerdef(nestedvarsdef);
  862. nestedvars:=tlocalvarsym.create('$nestedvars',vs_var,nestedvarsdef,[]);
  863. pd.localst.insert(nestedvars);
  864. pd.parentfpstruct:=nestedvars;
  865. pd.parentfpstructptrtype:=pnestedvarsdef;
  866. pd.parentfpinitblock:=cblocknode.create(nil);
  867. symtablestack.free;
  868. symtablestack:=old_symtablestack;
  869. end;
  870. function maybe_add_sym_to_parentfpstruct(pd: tprocdef; sym: tsym; vardef: tdef; addrparam: boolean): tsym;
  871. var
  872. fieldvardef,
  873. nestedvarsdef: tdef;
  874. nestedvarsst: tsymtable;
  875. initcode: tnode;
  876. old_filepos: tfileposinfo;
  877. begin
  878. nestedvarsdef:=tlocalvarsym(pd.parentfpstruct).vardef;
  879. result:=search_struct_member(trecorddef(nestedvarsdef),sym.name);
  880. if not assigned(result) then
  881. begin
  882. { mark that this symbol is mirrored in the parentfpstruct }
  883. tabstractnormalvarsym(sym).inparentfpstruct:=true;
  884. { add field to the struct holding all locals accessed
  885. by nested routines }
  886. nestedvarsst:=trecorddef(nestedvarsdef).symtable;
  887. { indicate whether or not this is a var/out/constref/... parameter }
  888. if addrparam then
  889. fieldvardef:=getpointerdef(vardef)
  890. else
  891. fieldvardef:=vardef;
  892. result:=tfieldvarsym.create(sym.realname,vs_value,fieldvardef,[]);
  893. if nestedvarsst.symlist.count=0 then
  894. include(tfieldvarsym(result).varoptions,vo_is_first_field);
  895. nestedvarsst.insert(result);
  896. trecordsymtable(nestedvarsst).addfield(tfieldvarsym(result),vis_public);
  897. { add initialization with original value if it's a parameter }
  898. if (sym.typ=paravarsym) then
  899. begin
  900. old_filepos:=current_filepos;
  901. fillchar(current_filepos,sizeof(current_filepos),0);
  902. initcode:=cloadnode.create(sym,sym.owner);
  903. { indicate that this load should not be transformed into a load
  904. from the parentfpstruct, but instead should load the original
  905. value }
  906. include(initcode.flags,nf_internal);
  907. { in case it's a var/out/constref parameter, store the address of the
  908. parameter in the struct }
  909. if addrparam then
  910. begin
  911. initcode:=caddrnode.create_internal(initcode);
  912. include(initcode.flags,nf_typedaddr);
  913. end;
  914. initcode:=cassignmentnode.create(
  915. csubscriptnode.create(result,cloadnode.create(pd.parentfpstruct,pd.parentfpstruct.owner)),
  916. initcode);
  917. tblocknode(pd.parentfpinitblock).left:=cstatementnode.create
  918. (initcode,tblocknode(pd.parentfpinitblock).left);
  919. current_filepos:=old_filepos;
  920. end;
  921. end;
  922. end;
  923. procedure redirect_parentfpstruct_local_syms(pd: tprocdef);
  924. var
  925. nestedvarsdef: trecorddef;
  926. sl: tpropaccesslist;
  927. fsym,
  928. lsym,
  929. aliassym: tsym;
  930. i: longint;
  931. begin
  932. nestedvarsdef:=trecorddef(tlocalvarsym(pd.parentfpstruct).vardef);
  933. for i:=0 to nestedvarsdef.symtable.symlist.count-1 do
  934. begin
  935. fsym:=tsym(nestedvarsdef.symtable.symlist[i]);
  936. if fsym.typ<>fieldvarsym then
  937. continue;
  938. lsym:=tsym(pd.localst.find(fsym.name));
  939. if not assigned(lsym) then
  940. lsym:=tsym(pd.parast.find(fsym.name));
  941. if not assigned(lsym) then
  942. internalerror(2011060408);
  943. { add an absolute variable that redirects to the field }
  944. sl:=tpropaccesslist.create;
  945. sl.addsym(sl_load,pd.parentfpstruct);
  946. sl.addsym(sl_subscript,tfieldvarsym(fsym));
  947. aliassym:=tabsolutevarsym.create_ref(lsym.name,tfieldvarsym(fsym).vardef,sl);
  948. { hide the original variable (can't delete, because there
  949. may be other loadnodes that reference it)
  950. -- only for locals; hiding parameters changes the
  951. function signature }
  952. if lsym.typ<>paravarsym then
  953. hidesym(lsym);
  954. { insert the absolute variable in the localst of the
  955. routine; ignore duplicates, because this will also check the
  956. parasymtable and we want to override parameters with our local
  957. versions }
  958. pd.localst.insert(aliassym,false);
  959. end;
  960. end;
  961. function find_sym_in_parentfpstruct(pd: tprocdef; sym: tsym): tsym;
  962. var
  963. nestedvarsdef: tdef;
  964. begin
  965. nestedvarsdef:=tlocalvarsym(pd.parentfpstruct).vardef;
  966. result:=search_struct_member(trecorddef(nestedvarsdef),sym.name);
  967. end;
  968. procedure finish_parentfpstruct(pd: tprocdef);
  969. begin
  970. trecordsymtable(trecorddef(tlocalvarsym(pd.parentfpstruct).vardef).symtable).addalignmentpadding;
  971. end;
  972. procedure maybe_guarantee_record_typesym(var def: tdef; st: tsymtable);
  973. var
  974. ts: ttypesym;
  975. begin
  976. { create a dummy typesym for the JVM target, because the record
  977. has to be wrapped by a class }
  978. if (target_info.system=system_jvm_java32) and
  979. (def.typ=recorddef) and
  980. not assigned(def.typesym) then
  981. begin
  982. ts:=ttypesym.create(trecorddef(def).symtable.realname^,def);
  983. st.insert(ts);
  984. ts.visibility:=vis_strictprivate;
  985. { this typesym can't be used by any Pascal code, so make sure we don't
  986. print a hint about it being unused }
  987. addsymref(ts);
  988. end;
  989. end;
  990. end.