pgenutil.pas 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  1. {
  2. Copyright (c) 2011
  3. Contains different functions that are used in the context of
  4. parsing generics.
  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. unit pgenutil;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. { common }
  23. cclasses,
  24. { global }
  25. globtype,
  26. { parser }
  27. pgentype,
  28. { symtable }
  29. symtype,symdef,symbase;
  30. procedure generate_specialization(var tt:tdef;parse_class_parent:boolean;_prettyname:string;parsedtype:tdef;symname:string;parsedpos:tfileposinfo);inline;
  31. procedure generate_specialization(var tt:tdef;parse_class_parent:boolean;_prettyname:string);inline;
  32. function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef):tdef;inline;
  33. function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef;symname:string):tdef;inline;
  34. function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef;parsedtype:tdef;symname:string;parsedpos:tfileposinfo):tdef;
  35. function generate_specialization_phase2(context:tspecializationcontext;genericdef:tstoreddef;parse_class_parent:boolean;_prettyname:ansistring):tdef;
  36. function check_generic_constraints(genericdef:tstoreddef;paradeflist:tfpobjectlist;poslist:tfplist):boolean;
  37. function parse_generic_parameters(allowconstraints:boolean):tfphashobjectlist;
  38. function parse_generic_specialization_types(genericdeflist:tfpobjectlist;poslist:tfplist;out prettyname,specializename:ansistring):boolean;
  39. procedure insert_generic_parameter_types(def:tstoreddef;genericdef:tstoreddef;genericlist:tfphashobjectlist);
  40. procedure maybe_insert_generic_rename_symbol(const name:tidstring;genericlist:tfphashobjectlist);
  41. function generate_generic_name(const name:tidstring;specializename:ansistring;owner_hierarchy:string):tidstring;
  42. procedure split_generic_name(const name:tidstring;out nongeneric:string;out count:longint);
  43. function resolve_generic_dummysym(const name:tidstring):tsym;
  44. function could_be_generic(const name:tidstring):boolean;inline;
  45. procedure generate_specialization_procs;
  46. procedure maybe_add_pending_specialization(def:tdef);
  47. procedure specialization_init(genericdef:tdef;var state:tspecializationstate);
  48. procedure specialization_done(var state:tspecializationstate);
  49. implementation
  50. uses
  51. { common }
  52. cutils,fpccrc,
  53. { global }
  54. globals,tokens,verbose,finput,
  55. { symtable }
  56. symconst,symsym,symtable,defcmp,procinfo,
  57. { modules }
  58. fmodule,
  59. node,nobj,
  60. { parser }
  61. scanner,
  62. pbase,pexpr,pdecsub,ptype,psub;
  63. procedure maybe_add_waiting_unit(tt:tdef);
  64. var
  65. hmodule : tmodule;
  66. begin
  67. if not assigned(tt) or
  68. not (df_generic in tt.defoptions) then
  69. exit;
  70. hmodule:=find_module_from_symtable(tt.owner);
  71. if not assigned(hmodule) then
  72. internalerror(2012092401);
  73. if hmodule=current_module then
  74. exit;
  75. if hmodule.state<>ms_compiled then
  76. begin
  77. {$ifdef DEBUG_UNITWAITING}
  78. Writeln('Unit ', current_module.modulename^,
  79. ' waiting for ', hmodule.modulename^);
  80. {$endif DEBUG_UNITWAITING}
  81. if current_module.waitingforunit.indexof(hmodule)<0 then
  82. current_module.waitingforunit.add(hmodule);
  83. if hmodule.waitingunits.indexof(current_module)<0 then
  84. hmodule.waitingunits.add(current_module);
  85. end;
  86. end;
  87. function check_generic_constraints(genericdef:tstoreddef;paradeflist:tfpobjectlist;poslist:tfplist):boolean;
  88. var
  89. i,j,
  90. intfcount : longint;
  91. formaldef,
  92. paradef : tstoreddef;
  93. objdef,
  94. paraobjdef,
  95. formalobjdef : tobjectdef;
  96. intffound : boolean;
  97. filepos : tfileposinfo;
  98. begin
  99. { check whether the given specialization parameters fit to the eventual
  100. constraints of the generic }
  101. if not assigned(genericdef.genericparas) or (genericdef.genericparas.count=0) then
  102. internalerror(2012101001);
  103. if genericdef.genericparas.count<>paradeflist.count then
  104. internalerror(2012101002);
  105. if paradeflist.count<>poslist.count then
  106. internalerror(2012120801);
  107. result:=true;
  108. for i:=0 to genericdef.genericparas.count-1 do
  109. begin
  110. filepos:=pfileposinfo(poslist[i])^;
  111. formaldef:=tstoreddef(ttypesym(genericdef.genericparas[i]).typedef);
  112. if formaldef.typ=undefineddef then
  113. { the parameter is of unspecified type, so no need to check }
  114. continue;
  115. if not (df_genconstraint in formaldef.defoptions) or
  116. not assigned(formaldef.genconstraintdata) then
  117. internalerror(2013021602);
  118. paradef:=tstoreddef(paradeflist[i]);
  119. { undefineddef is compatible with anything }
  120. if formaldef.typ=undefineddef then
  121. continue;
  122. if paradef.typ<>formaldef.typ then
  123. begin
  124. case formaldef.typ of
  125. recorddef:
  126. { delphi has own fantasy about record constraint
  127. (almost non-nullable/non-nilable value type) }
  128. if m_delphi in current_settings.modeswitches then
  129. case paradef.typ of
  130. floatdef,enumdef,orddef:
  131. continue;
  132. objectdef:
  133. if tobjectdef(paradef).objecttype=odt_object then
  134. continue
  135. else
  136. MessagePos(filepos,type_e_record_type_expected);
  137. else
  138. MessagePos(filepos,type_e_record_type_expected);
  139. end
  140. else
  141. MessagePos(filepos,type_e_record_type_expected);
  142. objectdef:
  143. case tobjectdef(formaldef).objecttype of
  144. odt_class,
  145. odt_javaclass:
  146. MessagePos1(filepos,type_e_class_type_expected,paradef.typename);
  147. odt_interfacecom,
  148. odt_interfacecorba,
  149. odt_dispinterface,
  150. odt_interfacejava:
  151. MessagePos1(filepos,type_e_interface_type_expected,paradef.typename);
  152. else
  153. internalerror(2012101003);
  154. end;
  155. errordef:
  156. { ignore }
  157. ;
  158. else
  159. internalerror(2012101004);
  160. end;
  161. result:=false;
  162. end
  163. else
  164. begin
  165. { the paradef types are the same, so do special checks for the
  166. cases in which they are needed }
  167. if formaldef.typ=objectdef then
  168. begin
  169. paraobjdef:=tobjectdef(paradef);
  170. formalobjdef:=tobjectdef(formaldef);
  171. if not (formalobjdef.objecttype in [odt_class,odt_javaclass,odt_interfacecom,odt_interfacecorba,odt_interfacejava,odt_dispinterface]) then
  172. internalerror(2012101102);
  173. if formalobjdef.objecttype in [odt_interfacecom,odt_interfacecorba,odt_interfacejava,odt_dispinterface] then
  174. begin
  175. { this is either a concerete interface or class type (the
  176. latter without specific implemented interfaces) }
  177. case paraobjdef.objecttype of
  178. odt_interfacecom,
  179. odt_interfacecorba,
  180. odt_interfacejava,
  181. odt_dispinterface:
  182. begin
  183. if (oo_is_forward in paraobjdef.objectoptions) and
  184. (paraobjdef.objecttype=formalobjdef.objecttype) and
  185. (df_genconstraint in formalobjdef.defoptions) and
  186. (
  187. (formalobjdef.objecttype=odt_interfacecom) and
  188. (formalobjdef.childof=interface_iunknown)
  189. )
  190. or
  191. (
  192. (formalobjdef.objecttype=odt_interfacecorba) and
  193. (formalobjdef.childof=nil)
  194. ) then
  195. continue;
  196. if not def_is_related(paraobjdef,formalobjdef.childof) then
  197. begin
  198. MessagePos2(filepos,type_e_incompatible_types,paraobjdef.typename,formalobjdef.childof.typename);
  199. result:=false;
  200. end;
  201. end;
  202. odt_class,
  203. odt_javaclass:
  204. begin
  205. objdef:=paraobjdef;
  206. intffound:=false;
  207. while assigned(objdef) do
  208. begin
  209. for j:=0 to objdef.implementedinterfaces.count-1 do
  210. if timplementedinterface(objdef.implementedinterfaces[j]).intfdef=formalobjdef.childof then
  211. begin
  212. intffound:=true;
  213. break;
  214. end;
  215. if intffound then
  216. break;
  217. objdef:=objdef.childof;
  218. end;
  219. result:=intffound;
  220. if not result then
  221. MessagePos2(filepos,parser_e_class_doesnt_implement_interface,paraobjdef.typename,formalobjdef.childof.typename);
  222. end;
  223. else
  224. begin
  225. MessagePos1(filepos,type_e_class_or_interface_type_expected,paraobjdef.typename);
  226. result:=false;
  227. end;
  228. end;
  229. end
  230. else
  231. begin
  232. { this is either a "class" or a concrete instance with
  233. or without implemented interfaces }
  234. if not (paraobjdef.objecttype in [odt_class,odt_javaclass]) then
  235. begin
  236. MessagePos1(filepos,type_e_class_type_expected,paraobjdef.typename);
  237. result:=false;
  238. continue;
  239. end;
  240. { for forward declared classes we allow pure TObject/class declarations }
  241. if (oo_is_forward in paraobjdef.objectoptions) and
  242. (df_genconstraint in formaldef.defoptions) then
  243. begin
  244. if (formalobjdef.childof=class_tobject) and
  245. not formalobjdef.implements_any_interfaces then
  246. continue;
  247. end;
  248. if assigned(formalobjdef.childof) and
  249. not def_is_related(paradef,formalobjdef.childof) then
  250. begin
  251. MessagePos2(filepos,type_e_incompatible_types,paraobjdef.typename,formalobjdef.childof.typename);
  252. result:=false;
  253. end;
  254. intfcount:=0;
  255. for j:=0 to formalobjdef.implementedinterfaces.count-1 do
  256. begin
  257. objdef:=paraobjdef;
  258. while assigned(objdef) do
  259. begin
  260. intffound:=assigned(
  261. find_implemented_interface(objdef,
  262. timplementedinterface(formalobjdef.implementedinterfaces[j]).intfdef
  263. )
  264. );
  265. if intffound then
  266. break;
  267. objdef:=objdef.childof;
  268. end;
  269. if intffound then
  270. inc(intfcount)
  271. else
  272. MessagePos2(filepos,parser_e_class_doesnt_implement_interface,paraobjdef.typename,timplementedinterface(formalobjdef.implementedinterfaces[j]).intfdef.typename);
  273. end;
  274. if intfcount<>formalobjdef.implementedinterfaces.count then
  275. result:=false;
  276. end;
  277. end;
  278. end;
  279. end;
  280. end;
  281. function parse_generic_specialization_types_internal(genericdeflist:tfpobjectlist;poslist:tfplist;out prettyname,specializename:ansistring;parsedtype:tdef;parsedpos:tfileposinfo):boolean;
  282. var
  283. old_block_type : tblock_type;
  284. first : boolean;
  285. typeparam : tnode;
  286. parampos : pfileposinfo;
  287. tmpparampos : tfileposinfo;
  288. namepart : string;
  289. prettynamepart : ansistring;
  290. module : tmodule;
  291. begin
  292. result:=true;
  293. if genericdeflist=nil then
  294. internalerror(2012061401);
  295. { set the block type to type, so that the parsed type are returned as
  296. ttypenode (e.g. classes are in non type-compatible blocks returned as
  297. tloadvmtaddrnode) }
  298. old_block_type:=block_type;
  299. { if parsedtype is set, then the first type identifer was already parsed
  300. (happens in inline specializations) and thus we only need to parse
  301. the remaining types and do as if the first one was already given }
  302. first:=not assigned(parsedtype);
  303. if assigned(parsedtype) then
  304. begin
  305. genericdeflist.Add(parsedtype);
  306. module:=find_module_from_symtable(parsedtype.owner);
  307. if not assigned(module) then
  308. internalerror(2016112801);
  309. namepart:='_$'+hexstr(module.moduleid,8)+'$$'+parsedtype.unique_id_str;
  310. specializename:='$'+namepart;
  311. prettyname:=parsedtype.fullownerhierarchyname(true)+parsedtype.typesym.prettyname;
  312. if assigned(poslist) then
  313. begin
  314. New(parampos);
  315. parampos^:=parsedpos;
  316. poslist.add(parampos);
  317. end;
  318. end
  319. else
  320. begin
  321. specializename:='$';
  322. prettyname:='';
  323. end;
  324. while not (token in [_GT,_RSHARPBRACKET]) do
  325. begin
  326. { "first" is set to false at the end of the loop! }
  327. if not first then
  328. consume(_COMMA);
  329. block_type:=bt_type;
  330. tmpparampos:=current_filepos;
  331. typeparam:=factor(false,[ef_type_only]);
  332. if typeparam.nodetype=typen then
  333. begin
  334. if tstoreddef(typeparam.resultdef).is_generic and
  335. (
  336. not parse_generic or
  337. not defs_belong_to_same_generic(typeparam.resultdef,current_genericdef)
  338. ) then
  339. Message(parser_e_no_generics_as_params);
  340. if assigned(poslist) then
  341. begin
  342. New(parampos);
  343. parampos^:=tmpparampos;
  344. poslist.add(parampos);
  345. end;
  346. if typeparam.resultdef.typ<>errordef then
  347. begin
  348. if not assigned(typeparam.resultdef.typesym) then
  349. message(type_e_generics_cannot_reference_itself)
  350. else if (typeparam.resultdef.typ<>errordef) then
  351. begin
  352. genericdeflist.Add(typeparam.resultdef);
  353. module:=find_module_from_symtable(typeparam.resultdef.owner);
  354. if not assigned(module) then
  355. internalerror(2016112802);
  356. namepart:='_$'+hexstr(module.moduleid,8)+'$$'+typeparam.resultdef.unique_id_str;
  357. { we use the full name of the type to uniquely identify it }
  358. if (symtablestack.top.symtabletype=parasymtable) and
  359. (symtablestack.top.defowner.typ=procdef) and
  360. (typeparam.resultdef.owner=symtablestack.top) then
  361. begin
  362. { special handling for specializations inside generic function declarations }
  363. prettynamepart:=tdef(symtablestack.top.defowner).fullownerhierarchyname(true)+tprocdef(symtablestack.top.defowner).procsym.prettyname;
  364. end
  365. else
  366. begin
  367. prettynamepart:=typeparam.resultdef.fullownerhierarchyname(true);
  368. end;
  369. specializename:=specializename+namepart;
  370. if not first then
  371. prettyname:=prettyname+',';
  372. prettyname:=prettyname+prettynamepart+typeparam.resultdef.typesym.prettyname;
  373. end;
  374. end
  375. else
  376. begin
  377. result:=false;
  378. end;
  379. end
  380. else
  381. begin
  382. Message(type_e_type_id_expected);
  383. result:=false;
  384. end;
  385. typeparam.free;
  386. first:=false;
  387. end;
  388. block_type:=old_block_type;
  389. end;
  390. function parse_generic_specialization_types(genericdeflist:tfpobjectlist;poslist:tfplist;out prettyname,specializename:ansistring):boolean;
  391. var
  392. dummypos : tfileposinfo;
  393. begin
  394. FillChar(dummypos, SizeOf(tfileposinfo), 0);
  395. result:=parse_generic_specialization_types_internal(genericdeflist,poslist,prettyname,specializename,nil,dummypos);
  396. end;
  397. procedure generate_specialization(var tt:tdef;parse_class_parent:boolean;_prettyname:string);
  398. var
  399. dummypos : tfileposinfo;
  400. begin
  401. FillChar(dummypos, SizeOf(tfileposinfo), 0);
  402. generate_specialization(tt,parse_class_parent,_prettyname,nil,'',dummypos);
  403. end;
  404. function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef):tdef;
  405. var
  406. dummypos : tfileposinfo;
  407. {$push}
  408. {$warn 5036 off}
  409. begin
  410. result:=generate_specialization_phase1(context,genericdef,nil,'',dummypos);
  411. end;
  412. {$pop}
  413. function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef;symname:string):tdef;
  414. var
  415. dummypos : tfileposinfo;
  416. {$push}
  417. {$warn 5036 off}
  418. begin
  419. result:=generate_specialization_phase1(context,genericdef,nil,symname,dummypos);
  420. end;
  421. {$pop}
  422. function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef;parsedtype:tdef;symname:string;parsedpos:tfileposinfo):tdef;
  423. var
  424. pt2 : tnode;
  425. errorrecovery,
  426. found,
  427. first,
  428. err : boolean;
  429. i,
  430. gencount : longint;
  431. def : tstoreddef;
  432. countstr,genname,ugenname : string;
  433. srsym : tsym;
  434. st : tsymtable;
  435. begin
  436. context:=nil;
  437. result:=nil;
  438. { either symname must be given or genericdef needs to be valid }
  439. errorrecovery:=false;
  440. if (symname='') and
  441. (not assigned(genericdef) or
  442. not assigned(genericdef.typesym) or
  443. (genericdef.typesym.typ<>typesym)) then
  444. begin
  445. errorrecovery:=true;
  446. result:=generrordef;
  447. end;
  448. { Only parse the parameters for recovery or
  449. for recording in genericbuf }
  450. if errorrecovery then
  451. begin
  452. first:=assigned(parsedtype);
  453. if not first and not try_to_consume(_LT) then
  454. consume(_LSHARPBRACKET);
  455. gencount:=0;
  456. { handle "<>" }
  457. if not first and ((token=_RSHARPBRACKET) or (token=_GT)) then
  458. Message(type_e_type_id_expected)
  459. else
  460. repeat
  461. if not first then
  462. begin
  463. pt2:=factor(false,[ef_type_only]);
  464. pt2.free;
  465. end;
  466. first:=false;
  467. inc(gencount);
  468. until not try_to_consume(_COMMA);
  469. if not try_to_consume(_GT) then
  470. consume(_RSHARPBRACKET);
  471. { we need to return a def that can later pass some checks like
  472. whether it's an interface or not }
  473. if not errorrecovery and
  474. (not assigned(result) or (result.typ=undefineddef)) then
  475. begin
  476. if (symname='') and tstoreddef(genericdef).is_generic then
  477. { this happens in non-Delphi modes }
  478. result:=genericdef
  479. else
  480. begin
  481. { find the corresponding generic symbol so that any checks
  482. done on the returned def will be handled correctly }
  483. str(gencount,countstr);
  484. if symname='' then
  485. genname:=ttypesym(genericdef.typesym).realname
  486. else
  487. genname:=symname;
  488. genname:=genname+'$'+countstr;
  489. ugenname:=upper(genname);
  490. { first check whether the found name is the same as that of
  491. the current def or one of its (generic) surrounding defs;
  492. this is necessary as the symbol of the generic can not yet
  493. be used for lookup as it still contains a reference to an
  494. errordef) }
  495. def:=current_genericdef;
  496. repeat
  497. if def.typ in [objectdef,recorddef] then
  498. if tabstractrecorddef(def).objname^=ugenname then
  499. begin
  500. result:=def;
  501. break;
  502. end;
  503. def:=tstoreddef(def.owner.defowner);
  504. until not assigned(def) or not (df_generic in def.defoptions);
  505. { it's not part of the current object hierarchy, so search
  506. for the symbol }
  507. if not assigned(result) then
  508. begin
  509. srsym:=nil;
  510. if not searchsym(ugenname,srsym,st) or
  511. (srsym.typ<>typesym) then
  512. begin
  513. identifier_not_found(genname);
  514. result:=generrordef;
  515. exit;
  516. end;
  517. result:=ttypesym(srsym).typedef;
  518. { this happens in non-Delphi modes if we encounter a
  519. specialization of the generic class or record we're
  520. currently parsing }
  521. if (result.typ=errordef) and assigned(current_structdef) and
  522. (current_structdef.objname^=ugenname) then
  523. result:=current_structdef;
  524. end;
  525. end;
  526. end;
  527. exit;
  528. end;
  529. if not assigned(parsedtype) and not try_to_consume(_LT) then
  530. begin
  531. consume(_LSHARPBRACKET);
  532. { handle "<>" }
  533. if (token=_GT) or (token=_RSHARPBRACKET) then
  534. begin
  535. Message(type_e_type_id_expected);
  536. if not try_to_consume(_GT) then
  537. try_to_consume(_RSHARPBRACKET);
  538. result:=generrordef;
  539. exit;
  540. end;
  541. end;
  542. context:=tspecializationcontext.create;
  543. { Parse type parameters }
  544. err:=not parse_generic_specialization_types_internal(context.genericdeflist,context.poslist,context.prettyname,context.specializename,parsedtype,parsedpos);
  545. if err then
  546. begin
  547. if not try_to_consume(_GT) then
  548. try_to_consume(_RSHARPBRACKET);
  549. context.free;
  550. context:=nil;
  551. result:=generrordef;
  552. exit;
  553. end;
  554. { use the name of the symbol as procvars return a user friendly version
  555. of the name }
  556. if symname='' then
  557. genname:=ttypesym(genericdef.typesym).realname
  558. else
  559. genname:=symname;
  560. { in case of non-Delphi mode the type name could already be a generic
  561. def (but maybe the wrong one) }
  562. if assigned(genericdef) and
  563. ([df_generic,df_specialization]*genericdef.defoptions<>[]) then
  564. begin
  565. { remove the type count suffix from the generic's name }
  566. for i:=Length(genname) downto 1 do
  567. if genname[i]='$' then
  568. begin
  569. genname:=copy(genname,1,i-1);
  570. break;
  571. end;
  572. { in case of a specialization we've only reached the specialization
  573. checksum yet }
  574. if df_specialization in genericdef.defoptions then
  575. for i:=length(genname) downto 1 do
  576. if genname[i]='$' then
  577. begin
  578. genname:=copy(genname,1,i-1);
  579. break;
  580. end;
  581. end
  582. else
  583. begin
  584. split_generic_name(genname,ugenname,gencount);
  585. if genname<>ugenname then
  586. genname:=ugenname;
  587. end;
  588. { search a generic with the given count of params }
  589. countstr:='';
  590. str(context.genericdeflist.Count,countstr);
  591. genname:=genname+'$'+countstr;
  592. ugenname:=upper(genname);
  593. context.genname:=genname;
  594. if assigned(genericdef) and (genericdef.owner.symtabletype in [objectsymtable,recordsymtable]) then
  595. begin
  596. if genericdef.owner.symtabletype = objectsymtable then
  597. found:=searchsym_in_class(tobjectdef(genericdef.owner.defowner),tobjectdef(genericdef.owner.defowner),ugenname,context.sym,context.symtable,[])
  598. else
  599. found:=searchsym_in_record(tabstractrecorddef(genericdef.owner.defowner),ugenname,context.sym,context.symtable);
  600. if not found then
  601. found:=searchsym(ugenname,context.sym,context.symtable);
  602. end
  603. else
  604. found:=searchsym(ugenname,context.sym,context.symtable);
  605. if not found or not (context.sym.typ in [typesym,procsym]) then
  606. begin
  607. identifier_not_found(genname);
  608. if not try_to_consume(_GT) then
  609. try_to_consume(_RSHARPBRACKET);
  610. context.free;
  611. context:=nil;
  612. result:=generrordef;
  613. exit;
  614. end;
  615. { we've found the correct def }
  616. if context.sym.typ=typesym then
  617. result:=tstoreddef(ttypesym(context.sym).typedef)
  618. else
  619. begin
  620. if tprocsym(context.sym).procdeflist.count=0 then
  621. internalerror(2015061203);
  622. result:=tstoreddef(tprocsym(context.sym).procdefList[0]);
  623. end;
  624. if not try_to_consume(_GT) then
  625. consume(_RSHARPBRACKET);
  626. end;
  627. function generate_specialization_phase2(context:tspecializationcontext;genericdef:tstoreddef;parse_class_parent:boolean;_prettyname:ansistring):tdef;
  628. procedure unset_forwarddef(def: tdef);
  629. var
  630. st : TSymtable;
  631. i : longint;
  632. begin
  633. case def.typ of
  634. procdef:
  635. tprocdef(def).forwarddef:=false;
  636. objectdef,
  637. recorddef:
  638. begin
  639. st:=def.getsymtable(gs_record);
  640. for i:=0 to st.deflist.count-1 do
  641. unset_forwarddef(tdef(st.deflist[i]));
  642. end;
  643. end;
  644. end;
  645. procedure retrieve_genericdef_or_procsym(sym:tsym;out gendef:tdef;out psym:tsym);
  646. var
  647. i : longint;
  648. begin
  649. gendef:=nil;
  650. psym:=nil;
  651. case sym.typ of
  652. typesym:
  653. begin
  654. gendef:=ttypesym(sym).typedef
  655. end;
  656. procsym:
  657. begin
  658. for i:=0 to tprocsym(sym).procdeflist.count-1 do
  659. if tstoreddef(tprocsym(sym).procdeflist[i]).genericdef=genericdef then
  660. begin
  661. gendef:=tdef(tprocsym(sym).procdeflist[i]);
  662. break;
  663. end;
  664. psym:=sym;
  665. end
  666. else
  667. internalerror(200710171);
  668. end;
  669. end;
  670. var
  671. finalspecializename,
  672. ufinalspecializename : tidstring;
  673. prettyname : ansistring;
  674. generictypelist : tfphashobjectlist;
  675. srsymtable,
  676. specializest : tsymtable;
  677. hashedid : thashedidstring;
  678. tempst : tglobalsymtable;
  679. psym,
  680. srsym : tsym;
  681. def : tdef;
  682. old_block_type : tblock_type;
  683. state : tspecializationstate;
  684. old_current_structdef : tabstractrecorddef;
  685. old_current_specializedef,
  686. old_current_genericdef : tstoreddef;
  687. old_current_procinfo : tprocinfo;
  688. hmodule : tmodule;
  689. oldcurrent_filepos : tfileposinfo;
  690. recordbuf : tdynamicarray;
  691. hadtypetoken : boolean;
  692. vmtbuilder : tvmtbuilder;
  693. i,
  694. replaydepth : longint;
  695. item : tobject;
  696. allequal,
  697. hintsprocessed : boolean;
  698. pd : tprocdef;
  699. pdflags : tpdflags;
  700. begin
  701. if not assigned(context) then
  702. internalerror(2015052203);
  703. result:=nil;
  704. pd:=nil;
  705. if not check_generic_constraints(genericdef,context.genericdeflist,context.poslist) then
  706. begin
  707. { the parameters didn't fit the constraints, so don't continue with the
  708. specialization }
  709. result:=generrordef;
  710. exit;
  711. end;
  712. { build the new type's name }
  713. finalspecializename:=generate_generic_name(context.genname,context.specializename,genericdef.ownerhierarchyname);
  714. ufinalspecializename:=upper(finalspecializename);
  715. if genericdef.typ=procdef then
  716. prettyname:=tprocdef(genericdef).procsym.prettyname
  717. else
  718. prettyname:=genericdef.typesym.prettyname;
  719. prettyname:=prettyname+'<'+context.prettyname+'>';
  720. generictypelist:=tfphashobjectlist.create(false);
  721. { build the list containing the types for the generic params }
  722. if not assigned(genericdef.genericparas) then
  723. internalerror(2013092601);
  724. if context.genericdeflist.count<>genericdef.genericparas.count then
  725. internalerror(2013092603);
  726. for i:=0 to genericdef.genericparas.Count-1 do
  727. begin
  728. srsym:=tsym(genericdef.genericparas[i]);
  729. if not (sp_generic_para in srsym.symoptions) then
  730. internalerror(2013092602);
  731. generictypelist.add(srsym.realname,tdef(context.genericdeflist[i]).typesym);
  732. end;
  733. { Special case if we are referencing the current defined object }
  734. if assigned(current_structdef) and
  735. (current_structdef.objname^=ufinalspecializename) then
  736. result:=current_structdef;
  737. { Can we reuse an already specialized type? }
  738. { for this first check whether we are currently specializing a nested
  739. type of the current (main) specialization (this is necessary, because
  740. during that time the symbol of the main specialization will still
  741. contain a reference to an errordef) }
  742. if not assigned(result) and assigned(current_specializedef) then
  743. begin
  744. def:=current_specializedef;
  745. repeat
  746. if def.typ in [objectdef,recorddef] then
  747. if tabstractrecorddef(def).objname^=ufinalspecializename then begin
  748. result:=def;
  749. break;
  750. end;
  751. if assigned(def.owner) then
  752. def:=tstoreddef(def.owner.defowner)
  753. else
  754. { this can happen when specializing a generic function }
  755. def:=nil;
  756. until not assigned(def) or not (df_specialization in def.defoptions);
  757. end;
  758. { if the genericdef is the def we are currently parsing (or one of its parents) then we can
  759. not use it for specializing as the tokenbuffer is not yet set (and we aren't done with
  760. parsing anyway), so for now we treat those still as generic defs without doing a partial
  761. specialization }
  762. if not assigned(result) then
  763. begin
  764. def:=current_genericdef;
  765. while assigned(def) and (def.typ in [recorddef,objectdef]) do
  766. begin
  767. if (df_generic in def.defoptions) and (def=genericdef) then
  768. begin
  769. result:=def;
  770. break;
  771. end;
  772. { the following happens when a routine with its parent struct
  773. as parameter is specialized as a parameter or result of a
  774. generic function }
  775. if (df_specialization in def.defoptions) and (tstoreddef(def).genericdef=genericdef) then
  776. begin
  777. if tstoreddef(def).genericparas.count=generictypelist.count then
  778. begin
  779. allequal:=true;
  780. for i:=0 to generictypelist.count-1 do
  781. begin
  782. if not equal_defs(ttypesym(generictypelist[i]).typedef,ttypesym(tstoreddef(def).genericparas[i]).typedef) then
  783. begin
  784. allequal:=false;
  785. break;
  786. end;
  787. end;
  788. if allequal then
  789. begin
  790. result:=def;
  791. break;
  792. end;
  793. end;
  794. end;
  795. def:=tstoreddef(def.owner.defowner);
  796. end;
  797. end;
  798. { decide in which symtable to put the specialization }
  799. if parse_generic and not assigned(result) then
  800. begin
  801. if assigned(current_procinfo) and (df_generic in current_procinfo.procdef.defoptions) then
  802. { if we are parsing the definition of a method we specialize into
  803. the local symtable of it }
  804. specializest:=current_procinfo.procdef.getsymtable(gs_local)
  805. else
  806. begin
  807. if not assigned(current_genericdef) then
  808. internalerror(2014050901);
  809. { we specialize the partial specialization into the symtable of the currently parsed
  810. generic }
  811. case current_genericdef.typ of
  812. procvardef:
  813. specializest:=current_genericdef.getsymtable(gs_para);
  814. procdef:
  815. specializest:=current_genericdef.getsymtable(gs_local);
  816. objectdef,
  817. recorddef:
  818. specializest:=current_genericdef.getsymtable(gs_record);
  819. arraydef:
  820. specializest:=tarraydef(current_genericdef).symtable;
  821. else
  822. internalerror(2014050902);
  823. end;
  824. end;
  825. end
  826. else
  827. if current_module.is_unit and current_module.in_interface then
  828. specializest:=current_module.globalsymtable
  829. else
  830. specializest:=current_module.localsymtable;
  831. if not assigned(specializest) then
  832. internalerror(2014050910);
  833. { now check whether there is a specialization somewhere else }
  834. psym:=nil;
  835. if not assigned(result) then
  836. begin
  837. hashedid.id:=ufinalspecializename;
  838. if specializest.symtabletype=objectsymtable then
  839. begin
  840. { search also in parent classes }
  841. if not assigned(current_genericdef) or (current_genericdef.typ<>objectdef) then
  842. internalerror(2016112901);
  843. if not searchsym_in_class(tobjectdef(current_genericdef),tobjectdef(current_genericdef),ufinalspecializename,srsym,srsymtable,[]) then
  844. srsym:=nil;
  845. end
  846. else
  847. srsym:=tsym(specializest.findwithhash(hashedid));
  848. if assigned(srsym) then
  849. begin
  850. retrieve_genericdef_or_procsym(srsym,result,psym);
  851. end
  852. else
  853. { the generic could have been specialized in the globalsymtable
  854. already, so search there as well }
  855. if (specializest<>current_module.globalsymtable) and assigned(current_module.globalsymtable) then
  856. begin
  857. srsym:=tsym(current_module.globalsymtable.findwithhash(hashedid));
  858. if assigned(srsym) then
  859. begin
  860. retrieve_genericdef_or_procsym(srsym,result,psym);
  861. end;
  862. end;
  863. end;
  864. if not assigned(result) then
  865. begin
  866. specialization_init(genericdef,state);
  867. { push a temporary global symtable so that the specialization is
  868. added to the correct symtable; this symtable does not contain
  869. any other symbols, so that the type resolution can not be
  870. influenced by symbols in the current unit }
  871. tempst:=tspecializesymtable.create(current_module.modulename^,current_module.moduleid);
  872. symtablestack.push(tempst);
  873. { Reparse the original type definition }
  874. begin
  875. old_current_specializedef:=nil;
  876. old_current_genericdef:=nil;
  877. old_current_structdef:=nil;
  878. old_current_procinfo:=current_procinfo;
  879. current_procinfo:=nil;
  880. if parse_class_parent then
  881. begin
  882. old_current_structdef:=current_structdef;
  883. old_current_genericdef:=current_genericdef;
  884. old_current_specializedef:=current_specializedef;
  885. if genericdef.owner.symtabletype in [recordsymtable,objectsymtable] then
  886. current_structdef:=tabstractrecorddef(genericdef.owner.defowner)
  887. else
  888. current_structdef:=nil;
  889. current_genericdef:=nil;
  890. current_specializedef:=nil;
  891. end;
  892. maybe_add_waiting_unit(genericdef);
  893. { First a new sym so we can reuse this specialization and
  894. references to this specialization can be handled }
  895. if genericdef.typ=procdef then
  896. if assigned(psym) then
  897. srsym:=psym
  898. else
  899. srsym:=cprocsym.create(finalspecializename)
  900. else
  901. srsym:=ctypesym.create(finalspecializename,generrordef,true);
  902. { insert the symbol only if we don't know already that we have
  903. a procsym to add it to }
  904. if not assigned(psym) then
  905. specializest.insert(srsym);
  906. { specializations are declarations as such it is the wisest to
  907. declare set the blocktype to "type"; otherwise we'll
  908. experience unexpected side effects like the addition of
  909. classrefdefs if we have a generic that's derived from another
  910. generic }
  911. old_block_type:=block_type;
  912. block_type:=bt_type;
  913. if (
  914. (genericdef.typ=procdef) and
  915. not assigned(tprocdef(genericdef).genericdecltokenbuf)
  916. ) or (
  917. (genericdef.typ<>procdef) and
  918. not assigned(genericdef.generictokenbuf)
  919. ) then
  920. internalerror(200511171);
  921. hmodule:=find_module_from_symtable(genericdef.owner);
  922. if hmodule=nil then
  923. internalerror(2012051202);
  924. oldcurrent_filepos:=current_filepos;
  925. { use the index the module got from the current compilation process }
  926. current_filepos.moduleindex:=hmodule.unit_index;
  927. current_tokenpos:=current_filepos;
  928. if parse_generic then
  929. begin
  930. recordbuf:=current_scanner.recordtokenbuf;
  931. current_scanner.recordtokenbuf:=nil;
  932. end
  933. else
  934. recordbuf:=nil;
  935. replaydepth:=current_scanner.replay_stack_depth;
  936. if genericdef.typ=procdef then
  937. begin
  938. current_scanner.startreplaytokens(tprocdef(genericdef).genericdecltokenbuf);
  939. parse_proc_head(tprocdef(genericdef).struct,tprocdef(genericdef).proctypeoption,false,genericdef,generictypelist,pd);
  940. if assigned(pd) then
  941. begin
  942. if assigned(psym) then
  943. pd.procsym:=psym
  944. else
  945. pd.procsym:=srsym;
  946. parse_proc_dec_finish(pd,po_classmethod in tprocdef(genericdef).procoptions,tprocdef(genericdef).struct);
  947. end;
  948. result:=pd;
  949. end
  950. else
  951. begin
  952. current_scanner.startreplaytokens(genericdef.generictokenbuf);
  953. hadtypetoken:=false;
  954. read_named_type(result,srsym,genericdef,generictypelist,false,hadtypetoken);
  955. ttypesym(srsym).typedef:=result;
  956. result.typesym:=srsym;
  957. if _prettyname<>'' then
  958. ttypesym(result.typesym).fprettyname:=_prettyname
  959. else
  960. ttypesym(result.typesym).fprettyname:=prettyname;
  961. end;
  962. current_filepos:=oldcurrent_filepos;
  963. { Note regarding hint directives:
  964. There is no need to remove the flags for them from the
  965. specialized generic symbol, because hint directives that
  966. follow the specialization are handled by the code in
  967. pdecl.types_dec and added to the type symbol.
  968. E.g.: TFoo = TBar<Blubb> deprecated;
  969. Here the symbol TBar$1$Blubb will contain the
  970. "sp_hint_deprecated" flag while the TFoo symbol won't.}
  971. case result.typ of
  972. { Build VMT indexes for classes and read hint directives }
  973. objectdef:
  974. begin
  975. if replaydepth>current_scanner.replay_stack_depth then
  976. begin
  977. try_consume_hintdirective(srsym.symoptions,srsym.deprecatedmsg);
  978. if replaydepth>current_scanner.replay_stack_depth then
  979. consume(_SEMICOLON);
  980. end;
  981. vmtbuilder:=TVMTBuilder.Create(tobjectdef(result));
  982. vmtbuilder.generate_vmt;
  983. vmtbuilder.free;
  984. end;
  985. { handle params, calling convention, etc }
  986. procvardef:
  987. begin
  988. hintsprocessed:=false;
  989. if replaydepth>current_scanner.replay_stack_depth then
  990. begin
  991. if not check_proc_directive(true) then
  992. begin
  993. hintsprocessed:=try_consume_hintdirective(ttypesym(srsym).symoptions,ttypesym(srsym).deprecatedmsg);
  994. if replaydepth>current_scanner.replay_stack_depth then
  995. consume(_SEMICOLON);
  996. end
  997. else
  998. hintsprocessed:=true;
  999. end;
  1000. if replaydepth>current_scanner.replay_stack_depth then
  1001. parse_var_proc_directives(ttypesym(srsym));
  1002. handle_calling_convention(tprocvardef(result));
  1003. if not hintsprocessed and (replaydepth>current_scanner.replay_stack_depth) then
  1004. begin
  1005. try_consume_hintdirective(ttypesym(srsym).symoptions,ttypesym(srsym).deprecatedmsg);
  1006. if replaydepth>current_scanner.replay_stack_depth then
  1007. consume(_SEMICOLON);
  1008. end;
  1009. end;
  1010. procdef:
  1011. begin
  1012. pdflags:=[pd_body,pd_implemen];
  1013. if genericdef.owner.symtabletype=objectsymtable then
  1014. include(pdflags,pd_object)
  1015. else if genericdef.owner.symtabletype=recordsymtable then
  1016. include(pdflags,pd_record);
  1017. parse_proc_directives(pd,pdflags);
  1018. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  1019. consume(_SEMICOLON);
  1020. handle_calling_convention(tprocdef(result),hcc_all);
  1021. proc_add_definition(tprocdef(result));
  1022. { for partial specializations we implicitely declare the routine as
  1023. having its implementation although we'll not specialize it in reality }
  1024. if parse_generic then
  1025. unset_forwarddef(result);
  1026. end;
  1027. else
  1028. { parse hint directives for records and arrays }
  1029. if replaydepth>current_scanner.replay_stack_depth then begin
  1030. try_consume_hintdirective(srsym.symoptions,srsym.deprecatedmsg);
  1031. if replaydepth>current_scanner.replay_stack_depth then
  1032. consume(_SEMICOLON);
  1033. end;
  1034. end;
  1035. { Consume the remainder of the buffer }
  1036. while current_scanner.replay_stack_depth>replaydepth do
  1037. consume(token);
  1038. if assigned(recordbuf) then
  1039. begin
  1040. if assigned(current_scanner.recordtokenbuf) then
  1041. internalerror(2014050909);
  1042. current_scanner.recordtokenbuf:=recordbuf;
  1043. end;
  1044. block_type:=old_block_type;
  1045. current_procinfo:=old_current_procinfo;
  1046. if parse_class_parent then
  1047. begin
  1048. current_structdef:=old_current_structdef;
  1049. current_genericdef:=old_current_genericdef;
  1050. current_specializedef:=old_current_specializedef;
  1051. end;
  1052. end;
  1053. { extract all created symbols and defs from the temporary symtable
  1054. and add them to the specializest }
  1055. for i:=tempst.SymList.Count-1 downto 0 do
  1056. begin
  1057. item:=tempst.SymList.Items[i];
  1058. { using changeowner the symbol is automatically added to the
  1059. new symtable }
  1060. tsym(item).ChangeOwner(specializest);
  1061. end;
  1062. for i:=tempst.DefList.Count-1 downto 0 do
  1063. begin
  1064. item:=tempst.DefList.Items[i];
  1065. { using changeowner the def is automatically added to the new
  1066. symtable }
  1067. tdef(item).ChangeOwner(specializest);
  1068. { for partial specializations we implicitely declare any methods as having their
  1069. implementations although we'll not specialize them in reality }
  1070. if parse_generic then
  1071. unset_forwarddef(tdef(item));
  1072. end;
  1073. { if a generic was declared during the specialization we need to
  1074. flag the specialize symtable accordingly }
  1075. if sto_has_generic in tempst.tableoptions then
  1076. specializest.includeoption(sto_has_generic);
  1077. tempst.free;
  1078. specialization_done(state);
  1079. { procdefs are only added once we know which overload we use }
  1080. if not parse_generic and (result.typ<>procdef) then
  1081. current_module.pendingspecializations.add(result.typename,result);
  1082. end;
  1083. generictypelist.free;
  1084. if assigned(genericdef) then
  1085. begin
  1086. { check the hints of the found generic symbol }
  1087. if genericdef.typ=procdef then
  1088. srsym:=tprocdef(genericdef).procsym
  1089. else
  1090. srsym:=genericdef.typesym;
  1091. check_hints(srsym,srsym.symoptions,srsym.deprecatedmsg);
  1092. end;
  1093. end;
  1094. procedure generate_specialization(var tt:tdef;parse_class_parent:boolean;_prettyname:string;parsedtype:tdef;symname:string;parsedpos:tfileposinfo);
  1095. var
  1096. context : tspecializationcontext;
  1097. genericdef : tstoreddef;
  1098. begin
  1099. genericdef:=tstoreddef(generate_specialization_phase1(context,tt,parsedtype,symname,parsedpos));
  1100. if genericdef<>generrordef then
  1101. genericdef:=tstoreddef(generate_specialization_phase2(context,genericdef,parse_class_parent,_prettyname));
  1102. tt:=genericdef;
  1103. if assigned(context) then
  1104. context.free;
  1105. end;
  1106. function parse_generic_parameters(allowconstraints:boolean):tfphashobjectlist;
  1107. var
  1108. generictype : ttypesym;
  1109. i,firstidx : longint;
  1110. srsymtable : tsymtable;
  1111. basedef,def : tdef;
  1112. defname : tidstring;
  1113. allowconstructor,
  1114. doconsume : boolean;
  1115. constraintdata : tgenericconstraintdata;
  1116. old_block_type : tblock_type;
  1117. begin
  1118. result:=tfphashobjectlist.create(false);
  1119. firstidx:=0;
  1120. old_block_type:=block_type;
  1121. block_type:=bt_type;
  1122. repeat
  1123. if token=_ID then
  1124. begin
  1125. generictype:=ctypesym.create(orgpattern,cundefinedtype,false);
  1126. { type parameters need to be added as strict private }
  1127. generictype.visibility:=vis_strictprivate;
  1128. include(generictype.symoptions,sp_generic_para);
  1129. result.add(orgpattern,generictype);
  1130. end;
  1131. consume(_ID);
  1132. if try_to_consume(_COLON) then
  1133. begin
  1134. if not allowconstraints then
  1135. { TODO }
  1136. Message(parser_e_illegal_expression{ parser_e_generic_constraints_not_allowed_here});
  1137. { construct a name which can be used for a type specification }
  1138. constraintdata:=tgenericconstraintdata.create;
  1139. defname:='';
  1140. str(current_module.deflist.count,defname);
  1141. defname:='$gendef'+defname;
  1142. allowconstructor:=m_delphi in current_settings.modeswitches;
  1143. basedef:=generrordef;
  1144. repeat
  1145. doconsume:=true;
  1146. case token of
  1147. _CONSTRUCTOR:
  1148. begin
  1149. if not allowconstructor or (gcf_constructor in constraintdata.flags) then
  1150. Message(parser_e_illegal_expression);
  1151. include(constraintdata.flags,gcf_constructor);
  1152. allowconstructor:=false;
  1153. end;
  1154. _CLASS:
  1155. begin
  1156. if gcf_class in constraintdata.flags then
  1157. Message(parser_e_illegal_expression);
  1158. if basedef=generrordef then
  1159. include(constraintdata.flags,gcf_class)
  1160. else
  1161. Message(parser_e_illegal_expression);
  1162. end;
  1163. _RECORD:
  1164. begin
  1165. if ([gcf_constructor,gcf_class]*constraintdata.flags<>[])
  1166. or (constraintdata.interfaces.count>0) then
  1167. Message(parser_e_illegal_expression)
  1168. else
  1169. begin
  1170. srsymtable:=trecordsymtable.create(defname,0,1,1);
  1171. basedef:=crecorddef.create(defname,srsymtable);
  1172. include(constraintdata.flags,gcf_record);
  1173. allowconstructor:=false;
  1174. end;
  1175. end;
  1176. else
  1177. begin
  1178. { after single_type "token" is the trailing ",", ";" or
  1179. ">"! }
  1180. doconsume:=false;
  1181. { def is already set to a class or record }
  1182. if gcf_record in constraintdata.flags then
  1183. Message(parser_e_illegal_expression);
  1184. single_type(def, [stoAllowSpecialization]);
  1185. { only types that are inheritable are allowed }
  1186. if (def.typ<>objectdef) or
  1187. not (tobjectdef(def).objecttype in [odt_class,odt_interfacecom,odt_interfacecorba,odt_interfacejava,odt_javaclass]) then
  1188. Message1(type_e_class_or_interface_type_expected,def.typename)
  1189. else
  1190. case tobjectdef(def).objecttype of
  1191. odt_class,
  1192. odt_javaclass:
  1193. begin
  1194. if gcf_class in constraintdata.flags then
  1195. { "class" + concrete class is not allowed }
  1196. Message(parser_e_illegal_expression)
  1197. else
  1198. { do we already have a concrete class? }
  1199. if basedef<>generrordef then
  1200. Message(parser_e_illegal_expression)
  1201. else
  1202. basedef:=def;
  1203. end;
  1204. odt_interfacecom,
  1205. odt_interfacecorba,
  1206. odt_interfacejava,
  1207. odt_dispinterface:
  1208. constraintdata.interfaces.add(def);
  1209. end;
  1210. end;
  1211. end;
  1212. if doconsume then
  1213. consume(token);
  1214. until not try_to_consume(_COMMA);
  1215. if ([gcf_class,gcf_constructor]*constraintdata.flags<>[]) or
  1216. (constraintdata.interfaces.count>1) or
  1217. (
  1218. (basedef.typ=objectdef) and
  1219. (tobjectdef(basedef).objecttype in [odt_javaclass,odt_class])
  1220. ) then
  1221. begin
  1222. if basedef.typ=errordef then
  1223. { don't pass an errordef as a parent to a tobjectdef }
  1224. basedef:=class_tobject
  1225. else
  1226. if (basedef.typ<>objectdef) or
  1227. not (tobjectdef(basedef).objecttype in [odt_javaclass,odt_class]) then
  1228. internalerror(2012101101);
  1229. basedef:=cobjectdef.create(tobjectdef(basedef).objecttype,defname,tobjectdef(basedef),false);
  1230. for i:=0 to constraintdata.interfaces.count-1 do
  1231. tobjectdef(basedef).implementedinterfaces.add(
  1232. timplementedinterface.create(tobjectdef(constraintdata.interfaces[i])));
  1233. end
  1234. else
  1235. if constraintdata.interfaces.count=1 then
  1236. begin
  1237. if basedef.typ<>errordef then
  1238. internalerror(2013021601);
  1239. def:=tdef(constraintdata.interfaces[0]);
  1240. basedef:=cobjectdef.create(tobjectdef(def).objecttype,defname,tobjectdef(def),false);
  1241. constraintdata.interfaces.delete(0);
  1242. end;
  1243. if basedef.typ<>errordef then
  1244. with tstoreddef(basedef) do
  1245. begin
  1246. genconstraintdata:=tgenericconstraintdata.create;
  1247. genconstraintdata.flags:=constraintdata.flags;
  1248. genconstraintdata.interfaces.assign(constraintdata.interfaces);
  1249. include(defoptions,df_genconstraint);
  1250. end;
  1251. for i:=firstidx to result.count-1 do
  1252. ttypesym(result[i]).typedef:=basedef;
  1253. { we need a typesym in case we do a Delphi-mode inline
  1254. specialization with this parameter; so just use the first sym }
  1255. if not assigned(basedef.typesym) then
  1256. basedef.typesym:=ttypesym(result[firstidx]);
  1257. firstidx:=result.count;
  1258. constraintdata.free;
  1259. end
  1260. else
  1261. begin
  1262. if token=_SEMICOLON then
  1263. begin
  1264. { two different typeless parameters are considered as incompatible }
  1265. for i:=firstidx to result.count-1 do
  1266. begin
  1267. ttypesym(result[i]).typedef:=cundefineddef.create(false);
  1268. ttypesym(result[i]).typedef.typesym:=ttypesym(result[i]);
  1269. end;
  1270. { a semicolon terminates a type parameter group }
  1271. firstidx:=result.count;
  1272. end;
  1273. end;
  1274. until not (try_to_consume(_COMMA) or try_to_consume(_SEMICOLON));
  1275. { two different typeless parameters are considered as incompatible }
  1276. for i:=firstidx to result.count-1 do
  1277. begin
  1278. ttypesym(result[i]).typedef:=cundefineddef.create(false);
  1279. ttypesym(result[i]).typedef.typesym:=ttypesym(result[i]);
  1280. end;
  1281. block_type:=old_block_type;
  1282. end;
  1283. procedure insert_generic_parameter_types(def:tstoreddef;genericdef:tstoreddef;genericlist:tfphashobjectlist);
  1284. var
  1285. i : longint;
  1286. generictype,sym : ttypesym;
  1287. st : tsymtable;
  1288. begin
  1289. def.genericdef:=genericdef;
  1290. if not assigned(genericlist) then
  1291. exit;
  1292. if assigned(genericdef) then
  1293. include(def.defoptions,df_specialization)
  1294. else
  1295. if genericlist.count>0 then
  1296. include(def.defoptions,df_generic);
  1297. case def.typ of
  1298. recorddef,objectdef: st:=tabstractrecorddef(def).symtable;
  1299. arraydef: st:=tarraydef(def).symtable;
  1300. procvardef,procdef: st:=tabstractprocdef(def).parast;
  1301. else
  1302. internalerror(201101020);
  1303. end;
  1304. if (genericlist.count>0) and not assigned(def.genericparas) then
  1305. def.genericparas:=tfphashobjectlist.create(false);
  1306. for i:=0 to genericlist.count-1 do
  1307. begin
  1308. generictype:=ttypesym(genericlist[i]);
  1309. if assigned(generictype.owner) then
  1310. begin
  1311. sym:=ctypesym.create(genericlist.nameofindex(i),generictype.typedef,true);
  1312. { type parameters need to be added as strict private }
  1313. sym.visibility:=vis_strictprivate;
  1314. st.insert(sym);
  1315. include(sym.symoptions,sp_generic_para);
  1316. end
  1317. else
  1318. begin
  1319. if (generictype.typedef.typ=undefineddef) and (generictype.typedef<>cundefinedtype) then
  1320. begin
  1321. { the generic parameters were parsed before the genericdef existed thus the
  1322. undefineddefs were added as part of the parent symtable }
  1323. if assigned(generictype.typedef.owner) then
  1324. generictype.typedef.owner.DefList.Extract(generictype.typedef);
  1325. generictype.typedef.changeowner(st);
  1326. end;
  1327. st.insert(generictype);
  1328. include(generictype.symoptions,sp_generic_para);
  1329. end;
  1330. def.genericparas.add(genericlist.nameofindex(i),generictype);
  1331. end;
  1332. end;
  1333. procedure maybe_insert_generic_rename_symbol(const name:tidstring;genericlist:tfphashobjectlist);
  1334. var
  1335. gensym : ttypesym;
  1336. begin
  1337. { for generics in non-Delphi modes we insert a private type symbol
  1338. that has the same base name as the currently parsed generic and
  1339. that references this defs }
  1340. if not (m_delphi in current_settings.modeswitches) and
  1341. (
  1342. (
  1343. parse_generic and
  1344. assigned(genericlist) and
  1345. (genericlist.count>0)
  1346. ) or
  1347. (
  1348. assigned(current_specializedef) and
  1349. assigned(current_structdef.genericdef) and
  1350. (current_structdef.genericdef.typ in [objectdef,recorddef]) and
  1351. (pos('$',name)>0)
  1352. )
  1353. ) then
  1354. begin
  1355. { we need to pass nil as def here, because the constructor wants
  1356. to set the typesym of the def which is not what we want }
  1357. gensym:=ctypesym.create(copy(name,1,pos('$',name)-1),nil,true);
  1358. gensym.typedef:=current_structdef;
  1359. include(gensym.symoptions,sp_internal);
  1360. { the symbol should be only visible to the generic class
  1361. itself }
  1362. gensym.visibility:=vis_strictprivate;
  1363. symtablestack.top.insert(gensym);
  1364. end;
  1365. end;
  1366. function generate_generic_name(const name:tidstring;specializename:ansistring;owner_hierarchy:string):tidstring;
  1367. var
  1368. crc : cardinal;
  1369. begin
  1370. if specializename='' then
  1371. internalerror(2012061901);
  1372. { build the new type's name }
  1373. crc:=UpdateCrc32(0,specializename[1],length(specializename));
  1374. result:=name+'$crc'+hexstr(crc,8);
  1375. if owner_hierarchy<>'' then
  1376. begin
  1377. crc:=UpdateCrc32(0,owner_hierarchy[1],length(owner_hierarchy));
  1378. result:=result+'$crc'+hexstr(crc,8);
  1379. end;
  1380. end;
  1381. procedure split_generic_name(const name:tidstring;out nongeneric:string;out count:longint);
  1382. var
  1383. i,code : longint;
  1384. countstr : string;
  1385. begin
  1386. for i:=length(name) downto 1 do
  1387. if name[i]='$' then
  1388. begin
  1389. nongeneric:=copy(name,1,i-1);
  1390. countstr:=copy(name,i+1,length(name)-i);
  1391. val(countstr,count,code);
  1392. if code<>0 then
  1393. break;
  1394. exit;
  1395. end;
  1396. nongeneric:=name;
  1397. count:=0;
  1398. end;
  1399. function resolve_generic_dummysym(const name:tidstring):tsym;
  1400. var
  1401. list : tfpobjectlist;
  1402. begin
  1403. list:=tfpobjectlist(current_module.genericdummysyms.find(name));
  1404. if assigned(list) and (list.count>0) then
  1405. result:=tgenericdummyentry(list.last).resolvedsym
  1406. else
  1407. result:=nil;
  1408. end;
  1409. function could_be_generic(const name:tidstring):boolean;
  1410. begin
  1411. result:=(name<>'') and
  1412. (current_module.genericdummysyms.findindexof(name)>=0);
  1413. end;
  1414. procedure specialization_init(genericdef:tdef;var state: tspecializationstate);
  1415. var
  1416. pu : tused_unit;
  1417. hmodule : tmodule;
  1418. unitsyms : TFPHashObjectList;
  1419. sym : tsym;
  1420. i : Integer;
  1421. begin
  1422. if not assigned(genericdef) then
  1423. internalerror(200705151);
  1424. { Setup symtablestack at definition time
  1425. to get types right, however this is not perfect, we should probably record
  1426. the resolved symbols }
  1427. state.oldsymtablestack:=symtablestack;
  1428. state.oldextendeddefs:=current_module.extendeddefs;
  1429. state.oldgenericdummysyms:=current_module.genericdummysyms;
  1430. current_module.extendeddefs:=TFPHashObjectList.create(true);
  1431. current_module.genericdummysyms:=tfphashobjectlist.create(true);
  1432. symtablestack:=tdefawaresymtablestack.create;
  1433. hmodule:=find_module_from_symtable(genericdef.owner);
  1434. if hmodule=nil then
  1435. internalerror(200705152);
  1436. { collect all unit syms in the generic's unit as we need to establish
  1437. their unitsym.module link again so that unit identifiers can be used }
  1438. unitsyms:=tfphashobjectlist.create(false);
  1439. if (hmodule<>current_module) and assigned(hmodule.globalsymtable) then
  1440. for i:=0 to hmodule.globalsymtable.symlist.count-1 do
  1441. begin
  1442. sym:=tsym(hmodule.globalsymtable.symlist[i]);
  1443. if sym.typ=unitsym then
  1444. unitsyms.add(upper(sym.realname),sym);
  1445. end;
  1446. { add all units if we are specializing inside the current unit (as the
  1447. generic could have been declared in the implementation part), but load
  1448. only interface units, if we are in a different unit as then the generic
  1449. needs to be in the interface section }
  1450. pu:=tused_unit(hmodule.used_units.first);
  1451. while assigned(pu) do
  1452. begin
  1453. if not assigned(pu.u.globalsymtable) then
  1454. { in certain circular, but valid unit constellations it can happen
  1455. that we specialize a generic in a different unit that was used
  1456. in the implementation section of the generic's unit and were the
  1457. interface is still being parsed and thus the localsymtable is in
  1458. reality the global symtable }
  1459. if pu.u.in_interface then
  1460. symtablestack.push(pu.u.localsymtable)
  1461. else
  1462. internalerror(200705153)
  1463. else
  1464. symtablestack.push(pu.u.globalsymtable);
  1465. sym:=tsym(unitsyms.find(pu.u.modulename^));
  1466. if assigned(sym) and not assigned(tunitsym(sym).module) then
  1467. tunitsym(sym).module:=pu.u;
  1468. pu:=tused_unit(pu.next);
  1469. end;
  1470. unitsyms.free;
  1471. if assigned(hmodule.globalsymtable) then
  1472. symtablestack.push(hmodule.globalsymtable);
  1473. { push the localsymtable if needed }
  1474. if ((hmodule<>current_module) or not current_module.in_interface)
  1475. and assigned(hmodule.localsymtable) then
  1476. symtablestack.push(hmodule.localsymtable);
  1477. end;
  1478. procedure specialization_done(var state: tspecializationstate);
  1479. begin
  1480. { Restore symtablestack }
  1481. current_module.extendeddefs.free;
  1482. current_module.extendeddefs:=state.oldextendeddefs;
  1483. current_module.genericdummysyms.free;
  1484. current_module.genericdummysyms:=state.oldgenericdummysyms;
  1485. symtablestack.free;
  1486. symtablestack:=state.oldsymtablestack;
  1487. { clear the state record to be on the safe side }
  1488. fillchar(state, sizeof(state), 0);
  1489. end;
  1490. {****************************************************************************
  1491. SPECIALIZATION BODY GENERATION
  1492. ****************************************************************************}
  1493. procedure process_procdef(def:tprocdef;hmodule:tmodule);
  1494. var
  1495. oldcurrent_filepos : tfileposinfo;
  1496. begin
  1497. if assigned(def.genericdef) and
  1498. (def.genericdef.typ=procdef) and
  1499. assigned(tprocdef(def.genericdef).generictokenbuf) then
  1500. begin
  1501. if not assigned(tprocdef(def.genericdef).generictokenbuf) then
  1502. internalerror(2015061902);
  1503. oldcurrent_filepos:=current_filepos;
  1504. current_filepos:=tprocdef(def.genericdef).fileinfo;
  1505. { use the index the module got from the current compilation process }
  1506. current_filepos.moduleindex:=hmodule.unit_index;
  1507. current_tokenpos:=current_filepos;
  1508. current_scanner.startreplaytokens(tprocdef(def.genericdef).generictokenbuf);
  1509. read_proc_body(def);
  1510. current_filepos:=oldcurrent_filepos;
  1511. end
  1512. { synthetic routines will be implemented afterwards }
  1513. else if def.synthetickind=tsk_none then
  1514. MessagePos1(def.fileinfo,sym_e_forward_not_resolved,def.fullprocname(false));
  1515. end;
  1516. function process_abstractrecorddef(def:tabstractrecorddef):boolean;
  1517. var
  1518. i : longint;
  1519. hp : tdef;
  1520. hmodule : tmodule;
  1521. begin
  1522. result:=true;
  1523. hmodule:=find_module_from_symtable(def.genericdef.owner);
  1524. if hmodule=nil then
  1525. internalerror(201202041);
  1526. for i:=0 to def.symtable.DefList.Count-1 do
  1527. begin
  1528. hp:=tdef(def.symtable.DefList[i]);
  1529. if hp.typ=procdef then
  1530. begin
  1531. { only generate the code if we need a body }
  1532. if assigned(tprocdef(hp).struct) and not tprocdef(hp).forwarddef then
  1533. continue;
  1534. { and the body is available already (which is implicitely the
  1535. case if the generic routine is part of another unit) }
  1536. if ((hmodule=current_module) or (hmodule.state=ms_compile)) and
  1537. { may not be assigned in case it's a synthetic procdef that
  1538. still needs to be generated }
  1539. assigned(tprocdef(hp).genericdef) and
  1540. tprocdef(tprocdef(hp).genericdef).forwarddef then
  1541. begin
  1542. result:=false;
  1543. continue;
  1544. end;
  1545. process_procdef(tprocdef(hp),hmodule);
  1546. end
  1547. else
  1548. if hp.typ in [objectdef,recorddef] then
  1549. { generate code for subtypes as well }
  1550. result:=process_abstractrecorddef(tabstractrecorddef(hp)) and result;
  1551. end;
  1552. end;
  1553. procedure generate_specialization_procs;
  1554. var
  1555. i : longint;
  1556. list,
  1557. readdlist : tfpobjectlist;
  1558. def : tstoreddef;
  1559. state : tspecializationstate;
  1560. hmodule : tmodule;
  1561. begin
  1562. { first copy all entries and then work with that list to ensure that
  1563. we don't get an infinite recursion }
  1564. list:=tfpobjectlist.create(false);
  1565. readdlist:=tfpobjectlist.create(false);
  1566. for i:=0 to current_module.pendingspecializations.Count-1 do
  1567. list.add(current_module.pendingspecializations.Items[i]);
  1568. current_module.pendingspecializations.clear;
  1569. for i:=0 to list.count-1 do
  1570. begin
  1571. def:=tstoreddef(list[i]);
  1572. if not tstoreddef(def).is_specialization then
  1573. continue;
  1574. case def.typ of
  1575. procdef:
  1576. begin
  1577. { the use of forwarddef should not backfire as the
  1578. specialization always belongs to the current module }
  1579. if not tprocdef(def).forwarddef then
  1580. continue;
  1581. if not assigned(def.genericdef) then
  1582. internalerror(2015061903);
  1583. hmodule:=find_module_from_symtable(def.genericdef.owner);
  1584. if hmodule=nil then
  1585. internalerror(2015061904);
  1586. { we need to check for a forward declaration only if the
  1587. generic was declared in the same unit (otherwise there
  1588. should be one) }
  1589. if ((hmodule=current_module) or (hmodule.state=ms_compile)) and tprocdef(def.genericdef).forwarddef then
  1590. begin
  1591. readdlist.add(def);
  1592. continue;
  1593. end;
  1594. specialization_init(tstoreddef(def).genericdef,state);
  1595. process_procdef(tprocdef(def),hmodule);
  1596. specialization_done(state);
  1597. end;
  1598. recorddef,
  1599. objectdef:
  1600. begin
  1601. specialization_init(tstoreddef(def).genericdef,state);
  1602. if not process_abstractrecorddef(tabstractrecorddef(def)) then
  1603. readdlist.add(def);
  1604. specialization_done(state);
  1605. end;
  1606. end;
  1607. end;
  1608. { add those defs back to the pending list for which we don't yet have
  1609. all method bodies }
  1610. for i:=0 to readdlist.count-1 do
  1611. current_module.pendingspecializations.add(tstoreddef(readdlist[i]).typename,readdlist[i]);
  1612. readdlist.free;
  1613. list.free;
  1614. end;
  1615. procedure maybe_add_pending_specialization(def:tdef);
  1616. var
  1617. hmodule : tmodule;
  1618. st : tsymtable;
  1619. begin
  1620. if parse_generic then
  1621. exit;
  1622. st:=def.owner;
  1623. while st.symtabletype in [localsymtable] do
  1624. st:=st.defowner.owner;
  1625. hmodule:=find_module_from_symtable(st);
  1626. if tstoreddef(def).is_specialization and (hmodule=current_module) then
  1627. current_module.pendingspecializations.add(def.typename,def);
  1628. end;
  1629. end.