symcreat.pas 54 KB

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