symcreat.pas 54 KB

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