symcreat.pas 40 KB

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