nobj.pas 41 KB

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