nobj.pas 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl
  3. Routines for the code generation of data structures
  4. like VMT, Messages, VTables, Interfaces descs
  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 nobj;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. cutils,cclasses,
  23. globtype,
  24. symdef,symsym
  25. ;
  26. type
  27. TVMTBuilder=class
  28. private
  29. _Class : tobjectdef;
  30. handledprotocols: tfpobjectlist;
  31. function is_new_vmt_entry(pd:tprocdef; out overridesclasshelper: boolean):boolean;
  32. procedure add_new_vmt_entry(pd:tprocdef; allowoverridingmethod: boolean);
  33. function check_msg_str(vmtpd, pd: tprocdef):boolean;
  34. function intf_search_procdef_by_name(proc: tprocdef;const name: string): tprocdef;
  35. procedure intf_get_procdefs(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  36. procedure intf_get_procdefs_recursive(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  37. procedure prot_get_procdefs_recursive(ImplProt:TImplementedInterface;ProtDef:TObjectDef);
  38. procedure intf_optimize_vtbls;
  39. procedure intf_allocate_vtbls;
  40. procedure generate_vmt_def;
  41. public
  42. constructor create(c:tobjectdef);
  43. procedure generate_vmt;
  44. procedure build_interface_mappings;
  45. end;
  46. implementation
  47. uses
  48. SysUtils,
  49. globals,verbose,systems,fmodule,
  50. node,
  51. symbase,symtable,symconst,symtype,defcmp,defutil,
  52. symcpu,
  53. dbgbase,
  54. wpobase
  55. ;
  56. {*****************************************************************************
  57. TVMTBuilder
  58. *****************************************************************************}
  59. constructor TVMTBuilder.create(c:tobjectdef);
  60. begin
  61. inherited Create;
  62. _Class:=c;
  63. end;
  64. procedure TVMTBuilder.add_new_vmt_entry(pd:tprocdef; allowoverridingmethod: boolean);
  65. var
  66. i : longint;
  67. vmtentry : pvmtentry;
  68. vmtpd : tprocdef;
  69. begin
  70. { new entry is needed, override was not possible }
  71. { Allowed when overriding a category method for a parent class in a
  72. descendent Objective-C class }
  73. if not allowoverridingmethod and
  74. (po_overridingmethod in pd.procoptions) then
  75. MessagePos1(pd.fileinfo,parser_e_nothing_to_be_overridden,pd.fullprocname(false));
  76. { check that all methods have overload directive }
  77. if not(m_fpc in current_settings.modeswitches) then
  78. begin
  79. for i:=0 to _class.vmtentries.count-1 do
  80. begin
  81. vmtentry:=pvmtentry(_class.vmtentries[i]);
  82. vmtpd:=tprocdef(vmtentry^.procdef);
  83. if (vmtpd.procsym=pd.procsym) and
  84. (not(po_overload in pd.procoptions) or
  85. not(po_overload in vmtpd.procoptions)) then
  86. begin
  87. MessagePos1(pd.fileinfo,parser_e_no_overload_for_all_procs,pd.procsym.realname);
  88. { recover }
  89. include(vmtpd.procoptions,po_overload);
  90. include(pd.procoptions,po_overload);
  91. end;
  92. end;
  93. end;
  94. { Register virtual method and give it a number }
  95. if (po_virtualmethod in pd.procoptions) then
  96. begin
  97. { store vmt entry number in procdef }
  98. if (pd.extnumber<>$ffff) and
  99. (pd.extnumber<>_class.VMTEntries.Count) then
  100. internalerror(200810283);
  101. pd.extnumber:=_class.VMTEntries.Count;
  102. new(vmtentry);
  103. vmtentry^.procdef:=pd;
  104. vmtentry^.procdefderef.reset;
  105. vmtentry^.visibility:=pd.visibility;
  106. _class.VMTEntries.Add(vmtentry);
  107. end;
  108. end;
  109. function TVMTBuilder.check_msg_str(vmtpd, pd: tprocdef): boolean;
  110. begin
  111. result:=true;
  112. if not(is_objc_class_or_protocol(_class)) then
  113. begin
  114. { the only requirement for normal methods is that both either
  115. have a message string or not (the value is irrelevant) }
  116. if ((pd.procoptions * [po_msgstr]) <> (vmtpd.procoptions * [po_msgstr])) then
  117. begin
  118. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  119. tprocsym(vmtpd.procsym).write_parameter_lists(pd);
  120. result:=false;
  121. end
  122. end
  123. else
  124. begin
  125. { the compiler should have ensured that the protocol or parent
  126. class method has a message name specified }
  127. if not(po_msgstr in vmtpd.procoptions) then
  128. internalerror(2009070601);
  129. if not(po_msgstr in pd.procoptions) then
  130. begin
  131. { copy the protocol's/parent class' message name to the one in
  132. the class if none has been specified there }
  133. include(pd.procoptions,po_msgstr);
  134. pd.messageinf.str:=stringdup(vmtpd.messageinf.str^);
  135. end
  136. else
  137. begin
  138. { if both have a message name, make sure they are equal }
  139. if (vmtpd.messageinf.str^<>pd.messageinf.str^) then
  140. begin
  141. MessagePos2(pd.fileinfo,parser_e_objc_message_name_changed,vmtpd.messageinf.str^,pd.messageinf.str^);
  142. result:=false;
  143. end;
  144. end;
  145. end;
  146. end;
  147. function TVMTBuilder.is_new_vmt_entry(pd:tprocdef; out overridesclasshelper: boolean):boolean;
  148. const
  149. po_comp = [po_classmethod,po_virtualmethod,po_staticmethod,po_interrupt,po_iocheck,po_msgint,
  150. po_exports,po_varargs,po_explicitparaloc,po_nostackframe];
  151. var
  152. i : longint;
  153. hasequalpara,
  154. hasoverloads,
  155. pdoverload : boolean;
  156. srsym : tsym;
  157. st : tsymtable;
  158. // returns true if we can stop checking, false if we have to continue
  159. function found_entry(var vmtpd: tprocdef; var vmtentryvis: tvisibility; updatevalues: boolean): boolean;
  160. {$ifdef jvm}
  161. var
  162. javanewtreeok: boolean;
  163. {$endif jvm}
  164. begin
  165. result:=false;
  166. { ignore hidden entries (e.g. virtual overridden by a static) that are not visible anymore }
  167. if vmtentryvis=vis_hidden then
  168. exit;
  169. { ignore different names }
  170. if vmtpd.procsym.name<>pd.procsym.name then
  171. exit;
  172. { hide private methods that are not visible anymore. For this check we
  173. must override the visibility with the highest value in the override chain.
  174. This is required for case (see tw3292) with protected-private-protected where the
  175. same vmtentry is used (PFV) }
  176. if not is_visible_for_object(vmtpd.owner,vmtentryvis,_class) then
  177. exit;
  178. { inherit overload }
  179. if (po_overload in vmtpd.procoptions) then
  180. begin
  181. include(pd.procoptions,po_overload);
  182. pdoverload:=true;
  183. end;
  184. { compare parameter types only, no specifiers yet }
  185. hasequalpara:=(compare_paras(vmtpd.paras,pd.paras,cp_none,[cpo_ignoreuniv,cpo_ignorehidden])>=te_equal);
  186. { check that we are not trying to override a final method }
  187. { in Java, new virtual inheritance trees can never be started ->
  188. treat all methods as "overriding" in the context of this check
  189. (Java does check whether the mangled names are identical, so if they
  190. are not we can stil get away with it) }
  191. if (po_finalmethod in vmtpd.procoptions) and
  192. hasequalpara and
  193. ((po_overridingmethod in pd.procoptions) or
  194. (is_javaclass(_class) and
  195. (pd.mangledname=vmtpd.mangledname))) and
  196. (is_class(_class) or is_objectpascal_helper(_class) or is_javaclass(_class)) then
  197. MessagePos1(pd.fileinfo,parser_e_final_can_no_be_overridden,pd.fullprocname(false))
  198. else
  199. { old definition has virtual
  200. new definition has no virtual or override }
  201. if (po_virtualmethod in vmtpd.procoptions) and
  202. (
  203. not(po_virtualmethod in pd.procoptions) or
  204. (
  205. { new one does not have reintroduce in case of an objccategory }
  206. (is_objccategory(_class) and
  207. not(po_reintroduce in pd.procoptions)) or
  208. { new one does not have override in case of objpas/objc/java class/intf/proto }
  209. ((is_class_or_interface_or_objc_or_java(_class) or is_objectpascal_helper(_class)) and
  210. not is_objccategory(_class) and
  211. not(po_overridingmethod in pd.procoptions)
  212. )
  213. )
  214. ) then
  215. begin
  216. if (
  217. not(pdoverload or hasoverloads) or
  218. hasequalpara
  219. ) then
  220. begin
  221. {$ifdef jvm}
  222. { if the mangled names are different, the inheritance trees
  223. are different too in Java; exception: when the parent method
  224. is a virtual class method or virtual constructor, because
  225. those are looked up dynamicall by name }
  226. javanewtreeok:=
  227. is_java_class_or_interface(_class) and
  228. (tcpuprocdef(pd).jvmmangledbasename(false)<>tcpuprocdef(vmtpd).jvmmangledbasename(false)) and
  229. ((vmtpd.proctypeoption<>potype_constructor) and
  230. not(po_staticmethod in vmtpd.procoptions));
  231. {$endif}
  232. if not(po_reintroduce in pd.procoptions) and
  233. not(po_java_nonvirtual in vmtpd.procoptions) then
  234. if not(is_objc_class_or_protocol(_class))
  235. {$ifdef jvm}
  236. and (not is_java_class_or_interface(_class) or
  237. javanewtreeok)
  238. {$endif jvm}
  239. then
  240. MessagePos1(pd.fileinfo,parser_w_should_use_override,pd.fullprocname(false))
  241. else
  242. begin
  243. { In Objective-C, you cannot create a new VMT entry to
  244. start a new inheritance tree. We therefore give an
  245. error when the class is implemented in Pascal, to
  246. avoid confusion due to things working differently
  247. with Object Pascal classes.
  248. In case of external classes, we only give a hint,
  249. because requiring override everywhere may make
  250. automated header translation tools too complex.
  251. The same goes for Java. }
  252. {$ifndef jvm}
  253. if hasequalpara then
  254. {$endif}
  255. begin
  256. if not(oo_is_external in _class.objectoptions) then
  257. if not is_objccategory(_class) then
  258. MessagePos1(pd.fileinfo,parser_e_must_use_override,FullTypeName(tdef(vmtpd.owner.defowner),nil))
  259. else
  260. MessagePos1(pd.fileinfo,parser_e_must_use_reintroduce_objc,FullTypeName(tdef(vmtpd.owner.defowner),nil))
  261. { there may be a lot of these in auto-translated
  262. headers, so only calculate the fulltypename if
  263. the hint will be shown }
  264. else if CheckVerbosity(V_Hint) then
  265. if not is_objccategory(_class) then
  266. MessagePos1(pd.fileinfo,parser_h_should_use_override,FullTypeName(tdef(vmtpd.owner.defowner),nil))
  267. else
  268. MessagePos1(pd.fileinfo,parser_h_should_use_reintroduce_objc,FullTypeName(tdef(vmtpd.owner.defowner),nil));
  269. end;
  270. { no new entry, but copy the message name if any from
  271. the procdef in the parent class }
  272. if not is_objc_class_or_protocol(_class) or
  273. hasequalpara then
  274. check_msg_str(vmtpd,pd);
  275. if updatevalues then
  276. begin
  277. { in case of Java, copy the real name from the parent,
  278. since overriding "Destroy" with "destroy" is not
  279. going to work very well }
  280. if is_java_class_or_interface(_class) and
  281. (pd.procsym.realname<>vmtpd.procsym.realname) then
  282. pd.procsym.realname:=vmtpd.procsym.realname;
  283. { in case we are overriding an abstract method,
  284. decrease the number of abstract methods in this class }
  285. if (po_abstractmethod in vmtpd.procoptions) then
  286. dec(tobjectdef(pd.owner.defowner).abstractcnt);
  287. if (vmtpd.extnumber<>i) then
  288. internalerror(2011083101);
  289. pd.extnumber:=vmtpd.extnumber;
  290. vmtpd:=pd;
  291. end;
  292. result:=true;
  293. exit;
  294. {$ifdef jvm}
  295. end
  296. else
  297. if not javanewtreeok and
  298. is_java_class_or_interface(_class) then
  299. begin
  300. { mangled names are the same -> can only override }
  301. MessagePos1(pd.fileinfo,parser_e_must_use_override,FullTypeName(tdef(vmtpd.owner.defowner),nil))
  302. {$endif jvm}
  303. end;
  304. { disable/hide old VMT entry }
  305. if updatevalues then
  306. vmtentryvis:=vis_hidden;
  307. end;
  308. end
  309. { both are virtual? }
  310. else if (po_virtualmethod in pd.procoptions) and
  311. (po_virtualmethod in vmtpd.procoptions) then
  312. begin
  313. { same parameter and return types (parameter specifiers will be checked below) }
  314. if hasequalpara and
  315. compatible_childmethod_resultdef(vmtpd.returndef,pd.returndef) then
  316. begin
  317. { inherite calling convention when it was explicit and the
  318. current definition has none explicit set }
  319. if (po_hascallingconvention in vmtpd.procoptions) and
  320. not(po_hascallingconvention in pd.procoptions) then
  321. begin
  322. pd.proccalloption:=vmtpd.proccalloption;
  323. include(pd.procoptions,po_hascallingconvention);
  324. end;
  325. { All parameter specifiers and some procedure the flags have to match
  326. except abstract and override }
  327. if (compare_paras(vmtpd.paras,pd.paras,cp_all,[cpo_ignoreuniv,cpo_ignorehidden])<te_equal) or
  328. (vmtpd.proccalloption<>pd.proccalloption) or
  329. (vmtpd.proctypeoption<>pd.proctypeoption) or
  330. ((vmtpd.procoptions*po_comp)<>(pd.procoptions*po_comp)) then
  331. begin
  332. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  333. tprocsym(vmtpd.procsym).write_parameter_lists(pd);
  334. end;
  335. check_msg_str(vmtpd,pd);
  336. { Give a note if the new visibility is lower. For a higher
  337. visibility update the vmt info }
  338. if vmtentryvis>pd.visibility then
  339. begin
  340. if po_auto_raised_visibility in vmtpd.procoptions then
  341. begin
  342. if updatevalues then
  343. begin
  344. pd.visibility:=vmtentryvis;
  345. { this one's visibility is now also auto-raised }
  346. include(pd.procoptions,po_auto_raised_visibility);
  347. end
  348. end
  349. else
  350. {$ifdef jvm}
  351. MessagePos4(pd.fileinfo,parser_e_method_lower_visibility,
  352. {$else jvm}
  353. MessagePos4(pd.fileinfo,parser_n_ignore_lower_visibility,
  354. {$endif jvm}
  355. pd.fullprocname(false),
  356. visibilityname[pd.visibility],tobjectdef(vmtpd.owner.defowner).objrealname^,visibilityname[vmtentryvis])
  357. end
  358. else if pd.visibility>vmtentryvis then
  359. begin
  360. if updatevalues then
  361. vmtentryvis:=pd.visibility;
  362. end;
  363. { override old virtual method in VMT }
  364. if updatevalues then
  365. begin
  366. { in case we are overriding an abstract method,
  367. decrease the number of abstract methods in this class }
  368. if (po_overridingmethod in pd.procoptions) and
  369. (po_abstractmethod in vmtpd.procoptions) then
  370. dec(tobjectdef(pd.owner.defowner).abstractcnt);
  371. if (vmtpd.extnumber<>i) then
  372. internalerror(200611084);
  373. pd.extnumber:=vmtpd.extnumber;
  374. { in case of Java, copy the real name from the parent,
  375. since overriding "Destroy" with "destroy" is not
  376. going to work very well }
  377. if is_java_class_or_interface(_class) and
  378. (pd.procsym.realname<>vmtpd.procsym.realname) then
  379. pd.procsym.realname:=vmtpd.procsym.realname;
  380. vmtpd:=pd;
  381. end;
  382. result:=true;
  383. exit;
  384. end
  385. { different parameters }
  386. else
  387. begin
  388. { when we got an override directive then can search futher for
  389. the procedure to override.
  390. If we are starting a new virtual tree then hide the old tree }
  391. if not(po_overridingmethod in pd.procoptions) and
  392. not(pdoverload or hasoverloads) then
  393. begin
  394. if not(po_reintroduce in pd.procoptions) then
  395. begin
  396. if not is_object(_class) and
  397. not is_objc_class_or_protocol(_class) and
  398. not is_java_class_or_interface(_class) then
  399. MessagePos1(pd.fileinfo,parser_w_should_use_override,pd.fullprocname(false))
  400. else
  401. { objects don't allow starting a new virtual tree
  402. and neither do Objective-C or Java }
  403. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,vmtpd.fullprocname(false));
  404. end;
  405. { disable/hide old VMT entry }
  406. if updatevalues then
  407. vmtentryvis:=vis_hidden;
  408. end;
  409. end;
  410. end;
  411. end;
  412. function found_category_method(st: tsymtable): boolean;
  413. var
  414. entrycount: longint;
  415. cat: tobjectdef;
  416. vmtpd: tprocdef;
  417. vmtvis: tvisibility;
  418. begin
  419. result:=false;
  420. if is_objccategory(tdef(st.defowner)) then
  421. begin
  422. cat:=tobjectdef(st.defowner);
  423. { go through all of the category's methods to find the
  424. vmtentry corresponding to the procdef we are handling }
  425. for entrycount:=0 to cat.vmtentries.Count-1 do
  426. begin
  427. vmtpd:=pvmtentry(cat.vmtentries[entrycount])^.procdef;
  428. vmtvis:=pvmtentry(cat.vmtentries[entrycount])^.visibility;
  429. { don't change the vmtentry of the category }
  430. if found_entry(vmtpd,vmtvis,false) then
  431. begin
  432. result:=true;
  433. exit;
  434. end;
  435. end;
  436. end;
  437. end;
  438. begin
  439. result:=false;
  440. overridesclasshelper:=false;
  441. { Load other values for easier readability }
  442. hasoverloads:=(tprocsym(pd.procsym).ProcdefList.Count>1);
  443. pdoverload:=(po_overload in pd.procoptions);
  444. { compare with all stored definitions }
  445. for i:=0 to _class.vmtentries.Count-1 do
  446. begin
  447. if found_entry(pvmtentry(_class.vmtentries[i])^.procdef, pvmtentry(_class.vmtentries[i])^.visibility,true) then
  448. exit;
  449. end;
  450. { in case of Objective-C, also check the categories that apply to this
  451. class' *parent* for methods to override (don't allow class X to
  452. "override" a method added by a category to class X itself, since in
  453. that case the category method will in fact replace class X'
  454. "overriding" method }
  455. if is_objcclass(_class) and
  456. assigned(_class.childof) and
  457. search_objc_helper(_class.childof,pd.procsym.name,srsym,st) then
  458. begin
  459. overridesclasshelper:=found_category_method(st);
  460. end;
  461. { No entry found, we need to create a new entry }
  462. result:=true;
  463. end;
  464. function TVMTBuilder.intf_search_procdef_by_name(proc: tprocdef;const name: string): tprocdef;
  465. const
  466. po_comp = [po_classmethod,po_staticmethod,po_interrupt,po_iocheck,po_msgint,
  467. po_exports,po_varargs,po_explicitparaloc,po_nostackframe];
  468. var
  469. implprocdef : Tprocdef;
  470. i: cardinal;
  471. hclass : tobjectdef;
  472. hashedid : THashedIDString;
  473. srsym : tsym;
  474. begin
  475. result:=nil;
  476. hashedid.id:=name;
  477. hclass:=_class;
  478. while assigned(hclass) do
  479. begin
  480. srsym:=tsym(hclass.symtable.FindWithHash(hashedid));
  481. if assigned(srsym) and
  482. (srsym.typ=procsym) then
  483. begin
  484. for i:=0 to Tprocsym(srsym).ProcdefList.Count-1 do
  485. begin
  486. implprocdef:=tprocdef(tprocsym(srsym).ProcdefList[i]);
  487. if (implprocdef.procsym=tprocsym(srsym)) and
  488. (compare_paras(proc.paras,implprocdef.paras,cp_all,[cpo_ignorehidden,cpo_ignoreuniv])>=te_equal) and
  489. (compare_defs(proc.returndef,implprocdef.returndef,nothingn)>=te_equal) and
  490. (proc.proccalloption=implprocdef.proccalloption) and
  491. (proc.proctypeoption=implprocdef.proctypeoption) and
  492. ((proc.procoptions*po_comp)=((implprocdef.procoptions+[po_virtualmethod])*po_comp)) and
  493. check_msg_str(proc,implprocdef) then
  494. begin
  495. { does the interface increase the visibility of the
  496. implementing method? }
  497. if implprocdef.visibility<proc.visibility then
  498. {$ifdef jvm}
  499. MessagePos2(implprocdef.fileinfo,type_e_interface_lower_visibility,proc.fullprocname(false),implprocdef.fullprocname(false));
  500. {$else}
  501. MessagePos2(implprocdef.fileinfo,type_w_interface_lower_visibility,proc.fullprocname(false),implprocdef.fullprocname(false));
  502. {$endif}
  503. result:=implprocdef;
  504. exit;
  505. end;
  506. end;
  507. end;
  508. hclass:=hclass.childof;
  509. end;
  510. end;
  511. procedure TVMTBuilder.intf_get_procdefs(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  512. var
  513. i : longint;
  514. def : tdef;
  515. hs,
  516. prefix,
  517. mappedname: string;
  518. implprocdef: tprocdef;
  519. begin
  520. prefix:=ImplIntf.IntfDef.symtable.name^+'.';
  521. for i:=0 to IntfDef.symtable.DefList.Count-1 do
  522. begin
  523. def:=tdef(IntfDef.symtable.DefList[i]);
  524. if assigned(def) and
  525. (def.typ=procdef) then
  526. begin
  527. { Find implementing procdef
  528. 1. Check for mapped name
  529. 2. Use symbol name, but only if there's no mapping,
  530. or we're processing ancestor of interface.
  531. When modifying this code, ensure that webtbs/tw11862, webtbs/tw4950
  532. and webtbf/tw19591 stay correct. }
  533. implprocdef:=nil;
  534. hs:=prefix+tprocdef(def).procsym.name;
  535. mappedname:=ImplIntf.GetMapping(hs);
  536. if mappedname<>'' then
  537. implprocdef:=intf_search_procdef_by_name(tprocdef(def),mappedname);
  538. if not assigned(implprocdef) then
  539. if (mappedname='') or (ImplIntf.IntfDef<>IntfDef) then
  540. implprocdef:=intf_search_procdef_by_name(tprocdef(def),tprocdef(def).procsym.name);
  541. { Add procdef to the implemented interface }
  542. if assigned(implprocdef) then
  543. begin
  544. if (tobjectdef(implprocdef.struct).objecttype<>odt_objcclass) then
  545. begin
  546. { in case of Java, copy the real name from the parent,
  547. since overriding "Destroy" with "destroy" is not
  548. going to work very well }
  549. if is_javaclass(implprocdef.struct) and
  550. (implprocdef.procsym.realname<>tprocdef(def).procsym.realname) then
  551. implprocdef.procsym.realname:=tprocdef(def).procsym.realname;
  552. ImplIntf.AddImplProc(implprocdef);
  553. end
  554. else
  555. begin
  556. { If no message name has been specified for the method
  557. in the objcclass, copy it from the protocol
  558. definition. }
  559. if not(po_msgstr in tprocdef(def).procoptions) then
  560. begin
  561. include(tprocdef(def).procoptions,po_msgstr);
  562. implprocdef.messageinf.str:=stringdup(tprocdef(def).messageinf.str^);
  563. end
  564. else
  565. begin
  566. { If a message name has been specified in the
  567. objcclass, it has to match the message name in the
  568. protocol definition. }
  569. if (implprocdef.messageinf.str^<>tprocdef(def).messageinf.str^) then
  570. MessagePos2(implprocdef.fileinfo,parser_e_objc_message_name_changed,tprocdef(def).messageinf.str^,implprocdef.messageinf.str^);
  571. end;
  572. end;
  573. end
  574. else
  575. if (ImplIntf.IType=etStandard) and
  576. not(po_optional in tprocdef(def).procoptions) then
  577. MessagePos1(_Class.typesym.fileinfo,sym_e_no_matching_implementation_found,tprocdef(def).fullprocname(false));
  578. end;
  579. end;
  580. end;
  581. procedure TVMTBuilder.intf_get_procdefs_recursive(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  582. begin
  583. if assigned(IntfDef.childof) then
  584. intf_get_procdefs_recursive(ImplIntf,IntfDef.childof);
  585. intf_get_procdefs(ImplIntf,IntfDef);
  586. end;
  587. procedure TVMTBuilder.prot_get_procdefs_recursive(ImplProt:TImplementedInterface;ProtDef:TObjectDef);
  588. var
  589. i: longint;
  590. begin
  591. { don't check the same protocol twice }
  592. if handledprotocols.IndexOf(ProtDef)<>-1 then
  593. exit;
  594. handledprotocols.add(ProtDef);
  595. for i:=0 to ProtDef.ImplementedInterfaces.count-1 do
  596. prot_get_procdefs_recursive(ImplProt,TImplementedInterface(ProtDef.ImplementedInterfaces[i]).intfdef);
  597. intf_get_procdefs(ImplProt,ProtDef);
  598. end;
  599. procedure TVMTBuilder.intf_optimize_vtbls;
  600. type
  601. tcompintfentry = record
  602. weight: longint;
  603. compintf: longint;
  604. end;
  605. { Max 1000 interface in the class header interfaces it's enough imho }
  606. tcompintfs = array[0..1000] of tcompintfentry;
  607. pcompintfs = ^tcompintfs;
  608. tequals = array[0..1000] of longint;
  609. pequals = ^tequals;
  610. timpls = array[0..1000] of longint;
  611. pimpls = ^timpls;
  612. var
  613. aequals: pequals;
  614. compats: pcompintfs;
  615. impls: pimpls;
  616. ImplIntfCount,
  617. w,i,j,k: longint;
  618. ImplIntfI,
  619. ImplIntfJ : TImplementedInterface;
  620. cij: boolean;
  621. cji: boolean;
  622. begin
  623. ImplIntfCount:=_class.ImplementedInterfaces.count;
  624. if ImplIntfCount>=High(tequals) then
  625. Internalerror(200006135);
  626. getmem(compats,sizeof(tcompintfentry)*ImplIntfCount);
  627. getmem(aequals,sizeof(longint)*ImplIntfCount);
  628. getmem(impls,sizeof(longint)*ImplIntfCount);
  629. filldword(compats^,(sizeof(tcompintfentry) div sizeof(dword))*ImplIntfCount,dword(-1));
  630. filldword(aequals^,ImplIntfCount,dword(-1));
  631. filldword(impls^,ImplIntfCount,dword(-1));
  632. { ismergepossible is a containing relation
  633. meaning of ismergepossible(a,b,w) =
  634. if implementorfunction map of a is contained implementorfunction map of b
  635. imp(a,b) and imp(b,c) => imp(a,c) ; imp(a,b) and imp(b,a) => a == b
  636. }
  637. { the order is very important for correct allocation }
  638. for i:=0 to ImplIntfCount-1 do
  639. begin
  640. for j:=i+1 to ImplIntfCount-1 do
  641. begin
  642. ImplIntfI:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  643. ImplIntfJ:=TImplementedInterface(_class.ImplementedInterfaces[j]);
  644. cij:=ImplIntfI.IsImplMergePossible(ImplIntfJ,w);
  645. cji:=ImplIntfJ.IsImplMergePossible(ImplIntfI,w);
  646. if cij and cji then { i equal j }
  647. begin
  648. { get minimum index of equal }
  649. if aequals^[j]=-1 then
  650. aequals^[j]:=i;
  651. end
  652. else if cij then
  653. begin
  654. { get minimum index of maximum weight }
  655. if compats^[i].weight<w then
  656. begin
  657. compats^[i].weight:=w;
  658. compats^[i].compintf:=j;
  659. end;
  660. end
  661. else if cji then
  662. begin
  663. { get minimum index of maximum weight }
  664. if (compats^[j].weight<w) then
  665. begin
  666. compats^[j].weight:=w;
  667. compats^[j].compintf:=i;
  668. end;
  669. end;
  670. end;
  671. end;
  672. { Reset, no replacements by default }
  673. for i:=0 to ImplIntfCount-1 do
  674. impls^[i]:=i;
  675. { Replace vtbls when equal or compat, repeat
  676. until there are no replacements possible anymore. This is
  677. needed for the cases like:
  678. First loop: 2->3, 3->1
  679. Second loop: 2->1 (because 3 was replaced with 1)
  680. }
  681. repeat
  682. k:=0;
  683. for i:=0 to ImplIntfCount-1 do
  684. begin
  685. if compats^[impls^[i]].compintf<>-1 then
  686. impls^[i]:=compats^[impls^[i]].compintf
  687. else if aequals^[impls^[i]]<>-1 then
  688. impls^[i]:=aequals^[impls^[i]]
  689. else
  690. inc(k);
  691. end;
  692. until k=ImplIntfCount;
  693. { Update the VtblImplIntf }
  694. for i:=0 to ImplIntfCount-1 do
  695. begin
  696. ImplIntfI:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  697. ImplIntfI.VtblImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[impls^[i]]);
  698. end;
  699. freemem(compats);
  700. freemem(aequals);
  701. freemem(impls);
  702. end;
  703. procedure TVMTBuilder.intf_allocate_vtbls;
  704. var
  705. i : longint;
  706. ImplIntf : TImplementedInterface;
  707. begin
  708. { Allocation vtbl space }
  709. for i:=0 to _class.ImplementedInterfaces.count-1 do
  710. begin
  711. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  712. { if it implements itself and if it's not implemented by delegation }
  713. if (ImplIntf.VtblImplIntf=ImplIntf) and (ImplIntf.IType=etStandard) then
  714. begin
  715. { allocate a pointer in the object memory }
  716. with tObjectSymtable(_class.symtable) do
  717. begin
  718. datasize:=align(datasize,voidpointertype.alignment);
  719. ImplIntf.Ioffset:=datasize;
  720. datasize:=datasize+voidpointertype.size;
  721. end;
  722. end;
  723. end;
  724. { Update ioffset of current interface with the ioffset from
  725. the interface that is reused to implements this interface }
  726. for i:=0 to _class.ImplementedInterfaces.count-1 do
  727. begin
  728. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  729. if ImplIntf.VtblImplIntf<>ImplIntf then
  730. ImplIntf.IOffset:=ImplIntf.VtblImplIntf.IOffset;
  731. end;
  732. end;
  733. procedure TVMTBuilder.generate_vmt_def;
  734. var
  735. i: longint;
  736. vmtdef: trecorddef;
  737. systemvmt: tdef;
  738. sym: tsym;
  739. vmtdefname: TIDString;
  740. begin
  741. { these types don't have an actual VMT, we only use the other methods
  742. in TVMTBuilder to determine duplicates/overrides }
  743. if _class.objecttype in [
  744. odt_helper,
  745. odt_objcclass,
  746. odt_objccategory,
  747. odt_objcprotocol,
  748. odt_javaclass,
  749. odt_interfacecom_property,
  750. odt_interfacecom_function,
  751. odt_interfacejava] then
  752. exit;
  753. { don't generate VMT for generics (only use duplicates/overrides detection) }
  754. { Note: don't use is_generic here as we also need to check nested non-
  755. generic classes }
  756. if df_generic in _class.defoptions then
  757. exit;
  758. { todo in the future }
  759. if _class.objecttype = odt_cppclass then
  760. exit;
  761. { the VMT definition may already exist in case of generics }
  762. vmtdefname:=internaltypeprefixName[itp_vmtdef]+_class.mangledparaname;
  763. if assigned(try_search_current_module_type(vmtdefname)) then
  764. exit;
  765. { create VMT type definition }
  766. vmtdef:=crecorddef.create_global_internal(
  767. vmtdefname,
  768. 0,
  769. target_info.alignment.recordalignmin,
  770. target_info.alignment.maxCrecordalign);
  771. { standard VMT fields }
  772. case _Class.objecttype of
  773. odt_class:
  774. begin
  775. systemvmt:=search_system_type('TVMT').typedef;
  776. { does the TVMT type look like we expect? (so that this code is
  777. easily triggered in case the definition of the VMT would
  778. change) }
  779. if (systemvmt.typ<>recorddef) or
  780. (trecorddef(systemvmt).symtable.SymList.count<>25) then
  781. internalerror(2015052601);
  782. { system.tvmt is a record that represents the VMT of TObject,
  783. including its virtual methods. We only want the non-method
  784. fields, as the methods will be added automatically based on
  785. the VMT we generated here only add the 12 first fields }
  786. for i:=0 to 11 do
  787. begin
  788. sym:=tsym(trecorddef(systemvmt).symtable.SymList[i]);
  789. if sym.typ<>fieldvarsym then
  790. internalerror(2015052602);
  791. vmtdef.add_field_by_def('',tfieldvarsym(sym).vardef);
  792. end;
  793. end;
  794. odt_interfacecom,odt_interfacecorba,odt_dispinterface:
  795. { nothing }
  796. ;
  797. odt_object:
  798. begin
  799. { size, -size, parent vmt [, dmt ] }
  800. vmtdef.add_field_by_def('',ptrsinttype);
  801. vmtdef.add_field_by_def('',ptrsinttype);
  802. vmtdef.add_field_by_def('',voidpointertype);
  803. {$ifdef WITHDMT}
  804. vmtdef.add_field_by_def('',voidpointertype);
  805. {$endif WITHDMT}
  806. end;
  807. else
  808. internalerror(2015052605);
  809. end;
  810. { now add the methods }
  811. for i:=0 to _class.vmtentries.count-1 do
  812. vmtdef.add_field_by_def('',
  813. cprocvardef.getreusableprocaddr(pvmtentry(_class.vmtentries[i])^.procdef)
  814. );
  815. { the VMT ends with a nil pointer }
  816. vmtdef.add_field_by_def('',voidcodepointertype);
  817. end;
  818. procedure TVMTBuilder.generate_vmt;
  819. var
  820. i : longint;
  821. def : tdef;
  822. old_current_structdef : tabstractrecorddef;
  823. overridesclasshelper : boolean;
  824. begin
  825. old_current_structdef:=current_structdef;
  826. current_structdef:=_class;
  827. _class.resetvmtentries;
  828. { inherit (copy) VMT from parent object }
  829. if assigned(_class.childof) then
  830. begin
  831. if not assigned(_class.childof.vmtentries) then
  832. internalerror(200810281);
  833. _class.copyvmtentries(_class.childof);
  834. end;
  835. { process all procdefs, we must process the defs to
  836. keep the same order as that is written in the source
  837. to be compatible with the indexes in the interface vtable (PFV) }
  838. for i:=0 to _class.symtable.DefList.Count-1 do
  839. begin
  840. def:=tdef(_class.symtable.DefList[i]);
  841. if def.typ=procdef then
  842. begin
  843. { VMT entry }
  844. if is_new_vmt_entry(tprocdef(def),overridesclasshelper) then
  845. add_new_vmt_entry(tprocdef(def),overridesclasshelper);
  846. end;
  847. end;
  848. build_interface_mappings;
  849. if assigned(_class.ImplementedInterfaces) and
  850. not(is_objc_class_or_protocol(_class)) and
  851. not(is_java_class_or_interface(_class)) then
  852. begin
  853. { Optimize interface tables to reuse wrappers }
  854. intf_optimize_vtbls;
  855. { Allocate interface tables }
  856. intf_allocate_vtbls;
  857. end;
  858. generate_vmt_def;
  859. current_structdef:=old_current_structdef;
  860. end;
  861. procedure TVMTBuilder.build_interface_mappings;
  862. var
  863. ImplIntf : TImplementedInterface;
  864. i: longint;
  865. begin
  866. { Find Procdefs implementing the interfaces (both Objective-C protocols
  867. and Java interfaces can have multiple parent interfaces, but in that
  868. case obviously no implementations are required) }
  869. if assigned(_class.ImplementedInterfaces) and
  870. not(_class.objecttype in [odt_objcprotocol,odt_interfacejava]) and
  871. // abstract java classes do not have to implement all interface
  872. // methods. todo: check that non-abstract descendents do!
  873. not((_class.objecttype=odt_javaclass) and (oo_is_abstract in _class.objectoptions)) then
  874. begin
  875. { Collect implementor functions into the tImplementedInterface.procdefs }
  876. case _class.objecttype of
  877. odt_class:
  878. begin
  879. for i:=0 to _class.ImplementedInterfaces.count-1 do
  880. begin
  881. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  882. intf_get_procdefs_recursive(ImplIntf,ImplIntf.IntfDef)
  883. end;
  884. end;
  885. odt_objcclass,
  886. odt_javaclass:
  887. begin
  888. { Object Pascal interfaces are afterwards optimized via the
  889. intf_optimize_vtbls() method, but we can't do this for
  890. protocols/Java interfaces -> check for duplicates here
  891. already. }
  892. handledprotocols:=tfpobjectlist.create(false);
  893. for i:=0 to _class.ImplementedInterfaces.count-1 do
  894. begin
  895. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  896. prot_get_procdefs_recursive(ImplIntf,ImplIntf.IntfDef);
  897. end;
  898. handledprotocols.free;
  899. end
  900. else
  901. internalerror(2009091801);
  902. end
  903. end;
  904. end;
  905. end.