nobj.pas 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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) then
  479. begin
  480. for i:=0 to Tprocsym(srsym).ProcdefList.Count-1 do
  481. begin
  482. implprocdef:=tprocdef(tprocsym(srsym).ProcdefList[i]);
  483. if (implprocdef.procsym=tprocsym(srsym)) and
  484. (compare_paras(proc.paras,implprocdef.paras,cp_all,[cpo_ignorehidden,cpo_ignoreuniv])>=te_equal) and
  485. (compare_defs(proc.returndef,implprocdef.returndef,nothingn)>=te_equal) and
  486. (proc.proccalloption=implprocdef.proccalloption) and
  487. (proc.proctypeoption=implprocdef.proctypeoption) and
  488. ((proc.procoptions*po_comp)=((implprocdef.procoptions+[po_virtualmethod])*po_comp)) and
  489. check_msg_str(proc,implprocdef) then
  490. begin
  491. { does the interface increase the visibility of the
  492. implementing method? }
  493. if implprocdef.visibility<proc.visibility then
  494. {$ifdef jvm}
  495. MessagePos2(implprocdef.fileinfo,type_e_interface_lower_visibility,proc.fullprocname(false),implprocdef.fullprocname(false));
  496. {$else}
  497. MessagePos2(implprocdef.fileinfo,type_w_interface_lower_visibility,proc.fullprocname(false),implprocdef.fullprocname(false));
  498. {$endif}
  499. result:=implprocdef;
  500. exit;
  501. end;
  502. end;
  503. end;
  504. hclass:=hclass.childof;
  505. end;
  506. end;
  507. procedure TVMTBuilder.intf_get_procdefs(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  508. var
  509. i : longint;
  510. def : tdef;
  511. hs,
  512. prefix,
  513. mappedname: string;
  514. implprocdef: tprocdef;
  515. begin
  516. prefix:=ImplIntf.IntfDef.symtable.name^+'.';
  517. for i:=0 to IntfDef.symtable.DefList.Count-1 do
  518. begin
  519. def:=tdef(IntfDef.symtable.DefList[i]);
  520. if assigned(def) and
  521. (def.typ=procdef) then
  522. begin
  523. { Find implementing procdef
  524. 1. Check for mapped name
  525. 2. Use symbol name, but only if there's no mapping,
  526. or we're processing ancestor of interface.
  527. When modifying this code, ensure that webtbs/tw11862, webtbs/tw4950
  528. and webtbf/tw19591 stay correct. }
  529. implprocdef:=nil;
  530. hs:=prefix+tprocdef(def).procsym.name;
  531. mappedname:=ImplIntf.GetMapping(hs);
  532. if mappedname<>'' then
  533. implprocdef:=intf_search_procdef_by_name(tprocdef(def),mappedname);
  534. if not assigned(implprocdef) then
  535. if (mappedname='') or (ImplIntf.IntfDef<>IntfDef) then
  536. implprocdef:=intf_search_procdef_by_name(tprocdef(def),tprocdef(def).procsym.name);
  537. { Add procdef to the implemented interface }
  538. if assigned(implprocdef) then
  539. begin
  540. if (tobjectdef(implprocdef.struct).objecttype<>odt_objcclass) then
  541. begin
  542. { in case of Java, copy the real name from the parent,
  543. since overriding "Destroy" with "destroy" is not
  544. going to work very well }
  545. if is_javaclass(implprocdef.struct) and
  546. (implprocdef.procsym.realname<>tprocdef(def).procsym.realname) then
  547. implprocdef.procsym.realname:=tprocdef(def).procsym.realname;
  548. ImplIntf.AddImplProc(implprocdef);
  549. end
  550. else
  551. begin
  552. { If no message name has been specified for the method
  553. in the objcclass, copy it from the protocol
  554. definition. }
  555. if not(po_msgstr in tprocdef(def).procoptions) then
  556. begin
  557. include(tprocdef(def).procoptions,po_msgstr);
  558. implprocdef.messageinf.str:=stringdup(tprocdef(def).messageinf.str^);
  559. end
  560. else
  561. begin
  562. { If a message name has been specified in the
  563. objcclass, it has to match the message name in the
  564. protocol definition. }
  565. if (implprocdef.messageinf.str^<>tprocdef(def).messageinf.str^) then
  566. MessagePos2(implprocdef.fileinfo,parser_e_objc_message_name_changed,tprocdef(def).messageinf.str^,implprocdef.messageinf.str^);
  567. end;
  568. end;
  569. end
  570. else
  571. if (ImplIntf.IType=etStandard) and
  572. not(po_optional in tprocdef(def).procoptions) then
  573. MessagePos1(_Class.typesym.fileinfo,sym_e_no_matching_implementation_found,tprocdef(def).fullprocname(false));
  574. end;
  575. end;
  576. end;
  577. procedure TVMTBuilder.intf_get_procdefs_recursive(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  578. begin
  579. if assigned(IntfDef.childof) then
  580. intf_get_procdefs_recursive(ImplIntf,IntfDef.childof);
  581. intf_get_procdefs(ImplIntf,IntfDef);
  582. end;
  583. procedure TVMTBuilder.prot_get_procdefs_recursive(ImplProt:TImplementedInterface;ProtDef:TObjectDef);
  584. var
  585. i: longint;
  586. begin
  587. { don't check the same protocol twice }
  588. if handledprotocols.IndexOf(ProtDef)<>-1 then
  589. exit;
  590. handledprotocols.add(ProtDef);
  591. for i:=0 to ProtDef.ImplementedInterfaces.count-1 do
  592. prot_get_procdefs_recursive(ImplProt,TImplementedInterface(ProtDef.ImplementedInterfaces[i]).intfdef);
  593. intf_get_procdefs(ImplProt,ProtDef);
  594. end;
  595. procedure TVMTBuilder.intf_optimize_vtbls;
  596. type
  597. tcompintfentry = record
  598. weight: longint;
  599. compintf: longint;
  600. end;
  601. { Max 1000 interface in the class header interfaces it's enough imho }
  602. tcompintfs = array[0..1000] of tcompintfentry;
  603. pcompintfs = ^tcompintfs;
  604. tequals = array[0..1000] of longint;
  605. pequals = ^tequals;
  606. timpls = array[0..1000] of longint;
  607. pimpls = ^timpls;
  608. var
  609. aequals: pequals;
  610. compats: pcompintfs;
  611. impls: pimpls;
  612. ImplIntfCount,
  613. w,i,j,k: longint;
  614. ImplIntfI,
  615. ImplIntfJ : TImplementedInterface;
  616. cij: boolean;
  617. cji: boolean;
  618. begin
  619. ImplIntfCount:=_class.ImplementedInterfaces.count;
  620. if ImplIntfCount>=High(tequals) then
  621. Internalerror(200006135);
  622. getmem(compats,sizeof(tcompintfentry)*ImplIntfCount);
  623. getmem(aequals,sizeof(longint)*ImplIntfCount);
  624. getmem(impls,sizeof(longint)*ImplIntfCount);
  625. filldword(compats^,(sizeof(tcompintfentry) div sizeof(dword))*ImplIntfCount,dword(-1));
  626. filldword(aequals^,ImplIntfCount,dword(-1));
  627. filldword(impls^,ImplIntfCount,dword(-1));
  628. { ismergepossible is a containing relation
  629. meaning of ismergepossible(a,b,w) =
  630. if implementorfunction map of a is contained implementorfunction map of b
  631. imp(a,b) and imp(b,c) => imp(a,c) ; imp(a,b) and imp(b,a) => a == b
  632. }
  633. { the order is very important for correct allocation }
  634. for i:=0 to ImplIntfCount-1 do
  635. begin
  636. for j:=i+1 to ImplIntfCount-1 do
  637. begin
  638. ImplIntfI:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  639. ImplIntfJ:=TImplementedInterface(_class.ImplementedInterfaces[j]);
  640. cij:=ImplIntfI.IsImplMergePossible(ImplIntfJ,w);
  641. cji:=ImplIntfJ.IsImplMergePossible(ImplIntfI,w);
  642. if cij and cji then { i equal j }
  643. begin
  644. { get minimum index of equal }
  645. if aequals^[j]=-1 then
  646. aequals^[j]:=i;
  647. end
  648. else if cij then
  649. begin
  650. { get minimum index of maximum weight }
  651. if compats^[i].weight<w then
  652. begin
  653. compats^[i].weight:=w;
  654. compats^[i].compintf:=j;
  655. end;
  656. end
  657. else if cji then
  658. begin
  659. { get minimum index of maximum weight }
  660. if (compats^[j].weight<w) then
  661. begin
  662. compats^[j].weight:=w;
  663. compats^[j].compintf:=i;
  664. end;
  665. end;
  666. end;
  667. end;
  668. { Reset, no replacements by default }
  669. for i:=0 to ImplIntfCount-1 do
  670. impls^[i]:=i;
  671. { Replace vtbls when equal or compat, repeat
  672. until there are no replacements possible anymore. This is
  673. needed for the cases like:
  674. First loop: 2->3, 3->1
  675. Second loop: 2->1 (because 3 was replaced with 1)
  676. }
  677. repeat
  678. k:=0;
  679. for i:=0 to ImplIntfCount-1 do
  680. begin
  681. if compats^[impls^[i]].compintf<>-1 then
  682. impls^[i]:=compats^[impls^[i]].compintf
  683. else if aequals^[impls^[i]]<>-1 then
  684. impls^[i]:=aequals^[impls^[i]]
  685. else
  686. inc(k);
  687. end;
  688. until k=ImplIntfCount;
  689. { Update the VtblImplIntf }
  690. for i:=0 to ImplIntfCount-1 do
  691. begin
  692. ImplIntfI:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  693. ImplIntfI.VtblImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[impls^[i]]);
  694. end;
  695. freemem(compats);
  696. freemem(aequals);
  697. freemem(impls);
  698. end;
  699. procedure TVMTBuilder.intf_allocate_vtbls;
  700. var
  701. i : longint;
  702. ImplIntf : TImplementedInterface;
  703. begin
  704. { Allocation vtbl space }
  705. for i:=0 to _class.ImplementedInterfaces.count-1 do
  706. begin
  707. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  708. { if it implements itself and if it's not implemented by delegation }
  709. if (ImplIntf.VtblImplIntf=ImplIntf) and (ImplIntf.IType=etStandard) then
  710. begin
  711. { allocate a pointer in the object memory }
  712. with tObjectSymtable(_class.symtable) do
  713. begin
  714. datasize:=align(datasize,voidpointertype.alignment);
  715. ImplIntf.Ioffset:=datasize;
  716. datasize:=datasize+voidpointertype.size;
  717. end;
  718. end;
  719. end;
  720. { Update ioffset of current interface with the ioffset from
  721. the interface that is reused to implements this interface }
  722. for i:=0 to _class.ImplementedInterfaces.count-1 do
  723. begin
  724. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  725. if ImplIntf.VtblImplIntf<>ImplIntf then
  726. ImplIntf.IOffset:=ImplIntf.VtblImplIntf.IOffset;
  727. end;
  728. end;
  729. procedure TVMTBuilder.generate_vmt_def;
  730. var
  731. i: longint;
  732. vmtdef: trecorddef;
  733. systemvmt: tdef;
  734. sym: tsym;
  735. vmtdefname: TIDString;
  736. begin
  737. { these types don't have an actual VMT, we only use the other methods
  738. in TVMTBuilder to determine duplicates/overrides }
  739. if _class.objecttype in [
  740. odt_helper,
  741. odt_objcclass,
  742. odt_objccategory,
  743. odt_objcprotocol,
  744. odt_javaclass,
  745. odt_interfacecom_property,
  746. odt_interfacecom_function,
  747. odt_interfacejava] then
  748. exit;
  749. { don't generate VMT for generics (only use duplicates/overrides detection) }
  750. { Note: don't use is_generic here as we also need to check nested non-
  751. generic classes }
  752. if df_generic in _class.defoptions then
  753. exit;
  754. { todo in the future }
  755. if _class.objecttype = odt_cppclass then
  756. exit;
  757. { the VMT definition may already exist in case of generics }
  758. vmtdefname:=internaltypeprefixName[itp_vmtdef]+_class.mangledparaname;
  759. if assigned(try_search_current_module_type(vmtdefname)) then
  760. exit;
  761. { create VMT type definition }
  762. vmtdef:=crecorddef.create_global_internal(
  763. vmtdefname,
  764. 0,
  765. target_info.alignment.recordalignmin,
  766. target_info.alignment.maxCrecordalign);
  767. { standard VMT fields }
  768. case _Class.objecttype of
  769. odt_class:
  770. begin
  771. systemvmt:=search_system_type('TVMT').typedef;
  772. if not assigned(systemvmt) then
  773. Message1(cg_f_internal_type_not_found,'TVMT');
  774. { does the TVMT type look like we expect? (so that this code is
  775. easily triggered in case the definition of the VMT would
  776. change) }
  777. if (systemvmt.typ<>recorddef) or
  778. (trecorddef(systemvmt).symtable.SymList.count<>27) then
  779. Message1(cg_f_internal_type_does_not_match,'TVMT');
  780. { system.tvmt is a record that represents the VMT of TObject,
  781. including its virtual methods. We only want the non-method
  782. fields, as the methods will be added automatically based on
  783. the VMT we generated here only add the 12 first fields }
  784. for i:=0 to 11 do
  785. begin
  786. sym:=tsym(trecorddef(systemvmt).symtable.SymList[i]);
  787. if sym.typ in [procsym,propertysym] then
  788. continue;
  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 ] (same names as for class) }
  800. vmtdef.add_field_by_def('vInstanceSize',sizesinttype);
  801. vmtdef.add_field_by_def('vInstanceSize2',sizesinttype);
  802. vmtdef.add_field_by_def('vParent',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.