symcreat.pas 47 KB

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