symcreat.pas 40 KB

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