eieio.el 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100
  1. ;;; eieio.el --- Enhanced Implementation of Emacs Interpreted Objects
  2. ;;; or maybe Eric's Implementation of Emacs Interpreted Objects
  3. ;; Copyright (C) 1995-1996, 1998-2012 Free Software Foundation, Inc.
  4. ;; Author: Eric M. Ludlam <zappo@gnu.org>
  5. ;; Version: 1.3
  6. ;; Keywords: OO, lisp
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;;
  20. ;; EIEIO is a series of Lisp routines which implements a subset of
  21. ;; CLOS, the Common Lisp Object System. In addition, EIEIO also adds
  22. ;; a few new features which help it integrate more strongly with the
  23. ;; Emacs running environment.
  24. ;;
  25. ;; See eieio.texi for complete documentation on using this package.
  26. ;;
  27. ;; Note: the implementation of the c3 algorithm is based on:
  28. ;; Kim Barrett et al.: A Monotonic Superclass Linearization for Dylan
  29. ;; Retrieved from:
  30. ;; http://192.220.96.201/dylan/linearization-oopsla96.html
  31. ;; There is funny stuff going on with typep and deftype. This
  32. ;; is the only way I seem to be able to make this stuff load properly.
  33. ;; @TODO - fix :initform to be a form, not a quoted value
  34. ;; @TODO - Prefix non-clos functions with `eieio-'.
  35. ;;; Code:
  36. (eval-when-compile
  37. (require 'cl))
  38. (defvar eieio-version "1.3"
  39. "Current version of EIEIO.")
  40. (defun eieio-version ()
  41. "Display the current version of EIEIO."
  42. (interactive)
  43. (message eieio-version))
  44. (eval-and-compile
  45. ;; About the above. EIEIO must process its own code when it compiles
  46. ;; itself, thus, by eval-and-compiling ourselves, we solve the problem.
  47. ;; Compatibility
  48. (if (fboundp 'compiled-function-arglist)
  49. ;; XEmacs can only access a compiled functions arglist like this:
  50. (defalias 'eieio-compiled-function-arglist 'compiled-function-arglist)
  51. ;; Emacs doesn't have this function, but since FUNC is a vector, we can just
  52. ;; grab the appropriate element.
  53. (defun eieio-compiled-function-arglist (func)
  54. "Return the argument list for the compiled function FUNC."
  55. (aref func 0))
  56. )
  57. ;;;
  58. ;; Variable declarations.
  59. ;;
  60. (defvar eieio-hook nil
  61. "*This hook is executed, then cleared each time `defclass' is called.")
  62. (defvar eieio-error-unsupported-class-tags nil
  63. "Non-nil to throw an error if an encountered tag is unsupported.
  64. This may prevent classes from CLOS applications from being used with EIEIO
  65. since EIEIO does not support all CLOS tags.")
  66. (defvar eieio-skip-typecheck nil
  67. "*If non-nil, skip all slot typechecking.
  68. Set this to t permanently if a program is functioning well to get a
  69. small speed increase. This variable is also used internally to handle
  70. default setting for optimization purposes.")
  71. (defvar eieio-optimize-primary-methods-flag t
  72. "Non-nil means to optimize the method dispatch on primary methods.")
  73. ;; State Variables
  74. ;; FIXME: These two constants below should have an `eieio-' prefix added!!
  75. (defvar this nil
  76. "Inside a method, this variable is the object in question.
  77. DO NOT SET THIS YOURSELF unless you are trying to simulate friendly slots.
  78. Note: Embedded methods are no longer supported. The variable THIS is
  79. still set for CLOS methods for the sake of routines like
  80. `call-next-method'.")
  81. (defvar scoped-class nil
  82. "This is set to a class when a method is running.
  83. This is so we know we are allowed to check private parts or how to
  84. execute a `call-next-method'. DO NOT SET THIS YOURSELF!")
  85. (defvar eieio-initializing-object nil
  86. "Set to non-nil while initializing an object.")
  87. (defconst eieio-unbound
  88. (if (and (boundp 'eieio-unbound) (symbolp eieio-unbound))
  89. eieio-unbound
  90. (make-symbol "unbound"))
  91. "Uninterned symbol representing an unbound slot in an object.")
  92. ;; This is a bootstrap for eieio-default-superclass so it has a value
  93. ;; while it is being built itself.
  94. (defvar eieio-default-superclass nil)
  95. ;; FIXME: The constants below should have an `eieio-' prefix added!!
  96. (defconst class-symbol 1 "Class's symbol (self-referencing.).")
  97. (defconst class-parent 2 "Class parent slot.")
  98. (defconst class-children 3 "Class children class slot.")
  99. (defconst class-symbol-obarray 4 "Obarray permitting fast access to variable position indexes.")
  100. ;; @todo
  101. ;; the word "public" here is leftovers from the very first version.
  102. ;; Get rid of it!
  103. (defconst class-public-a 5 "Class attribute index.")
  104. (defconst class-public-d 6 "Class attribute defaults index.")
  105. (defconst class-public-doc 7 "Class documentation strings for attributes.")
  106. (defconst class-public-type 8 "Class type for a slot.")
  107. (defconst class-public-custom 9 "Class custom type for a slot.")
  108. (defconst class-public-custom-label 10 "Class custom group for a slot.")
  109. (defconst class-public-custom-group 11 "Class custom group for a slot.")
  110. (defconst class-public-printer 12 "Printer for a slot.")
  111. (defconst class-protection 13 "Class protection for a slot.")
  112. (defconst class-initarg-tuples 14 "Class initarg tuples list.")
  113. (defconst class-class-allocation-a 15 "Class allocated attributes.")
  114. (defconst class-class-allocation-doc 16 "Class allocated documentation.")
  115. (defconst class-class-allocation-type 17 "Class allocated value type.")
  116. (defconst class-class-allocation-custom 18 "Class allocated custom descriptor.")
  117. (defconst class-class-allocation-custom-label 19 "Class allocated custom descriptor.")
  118. (defconst class-class-allocation-custom-group 20 "Class allocated custom group.")
  119. (defconst class-class-allocation-printer 21 "Class allocated printer for a slot.")
  120. (defconst class-class-allocation-protection 22 "Class allocated protection list.")
  121. (defconst class-class-allocation-values 23 "Class allocated value vector.")
  122. (defconst class-default-object-cache 24
  123. "Cache index of what a newly created object would look like.
  124. This will speed up instantiation time as only a `copy-sequence' will
  125. be needed, instead of looping over all the values and setting them
  126. from the default.")
  127. (defconst class-options 25
  128. "Storage location of tagged class options.
  129. Stored outright without modifications or stripping.")
  130. (defconst class-num-slots 26
  131. "Number of slots in the class definition object.")
  132. (defconst object-class 1 "Index in an object vector where the class is stored.")
  133. (defconst object-name 2 "Index in an object where the name is stored.")
  134. (defconst method-static 0 "Index into :static tag on a method.")
  135. (defconst method-before 1 "Index into :before tag on a method.")
  136. (defconst method-primary 2 "Index into :primary tag on a method.")
  137. (defconst method-after 3 "Index into :after tag on a method.")
  138. (defconst method-num-lists 4 "Number of indexes into methods vector in which groups of functions are kept.")
  139. (defconst method-generic-before 4 "Index into generic :before tag on a method.")
  140. (defconst method-generic-primary 5 "Index into generic :primary tag on a method.")
  141. (defconst method-generic-after 6 "Index into generic :after tag on a method.")
  142. (defconst method-num-slots 7 "Number of indexes into a method's vector.")
  143. (defsubst eieio-specialized-key-to-generic-key (key)
  144. "Convert a specialized KEY into a generic method key."
  145. (cond ((eq key method-static) 0) ;; don't convert
  146. ((< key method-num-lists) (+ key 3)) ;; The conversion
  147. (t key) ;; already generic.. maybe.
  148. ))
  149. ;;; Important macros used in eieio.
  150. ;;
  151. (defmacro class-v (class)
  152. "Internal: Return the class vector from the CLASS symbol."
  153. ;; No check: If eieio gets this far, it's probably been checked already.
  154. `(get ,class 'eieio-class-definition))
  155. (defmacro class-p (class)
  156. "Return t if CLASS is a valid class vector.
  157. CLASS is a symbol."
  158. ;; this new method is faster since it doesn't waste time checking lots of
  159. ;; things.
  160. `(condition-case nil
  161. (eq (aref (class-v ,class) 0) 'defclass)
  162. (error nil)))
  163. (defmacro eieio-object-p (obj)
  164. "Return non-nil if OBJ is an EIEIO object."
  165. `(condition-case nil
  166. (let ((tobj ,obj))
  167. (and (eq (aref tobj 0) 'object)
  168. (class-p (aref tobj object-class))))
  169. (error nil)))
  170. (defalias 'object-p 'eieio-object-p)
  171. (defmacro class-constructor (class)
  172. "Return the symbol representing the constructor of CLASS."
  173. `(aref (class-v ,class) class-symbol))
  174. (defmacro generic-p (method)
  175. "Return t if symbol METHOD is a generic function.
  176. Only methods have the symbol `eieio-method-obarray' as a property
  177. \(which contains a list of all bindings to that method type.)"
  178. `(and (fboundp ,method) (get ,method 'eieio-method-obarray)))
  179. (defun generic-primary-only-p (method)
  180. "Return t if symbol METHOD is a generic function with only primary methods.
  181. Only methods have the symbol `eieio-method-obarray' as a property (which
  182. contains a list of all bindings to that method type.)
  183. Methods with only primary implementations are executed in an optimized way."
  184. (and (generic-p method)
  185. (let ((M (get method 'eieio-method-tree)))
  186. (and (< 0 (length (aref M method-primary)))
  187. (not (aref M method-static))
  188. (not (aref M method-before))
  189. (not (aref M method-after))
  190. (not (aref M method-generic-before))
  191. (not (aref M method-generic-primary))
  192. (not (aref M method-generic-after))))
  193. ))
  194. (defun generic-primary-only-one-p (method)
  195. "Return t if symbol METHOD is a generic function with only primary methods.
  196. Only methods have the symbol `eieio-method-obarray' as a property (which
  197. contains a list of all bindings to that method type.)
  198. Methods with only primary implementations are executed in an optimized way."
  199. (and (generic-p method)
  200. (let ((M (get method 'eieio-method-tree)))
  201. (and (= 1 (length (aref M method-primary)))
  202. (not (aref M method-static))
  203. (not (aref M method-before))
  204. (not (aref M method-after))
  205. (not (aref M method-generic-before))
  206. (not (aref M method-generic-primary))
  207. (not (aref M method-generic-after))))
  208. ))
  209. (defmacro class-option-assoc (list option)
  210. "Return from LIST the found OPTION, or nil if it doesn't exist."
  211. `(car-safe (cdr (memq ,option ,list))))
  212. (defmacro class-option (class option)
  213. "Return the value stored for CLASS' OPTION.
  214. Return nil if that option doesn't exist."
  215. `(class-option-assoc (aref (class-v ,class) class-options) ',option))
  216. (defmacro class-abstract-p (class)
  217. "Return non-nil if CLASS is abstract.
  218. Abstract classes cannot be instantiated."
  219. `(class-option ,class :abstract))
  220. (defmacro class-method-invocation-order (class)
  221. "Return the invocation order of CLASS.
  222. Abstract classes cannot be instantiated."
  223. `(or (class-option ,class :method-invocation-order)
  224. :breadth-first))
  225. ;;; Defining a new class
  226. ;;
  227. (defmacro defclass (name superclass slots &rest options-and-doc)
  228. "Define NAME as a new class derived from SUPERCLASS with SLOTS.
  229. OPTIONS-AND-DOC is used as the class' options and base documentation.
  230. SUPERCLASS is a list of superclasses to inherit from, with SLOTS
  231. being the slots residing in that class definition. NOTE: Currently
  232. only one slot may exist in SUPERCLASS as multiple inheritance is not
  233. yet supported. Supported tags are:
  234. :initform - Initializing form.
  235. :initarg - Tag used during initialization.
  236. :accessor - Tag used to create a function to access this slot.
  237. :allocation - Specify where the value is stored.
  238. Defaults to `:instance', but could also be `:class'.
  239. :writer - A function symbol which will `write' an object's slot.
  240. :reader - A function symbol which will `read' an object.
  241. :type - The type of data allowed in this slot (see `typep').
  242. :documentation
  243. - A string documenting use of this slot.
  244. The following are extensions on CLOS:
  245. :protection - Specify protection for this slot.
  246. Defaults to `:public'. Also use `:protected', or `:private'.
  247. :custom - When customizing an object, the custom :type. Public only.
  248. :label - A text string label used for a slot when customizing.
  249. :group - Name of a customization group this slot belongs in.
  250. :printer - A function to call to print the value of a slot.
  251. See `eieio-override-prin1' as an example.
  252. A class can also have optional options. These options happen in place
  253. of documentation (including a :documentation tag), in addition to
  254. documentation, or not at all. Supported options are:
  255. :documentation - The doc-string used for this class.
  256. Options added to EIEIO:
  257. :allow-nil-initform - Non-nil to skip typechecking of null initforms.
  258. :custom-groups - List of custom group names. Organizes slots into
  259. reasonable groups for customizations.
  260. :abstract - Non-nil to prevent instances of this class.
  261. If a string, use as an error string if someone does
  262. try to make an instance.
  263. :method-invocation-order
  264. - Control the method invocation order if there is
  265. multiple inheritance. Valid values are:
  266. :breadth-first - The default.
  267. :depth-first
  268. Options in CLOS not supported in EIEIO:
  269. :metaclass - Class to use in place of `standard-class'
  270. :default-initargs - Initargs to use when initializing new objects of
  271. this class.
  272. Due to the way class options are set up, you can add any tags you wish,
  273. and reference them using the function `class-option'."
  274. ;; We must `eval-and-compile' this so that when we byte compile
  275. ;; an eieio program, there is no need to load it ahead of time.
  276. ;; It also provides lots of nice debugging errors at compile time.
  277. `(eval-and-compile
  278. (eieio-defclass ',name ',superclass ',slots ',options-and-doc)))
  279. (defvar eieio-defclass-autoload-map (make-vector 7 nil)
  280. "Symbol map of superclasses we find in autoloads.")
  281. ;; We autoload this because it's used in `make-autoload'.
  282. ;;;###autoload
  283. (defun eieio-defclass-autoload (cname superclasses filename doc)
  284. "Create autoload symbols for the EIEIO class CNAME.
  285. SUPERCLASSES are the superclasses that CNAME inherits from.
  286. DOC is the docstring for CNAME.
  287. This function creates a mock-class for CNAME and adds it into
  288. SUPERCLASSES as children.
  289. It creates an autoload function for CNAME's constructor."
  290. ;; Assume we've already debugged inputs.
  291. (let* ((oldc (when (class-p cname) (class-v cname)))
  292. (newc (make-vector class-num-slots nil))
  293. )
  294. (if oldc
  295. nil ;; Do nothing if we already have this class.
  296. ;; Create the class in NEWC, but don't fill anything else in.
  297. (aset newc 0 'defclass)
  298. (aset newc class-symbol cname)
  299. (let ((clear-parent nil))
  300. ;; No parents?
  301. (when (not superclasses)
  302. (setq superclasses '(eieio-default-superclass)
  303. clear-parent t)
  304. )
  305. ;; Hook our new class into the existing structures so we can
  306. ;; autoload it later.
  307. (dolist (SC superclasses)
  308. ;; TODO - If we create an autoload that is in the map, that
  309. ;; map needs to be cleared!
  310. ;; Does our parent exist?
  311. (if (not (class-p SC))
  312. ;; Create a symbol for this parent, and then store this
  313. ;; parent on that symbol.
  314. (let ((sym (intern (symbol-name SC) eieio-defclass-autoload-map)))
  315. (if (not (boundp sym))
  316. (set sym (list cname))
  317. (add-to-list sym cname))
  318. )
  319. ;; We have a parent, save the child in there.
  320. (when (not (member cname (aref (class-v SC) class-children)))
  321. (aset (class-v SC) class-children
  322. (cons cname (aref (class-v SC) class-children)))))
  323. ;; save parent in child
  324. (aset newc class-parent (cons SC (aref newc class-parent)))
  325. )
  326. ;; turn this into a usable self-pointing symbol
  327. (set cname cname)
  328. ;; Store the new class vector definition into the symbol. We need to
  329. ;; do this first so that we can call defmethod for the accessor.
  330. ;; The vector will be updated by the following while loop and will not
  331. ;; need to be stored a second time.
  332. (put cname 'eieio-class-definition newc)
  333. ;; Clear the parent
  334. (if clear-parent (aset newc class-parent nil))
  335. ;; Create an autoload on top of our constructor function.
  336. (autoload cname filename doc nil nil)
  337. (autoload (intern (concat (symbol-name cname) "-p")) filename "" nil nil)
  338. (autoload (intern (concat (symbol-name cname) "-child-p")) filename "" nil nil)
  339. ))))
  340. (defsubst eieio-class-un-autoload (cname)
  341. "If class CNAME is in an autoload state, load its file."
  342. (when (eq (car-safe (symbol-function cname)) 'autoload)
  343. (load-library (car (cdr (symbol-function cname))))))
  344. (defun eieio-defclass (cname superclasses slots options-and-doc)
  345. ;; FIXME: Most of this should be moved to the `defclass' macro.
  346. "Define CNAME as a new subclass of SUPERCLASSES.
  347. SLOTS are the slots residing in that class definition, and options or
  348. documentation OPTIONS-AND-DOC is the toplevel documentation for this class.
  349. See `defclass' for more information."
  350. ;; Run our eieio-hook each time, and clear it when we are done.
  351. ;; This way people can add hooks safely if they want to modify eieio
  352. ;; or add definitions when eieio is loaded or something like that.
  353. (run-hooks 'eieio-hook)
  354. (setq eieio-hook nil)
  355. (if (not (symbolp cname)) (signal 'wrong-type-argument '(symbolp cname)))
  356. (if (not (listp superclasses)) (signal 'wrong-type-argument '(listp superclasses)))
  357. (let* ((pname (if superclasses superclasses nil))
  358. (newc (make-vector class-num-slots nil))
  359. (oldc (when (class-p cname) (class-v cname)))
  360. (groups nil) ;; list of groups id'd from slots
  361. (options nil)
  362. (clearparent nil))
  363. (aset newc 0 'defclass)
  364. (aset newc class-symbol cname)
  365. ;; If this class already existed, and we are updating its structure,
  366. ;; make sure we keep the old child list. This can cause bugs, but
  367. ;; if no new slots are created, it also saves time, and prevents
  368. ;; method table breakage, particularly when the users is only
  369. ;; byte compiling an EIEIO file.
  370. (if oldc
  371. (aset newc class-children (aref oldc class-children))
  372. ;; If the old class did not exist, but did exist in the autoload map, then adopt those children.
  373. ;; This is like the above, but deals with autoloads nicely.
  374. (let ((sym (intern-soft (symbol-name cname) eieio-defclass-autoload-map)))
  375. (when sym
  376. (condition-case nil
  377. (aset newc class-children (symbol-value sym))
  378. (error nil))
  379. (unintern (symbol-name cname) eieio-defclass-autoload-map)
  380. ))
  381. )
  382. (cond ((and (stringp (car options-and-doc))
  383. (/= 1 (% (length options-and-doc) 2)))
  384. (error "Too many arguments to `defclass'"))
  385. ((and (symbolp (car options-and-doc))
  386. (/= 0 (% (length options-and-doc) 2)))
  387. (error "Too many arguments to `defclass'"))
  388. )
  389. (setq options
  390. (if (stringp (car options-and-doc))
  391. (cons :documentation options-and-doc)
  392. options-and-doc))
  393. (if pname
  394. (progn
  395. (while pname
  396. (if (and (car pname) (symbolp (car pname)))
  397. (if (not (class-p (car pname)))
  398. ;; bad class
  399. (error "Given parent class %s is not a class" (car pname))
  400. ;; good parent class...
  401. ;; save new child in parent
  402. (when (not (member cname (aref (class-v (car pname)) class-children)))
  403. (aset (class-v (car pname)) class-children
  404. (cons cname (aref (class-v (car pname)) class-children))))
  405. ;; Get custom groups, and store them into our local copy.
  406. (mapc (lambda (g) (add-to-list 'groups g))
  407. (class-option (car pname) :custom-groups))
  408. ;; save parent in child
  409. (aset newc class-parent (cons (car pname) (aref newc class-parent))))
  410. (error "Invalid parent class %s" pname))
  411. (setq pname (cdr pname)))
  412. ;; Reverse the list of our parents so that they are prioritized in
  413. ;; the same order as specified in the code.
  414. (aset newc class-parent (nreverse (aref newc class-parent))) )
  415. ;; If there is nothing to loop over, then inherit from the
  416. ;; default superclass.
  417. (unless (eq cname 'eieio-default-superclass)
  418. ;; adopt the default parent here, but clear it later...
  419. (setq clearparent t)
  420. ;; save new child in parent
  421. (if (not (member cname (aref (class-v 'eieio-default-superclass) class-children)))
  422. (aset (class-v 'eieio-default-superclass) class-children
  423. (cons cname (aref (class-v 'eieio-default-superclass) class-children))))
  424. ;; save parent in child
  425. (aset newc class-parent (list eieio-default-superclass))))
  426. ;; turn this into a usable self-pointing symbol
  427. (set cname cname)
  428. ;; These two tests must be created right away so we can have self-
  429. ;; referencing classes. ei, a class whose slot can contain only
  430. ;; pointers to itself.
  431. ;; Create the test function
  432. (let ((csym (intern (concat (symbol-name cname) "-p"))))
  433. (fset csym
  434. (list 'lambda (list 'obj)
  435. (format "Test OBJ to see if it an object of type %s" cname)
  436. (list 'and '(eieio-object-p obj)
  437. (list 'same-class-p 'obj cname)))))
  438. ;; Make sure the method invocation order is a valid value.
  439. (let ((io (class-option-assoc options :method-invocation-order)))
  440. (when (and io (not (member io '(:depth-first :breadth-first :c3))))
  441. (error "Method invocation order %s is not allowed" io)
  442. ))
  443. ;; Create a handy child test too
  444. (let ((csym (intern (concat (symbol-name cname) "-child-p"))))
  445. (fset csym
  446. `(lambda (obj)
  447. ,(format
  448. "Test OBJ to see if it an object is a child of type %s"
  449. cname)
  450. (and (eieio-object-p obj)
  451. (object-of-class-p obj ,cname))))
  452. ;; When using typep, (typep OBJ 'myclass) returns t for objects which
  453. ;; are subclasses of myclass. For our predicates, however, it is
  454. ;; important for EIEIO to be backwards compatible, where
  455. ;; myobject-p, and myobject-child-p are different.
  456. ;; "cl" uses this technique to specify symbols with specific typep
  457. ;; test, so we can let typep have the CLOS documented behavior
  458. ;; while keeping our above predicate clean.
  459. ;; It would be cleaner to use `defsetf' here, but that requires cl
  460. ;; at runtime.
  461. (put cname 'cl-deftype-handler
  462. (list 'lambda () `(list 'satisfies (quote ,csym)))))
  463. ;; before adding new slots, let's add all the methods and classes
  464. ;; in from the parent class
  465. (eieio-copy-parents-into-subclass newc superclasses)
  466. ;; Store the new class vector definition into the symbol. We need to
  467. ;; do this first so that we can call defmethod for the accessor.
  468. ;; The vector will be updated by the following while loop and will not
  469. ;; need to be stored a second time.
  470. (put cname 'eieio-class-definition newc)
  471. ;; Query each slot in the declaration list and mangle into the
  472. ;; class structure I have defined.
  473. (while slots
  474. (let* ((slot1 (car slots))
  475. (name (car slot1))
  476. (slot (cdr slot1))
  477. (acces (plist-get slot ':accessor))
  478. (init (or (plist-get slot ':initform)
  479. (if (member ':initform slot) nil
  480. eieio-unbound)))
  481. (initarg (plist-get slot ':initarg))
  482. (docstr (plist-get slot ':documentation))
  483. (prot (plist-get slot ':protection))
  484. (reader (plist-get slot ':reader))
  485. (writer (plist-get slot ':writer))
  486. (alloc (plist-get slot ':allocation))
  487. (type (plist-get slot ':type))
  488. (custom (plist-get slot ':custom))
  489. (label (plist-get slot ':label))
  490. (customg (plist-get slot ':group))
  491. (printer (plist-get slot ':printer))
  492. (skip-nil (class-option-assoc options :allow-nil-initform))
  493. )
  494. (if eieio-error-unsupported-class-tags
  495. (let ((tmp slot))
  496. (while tmp
  497. (if (not (member (car tmp) '(:accessor
  498. :initform
  499. :initarg
  500. :documentation
  501. :protection
  502. :reader
  503. :writer
  504. :allocation
  505. :type
  506. :custom
  507. :label
  508. :group
  509. :printer
  510. :allow-nil-initform
  511. :custom-groups)))
  512. (signal 'invalid-slot-type (list (car tmp))))
  513. (setq tmp (cdr (cdr tmp))))))
  514. ;; Clean up the meaning of protection.
  515. (cond ((or (eq prot 'public) (eq prot :public)) (setq prot nil))
  516. ((or (eq prot 'protected) (eq prot :protected)) (setq prot 'protected))
  517. ((or (eq prot 'private) (eq prot :private)) (setq prot 'private))
  518. ((eq prot nil) nil)
  519. (t (signal 'invalid-slot-type (list ':protection prot))))
  520. ;; Make sure the :allocation parameter has a valid value.
  521. (if (not (or (not alloc) (eq alloc :class) (eq alloc :instance)))
  522. (signal 'invalid-slot-type (list ':allocation alloc)))
  523. ;; The default type specifier is supposed to be t, meaning anything.
  524. (if (not type) (setq type t))
  525. ;; Label is nil, or a string
  526. (if (not (or (null label) (stringp label)))
  527. (signal 'invalid-slot-type (list ':label label)))
  528. ;; Is there an initarg, but allocation of class?
  529. (if (and initarg (eq alloc :class))
  530. (message "Class allocated slots do not need :initarg"))
  531. ;; intern the symbol so we can use it blankly
  532. (if initarg (set initarg initarg))
  533. ;; The customgroup should be a list of symbols
  534. (cond ((null customg)
  535. (setq customg '(default)))
  536. ((not (listp customg))
  537. (setq customg (list customg))))
  538. ;; The customgroup better be a symbol, or list of symbols.
  539. (mapc (lambda (cg)
  540. (if (not (symbolp cg))
  541. (signal 'invalid-slot-type (list ':group cg))))
  542. customg)
  543. ;; First up, add this slot into our new class.
  544. (eieio-add-new-slot newc name init docstr type custom label customg printer
  545. prot initarg alloc 'defaultoverride skip-nil)
  546. ;; We need to id the group, and store them in a group list attribute.
  547. (mapc (lambda (cg) (add-to-list 'groups cg)) customg)
  548. ;; anyone can have an accessor function. This creates a function
  549. ;; of the specified name, and also performs a `defsetf' if applicable
  550. ;; so that users can `setf' the space returned by this function
  551. (if acces
  552. (progn
  553. (eieio--defmethod
  554. acces (if (eq alloc :class) :static :primary) cname
  555. `(lambda (this)
  556. ,(format
  557. "Retrieves the slot `%s' from an object of class `%s'"
  558. name cname)
  559. (if (slot-boundp this ',name)
  560. (eieio-oref this ',name)
  561. ;; Else - Some error? nil?
  562. nil)))
  563. ;; Provide a setf method. It would be cleaner to use
  564. ;; defsetf, but that would require CL at runtime.
  565. (put acces 'setf-method
  566. `(lambda (widget)
  567. (let* ((--widget-sym-- (make-symbol "--widget--"))
  568. (--store-sym-- (make-symbol "--store--")))
  569. (list
  570. (list --widget-sym--)
  571. (list widget)
  572. (list --store-sym--)
  573. (list 'eieio-oset --widget-sym-- '',name --store-sym--)
  574. (list 'getfoo --widget-sym--)))))))
  575. ;; If a writer is defined, then create a generic method of that
  576. ;; name whose purpose is to set the value of the slot.
  577. (if writer
  578. (eieio--defmethod
  579. writer nil cname
  580. `(lambda (this value)
  581. ,(format "Set the slot `%s' of an object of class `%s'"
  582. name cname)
  583. (setf (slot-value this ',name) value))))
  584. ;; If a reader is defined, then create a generic method
  585. ;; of that name whose purpose is to access this slot value.
  586. (if reader
  587. (eieio--defmethod
  588. reader nil cname
  589. `(lambda (this)
  590. ,(format "Access the slot `%s' from object of class `%s'"
  591. name cname)
  592. (slot-value this ',name))))
  593. )
  594. (setq slots (cdr slots)))
  595. ;; Now that everything has been loaded up, all our lists are backwards! Fix that up now.
  596. (aset newc class-public-a (nreverse (aref newc class-public-a)))
  597. (aset newc class-public-d (nreverse (aref newc class-public-d)))
  598. (aset newc class-public-doc (nreverse (aref newc class-public-doc)))
  599. (aset newc class-public-type
  600. (apply 'vector (nreverse (aref newc class-public-type))))
  601. (aset newc class-public-custom (nreverse (aref newc class-public-custom)))
  602. (aset newc class-public-custom-label (nreverse (aref newc class-public-custom-label)))
  603. (aset newc class-public-custom-group (nreverse (aref newc class-public-custom-group)))
  604. (aset newc class-public-printer (nreverse (aref newc class-public-printer)))
  605. (aset newc class-protection (nreverse (aref newc class-protection)))
  606. (aset newc class-initarg-tuples (nreverse (aref newc class-initarg-tuples)))
  607. ;; The storage for class-class-allocation-type needs to be turned into
  608. ;; a vector now.
  609. (aset newc class-class-allocation-type
  610. (apply 'vector (aref newc class-class-allocation-type)))
  611. ;; Also, take class allocated values, and vectorize them for speed.
  612. (aset newc class-class-allocation-values
  613. (apply 'vector (aref newc class-class-allocation-values)))
  614. ;; Attach slot symbols into an obarray, and store the index of
  615. ;; this slot as the variable slot in this new symbol. We need to
  616. ;; know about primes, because obarrays are best set in vectors of
  617. ;; prime number length, and we also need to make our vector small
  618. ;; to save space, and also optimal for the number of items we have.
  619. (let* ((cnt 0)
  620. (pubsyms (aref newc class-public-a))
  621. (prots (aref newc class-protection))
  622. (l (length pubsyms))
  623. (vl (let ((primes '( 3 5 7 11 13 17 19 23 29 31 37 41 43 47
  624. 53 59 61 67 71 73 79 83 89 97 101 )))
  625. (while (and primes (< (car primes) l))
  626. (setq primes (cdr primes)))
  627. (car primes)))
  628. (oa (make-vector vl 0))
  629. (newsym))
  630. (while pubsyms
  631. (setq newsym (intern (symbol-name (car pubsyms)) oa))
  632. (set newsym cnt)
  633. (setq cnt (1+ cnt))
  634. (if (car prots) (put newsym 'protection (car prots)))
  635. (setq pubsyms (cdr pubsyms)
  636. prots (cdr prots)))
  637. (aset newc class-symbol-obarray oa)
  638. )
  639. ;; Create the constructor function
  640. (if (class-option-assoc options :abstract)
  641. ;; Abstract classes cannot be instantiated. Say so.
  642. (let ((abs (class-option-assoc options :abstract)))
  643. (if (not (stringp abs))
  644. (setq abs (format "Class %s is abstract" cname)))
  645. (fset cname
  646. `(lambda (&rest stuff)
  647. ,(format "You cannot create a new object of type %s" cname)
  648. (error ,abs))))
  649. ;; Non-abstract classes need a constructor.
  650. (fset cname
  651. `(lambda (newname &rest slots)
  652. ,(format "Create a new object with name NAME of class type %s" cname)
  653. (apply 'constructor ,cname newname slots)))
  654. )
  655. ;; Set up a specialized doc string.
  656. ;; Use stored value since it is calculated in a non-trivial way
  657. (put cname 'variable-documentation
  658. (class-option-assoc options :documentation))
  659. ;; We have a list of custom groups. Store them into the options.
  660. (let ((g (class-option-assoc options :custom-groups)))
  661. (mapc (lambda (cg) (add-to-list 'g cg)) groups)
  662. (if (memq :custom-groups options)
  663. (setcar (cdr (memq :custom-groups options)) g)
  664. (setq options (cons :custom-groups (cons g options)))))
  665. ;; Set up the options we have collected.
  666. (aset newc class-options options)
  667. ;; if this is a superclass, clear out parent (which was set to the
  668. ;; default superclass eieio-default-superclass)
  669. (if clearparent (aset newc class-parent nil))
  670. ;; Create the cached default object.
  671. (let ((cache (make-vector (+ (length (aref newc class-public-a))
  672. 3) nil)))
  673. (aset cache 0 'object)
  674. (aset cache object-class cname)
  675. (aset cache object-name 'default-cache-object)
  676. (let ((eieio-skip-typecheck t))
  677. ;; All type-checking has been done to our satisfaction
  678. ;; before this call. Don't waste our time in this call..
  679. (eieio-set-defaults cache t))
  680. (aset newc class-default-object-cache cache))
  681. ;; Return our new class object
  682. ;; newc
  683. cname
  684. ))
  685. (defun eieio-perform-slot-validation-for-default (slot spec value skipnil)
  686. "For SLOT, signal if SPEC does not match VALUE.
  687. If SKIPNIL is non-nil, then if VALUE is nil return t instead."
  688. (if (and (not (eieio-eval-default-p value))
  689. (not eieio-skip-typecheck)
  690. (not (and skipnil (null value)))
  691. (not (eieio-perform-slot-validation spec value)))
  692. (signal 'invalid-slot-type (list slot spec value))))
  693. (defun eieio-add-new-slot (newc a d doc type cust label custg print prot init alloc
  694. &optional defaultoverride skipnil)
  695. "Add into NEWC attribute A.
  696. If A already exists in NEWC, then do nothing. If it doesn't exist,
  697. then also add in D (default), DOC, TYPE, CUST, LABEL, CUSTG, PRINT, PROT, and INIT arg.
  698. Argument ALLOC specifies if the slot is allocated per instance, or per class.
  699. If optional DEFAULTOVERRIDE is non-nil, then if A exists in NEWC,
  700. we must override its value for a default.
  701. Optional argument SKIPNIL indicates if type checking should be skipped
  702. if default value is nil."
  703. ;; Make sure we duplicate those items that are sequences.
  704. (condition-case nil
  705. (if (sequencep d) (setq d (copy-sequence d)))
  706. ;; This copy can fail on a cons cell with a non-cons in the cdr. Let's skip it if it doesn't work.
  707. (error nil))
  708. (if (sequencep type) (setq type (copy-sequence type)))
  709. (if (sequencep cust) (setq cust (copy-sequence cust)))
  710. (if (sequencep custg) (setq custg (copy-sequence custg)))
  711. ;; To prevent override information w/out specification of storage,
  712. ;; we need to do this little hack.
  713. (if (member a (aref newc class-class-allocation-a)) (setq alloc ':class))
  714. (if (or (not alloc) (and (symbolp alloc) (eq alloc ':instance)))
  715. ;; In this case, we modify the INSTANCE version of a given slot.
  716. (progn
  717. ;; Only add this element if it is so-far unique
  718. (if (not (member a (aref newc class-public-a)))
  719. (progn
  720. (eieio-perform-slot-validation-for-default a type d skipnil)
  721. (aset newc class-public-a (cons a (aref newc class-public-a)))
  722. (aset newc class-public-d (cons d (aref newc class-public-d)))
  723. (aset newc class-public-doc (cons doc (aref newc class-public-doc)))
  724. (aset newc class-public-type (cons type (aref newc class-public-type)))
  725. (aset newc class-public-custom (cons cust (aref newc class-public-custom)))
  726. (aset newc class-public-custom-label (cons label (aref newc class-public-custom-label)))
  727. (aset newc class-public-custom-group (cons custg (aref newc class-public-custom-group)))
  728. (aset newc class-public-printer (cons print (aref newc class-public-printer)))
  729. (aset newc class-protection (cons prot (aref newc class-protection)))
  730. (aset newc class-initarg-tuples (cons (cons init a) (aref newc class-initarg-tuples)))
  731. )
  732. ;; When defaultoverride is true, we are usually adding new local
  733. ;; attributes which must override the default value of any slot
  734. ;; passed in by one of the parent classes.
  735. (when defaultoverride
  736. ;; There is a match, and we must override the old value.
  737. (let* ((ca (aref newc class-public-a))
  738. (np (member a ca))
  739. (num (- (length ca) (length np)))
  740. (dp (if np (nthcdr num (aref newc class-public-d))
  741. nil))
  742. (tp (if np (nth num (aref newc class-public-type))))
  743. )
  744. (if (not np)
  745. (error "EIEIO internal error overriding default value for %s"
  746. a)
  747. ;; If type is passed in, is it the same?
  748. (if (not (eq type t))
  749. (if (not (equal type tp))
  750. (error
  751. "Child slot type `%s' does not match inherited type `%s' for `%s'"
  752. type tp a)))
  753. ;; If we have a repeat, only update the initarg...
  754. (unless (eq d eieio-unbound)
  755. (eieio-perform-slot-validation-for-default a tp d skipnil)
  756. (setcar dp d))
  757. ;; If we have a new initarg, check for it.
  758. (when init
  759. (let* ((inits (aref newc class-initarg-tuples))
  760. (inita (rassq a inits)))
  761. ;; Replace the CAR of the associate INITA.
  762. ;;(message "Initarg: %S replace %s" inita init)
  763. (setcar inita init)
  764. ))
  765. ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
  766. ;; checked and SHOULD match the superclass
  767. ;; protection. Otherwise an error is thrown. However
  768. ;; I wonder if a more flexible schedule might be
  769. ;; implemented.
  770. ;;
  771. ;; EML - We used to have (if prot... here,
  772. ;; but a prot of 'nil means public.
  773. ;;
  774. (let ((super-prot (nth num (aref newc class-protection)))
  775. )
  776. (if (not (eq prot super-prot))
  777. (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
  778. prot super-prot a)))
  779. ;; End original PLN
  780. ;; PLN Tue Jun 26 11:57:06 2007 :
  781. ;; Do a non redundant combination of ancient custom
  782. ;; groups and new ones.
  783. (when custg
  784. (let* ((groups
  785. (nthcdr num (aref newc class-public-custom-group)))
  786. (list1 (car groups))
  787. (list2 (if (listp custg) custg (list custg))))
  788. (if (< (length list1) (length list2))
  789. (setq list1 (prog1 list2 (setq list2 list1))))
  790. (dolist (elt list2)
  791. (unless (memq elt list1)
  792. (push elt list1)))
  793. (setcar groups list1)))
  794. ;; End PLN
  795. ;; PLN Mon Jun 25 22:44:34 2007 : If a new cust is
  796. ;; set, simply replaces the old one.
  797. (when cust
  798. ;; (message "Custom type redefined to %s" cust)
  799. (setcar (nthcdr num (aref newc class-public-custom)) cust))
  800. ;; If a new label is specified, it simply replaces
  801. ;; the old one.
  802. (when label
  803. ;; (message "Custom label redefined to %s" label)
  804. (setcar (nthcdr num (aref newc class-public-custom-label)) label))
  805. ;; End PLN
  806. ;; PLN Sat Jun 30 17:24:42 2007 : when a new
  807. ;; doc is specified, simply replaces the old one.
  808. (when doc
  809. ;;(message "Documentation redefined to %s" doc)
  810. (setcar (nthcdr num (aref newc class-public-doc))
  811. doc))
  812. ;; End PLN
  813. ;; If a new printer is specified, it simply replaces
  814. ;; the old one.
  815. (when print
  816. ;; (message "printer redefined to %s" print)
  817. (setcar (nthcdr num (aref newc class-public-printer)) print))
  818. )))
  819. ))
  820. ;; CLASS ALLOCATED SLOTS
  821. (let ((value (eieio-default-eval-maybe d)))
  822. (if (not (member a (aref newc class-class-allocation-a)))
  823. (progn
  824. (eieio-perform-slot-validation-for-default a type value skipnil)
  825. ;; Here we have found a :class version of a slot. This
  826. ;; requires a very different approach.
  827. (aset newc class-class-allocation-a (cons a (aref newc class-class-allocation-a)))
  828. (aset newc class-class-allocation-doc (cons doc (aref newc class-class-allocation-doc)))
  829. (aset newc class-class-allocation-type (cons type (aref newc class-class-allocation-type)))
  830. (aset newc class-class-allocation-custom (cons cust (aref newc class-class-allocation-custom)))
  831. (aset newc class-class-allocation-custom-label (cons label (aref newc class-class-allocation-custom-label)))
  832. (aset newc class-class-allocation-custom-group (cons custg (aref newc class-class-allocation-custom-group)))
  833. (aset newc class-class-allocation-protection (cons prot (aref newc class-class-allocation-protection)))
  834. ;; Default value is stored in the 'values section, since new objects
  835. ;; can't initialize from this element.
  836. (aset newc class-class-allocation-values (cons value (aref newc class-class-allocation-values))))
  837. (when defaultoverride
  838. ;; There is a match, and we must override the old value.
  839. (let* ((ca (aref newc class-class-allocation-a))
  840. (np (member a ca))
  841. (num (- (length ca) (length np)))
  842. (dp (if np
  843. (nthcdr num
  844. (aref newc class-class-allocation-values))
  845. nil))
  846. (tp (if np (nth num (aref newc class-class-allocation-type))
  847. nil)))
  848. (if (not np)
  849. (error "EIEIO internal error overriding default value for %s"
  850. a)
  851. ;; If type is passed in, is it the same?
  852. (if (not (eq type t))
  853. (if (not (equal type tp))
  854. (error
  855. "Child slot type `%s' does not match inherited type `%s' for `%s'"
  856. type tp a)))
  857. ;; EML - Note: the only reason to override a class bound slot
  858. ;; is to change the default, so allow unbound in.
  859. ;; If we have a repeat, only update the value...
  860. (eieio-perform-slot-validation-for-default a tp value skipnil)
  861. (setcar dp value))
  862. ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
  863. ;; checked and SHOULD match the superclass
  864. ;; protection. Otherwise an error is thrown. However
  865. ;; I wonder if a more flexible schedule might be
  866. ;; implemented.
  867. (let ((super-prot
  868. (car (nthcdr num (aref newc class-class-allocation-protection)))))
  869. (if (not (eq prot super-prot))
  870. (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
  871. prot super-prot a)))
  872. ;; Do a non redundant combination of ancient custom groups
  873. ;; and new ones.
  874. (when custg
  875. (let* ((groups
  876. (nthcdr num (aref newc class-class-allocation-custom-group)))
  877. (list1 (car groups))
  878. (list2 (if (listp custg) custg (list custg))))
  879. (if (< (length list1) (length list2))
  880. (setq list1 (prog1 list2 (setq list2 list1))))
  881. (dolist (elt list2)
  882. (unless (memq elt list1)
  883. (push elt list1)))
  884. (setcar groups list1)))
  885. ;; PLN Sat Jun 30 17:24:42 2007 : when a new
  886. ;; doc is specified, simply replaces the old one.
  887. (when doc
  888. ;;(message "Documentation redefined to %s" doc)
  889. (setcar (nthcdr num (aref newc class-class-allocation-doc))
  890. doc))
  891. ;; End PLN
  892. ;; If a new printer is specified, it simply replaces
  893. ;; the old one.
  894. (when print
  895. ;; (message "printer redefined to %s" print)
  896. (setcar (nthcdr num (aref newc class-class-allocation-printer)) print))
  897. ))
  898. ))
  899. ))
  900. (defun eieio-copy-parents-into-subclass (newc parents)
  901. "Copy into NEWC the slots of PARENTS.
  902. Follow the rules of not overwriting early parents when applying to
  903. the new child class."
  904. (let ((ps (aref newc class-parent))
  905. (sn (class-option-assoc (aref newc class-options)
  906. ':allow-nil-initform)))
  907. (while ps
  908. ;; First, duplicate all the slots of the parent.
  909. (let ((pcv (class-v (car ps))))
  910. (let ((pa (aref pcv class-public-a))
  911. (pd (aref pcv class-public-d))
  912. (pdoc (aref pcv class-public-doc))
  913. (ptype (aref pcv class-public-type))
  914. (pcust (aref pcv class-public-custom))
  915. (plabel (aref pcv class-public-custom-label))
  916. (pcustg (aref pcv class-public-custom-group))
  917. (printer (aref pcv class-public-printer))
  918. (pprot (aref pcv class-protection))
  919. (pinit (aref pcv class-initarg-tuples))
  920. (i 0))
  921. (while pa
  922. (eieio-add-new-slot newc
  923. (car pa) (car pd) (car pdoc) (aref ptype i)
  924. (car pcust) (car plabel) (car pcustg)
  925. (car printer)
  926. (car pprot) (car-safe (car pinit)) nil nil sn)
  927. ;; Increment each value.
  928. (setq pa (cdr pa)
  929. pd (cdr pd)
  930. pdoc (cdr pdoc)
  931. i (1+ i)
  932. pcust (cdr pcust)
  933. plabel (cdr plabel)
  934. pcustg (cdr pcustg)
  935. printer (cdr printer)
  936. pprot (cdr pprot)
  937. pinit (cdr pinit))
  938. )) ;; while/let
  939. ;; Now duplicate all the class alloc slots.
  940. (let ((pa (aref pcv class-class-allocation-a))
  941. (pdoc (aref pcv class-class-allocation-doc))
  942. (ptype (aref pcv class-class-allocation-type))
  943. (pcust (aref pcv class-class-allocation-custom))
  944. (plabel (aref pcv class-class-allocation-custom-label))
  945. (pcustg (aref pcv class-class-allocation-custom-group))
  946. (printer (aref pcv class-class-allocation-printer))
  947. (pprot (aref pcv class-class-allocation-protection))
  948. (pval (aref pcv class-class-allocation-values))
  949. (i 0))
  950. (while pa
  951. (eieio-add-new-slot newc
  952. (car pa) (aref pval i) (car pdoc) (aref ptype i)
  953. (car pcust) (car plabel) (car pcustg)
  954. (car printer)
  955. (car pprot) nil ':class sn)
  956. ;; Increment each value.
  957. (setq pa (cdr pa)
  958. pdoc (cdr pdoc)
  959. pcust (cdr pcust)
  960. plabel (cdr plabel)
  961. pcustg (cdr pcustg)
  962. printer (cdr printer)
  963. pprot (cdr pprot)
  964. i (1+ i))
  965. ))) ;; while/let
  966. ;; Loop over each parent class
  967. (setq ps (cdr ps)))
  968. ))
  969. ;;; CLOS style implementation of object creators.
  970. ;;
  971. (defun make-instance (class &rest initargs)
  972. "Make a new instance of CLASS based on INITARGS.
  973. CLASS is a class symbol. For example:
  974. (make-instance 'foo)
  975. INITARGS is a property list with keywords based on the :initarg
  976. for each slot. For example:
  977. (make-instance 'foo :slot1 value1 :slotN valueN)
  978. Compatibility note:
  979. If the first element of INITARGS is a string, it is used as the
  980. name of the class.
  981. In EIEIO, the class' constructor requires a name for use when printing.
  982. `make-instance' in CLOS doesn't use names the way Emacs does, so the
  983. class is used as the name slot instead when INITARGS doesn't start with
  984. a string."
  985. (if (and (car initargs) (stringp (car initargs)))
  986. (apply (class-constructor class) initargs)
  987. (apply (class-constructor class)
  988. (cond ((symbolp class) (symbol-name class))
  989. (t (format "%S" class)))
  990. initargs)))
  991. ;;; CLOS methods and generics
  992. ;;
  993. (put 'eieio--defalias 'byte-hunk-handler
  994. #'byte-compile-file-form-defalias) ;;(get 'defalias 'byte-hunk-handler)
  995. (defun eieio--defalias (name body)
  996. "Like `defalias', but with less side-effects.
  997. More specifically, it has no side-effects at all when the new function
  998. definition is the same (`eq') as the old one."
  999. (unless (and (fboundp name)
  1000. (eq (symbol-function name) body))
  1001. (defalias name body)))
  1002. (defmacro defgeneric (method args &optional doc-string)
  1003. "Create a generic function METHOD.
  1004. DOC-STRING is the base documentation for this class. A generic
  1005. function has no body, as its purpose is to decide which method body
  1006. is appropriate to use. Uses `defmethod' to create methods, and calls
  1007. `defgeneric' for you. With this implementation the ARGS are
  1008. currently ignored. You can use `defgeneric' to apply specialized
  1009. top level documentation to a method."
  1010. `(eieio--defalias ',method
  1011. (eieio--defgeneric-init-form ',method ,doc-string)))
  1012. (defun eieio--defgeneric-init-form (method doc-string)
  1013. "Form to use for the initial definition of a generic."
  1014. (cond
  1015. ((or (not (fboundp method))
  1016. (eq 'autoload (car-safe (symbol-function method))))
  1017. ;; Make sure the method tables are installed.
  1018. (eieiomt-install method)
  1019. ;; Construct the actual body of this function.
  1020. (eieio-defgeneric-form method doc-string))
  1021. ((generic-p method) (symbol-function method)) ;Leave it as-is.
  1022. (t (error "You cannot create a generic/method over an existing symbol: %s"
  1023. method))))
  1024. (defun eieio-defgeneric-form (method doc-string)
  1025. "The lambda form that would be used as the function defined on METHOD.
  1026. All methods should call the same EIEIO function for dispatch.
  1027. DOC-STRING is the documentation attached to METHOD."
  1028. `(lambda (&rest local-args)
  1029. ,doc-string
  1030. (eieio-generic-call (quote ,method) local-args)))
  1031. (defsubst eieio-defgeneric-reset-generic-form (method)
  1032. "Setup METHOD to call the generic form."
  1033. (let ((doc-string (documentation method)))
  1034. (fset method (eieio-defgeneric-form method doc-string))))
  1035. (defun eieio-defgeneric-form-primary-only (method doc-string)
  1036. "The lambda form that would be used as the function defined on METHOD.
  1037. All methods should call the same EIEIO function for dispatch.
  1038. DOC-STRING is the documentation attached to METHOD."
  1039. `(lambda (&rest local-args)
  1040. ,doc-string
  1041. (eieio-generic-call-primary-only (quote ,method) local-args)))
  1042. (defsubst eieio-defgeneric-reset-generic-form-primary-only (method)
  1043. "Setup METHOD to call the generic form."
  1044. (let ((doc-string (documentation method)))
  1045. (fset method (eieio-defgeneric-form-primary-only method doc-string))))
  1046. (defun eieio-defgeneric-form-primary-only-one (method doc-string
  1047. class
  1048. impl
  1049. )
  1050. "The lambda form that would be used as the function defined on METHOD.
  1051. All methods should call the same EIEIO function for dispatch.
  1052. DOC-STRING is the documentation attached to METHOD.
  1053. CLASS is the class symbol needed for private method access.
  1054. IMPL is the symbol holding the method implementation."
  1055. ;; NOTE: I tried out byte compiling this little fcn. Turns out it
  1056. ;; is faster to execute this for not byte-compiled. ie, install this,
  1057. ;; then measure calls going through here. I wonder why.
  1058. (require 'bytecomp)
  1059. (let ((byte-compile-warnings nil))
  1060. (byte-compile
  1061. `(lambda (&rest local-args)
  1062. ,doc-string
  1063. ;; This is a cool cheat. Usually we need to look up in the
  1064. ;; method table to find out if there is a method or not. We can
  1065. ;; instead make that determination at load time when there is
  1066. ;; only one method. If the first arg is not a child of the class
  1067. ;; of that one implementation, then clearly, there is no method def.
  1068. (if (not (eieio-object-p (car local-args)))
  1069. ;; Not an object. Just signal.
  1070. (signal 'no-method-definition
  1071. (list ',method local-args))
  1072. ;; We do have an object. Make sure it is the right type.
  1073. (if ,(if (eq class eieio-default-superclass)
  1074. nil ; default superclass means just an obj. Already asked.
  1075. `(not (child-of-class-p (aref (car local-args) object-class)
  1076. ',class)))
  1077. ;; If not the right kind of object, call no applicable
  1078. (apply 'no-applicable-method (car local-args)
  1079. ',method local-args)
  1080. ;; It is ok, do the call.
  1081. ;; Fill in inter-call variables then evaluate the method.
  1082. (let ((scoped-class ',class)
  1083. (eieio-generic-call-next-method-list nil)
  1084. (eieio-generic-call-key method-primary)
  1085. (eieio-generic-call-methodname ',method)
  1086. (eieio-generic-call-arglst local-args)
  1087. )
  1088. (apply #',impl local-args)
  1089. ;;(,impl local-args)
  1090. )))))))
  1091. (defsubst eieio-defgeneric-reset-generic-form-primary-only-one (method)
  1092. "Setup METHOD to call the generic form."
  1093. (let* ((doc-string (documentation method))
  1094. (M (get method 'eieio-method-tree))
  1095. (entry (car (aref M method-primary)))
  1096. )
  1097. (fset method (eieio-defgeneric-form-primary-only-one
  1098. method doc-string
  1099. (car entry)
  1100. (cdr entry)
  1101. ))))
  1102. (defun eieio-unbind-method-implementations (method)
  1103. "Make the generic method METHOD have no implementations.
  1104. It will leave the original generic function in place,
  1105. but remove reference to all implementations of METHOD."
  1106. (put method 'eieio-method-tree nil)
  1107. (put method 'eieio-method-obarray nil))
  1108. (defmacro defmethod (method &rest args)
  1109. "Create a new METHOD through `defgeneric' with ARGS.
  1110. The optional second argument KEY is a specifier that
  1111. modifies how the method is called, including:
  1112. :before - Method will be called before the :primary
  1113. :primary - The default if not specified
  1114. :after - Method will be called after the :primary
  1115. :static - First arg could be an object or class
  1116. The next argument is the ARGLIST. The ARGLIST specifies the arguments
  1117. to the method as with `defun'. The first argument can have a type
  1118. specifier, such as:
  1119. ((VARNAME CLASS) ARG2 ...)
  1120. where VARNAME is the name of the local variable for the method being
  1121. created. The CLASS is a class symbol for a class made with `defclass'.
  1122. A DOCSTRING comes after the ARGLIST, and is optional.
  1123. All the rest of the args are the BODY of the method. A method will
  1124. return the value of the last form in the BODY.
  1125. Summary:
  1126. (defmethod mymethod [:before | :primary | :after | :static]
  1127. ((typearg class-name) arg2 &optional opt &rest rest)
  1128. \"doc-string\"
  1129. body)"
  1130. (let* ((key (if (keywordp (car args)) (pop args)))
  1131. (params (car args))
  1132. (arg1 (car params))
  1133. (fargs (if (consp arg1)
  1134. (cons (car arg1) (cdr params))
  1135. params))
  1136. (class (if (consp arg1) (nth 1 arg1)))
  1137. (code `(lambda ,fargs ,@(cdr args))))
  1138. `(progn
  1139. ;; Make sure there is a generic and the byte-compiler sees it.
  1140. (defgeneric ,method ,args
  1141. ,(or (documentation code)
  1142. (format "Generically created method `%s'." method)))
  1143. (eieio--defmethod ',method ',key ',class #',code))))
  1144. (defun eieio--defmethod (method kind argclass code)
  1145. "Work part of the `defmethod' macro defining METHOD with ARGS."
  1146. (let ((key
  1147. ;; find optional keys
  1148. (cond ((or (eq ':BEFORE kind)
  1149. (eq ':before kind))
  1150. method-before)
  1151. ((or (eq ':AFTER kind)
  1152. (eq ':after kind))
  1153. method-after)
  1154. ((or (eq ':PRIMARY kind)
  1155. (eq ':primary kind))
  1156. method-primary)
  1157. ((or (eq ':STATIC kind)
  1158. (eq ':static kind))
  1159. method-static)
  1160. ;; Primary key
  1161. (t method-primary))))
  1162. ;; Make sure there is a generic (when called from defclass).
  1163. (eieio--defalias
  1164. method (eieio--defgeneric-init-form
  1165. method (or (documentation code)
  1166. (format "Generically created method `%s'." method))))
  1167. ;; create symbol for property to bind to. If the first arg is of
  1168. ;; the form (varname vartype) and `vartype' is a class, then
  1169. ;; that class will be the type symbol. If not, then it will fall
  1170. ;; under the type `primary' which is a non-specific calling of the
  1171. ;; function.
  1172. (if argclass
  1173. (if (not (class-p argclass))
  1174. (error "Unknown class type %s in method parameters"
  1175. argclass))
  1176. (if (= key -1)
  1177. (signal 'wrong-type-argument (list :static 'non-class-arg)))
  1178. ;; generics are higher
  1179. (setq key (eieio-specialized-key-to-generic-key key)))
  1180. ;; Put this lambda into the symbol so we can find it
  1181. (eieiomt-add method code key argclass)
  1182. )
  1183. (when eieio-optimize-primary-methods-flag
  1184. ;; Optimizing step:
  1185. ;;
  1186. ;; If this method, after this setup, only has primary methods, then
  1187. ;; we can setup the generic that way.
  1188. (if (generic-primary-only-p method)
  1189. ;; If there is only one primary method, then we can go one more
  1190. ;; optimization step.
  1191. (if (generic-primary-only-one-p method)
  1192. (eieio-defgeneric-reset-generic-form-primary-only-one method)
  1193. (eieio-defgeneric-reset-generic-form-primary-only method))
  1194. (eieio-defgeneric-reset-generic-form method)))
  1195. method)
  1196. ;;; Slot type validation
  1197. ;; This is a hideous hack for replacing `typep' from cl-macs, to avoid
  1198. ;; requiring the CL library at run-time. It can be eliminated if/when
  1199. ;; `typep' is merged into Emacs core.
  1200. (defun eieio--typep (val type)
  1201. (if (symbolp type)
  1202. (cond ((get type 'cl-deftype-handler)
  1203. (eieio--typep val (funcall (get type 'cl-deftype-handler))))
  1204. ((eq type t) t)
  1205. ((eq type 'null) (null val))
  1206. ((eq type 'atom) (atom val))
  1207. ((eq type 'float) (and (numberp val) (not (integerp val))))
  1208. ((eq type 'real) (numberp val))
  1209. ((eq type 'fixnum) (integerp val))
  1210. ((memq type '(character string-char)) (characterp val))
  1211. (t
  1212. (let* ((name (symbol-name type))
  1213. (namep (intern (concat name "p"))))
  1214. (if (fboundp namep)
  1215. (funcall `(lambda () (,namep val)))
  1216. (funcall `(lambda ()
  1217. (,(intern (concat name "-p")) val)))))))
  1218. (cond ((get (car type) 'cl-deftype-handler)
  1219. (eieio--typep val (apply (get (car type) 'cl-deftype-handler)
  1220. (cdr type))))
  1221. ((memq (car type) '(integer float real number))
  1222. (and (eieio--typep val (car type))
  1223. (or (memq (cadr type) '(* nil))
  1224. (if (consp (cadr type))
  1225. (> val (car (cadr type)))
  1226. (>= val (cadr type))))
  1227. (or (memq (caddr type) '(* nil))
  1228. (if (consp (car (cddr type)))
  1229. (< val (caar (cddr type)))
  1230. (<= val (car (cddr type)))))))
  1231. ((memq (car type) '(and or not))
  1232. (eval (cons (car type)
  1233. (mapcar (lambda (x)
  1234. `(eieio--typep (quote ,val) (quote ,x)))
  1235. (cdr type)))))
  1236. ((memq (car type) '(member member*))
  1237. (memql val (cdr type)))
  1238. ((eq (car type) 'satisfies)
  1239. (funcall `(lambda () (,(cadr type) val))))
  1240. (t (error "Bad type spec: %s" type)))))
  1241. (defun eieio-perform-slot-validation (spec value)
  1242. "Return non-nil if SPEC does not match VALUE."
  1243. (or (eq spec t) ; t always passes
  1244. (eq value eieio-unbound) ; unbound always passes
  1245. (eieio--typep value spec)))
  1246. (defun eieio-validate-slot-value (class slot-idx value slot)
  1247. "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
  1248. Checks the :type specifier.
  1249. SLOT is the slot that is being checked, and is only used when throwing
  1250. an error."
  1251. (if eieio-skip-typecheck
  1252. nil
  1253. ;; Trim off object IDX junk added in for the object index.
  1254. (setq slot-idx (- slot-idx 3))
  1255. (let ((st (aref (aref (class-v class) class-public-type) slot-idx)))
  1256. (if (not (eieio-perform-slot-validation st value))
  1257. (signal 'invalid-slot-type (list class slot st value))))))
  1258. (defun eieio-validate-class-slot-value (class slot-idx value slot)
  1259. "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
  1260. Checks the :type specifier.
  1261. SLOT is the slot that is being checked, and is only used when throwing
  1262. an error."
  1263. (if eieio-skip-typecheck
  1264. nil
  1265. (let ((st (aref (aref (class-v class) class-class-allocation-type)
  1266. slot-idx)))
  1267. (if (not (eieio-perform-slot-validation st value))
  1268. (signal 'invalid-slot-type (list class slot st value))))))
  1269. (defun eieio-barf-if-slot-unbound (value instance slotname fn)
  1270. "Throw a signal if VALUE is a representation of an UNBOUND slot.
  1271. INSTANCE is the object being referenced. SLOTNAME is the offending
  1272. slot. If the slot is ok, return VALUE.
  1273. Argument FN is the function calling this verifier."
  1274. (if (and (eq value eieio-unbound) (not eieio-skip-typecheck))
  1275. (slot-unbound instance (object-class instance) slotname fn)
  1276. value))
  1277. ;;; Get/Set slots in an object.
  1278. ;;
  1279. (defmacro oref (obj slot)
  1280. "Retrieve the value stored in OBJ in the slot named by SLOT.
  1281. Slot is the name of the slot when created by `defclass' or the label
  1282. created by the :initarg tag."
  1283. `(eieio-oref ,obj (quote ,slot)))
  1284. (defun eieio-oref (obj slot)
  1285. "Return the value in OBJ at SLOT in the object vector."
  1286. (if (not (or (eieio-object-p obj) (class-p obj)))
  1287. (signal 'wrong-type-argument (list '(or eieio-object-p class-p) obj)))
  1288. (if (not (symbolp slot))
  1289. (signal 'wrong-type-argument (list 'symbolp slot)))
  1290. (if (class-p obj) (eieio-class-un-autoload obj))
  1291. (let* ((class (if (class-p obj) obj (aref obj object-class)))
  1292. (c (eieio-slot-name-index class obj slot)))
  1293. (if (not c)
  1294. ;; It might be missing because it is a :class allocated slot.
  1295. ;; Let's check that info out.
  1296. (if (setq c (eieio-class-slot-name-index class slot))
  1297. ;; Oref that slot.
  1298. (aref (aref (class-v class) class-class-allocation-values) c)
  1299. ;; The slot-missing method is a cool way of allowing an object author
  1300. ;; to intercept missing slot definitions. Since it is also the LAST
  1301. ;; thing called in this fn, its return value would be retrieved.
  1302. (slot-missing obj slot 'oref)
  1303. ;;(signal 'invalid-slot-name (list (object-name obj) slot))
  1304. )
  1305. (if (not (eieio-object-p obj))
  1306. (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1307. (eieio-barf-if-slot-unbound (aref obj c) obj slot 'oref))))
  1308. (defalias 'slot-value 'eieio-oref)
  1309. (defalias 'set-slot-value 'eieio-oset)
  1310. (defmacro oref-default (obj slot)
  1311. "Get the default value of OBJ (maybe a class) for SLOT.
  1312. The default value is the value installed in a class with the :initform
  1313. tag. SLOT can be the slot name, or the tag specified by the :initarg
  1314. tag in the `defclass' call."
  1315. `(eieio-oref-default ,obj (quote ,slot)))
  1316. (defun eieio-oref-default (obj slot)
  1317. "Do the work for the macro `oref-default' with similar parameters.
  1318. Fills in OBJ's SLOT with its default value."
  1319. (if (not (or (eieio-object-p obj) (class-p obj))) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1320. (if (not (symbolp slot)) (signal 'wrong-type-argument (list 'symbolp slot)))
  1321. (let* ((cl (if (eieio-object-p obj) (aref obj object-class) obj))
  1322. (c (eieio-slot-name-index cl obj slot)))
  1323. (if (not c)
  1324. ;; It might be missing because it is a :class allocated slot.
  1325. ;; Let's check that info out.
  1326. (if (setq c
  1327. (eieio-class-slot-name-index cl slot))
  1328. ;; Oref that slot.
  1329. (aref (aref (class-v cl) class-class-allocation-values)
  1330. c)
  1331. (slot-missing obj slot 'oref-default)
  1332. ;;(signal 'invalid-slot-name (list (class-name cl) slot))
  1333. )
  1334. (eieio-barf-if-slot-unbound
  1335. (let ((val (nth (- c 3) (aref (class-v cl) class-public-d))))
  1336. (eieio-default-eval-maybe val))
  1337. obj cl 'oref-default))))
  1338. (defsubst eieio-eval-default-p (val)
  1339. "Whether the default value VAL should be evaluated for use."
  1340. (and (consp val) (symbolp (car val)) (fboundp (car val))))
  1341. (defun eieio-default-eval-maybe (val)
  1342. "Check VAL, and return what `oref-default' would provide."
  1343. (cond
  1344. ;; Is it a function call? If so, evaluate it.
  1345. ((eieio-eval-default-p val)
  1346. (eval val))
  1347. ;;;; check for quoted things, and unquote them
  1348. ;;((and (consp val) (eq (car val) 'quote))
  1349. ;; (car (cdr val)))
  1350. ;; return it verbatim
  1351. (t val)))
  1352. ;;; Object Set macros
  1353. ;;
  1354. (defmacro oset (obj slot value)
  1355. "Set the value in OBJ for slot SLOT to VALUE.
  1356. SLOT is the slot name as specified in `defclass' or the tag created
  1357. with in the :initarg slot. VALUE can be any Lisp object."
  1358. `(eieio-oset ,obj (quote ,slot) ,value))
  1359. (defun eieio-oset (obj slot value)
  1360. "Do the work for the macro `oset'.
  1361. Fills in OBJ's SLOT with VALUE."
  1362. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1363. (if (not (symbolp slot)) (signal 'wrong-type-argument (list 'symbolp slot)))
  1364. (let ((c (eieio-slot-name-index (object-class-fast obj) obj slot)))
  1365. (if (not c)
  1366. ;; It might be missing because it is a :class allocated slot.
  1367. ;; Let's check that info out.
  1368. (if (setq c
  1369. (eieio-class-slot-name-index (aref obj object-class) slot))
  1370. ;; Oset that slot.
  1371. (progn
  1372. (eieio-validate-class-slot-value (object-class-fast obj) c value slot)
  1373. (aset (aref (class-v (aref obj object-class))
  1374. class-class-allocation-values)
  1375. c value))
  1376. ;; See oref for comment on `slot-missing'
  1377. (slot-missing obj slot 'oset value)
  1378. ;;(signal 'invalid-slot-name (list (object-name obj) slot))
  1379. )
  1380. (eieio-validate-slot-value (object-class-fast obj) c value slot)
  1381. (aset obj c value))))
  1382. (defmacro oset-default (class slot value)
  1383. "Set the default slot in CLASS for SLOT to VALUE.
  1384. The default value is usually set with the :initform tag during class
  1385. creation. This allows users to change the default behavior of classes
  1386. after they are created."
  1387. `(eieio-oset-default ,class (quote ,slot) ,value))
  1388. (defun eieio-oset-default (class slot value)
  1389. "Do the work for the macro `oset-default'.
  1390. Fills in the default value in CLASS' in SLOT with VALUE."
  1391. (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
  1392. (if (not (symbolp slot)) (signal 'wrong-type-argument (list 'symbolp slot)))
  1393. (let* ((scoped-class class)
  1394. (c (eieio-slot-name-index class nil slot)))
  1395. (if (not c)
  1396. ;; It might be missing because it is a :class allocated slot.
  1397. ;; Let's check that info out.
  1398. (if (setq c (eieio-class-slot-name-index class slot))
  1399. (progn
  1400. ;; Oref that slot.
  1401. (eieio-validate-class-slot-value class c value slot)
  1402. (aset (aref (class-v class) class-class-allocation-values) c
  1403. value))
  1404. (signal 'invalid-slot-name (list (class-name class) slot)))
  1405. (eieio-validate-slot-value class c value slot)
  1406. ;; Set this into the storage for defaults.
  1407. (setcar (nthcdr (- c 3) (aref (class-v class) class-public-d))
  1408. value)
  1409. ;; Take the value, and put it into our cache object.
  1410. (eieio-oset (aref (class-v class) class-default-object-cache)
  1411. slot value)
  1412. )))
  1413. ;;; Handy CLOS macros
  1414. ;;
  1415. (defmacro with-slots (spec-list object &rest body)
  1416. "Bind SPEC-LIST lexically to slot values in OBJECT, and execute BODY.
  1417. This establishes a lexical environment for referring to the slots in
  1418. the instance named by the given slot-names as though they were
  1419. variables. Within such a context the value of the slot can be
  1420. specified by using its slot name, as if it were a lexically bound
  1421. variable. Both setf and setq can be used to set the value of the
  1422. slot.
  1423. SPEC-LIST is of a form similar to `let'. For example:
  1424. ((VAR1 SLOT1)
  1425. SLOT2
  1426. SLOTN
  1427. (VARN+1 SLOTN+1))
  1428. Where each VAR is the local variable given to the associated
  1429. SLOT. A slot specified without a variable name is given a
  1430. variable name of the same name as the slot."
  1431. (declare (indent 2))
  1432. ;; Transform the spec-list into a symbol-macrolet spec-list.
  1433. (let ((mappings (mapcar (lambda (entry)
  1434. (let ((var (if (listp entry) (car entry) entry))
  1435. (slot (if (listp entry) (cadr entry) entry)))
  1436. (list var `(slot-value ,object ',slot))))
  1437. spec-list)))
  1438. (append (list 'symbol-macrolet mappings)
  1439. body)))
  1440. ;;; Simple generators, and query functions. None of these would do
  1441. ;; well embedded into an object.
  1442. ;;
  1443. (defmacro object-class-fast (obj) "Return the class struct defining OBJ with no check."
  1444. `(aref ,obj object-class))
  1445. (defun class-name (class) "Return a Lisp like symbol name for CLASS."
  1446. (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
  1447. ;; I think this is supposed to return a symbol, but to me CLASS is a symbol,
  1448. ;; and I wanted a string. Arg!
  1449. (format "#<class %s>" (symbol-name class)))
  1450. (defun object-name (obj &optional extra)
  1451. "Return a Lisp like symbol string for object OBJ.
  1452. If EXTRA, include that in the string returned to represent the symbol."
  1453. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1454. (format "#<%s %s%s>" (symbol-name (object-class-fast obj))
  1455. (aref obj object-name) (or extra "")))
  1456. (defun object-name-string (obj) "Return a string which is OBJ's name."
  1457. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1458. (aref obj object-name))
  1459. (defun object-set-name-string (obj name) "Set the string which is OBJ's NAME."
  1460. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1461. (if (not (stringp name)) (signal 'wrong-type-argument (list 'stringp name)))
  1462. (aset obj object-name name))
  1463. (defun object-class (obj) "Return the class struct defining OBJ."
  1464. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1465. (object-class-fast obj))
  1466. (defalias 'class-of 'object-class)
  1467. (defun object-class-name (obj) "Return a Lisp like symbol name for OBJ's class."
  1468. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1469. (class-name (object-class-fast obj)))
  1470. (defmacro class-parents-fast (class) "Return parent classes to CLASS with no check."
  1471. `(aref (class-v ,class) class-parent))
  1472. (defun class-parents (class)
  1473. "Return parent classes to CLASS. (overload of variable).
  1474. The CLOS function `class-direct-superclasses' is aliased to this function."
  1475. (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
  1476. (class-parents-fast class))
  1477. (defmacro class-children-fast (class) "Return child classes to CLASS with no check."
  1478. `(aref (class-v ,class) class-children))
  1479. (defun class-children (class)
  1480. "Return child classes to CLASS.
  1481. The CLOS function `class-direct-subclasses' is aliased to this function."
  1482. (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
  1483. (class-children-fast class))
  1484. (defun eieio-c3-candidate (class remaining-inputs)
  1485. "Returns CLASS if it can go in the result now, otherwise nil"
  1486. ;; Ensure CLASS is not in any position but the first in any of the
  1487. ;; element lists of REMAINING-INPUTS.
  1488. (and (not (let ((found nil))
  1489. (while (and remaining-inputs (not found))
  1490. (setq found (member class (cdr (car remaining-inputs)))
  1491. remaining-inputs (cdr remaining-inputs)))
  1492. found))
  1493. class))
  1494. (defun eieio-c3-merge-lists (reversed-partial-result remaining-inputs)
  1495. "Merge REVERSED-PARTIAL-RESULT REMAINING-INPUTS in a consistent order, if possible.
  1496. If a consistent order does not exist, signal an error."
  1497. (if (let ((tail remaining-inputs)
  1498. (found nil))
  1499. (while (and tail (not found))
  1500. (setq found (car tail) tail (cdr tail)))
  1501. (not found))
  1502. ;; If all remaining inputs are empty lists, we are done.
  1503. (nreverse reversed-partial-result)
  1504. ;; Otherwise, we try to find the next element of the result. This
  1505. ;; is achieved by considering the first element of each
  1506. ;; (non-empty) input list and accepting a candidate if it is
  1507. ;; consistent with the rests of the input lists.
  1508. (let* ((found nil)
  1509. (tail remaining-inputs)
  1510. (next (progn
  1511. (while (and tail (not found))
  1512. (setq found (and (car tail)
  1513. (eieio-c3-candidate (caar tail)
  1514. remaining-inputs))
  1515. tail (cdr tail)))
  1516. found)))
  1517. (if next
  1518. ;; The graph is consistent so far, add NEXT to result and
  1519. ;; merge input lists, dropping NEXT from their heads where
  1520. ;; applicable.
  1521. (eieio-c3-merge-lists
  1522. (cons next reversed-partial-result)
  1523. (mapcar (lambda (l) (if (eq (first l) next) (rest l) l))
  1524. remaining-inputs))
  1525. ;; The graph is inconsistent, give up
  1526. (signal 'inconsistent-class-hierarchy (list remaining-inputs))))))
  1527. (defun eieio-class-precedence-dfs (class)
  1528. "Return all parents of CLASS in depth-first order."
  1529. (let* ((parents (class-parents-fast class))
  1530. (classes (copy-sequence
  1531. (apply #'append
  1532. (list class)
  1533. (or
  1534. (mapcar
  1535. (lambda (parent)
  1536. (cons parent
  1537. (eieio-class-precedence-dfs parent)))
  1538. parents)
  1539. '((eieio-default-superclass))))))
  1540. (tail classes))
  1541. ;; Remove duplicates.
  1542. (while tail
  1543. (setcdr tail (delq (car tail) (cdr tail)))
  1544. (setq tail (cdr tail)))
  1545. classes))
  1546. (defun eieio-class-precedence-bfs (class)
  1547. "Return all parents of CLASS in breadth-first order."
  1548. (let ((result)
  1549. (queue (or (class-parents-fast class)
  1550. '(eieio-default-superclass))))
  1551. (while queue
  1552. (let ((head (pop queue)))
  1553. (unless (member head result)
  1554. (push head result)
  1555. (unless (eq head 'eieio-default-superclass)
  1556. (setq queue (append queue (or (class-parents-fast head)
  1557. '(eieio-default-superclass))))))))
  1558. (cons class (nreverse result)))
  1559. )
  1560. (defun eieio-class-precedence-c3 (class)
  1561. "Return all parents of CLASS in c3 order."
  1562. (let ((parents (class-parents-fast class)))
  1563. (eieio-c3-merge-lists
  1564. (list class)
  1565. (append
  1566. (or
  1567. (mapcar
  1568. (lambda (x)
  1569. (eieio-class-precedence-c3 x))
  1570. parents)
  1571. '((eieio-default-superclass)))
  1572. (list parents))))
  1573. )
  1574. (defun class-precedence-list (class)
  1575. "Return (transitively closed) list of parents of CLASS.
  1576. The order, in which the parents are returned depends on the
  1577. method invocation orders of the involved classes."
  1578. (if (or (null class) (eq class 'eieio-default-superclass))
  1579. nil
  1580. (case (class-method-invocation-order class)
  1581. (:depth-first
  1582. (eieio-class-precedence-dfs class))
  1583. (:breadth-first
  1584. (eieio-class-precedence-bfs class))
  1585. (:c3
  1586. (eieio-class-precedence-c3 class))))
  1587. )
  1588. ;; Official CLOS functions.
  1589. (defalias 'class-direct-superclasses 'class-parents)
  1590. (defalias 'class-direct-subclasses 'class-children)
  1591. (defmacro class-parent-fast (class) "Return first parent class to CLASS with no check."
  1592. `(car (class-parents-fast ,class)))
  1593. (defmacro class-parent (class) "Return first parent class to CLASS. (overload of variable)."
  1594. `(car (class-parents ,class)))
  1595. (defmacro same-class-fast-p (obj class) "Return t if OBJ is of class-type CLASS with no error checking."
  1596. `(eq (aref ,obj object-class) ,class))
  1597. (defun same-class-p (obj class) "Return t if OBJ is of class-type CLASS."
  1598. (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
  1599. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1600. (same-class-fast-p obj class))
  1601. (defun object-of-class-p (obj class)
  1602. "Return non-nil if OBJ is an instance of CLASS or CLASS' subclasses."
  1603. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1604. ;; class will be checked one layer down
  1605. (child-of-class-p (aref obj object-class) class))
  1606. ;; Backwards compatibility
  1607. (defalias 'obj-of-class-p 'object-of-class-p)
  1608. (defun child-of-class-p (child class)
  1609. "Return non-nil if CHILD class is a subclass of CLASS."
  1610. (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
  1611. (if (not (class-p child)) (signal 'wrong-type-argument (list 'class-p child)))
  1612. (let ((p nil))
  1613. (while (and child (not (eq child class)))
  1614. (setq p (append p (aref (class-v child) class-parent))
  1615. child (car p)
  1616. p (cdr p)))
  1617. (if child t)))
  1618. (defun object-slots (obj)
  1619. "Return list of slots available in OBJ."
  1620. (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
  1621. (aref (class-v (object-class-fast obj)) class-public-a))
  1622. (defun class-slot-initarg (class slot) "Fetch from CLASS, SLOT's :initarg."
  1623. (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
  1624. (let ((ia (aref (class-v class) class-initarg-tuples))
  1625. (f nil))
  1626. (while (and ia (not f))
  1627. (if (eq (cdr (car ia)) slot)
  1628. (setq f (car (car ia))))
  1629. (setq ia (cdr ia)))
  1630. f))
  1631. ;;; CLOS queries into classes and slots
  1632. ;;
  1633. (defun slot-boundp (object slot)
  1634. "Return non-nil if OBJECT's SLOT is bound.
  1635. Setting a slot's value makes it bound. Calling `slot-makeunbound' will
  1636. make a slot unbound.
  1637. OBJECT can be an instance or a class."
  1638. ;; Skip typechecking while retrieving this value.
  1639. (let ((eieio-skip-typecheck t))
  1640. ;; Return nil if the magic symbol is in there.
  1641. (not (eq (cond
  1642. ((eieio-object-p object) (eieio-oref object slot))
  1643. ((class-p object) (eieio-oref-default object slot))
  1644. (t (signal 'wrong-type-argument (list 'eieio-object-p object))))
  1645. eieio-unbound))))
  1646. (defun slot-makeunbound (object slot)
  1647. "In OBJECT, make SLOT unbound."
  1648. (eieio-oset object slot eieio-unbound))
  1649. (defun slot-exists-p (object-or-class slot)
  1650. "Return non-nil if OBJECT-OR-CLASS has SLOT."
  1651. (let ((cv (class-v (cond ((eieio-object-p object-or-class)
  1652. (object-class object-or-class))
  1653. ((class-p object-or-class)
  1654. object-or-class))
  1655. )))
  1656. (or (memq slot (aref cv class-public-a))
  1657. (memq slot (aref cv class-class-allocation-a)))
  1658. ))
  1659. (defun find-class (symbol &optional errorp)
  1660. "Return the class that SYMBOL represents.
  1661. If there is no class, nil is returned if ERRORP is nil.
  1662. If ERRORP is non-nil, `wrong-argument-type' is signaled."
  1663. (if (not (class-p symbol))
  1664. (if errorp (signal 'wrong-type-argument (list 'class-p symbol))
  1665. nil)
  1666. (class-v symbol)))
  1667. ;;; Slightly more complex utility functions for objects
  1668. ;;
  1669. (defun object-assoc (key slot list)
  1670. "Return an object if KEY is `equal' to SLOT's value of an object in LIST.
  1671. LIST is a list of objects whose slots are searched.
  1672. Objects in LIST do not need to have a slot named SLOT, nor does
  1673. SLOT need to be bound. If these errors occur, those objects will
  1674. be ignored."
  1675. (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
  1676. (while (and list (not (condition-case nil
  1677. ;; This prevents errors for missing slots.
  1678. (equal key (eieio-oref (car list) slot))
  1679. (error nil))))
  1680. (setq list (cdr list)))
  1681. (car list))
  1682. (defun object-assoc-list (slot list)
  1683. "Return an association list with the contents of SLOT as the key element.
  1684. LIST must be a list of objects with SLOT in it.
  1685. This is useful when you need to do completing read on an object group."
  1686. (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
  1687. (let ((assoclist nil))
  1688. (while list
  1689. (setq assoclist (cons (cons (eieio-oref (car list) slot)
  1690. (car list))
  1691. assoclist))
  1692. (setq list (cdr list)))
  1693. (nreverse assoclist)))
  1694. (defun object-assoc-list-safe (slot list)
  1695. "Return an association list with the contents of SLOT as the key element.
  1696. LIST must be a list of objects, but those objects do not need to have
  1697. SLOT in it. If it does not, then that element is left out of the association
  1698. list."
  1699. (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
  1700. (let ((assoclist nil))
  1701. (while list
  1702. (if (slot-exists-p (car list) slot)
  1703. (setq assoclist (cons (cons (eieio-oref (car list) slot)
  1704. (car list))
  1705. assoclist)))
  1706. (setq list (cdr list)))
  1707. (nreverse assoclist)))
  1708. (defun object-add-to-list (object slot item &optional append)
  1709. "In OBJECT's SLOT, add ITEM to the list of elements.
  1710. Optional argument APPEND indicates we need to append to the list.
  1711. If ITEM already exists in the list in SLOT, then it is not added.
  1712. Comparison is done with `equal' through the `member' function call.
  1713. If SLOT is unbound, bind it to the list containing ITEM."
  1714. (let (ov)
  1715. ;; Find the originating list.
  1716. (if (not (slot-boundp object slot))
  1717. (setq ov (list item))
  1718. (setq ov (eieio-oref object slot))
  1719. ;; turn it into a list.
  1720. (unless (listp ov)
  1721. (setq ov (list ov)))
  1722. ;; Do the combination
  1723. (if (not (member item ov))
  1724. (setq ov
  1725. (if append
  1726. (append ov (list item))
  1727. (cons item ov)))))
  1728. ;; Set back into the slot.
  1729. (eieio-oset object slot ov)))
  1730. (defun object-remove-from-list (object slot item)
  1731. "In OBJECT's SLOT, remove occurrences of ITEM.
  1732. Deletion is done with `delete', which deletes by side effect,
  1733. and comparisons are done with `equal'.
  1734. If SLOT is unbound, do nothing."
  1735. (if (not (slot-boundp object slot))
  1736. nil
  1737. (eieio-oset object slot (delete item (eieio-oref object slot)))))
  1738. ;;; EIEIO internal search functions
  1739. ;;
  1740. (defun eieio-slot-originating-class-p (start-class slot)
  1741. "Return non-nil if START-CLASS is the first class to define SLOT.
  1742. This is for testing if `scoped-class' is the class that defines SLOT
  1743. so that we can protect private slots."
  1744. (let ((par (class-parents start-class))
  1745. (ret t))
  1746. (if (not par)
  1747. t
  1748. (while (and par ret)
  1749. (if (intern-soft (symbol-name slot)
  1750. (aref (class-v (car par))
  1751. class-symbol-obarray))
  1752. (setq ret nil))
  1753. (setq par (cdr par)))
  1754. ret)))
  1755. (defun eieio-slot-name-index (class obj slot)
  1756. "In CLASS for OBJ find the index of the named SLOT.
  1757. The slot is a symbol which is installed in CLASS by the `defclass'
  1758. call. OBJ can be nil, but if it is an object, and the slot in question
  1759. is protected, access will be allowed if OBJ is a child of the currently
  1760. `scoped-class'.
  1761. If SLOT is the value created with :initarg instead,
  1762. reverse-lookup that name, and recurse with the associated slot value."
  1763. ;; Removed checks to outside this call
  1764. (let* ((fsym (intern-soft (symbol-name slot)
  1765. (aref (class-v class)
  1766. class-symbol-obarray)))
  1767. (fsi (if (symbolp fsym) (symbol-value fsym) nil)))
  1768. (if (integerp fsi)
  1769. (cond
  1770. ((not (get fsym 'protection))
  1771. (+ 3 fsi))
  1772. ((and (eq (get fsym 'protection) 'protected)
  1773. scoped-class
  1774. (or (child-of-class-p class scoped-class)
  1775. (and (eieio-object-p obj)
  1776. (child-of-class-p class (object-class obj)))))
  1777. (+ 3 fsi))
  1778. ((and (eq (get fsym 'protection) 'private)
  1779. (or (and scoped-class
  1780. (eieio-slot-originating-class-p scoped-class slot))
  1781. eieio-initializing-object))
  1782. (+ 3 fsi))
  1783. (t nil))
  1784. (let ((fn (eieio-initarg-to-attribute class slot)))
  1785. (if fn (eieio-slot-name-index class obj fn) nil)))))
  1786. (defun eieio-class-slot-name-index (class slot)
  1787. "In CLASS find the index of the named SLOT.
  1788. The slot is a symbol which is installed in CLASS by the `defclass'
  1789. call. If SLOT is the value created with :initarg instead,
  1790. reverse-lookup that name, and recurse with the associated slot value."
  1791. ;; This will happen less often, and with fewer slots. Do this the
  1792. ;; storage cheap way.
  1793. (let* ((a (aref (class-v class) class-class-allocation-a))
  1794. (l1 (length a))
  1795. (af (memq slot a))
  1796. (l2 (length af)))
  1797. ;; Slot # is length of the total list, minus the remaining list of
  1798. ;; the found slot.
  1799. (if af (- l1 l2))))
  1800. ;;; CLOS generics internal function handling
  1801. ;;
  1802. (defvar eieio-generic-call-methodname nil
  1803. "When using `call-next-method', provides a context on how to do it.")
  1804. (defvar eieio-generic-call-arglst nil
  1805. "When using `call-next-method', provides a context for parameters.")
  1806. (defvar eieio-generic-call-key nil
  1807. "When using `call-next-method', provides a context for the current key.
  1808. Keys are a number representing :before, :primary, and :after methods.")
  1809. (defvar eieio-generic-call-next-method-list nil
  1810. "When executing a PRIMARY or STATIC method, track the 'next-method'.
  1811. During executions, the list is first generated, then as each next method
  1812. is called, the next method is popped off the stack.")
  1813. (defvar eieio-pre-method-execution-hooks nil
  1814. "*Hooks run just before a method is executed.
  1815. The hook function must accept one argument, the list of forms
  1816. about to be executed.")
  1817. (defun eieio-generic-call (method args)
  1818. "Call METHOD with ARGS.
  1819. ARGS provides the context on which implementation to use.
  1820. This should only be called from a generic function."
  1821. ;; We must expand our arguments first as they are always
  1822. ;; passed in as quoted symbols
  1823. (let ((newargs nil) (mclass nil) (lambdas nil) (tlambdas nil) (keys nil)
  1824. (eieio-generic-call-methodname method)
  1825. (eieio-generic-call-arglst args)
  1826. (firstarg nil)
  1827. (primarymethodlist nil))
  1828. ;; get a copy
  1829. (setq newargs args
  1830. firstarg (car newargs))
  1831. ;; Is the class passed in autoloaded?
  1832. ;; Since class names are also constructors, they can be autoloaded
  1833. ;; via the autoload command. Check for this, and load them in.
  1834. ;; It's ok if it doesn't turn out to be a class. Probably want that
  1835. ;; function loaded anyway.
  1836. (if (and (symbolp firstarg)
  1837. (fboundp firstarg)
  1838. (listp (symbol-function firstarg))
  1839. (eq 'autoload (car (symbol-function firstarg))))
  1840. (load (nth 1 (symbol-function firstarg))))
  1841. ;; Determine the class to use.
  1842. (cond ((eieio-object-p firstarg)
  1843. (setq mclass (object-class-fast firstarg)))
  1844. ((class-p firstarg)
  1845. (setq mclass firstarg))
  1846. )
  1847. ;; Make sure the class is a valid class
  1848. ;; mclass can be nil (meaning a generic for should be used.
  1849. ;; mclass cannot have a value that is not a class, however.
  1850. (when (and (not (null mclass)) (not (class-p mclass)))
  1851. (error "Cannot dispatch method %S on class %S"
  1852. method mclass)
  1853. )
  1854. ;; Now create a list in reverse order of all the calls we have
  1855. ;; make in order to successfully do this right. Rules:
  1856. ;; 1) Only call generics if scoped-class is not defined
  1857. ;; This prevents multiple calls in the case of recursion
  1858. ;; 2) Only call static if this is a static method.
  1859. ;; 3) Only call specifics if the definition allows for them.
  1860. ;; 4) Call in order based on :before, :primary, and :after
  1861. (when (eieio-object-p firstarg)
  1862. ;; Non-static calls do all this stuff.
  1863. ;; :after methods
  1864. (setq tlambdas
  1865. (if mclass
  1866. (eieiomt-method-list method method-after mclass)
  1867. (list (eieio-generic-form method method-after nil)))
  1868. ;;(or (and mclass (eieio-generic-form method method-after mclass))
  1869. ;; (eieio-generic-form method method-after nil))
  1870. )
  1871. (setq lambdas (append tlambdas lambdas)
  1872. keys (append (make-list (length tlambdas) method-after) keys))
  1873. ;; :primary methods
  1874. (setq tlambdas
  1875. (or (and mclass (eieio-generic-form method method-primary mclass))
  1876. (eieio-generic-form method method-primary nil)))
  1877. (when tlambdas
  1878. (setq lambdas (cons tlambdas lambdas)
  1879. keys (cons method-primary keys)
  1880. primarymethodlist
  1881. (eieiomt-method-list method method-primary mclass)))
  1882. ;; :before methods
  1883. (setq tlambdas
  1884. (if mclass
  1885. (eieiomt-method-list method method-before mclass)
  1886. (list (eieio-generic-form method method-before nil)))
  1887. ;;(or (and mclass (eieio-generic-form method method-before mclass))
  1888. ;; (eieio-generic-form method method-before nil))
  1889. )
  1890. (setq lambdas (append tlambdas lambdas)
  1891. keys (append (make-list (length tlambdas) method-before) keys))
  1892. )
  1893. (if mclass
  1894. ;; For the case of a class,
  1895. ;; if there were no methods found, then there could be :static methods.
  1896. (when (not lambdas)
  1897. (setq tlambdas
  1898. (eieio-generic-form method method-static mclass))
  1899. (setq lambdas (cons tlambdas lambdas)
  1900. keys (cons method-static keys)
  1901. primarymethodlist ;; Re-use even with bad name here
  1902. (eieiomt-method-list method method-static mclass)))
  1903. ;; For the case of no class (ie - mclass == nil) then there may
  1904. ;; be a primary method.
  1905. (setq tlambdas
  1906. (eieio-generic-form method method-primary nil))
  1907. (when tlambdas
  1908. (setq lambdas (cons tlambdas lambdas)
  1909. keys (cons method-primary keys)
  1910. primarymethodlist
  1911. (eieiomt-method-list method method-primary nil)))
  1912. )
  1913. (run-hook-with-args 'eieio-pre-method-execution-hooks
  1914. primarymethodlist)
  1915. ;; Now loop through all occurrences forms which we must execute
  1916. ;; (which are happily sorted now) and execute them all!
  1917. (let ((rval nil) (lastval nil) (rvalever nil) (found nil))
  1918. (while lambdas
  1919. (if (car lambdas)
  1920. (let* ((scoped-class (cdr (car lambdas)))
  1921. (eieio-generic-call-key (car keys))
  1922. (has-return-val
  1923. (or (= eieio-generic-call-key method-primary)
  1924. (= eieio-generic-call-key method-static)))
  1925. (eieio-generic-call-next-method-list
  1926. ;; Use the cdr, as the first element is the fcn
  1927. ;; we are calling right now.
  1928. (when has-return-val (cdr primarymethodlist)))
  1929. )
  1930. (setq found t)
  1931. ;;(setq rval (apply (car (car lambdas)) newargs))
  1932. (setq lastval (apply (car (car lambdas)) newargs))
  1933. (when has-return-val
  1934. (setq rval lastval
  1935. rvalever t))
  1936. ))
  1937. (setq lambdas (cdr lambdas)
  1938. keys (cdr keys)))
  1939. (if (not found)
  1940. (if (eieio-object-p (car args))
  1941. (setq rval (apply 'no-applicable-method (car args) method args)
  1942. rvalever t)
  1943. (signal
  1944. 'no-method-definition
  1945. (list method args))))
  1946. ;; Right Here... it could be that lastval is returned when
  1947. ;; rvalever is nil. Is that right?
  1948. rval)))
  1949. (defun eieio-generic-call-primary-only (method args)
  1950. "Call METHOD with ARGS for methods with only :PRIMARY implementations.
  1951. ARGS provides the context on which implementation to use.
  1952. This should only be called from a generic function.
  1953. This method is like `eieio-generic-call', but only
  1954. implementations in the :PRIMARY slot are queried. After many
  1955. years of use, it appears that over 90% of methods in use
  1956. have :PRIMARY implementations only. We can therefore optimize
  1957. for this common case to improve performance."
  1958. ;; We must expand our arguments first as they are always
  1959. ;; passed in as quoted symbols
  1960. (let ((newargs nil) (mclass nil) (lambdas nil)
  1961. (eieio-generic-call-methodname method)
  1962. (eieio-generic-call-arglst args)
  1963. (firstarg nil)
  1964. (primarymethodlist nil)
  1965. )
  1966. ;; get a copy
  1967. (setq newargs args
  1968. firstarg (car newargs))
  1969. ;; Determine the class to use.
  1970. (cond ((eieio-object-p firstarg)
  1971. (setq mclass (object-class-fast firstarg)))
  1972. ((not firstarg)
  1973. (error "Method %s called on nil" method))
  1974. ((not (eieio-object-p firstarg))
  1975. (error "Primary-only method %s called on something not an object" method))
  1976. (t
  1977. (error "EIEIO Error: Improperly classified method %s as primary only"
  1978. method)
  1979. ))
  1980. ;; Make sure the class is a valid class
  1981. ;; mclass can be nil (meaning a generic for should be used.
  1982. ;; mclass cannot have a value that is not a class, however.
  1983. (when (null mclass)
  1984. (error "Cannot dispatch method %S on class %S" method mclass)
  1985. )
  1986. ;; :primary methods
  1987. (setq lambdas (eieio-generic-form method method-primary mclass))
  1988. (setq primarymethodlist ;; Re-use even with bad name here
  1989. (eieiomt-method-list method method-primary mclass))
  1990. ;; Now loop through all occurrences forms which we must execute
  1991. ;; (which are happily sorted now) and execute them all!
  1992. (let* ((rval nil) (lastval nil) (rvalever nil)
  1993. (scoped-class (cdr lambdas))
  1994. (eieio-generic-call-key method-primary)
  1995. ;; Use the cdr, as the first element is the fcn
  1996. ;; we are calling right now.
  1997. (eieio-generic-call-next-method-list (cdr primarymethodlist))
  1998. )
  1999. (if (or (not lambdas) (not (car lambdas)))
  2000. ;; No methods found for this impl...
  2001. (if (eieio-object-p (car args))
  2002. (setq rval (apply 'no-applicable-method (car args) method args)
  2003. rvalever t)
  2004. (signal
  2005. 'no-method-definition
  2006. (list method args)))
  2007. ;; Do the regular implementation here.
  2008. (run-hook-with-args 'eieio-pre-method-execution-hooks
  2009. lambdas)
  2010. (setq lastval (apply (car lambdas) newargs))
  2011. (setq rval lastval
  2012. rvalever t)
  2013. )
  2014. ;; Right Here... it could be that lastval is returned when
  2015. ;; rvalever is nil. Is that right?
  2016. rval)))
  2017. (defun eieiomt-method-list (method key class)
  2018. "Return an alist list of methods lambdas.
  2019. METHOD is the method name.
  2020. KEY represents either :before, or :after methods.
  2021. CLASS is the starting class to search from in the method tree.
  2022. If CLASS is nil, then an empty list of methods should be returned."
  2023. ;; Note: eieiomt - the MT means MethodTree. See more comments below
  2024. ;; for the rest of the eieiomt methods.
  2025. ;; Collect lambda expressions stored for the class and its parent
  2026. ;; classes.
  2027. (let (lambdas)
  2028. (dolist (ancestor (class-precedence-list class))
  2029. ;; Lookup the form to use for the PRIMARY object for the next level
  2030. (let ((tmpl (eieio-generic-form method key ancestor)))
  2031. (when (and tmpl
  2032. (or (not lambdas)
  2033. ;; This prevents duplicates coming out of the
  2034. ;; class method optimizer. Perhaps we should
  2035. ;; just not optimize before/afters?
  2036. (not (member tmpl lambdas))))
  2037. (push tmpl lambdas))))
  2038. ;; Return collected lambda. For :after methods, return in current
  2039. ;; order (most general class last); Otherwise, reverse order.
  2040. (if (eq key method-after)
  2041. lambdas
  2042. (nreverse lambdas))))
  2043. (defun next-method-p ()
  2044. "Return non-nil if there is a next method.
  2045. Returns a list of lambda expressions which is the `next-method'
  2046. order."
  2047. eieio-generic-call-next-method-list)
  2048. (defun call-next-method (&rest replacement-args)
  2049. "Call the superclass method from a subclass method.
  2050. The superclass method is specified in the current method list,
  2051. and is called the next method.
  2052. If REPLACEMENT-ARGS is non-nil, then use them instead of
  2053. `eieio-generic-call-arglst'. The generic arg list are the
  2054. arguments passed in at the top level.
  2055. Use `next-method-p' to find out if there is a next method to call."
  2056. (if (not scoped-class)
  2057. (error "`call-next-method' not called within a class specific method"))
  2058. (if (and (/= eieio-generic-call-key method-primary)
  2059. (/= eieio-generic-call-key method-static))
  2060. (error "Cannot `call-next-method' except in :primary or :static methods")
  2061. )
  2062. (let ((newargs (or replacement-args eieio-generic-call-arglst))
  2063. (next (car eieio-generic-call-next-method-list))
  2064. )
  2065. (if (or (not next) (not (car next)))
  2066. (apply 'no-next-method (car newargs) (cdr newargs))
  2067. (let* ((eieio-generic-call-next-method-list
  2068. (cdr eieio-generic-call-next-method-list))
  2069. (eieio-generic-call-arglst newargs)
  2070. (scoped-class (cdr next))
  2071. (fcn (car next))
  2072. )
  2073. (apply fcn newargs)
  2074. ))))
  2075. ;;;
  2076. ;; eieio-method-tree : eieiomt-
  2077. ;;
  2078. ;; Stored as eieio-method-tree in property list of a generic method
  2079. ;;
  2080. ;; (eieio-method-tree . [BEFORE PRIMARY AFTER
  2081. ;; genericBEFORE genericPRIMARY genericAFTER])
  2082. ;; and
  2083. ;; (eieio-method-obarray . [BEFORE PRIMARY AFTER
  2084. ;; genericBEFORE genericPRIMARY genericAFTER])
  2085. ;; where the association is a vector.
  2086. ;; (aref 0 -- all static methods.
  2087. ;; (aref 1 -- all methods classified as :before
  2088. ;; (aref 2 -- all methods classified as :primary
  2089. ;; (aref 3 -- all methods classified as :after
  2090. ;; (aref 4 -- a generic classified as :before
  2091. ;; (aref 5 -- a generic classified as :primary
  2092. ;; (aref 6 -- a generic classified as :after
  2093. ;;
  2094. (defvar eieiomt-optimizing-obarray nil
  2095. "While mapping atoms, this contain the obarray being optimized.")
  2096. (defun eieiomt-install (method-name)
  2097. "Install the method tree, and obarray onto METHOD-NAME.
  2098. Do not do the work if they already exist."
  2099. (let ((emtv (get method-name 'eieio-method-tree))
  2100. (emto (get method-name 'eieio-method-obarray)))
  2101. (if (or (not emtv) (not emto))
  2102. (progn
  2103. (setq emtv (put method-name 'eieio-method-tree
  2104. (make-vector method-num-slots nil))
  2105. emto (put method-name 'eieio-method-obarray
  2106. (make-vector method-num-slots nil)))
  2107. (aset emto 0 (make-vector 11 0))
  2108. (aset emto 1 (make-vector 11 0))
  2109. (aset emto 2 (make-vector 41 0))
  2110. (aset emto 3 (make-vector 11 0))
  2111. ))))
  2112. (defun eieiomt-add (method-name method key class)
  2113. "Add to METHOD-NAME the forms METHOD in a call position KEY for CLASS.
  2114. METHOD-NAME is the name created by a call to `defgeneric'.
  2115. METHOD are the forms for a given implementation.
  2116. KEY is an integer (see comment in eieio.el near this function) which
  2117. is associated with the :static :before :primary and :after tags.
  2118. It also indicates if CLASS is defined or not.
  2119. CLASS is the class this method is associated with."
  2120. (if (or (> key method-num-slots) (< key 0))
  2121. (error "eieiomt-add: method key error!"))
  2122. (let ((emtv (get method-name 'eieio-method-tree))
  2123. (emto (get method-name 'eieio-method-obarray)))
  2124. ;; Make sure the method tables are available.
  2125. (if (or (not emtv) (not emto))
  2126. (error "Programmer error: eieiomt-add"))
  2127. ;; only add new cells on if it doesn't already exist!
  2128. (if (assq class (aref emtv key))
  2129. (setcdr (assq class (aref emtv key)) method)
  2130. (aset emtv key (cons (cons class method) (aref emtv key))))
  2131. ;; Add function definition into newly created symbol, and store
  2132. ;; said symbol in the correct obarray, otherwise use the
  2133. ;; other array to keep this stuff
  2134. (if (< key method-num-lists)
  2135. (let ((nsym (intern (symbol-name class) (aref emto key))))
  2136. (fset nsym method)))
  2137. ;; Now optimize the entire obarray
  2138. (if (< key method-num-lists)
  2139. (let ((eieiomt-optimizing-obarray (aref emto key)))
  2140. ;; @todo - Is this overkill? Should we just clear the symbol?
  2141. (mapatoms 'eieiomt-sym-optimize eieiomt-optimizing-obarray)))
  2142. ))
  2143. (defun eieiomt-next (class)
  2144. "Return the next parent class for CLASS.
  2145. If CLASS is a superclass, return variable `eieio-default-superclass'.
  2146. If CLASS is variable `eieio-default-superclass' then return nil.
  2147. This is different from function `class-parent' as class parent returns
  2148. nil for superclasses. This function performs no type checking!"
  2149. ;; No type-checking because all calls are made from functions which
  2150. ;; are safe and do checking for us.
  2151. (or (class-parents-fast class)
  2152. (if (eq class 'eieio-default-superclass)
  2153. nil
  2154. '(eieio-default-superclass))))
  2155. (defun eieiomt-sym-optimize (s)
  2156. "Find the next class above S which has a function body for the optimizer."
  2157. ;; Set the value to nil in case there is no nearest cell.
  2158. (set s nil)
  2159. ;; Find the nearest cell that has a function body. If we find one,
  2160. ;; we replace the nil from above.
  2161. (let ((external-symbol (intern-soft (symbol-name s))))
  2162. (catch 'done
  2163. (dolist (ancestor (rest (class-precedence-list external-symbol)))
  2164. (let ((ov (intern-soft (symbol-name ancestor)
  2165. eieiomt-optimizing-obarray)))
  2166. (when (fboundp ov)
  2167. (set s ov) ;; store ov as our next symbol
  2168. (throw 'done ancestor)))))))
  2169. (defun eieio-generic-form (method key class)
  2170. "Return the lambda form belonging to METHOD using KEY based upon CLASS.
  2171. If CLASS is not a class then use `generic' instead. If class has
  2172. no form, but has a parent class, then trace to that parent class.
  2173. The first time a form is requested from a symbol, an optimized path
  2174. is memorized for faster future use."
  2175. (let ((emto (aref (get method 'eieio-method-obarray)
  2176. (if class key (eieio-specialized-key-to-generic-key key)))))
  2177. (if (class-p class)
  2178. ;; 1) find our symbol
  2179. (let ((cs (intern-soft (symbol-name class) emto)))
  2180. (if (not cs)
  2181. ;; 2) If there isn't one, then make one.
  2182. ;; This can be slow since it only occurs once
  2183. (progn
  2184. (setq cs (intern (symbol-name class) emto))
  2185. ;; 2.1) Cache its nearest neighbor with a quick optimize
  2186. ;; which should only occur once for this call ever
  2187. (let ((eieiomt-optimizing-obarray emto))
  2188. (eieiomt-sym-optimize cs))))
  2189. ;; 3) If it's bound return this one.
  2190. (if (fboundp cs)
  2191. (cons cs (aref (class-v class) class-symbol))
  2192. ;; 4) If it's not bound then this variable knows something
  2193. (if (symbol-value cs)
  2194. (progn
  2195. ;; 4.1) This symbol holds the next class in its value
  2196. (setq class (symbol-value cs)
  2197. cs (intern-soft (symbol-name class) emto))
  2198. ;; 4.2) The optimizer should always have chosen a
  2199. ;; function-symbol
  2200. ;;(if (fboundp cs)
  2201. (cons cs (aref (class-v (intern (symbol-name class)))
  2202. class-symbol))
  2203. ;;(error "EIEIO optimizer: erratic data loss!"))
  2204. )
  2205. ;; There never will be a funcall...
  2206. nil)))
  2207. ;; for a generic call, what is a list, is the function body we want.
  2208. (let ((emtl (aref (get method 'eieio-method-tree)
  2209. (if class key (eieio-specialized-key-to-generic-key key)))))
  2210. (if emtl
  2211. ;; The car of EMTL is supposed to be a class, which in this
  2212. ;; case is nil, so skip it.
  2213. (cons (cdr (car emtl)) nil)
  2214. nil)))))
  2215. ;;;
  2216. ;; Way to assign slots based on a list. Used for constructors, or
  2217. ;; even resetting an object at run-time
  2218. ;;
  2219. (defun eieio-set-defaults (obj &optional set-all)
  2220. "Take object OBJ, and reset all slots to their defaults.
  2221. If SET-ALL is non-nil, then when a default is nil, that value is
  2222. reset. If SET-ALL is nil, the slots are only reset if the default is
  2223. not nil."
  2224. (let ((scoped-class (aref obj object-class))
  2225. (eieio-initializing-object t)
  2226. (pub (aref (class-v (aref obj object-class)) class-public-a)))
  2227. (while pub
  2228. (let ((df (eieio-oref-default obj (car pub))))
  2229. (if (or df set-all)
  2230. (eieio-oset obj (car pub) df)))
  2231. (setq pub (cdr pub)))))
  2232. (defun eieio-initarg-to-attribute (class initarg)
  2233. "For CLASS, convert INITARG to the actual attribute name.
  2234. If there is no translation, pass it in directly (so we can cheat if
  2235. need be... May remove that later...)"
  2236. (let ((tuple (assoc initarg (aref (class-v class) class-initarg-tuples))))
  2237. (if tuple
  2238. (cdr tuple)
  2239. nil)))
  2240. (defun eieio-attribute-to-initarg (class attribute)
  2241. "In CLASS, convert the ATTRIBUTE into the corresponding init argument tag.
  2242. This is usually a symbol that starts with `:'."
  2243. (let ((tuple (rassoc attribute (aref (class-v class) class-initarg-tuples))))
  2244. (if tuple
  2245. (car tuple)
  2246. nil)))
  2247. ;;; Here are some special types of errors
  2248. ;;
  2249. (intern "no-method-definition")
  2250. (put 'no-method-definition 'error-conditions '(no-method-definition error))
  2251. (put 'no-method-definition 'error-message "No method definition")
  2252. (intern "no-next-method")
  2253. (put 'no-next-method 'error-conditions '(no-next-method error))
  2254. (put 'no-next-method 'error-message "No next method")
  2255. (intern "invalid-slot-name")
  2256. (put 'invalid-slot-name 'error-conditions '(invalid-slot-name error))
  2257. (put 'invalid-slot-name 'error-message "Invalid slot name")
  2258. (intern "invalid-slot-type")
  2259. (put 'invalid-slot-type 'error-conditions '(invalid-slot-type error nil))
  2260. (put 'invalid-slot-type 'error-message "Invalid slot type")
  2261. (intern "unbound-slot")
  2262. (put 'unbound-slot 'error-conditions '(unbound-slot error nil))
  2263. (put 'unbound-slot 'error-message "Unbound slot")
  2264. (intern "inconsistent-class-hierarchy")
  2265. (put 'inconsistent-class-hierarchy 'error-conditions
  2266. '(inconsistent-class-hierarchy error nil))
  2267. (put 'inconsistent-class-hierarchy 'error-message "Inconsistent class hierarchy")
  2268. ;;; Here are some CLOS items that need the CL package
  2269. ;;
  2270. (defsetf slot-value (obj slot) (store) (list 'eieio-oset obj slot store))
  2271. (defsetf eieio-oref (obj slot) (store) (list 'eieio-oset obj slot store))
  2272. ;; The below setf method was written by Arnd Kohrs <kohrs@acm.org>
  2273. (define-setf-method oref (obj slot)
  2274. (with-no-warnings
  2275. (require 'cl)
  2276. (let ((obj-temp (gensym))
  2277. (slot-temp (gensym))
  2278. (store-temp (gensym)))
  2279. (list (list obj-temp slot-temp)
  2280. (list obj `(quote ,slot))
  2281. (list store-temp)
  2282. (list 'set-slot-value obj-temp slot-temp
  2283. store-temp)
  2284. (list 'slot-value obj-temp slot-temp)))))
  2285. ;;;
  2286. ;; We want all objects created by EIEIO to have some default set of
  2287. ;; behaviors so we can create object utilities, and allow various
  2288. ;; types of error checking. To do this, create the default EIEIO
  2289. ;; class, and when no parent class is specified, use this as the
  2290. ;; default. (But don't store it in the other classes as the default,
  2291. ;; allowing for transparent support.)
  2292. ;;
  2293. (defclass eieio-default-superclass nil
  2294. nil
  2295. "Default parent class for classes with no specified parent class.
  2296. Its slots are automatically adopted by classes with no specified parents.
  2297. This class is not stored in the `parent' slot of a class vector."
  2298. :abstract t)
  2299. (defalias 'standard-class 'eieio-default-superclass)
  2300. (defgeneric constructor (class newname &rest slots)
  2301. "Default constructor for CLASS `eieio-default-superclass'.")
  2302. (defmethod constructor :static
  2303. ((class eieio-default-superclass) newname &rest slots)
  2304. "Default constructor for CLASS `eieio-default-superclass'.
  2305. NEWNAME is the name to be given to the constructed object.
  2306. SLOTS are the initialization slots used by `shared-initialize'.
  2307. This static method is called when an object is constructed.
  2308. It allocates the vector used to represent an EIEIO object, and then
  2309. calls `shared-initialize' on that object."
  2310. (let* ((new-object (copy-sequence (aref (class-v class)
  2311. class-default-object-cache))))
  2312. ;; Update the name for the newly created object.
  2313. (aset new-object object-name newname)
  2314. ;; Call the initialize method on the new object with the slots
  2315. ;; that were passed down to us.
  2316. (initialize-instance new-object slots)
  2317. ;; Return the created object.
  2318. new-object))
  2319. (defgeneric shared-initialize (obj slots)
  2320. "Set slots of OBJ with SLOTS which is a list of name/value pairs.
  2321. Called from the constructor routine.")
  2322. (defmethod shared-initialize ((obj eieio-default-superclass) slots)
  2323. "Set slots of OBJ with SLOTS which is a list of name/value pairs.
  2324. Called from the constructor routine."
  2325. (let ((scoped-class (aref obj object-class)))
  2326. (while slots
  2327. (let ((rn (eieio-initarg-to-attribute (object-class-fast obj)
  2328. (car slots))))
  2329. (if (not rn)
  2330. (slot-missing obj (car slots) 'oset (car (cdr slots)))
  2331. (eieio-oset obj rn (car (cdr slots)))))
  2332. (setq slots (cdr (cdr slots))))))
  2333. (defgeneric initialize-instance (this &optional slots)
  2334. "Construct the new object THIS based on SLOTS.")
  2335. (defmethod initialize-instance ((this eieio-default-superclass)
  2336. &optional slots)
  2337. "Construct the new object THIS based on SLOTS.
  2338. SLOTS is a tagged list where odd numbered elements are tags, and
  2339. even numbered elements are the values to store in the tagged slot.
  2340. If you overload the `initialize-instance', there you will need to
  2341. call `shared-initialize' yourself, or you can call `call-next-method'
  2342. to have this constructor called automatically. If these steps are
  2343. not taken, then new objects of your class will not have their values
  2344. dynamically set from SLOTS."
  2345. ;; First, see if any of our defaults are `lambda', and
  2346. ;; re-evaluate them and apply the value to our slots.
  2347. (let* ((scoped-class (class-v (aref this object-class)))
  2348. (slot (aref scoped-class class-public-a))
  2349. (defaults (aref scoped-class class-public-d)))
  2350. (while slot
  2351. ;; For each slot, see if we need to evaluate it.
  2352. ;;
  2353. ;; Paul Landes said in an email:
  2354. ;; > CL evaluates it if it can, and otherwise, leaves it as
  2355. ;; > the quoted thing as you already have. This is by the
  2356. ;; > Sonya E. Keene book and other things I've look at on the
  2357. ;; > web.
  2358. (let ((dflt (eieio-default-eval-maybe (car defaults))))
  2359. (when (not (eq dflt (car defaults)))
  2360. (eieio-oset this (car slot) dflt) ))
  2361. ;; Next.
  2362. (setq slot (cdr slot)
  2363. defaults (cdr defaults))))
  2364. ;; Shared initialize will parse our slots for us.
  2365. (shared-initialize this slots))
  2366. (defgeneric slot-missing (object slot-name operation &optional new-value)
  2367. "Method invoked when an attempt to access a slot in OBJECT fails.")
  2368. (defmethod slot-missing ((object eieio-default-superclass) slot-name
  2369. operation &optional new-value)
  2370. "Method invoked when an attempt to access a slot in OBJECT fails.
  2371. SLOT-NAME is the name of the failed slot, OPERATION is the type of access
  2372. that was requested, and optional NEW-VALUE is the value that was desired
  2373. to be set.
  2374. This method is called from `oref', `oset', and other functions which
  2375. directly reference slots in EIEIO objects."
  2376. (signal 'invalid-slot-name (list (object-name object)
  2377. slot-name)))
  2378. (defgeneric slot-unbound (object class slot-name fn)
  2379. "Slot unbound is invoked during an attempt to reference an unbound slot.")
  2380. (defmethod slot-unbound ((object eieio-default-superclass)
  2381. class slot-name fn)
  2382. "Slot unbound is invoked during an attempt to reference an unbound slot.
  2383. OBJECT is the instance of the object being reference. CLASS is the
  2384. class of OBJECT, and SLOT-NAME is the offending slot. This function
  2385. throws the signal `unbound-slot'. You can overload this function and
  2386. return the value to use in place of the unbound value.
  2387. Argument FN is the function signaling this error.
  2388. Use `slot-boundp' to determine if a slot is bound or not.
  2389. In CLOS, the argument list is (CLASS OBJECT SLOT-NAME), but
  2390. EIEIO can only dispatch on the first argument, so the first two are swapped."
  2391. (signal 'unbound-slot (list (class-name class) (object-name object)
  2392. slot-name fn)))
  2393. (defgeneric no-applicable-method (object method &rest args)
  2394. "Called if there are no implementations for OBJECT in METHOD.")
  2395. (defmethod no-applicable-method ((object eieio-default-superclass)
  2396. method &rest args)
  2397. "Called if there are no implementations for OBJECT in METHOD.
  2398. OBJECT is the object which has no method implementation.
  2399. ARGS are the arguments that were passed to METHOD.
  2400. Implement this for a class to block this signal. The return
  2401. value becomes the return value of the original method call."
  2402. (signal 'no-method-definition (list method (object-name object)))
  2403. )
  2404. (defgeneric no-next-method (object &rest args)
  2405. "Called from `call-next-method' when no additional methods are available.")
  2406. (defmethod no-next-method ((object eieio-default-superclass)
  2407. &rest args)
  2408. "Called from `call-next-method' when no additional methods are available.
  2409. OBJECT is othe object being called on `call-next-method'.
  2410. ARGS are the arguments it is called by.
  2411. This method signals `no-next-method' by default. Override this
  2412. method to not throw an error, and its return value becomes the
  2413. return value of `call-next-method'."
  2414. (signal 'no-next-method (list (object-name object) args))
  2415. )
  2416. (defgeneric clone (obj &rest params)
  2417. "Make a copy of OBJ, and then supply PARAMS.
  2418. PARAMS is a parameter list of the same form used by `initialize-instance'.
  2419. When overloading `clone', be sure to call `call-next-method'
  2420. first and modify the returned object.")
  2421. (defmethod clone ((obj eieio-default-superclass) &rest params)
  2422. "Make a copy of OBJ, and then apply PARAMS."
  2423. (let ((nobj (copy-sequence obj))
  2424. (nm (aref obj object-name))
  2425. (passname (and params (stringp (car params))))
  2426. (num 1))
  2427. (if params (shared-initialize nobj (if passname (cdr params) params)))
  2428. (if (not passname)
  2429. (save-match-data
  2430. (if (string-match "-\\([0-9]+\\)" nm)
  2431. (setq num (1+ (string-to-number (match-string 1 nm)))
  2432. nm (substring nm 0 (match-beginning 0))))
  2433. (aset nobj object-name (concat nm "-" (int-to-string num))))
  2434. (aset nobj object-name (car params)))
  2435. nobj))
  2436. (defgeneric destructor (this &rest params)
  2437. "Destructor for cleaning up any dynamic links to our object.")
  2438. (defmethod destructor ((this eieio-default-superclass) &rest params)
  2439. "Destructor for cleaning up any dynamic links to our object.
  2440. Argument THIS is the object being destroyed. PARAMS are additional
  2441. ignored parameters."
  2442. ;; No cleanup... yet.
  2443. )
  2444. (defgeneric object-print (this &rest strings)
  2445. "Pretty printer for object THIS. Call function `object-name' with STRINGS.
  2446. It is sometimes useful to put a summary of the object into the
  2447. default #<notation> string when using EIEIO browsing tools.
  2448. Implement this method to customize the summary.")
  2449. (defmethod object-print ((this eieio-default-superclass) &rest strings)
  2450. "Pretty printer for object THIS. Call function `object-name' with STRINGS.
  2451. The default method for printing object THIS is to use the
  2452. function `object-name'.
  2453. It is sometimes useful to put a summary of the object into the
  2454. default #<notation> string when using EIEIO browsing tools.
  2455. Implement this function and specify STRINGS in a call to
  2456. `call-next-method' to provide additional summary information.
  2457. When passing in extra strings from child classes, always remember
  2458. to prepend a space."
  2459. (object-name this (apply 'concat strings)))
  2460. (defvar eieio-print-depth 0
  2461. "When printing, keep track of the current indentation depth.")
  2462. (defgeneric object-write (this &optional comment)
  2463. "Write out object THIS to the current stream.
  2464. Optional COMMENT will add comments to the beginning of the output.")
  2465. (defmethod object-write ((this eieio-default-superclass) &optional comment)
  2466. "Write object THIS out to the current stream.
  2467. This writes out the vector version of this object. Complex and recursive
  2468. object are discouraged from being written.
  2469. If optional COMMENT is non-nil, include comments when outputting
  2470. this object."
  2471. (when comment
  2472. (princ ";; Object ")
  2473. (princ (object-name-string this))
  2474. (princ "\n")
  2475. (princ comment)
  2476. (princ "\n"))
  2477. (let* ((cl (object-class this))
  2478. (cv (class-v cl)))
  2479. ;; Now output readable lisp to recreate this object
  2480. ;; It should look like this:
  2481. ;; (<constructor> <name> <slot> <slot> ... )
  2482. ;; Each slot's slot is writen using its :writer.
  2483. (princ (make-string (* eieio-print-depth 2) ? ))
  2484. (princ "(")
  2485. (princ (symbol-name (class-constructor (object-class this))))
  2486. (princ " \"")
  2487. (princ (object-name-string this))
  2488. (princ "\"\n")
  2489. ;; Loop over all the public slots
  2490. (let ((publa (aref cv class-public-a))
  2491. (publd (aref cv class-public-d))
  2492. (publp (aref cv class-public-printer))
  2493. (eieio-print-depth (1+ eieio-print-depth)))
  2494. (while publa
  2495. (when (slot-boundp this (car publa))
  2496. (let ((i (class-slot-initarg cl (car publa)))
  2497. (v (eieio-oref this (car publa)))
  2498. )
  2499. (unless (or (not i) (equal v (car publd)))
  2500. (princ (make-string (* eieio-print-depth 2) ? ))
  2501. (princ (symbol-name i))
  2502. (princ " ")
  2503. (if (car publp)
  2504. ;; Use our public printer
  2505. (funcall (car publp) v)
  2506. ;; Use our generic override prin1 function.
  2507. (eieio-override-prin1 v))
  2508. (princ "\n"))))
  2509. (setq publa (cdr publa) publd (cdr publd)
  2510. publp (cdr publp)))
  2511. (princ (make-string (* eieio-print-depth 2) ? )))
  2512. (princ ")\n")))
  2513. (defun eieio-override-prin1 (thing)
  2514. "Perform a `prin1' on THING taking advantage of object knowledge."
  2515. (cond ((eieio-object-p thing)
  2516. (object-write thing))
  2517. ((listp thing)
  2518. (eieio-list-prin1 thing))
  2519. ((class-p thing)
  2520. (princ (class-name thing)))
  2521. ((symbolp thing)
  2522. (princ (concat "'" (symbol-name thing))))
  2523. (t (prin1 thing))))
  2524. (defun eieio-list-prin1 (list)
  2525. "Display LIST where list may contain objects."
  2526. (if (not (eieio-object-p (car list)))
  2527. (progn
  2528. (princ "'")
  2529. (prin1 list))
  2530. (princ "(list ")
  2531. (if (eieio-object-p (car list)) (princ "\n "))
  2532. (while list
  2533. (if (eieio-object-p (car list))
  2534. (object-write (car list))
  2535. (princ "'")
  2536. (prin1 (car list)))
  2537. (princ " ")
  2538. (setq list (cdr list)))
  2539. (princ (make-string (* eieio-print-depth 2) ? ))
  2540. (princ ")")))
  2541. ;;; Unimplemented functions from CLOS
  2542. ;;
  2543. (defun change-class (obj class)
  2544. "Change the class of OBJ to type CLASS.
  2545. This may create or delete slots, but does not affect the return value
  2546. of `eq'."
  2547. (error "EIEIO: `change-class' is unimplemented"))
  2548. )
  2549. ;;; Obsolete backward compatibility functions.
  2550. ;; Needed to run byte-code compiled with the EIEIO of Emacs-23.
  2551. (defun eieio-defmethod (method args)
  2552. "Obsolete work part of an old version of the `defmethod' macro."
  2553. (let ((key nil) (body nil) (firstarg nil) (argfix nil) (argclass nil) loopa)
  2554. ;; find optional keys
  2555. (setq key
  2556. (cond ((or (eq ':BEFORE (car args))
  2557. (eq ':before (car args)))
  2558. (setq args (cdr args))
  2559. method-before)
  2560. ((or (eq ':AFTER (car args))
  2561. (eq ':after (car args)))
  2562. (setq args (cdr args))
  2563. method-after)
  2564. ((or (eq ':PRIMARY (car args))
  2565. (eq ':primary (car args)))
  2566. (setq args (cdr args))
  2567. method-primary)
  2568. ((or (eq ':STATIC (car args))
  2569. (eq ':static (car args)))
  2570. (setq args (cdr args))
  2571. method-static)
  2572. ;; Primary key
  2573. (t method-primary)))
  2574. ;; get body, and fix contents of args to be the arguments of the fn.
  2575. (setq body (cdr args)
  2576. args (car args))
  2577. (setq loopa args)
  2578. ;; Create a fixed version of the arguments
  2579. (while loopa
  2580. (setq argfix (cons (if (listp (car loopa)) (car (car loopa)) (car loopa))
  2581. argfix))
  2582. (setq loopa (cdr loopa)))
  2583. ;; make sure there is a generic
  2584. (eieio-defgeneric
  2585. method
  2586. (if (stringp (car body))
  2587. (car body) (format "Generically created method `%s'." method)))
  2588. ;; create symbol for property to bind to. If the first arg is of
  2589. ;; the form (varname vartype) and `vartype' is a class, then
  2590. ;; that class will be the type symbol. If not, then it will fall
  2591. ;; under the type `primary' which is a non-specific calling of the
  2592. ;; function.
  2593. (setq firstarg (car args))
  2594. (if (listp firstarg)
  2595. (progn
  2596. (setq argclass (nth 1 firstarg))
  2597. (if (not (class-p argclass))
  2598. (error "Unknown class type %s in method parameters"
  2599. (nth 1 firstarg))))
  2600. (if (= key -1)
  2601. (signal 'wrong-type-argument (list :static 'non-class-arg)))
  2602. ;; generics are higher
  2603. (setq key (eieio-specialized-key-to-generic-key key)))
  2604. ;; Put this lambda into the symbol so we can find it
  2605. (if (byte-code-function-p (car-safe body))
  2606. (eieiomt-add method (car-safe body) key argclass)
  2607. (eieiomt-add method (append (list 'lambda (reverse argfix)) body)
  2608. key argclass))
  2609. )
  2610. (when eieio-optimize-primary-methods-flag
  2611. ;; Optimizing step:
  2612. ;;
  2613. ;; If this method, after this setup, only has primary methods, then
  2614. ;; we can setup the generic that way.
  2615. (if (generic-primary-only-p method)
  2616. ;; If there is only one primary method, then we can go one more
  2617. ;; optimization step.
  2618. (if (generic-primary-only-one-p method)
  2619. (eieio-defgeneric-reset-generic-form-primary-only-one method)
  2620. (eieio-defgeneric-reset-generic-form-primary-only method))
  2621. (eieio-defgeneric-reset-generic-form method)))
  2622. method)
  2623. (make-obsolete 'eieio-defmethod 'eieio--defmethod "24.1")
  2624. (defun eieio-defgeneric (method doc-string)
  2625. "Obsolete work part of an old version of the `defgeneric' macro."
  2626. (if (and (fboundp method) (not (generic-p method))
  2627. (or (byte-code-function-p (symbol-function method))
  2628. (not (eq 'autoload (car (symbol-function method)))))
  2629. )
  2630. (error "You cannot create a generic/method over an existing symbol: %s"
  2631. method))
  2632. ;; Don't do this over and over.
  2633. (unless (fboundp 'method)
  2634. ;; This defun tells emacs where the first definition of this
  2635. ;; method is defined.
  2636. `(defun ,method nil)
  2637. ;; Make sure the method tables are installed.
  2638. (eieiomt-install method)
  2639. ;; Apply the actual body of this function.
  2640. (fset method (eieio-defgeneric-form method doc-string))
  2641. ;; Return the method
  2642. 'method))
  2643. (make-obsolete 'eieio-defgeneric nil "24.1")
  2644. ;;; Interfacing with edebug
  2645. ;;
  2646. (defun eieio-edebug-prin1-to-string (object &optional noescape)
  2647. "Display EIEIO OBJECT in fancy format.
  2648. Overrides the edebug default.
  2649. Optional argument NOESCAPE is passed to `prin1-to-string' when appropriate."
  2650. (cond ((class-p object) (class-name object))
  2651. ((eieio-object-p object) (object-print object))
  2652. ((and (listp object) (or (class-p (car object))
  2653. (eieio-object-p (car object))))
  2654. (concat "(" (mapconcat 'eieio-edebug-prin1-to-string object " ") ")"))
  2655. (t (prin1-to-string object noescape))))
  2656. (add-hook 'edebug-setup-hook
  2657. (lambda ()
  2658. (def-edebug-spec defmethod
  2659. (&define ; this means we are defining something
  2660. [&or name ("setf" :name setf name)]
  2661. ;; ^^ This is the methods symbol
  2662. [ &optional symbolp ] ; this is key :before etc
  2663. list ; arguments
  2664. [ &optional stringp ] ; documentation string
  2665. def-body ; part to be debugged
  2666. ))
  2667. ;; The rest of the macros
  2668. (def-edebug-spec oref (form quote))
  2669. (def-edebug-spec oref-default (form quote))
  2670. (def-edebug-spec oset (form quote form))
  2671. (def-edebug-spec oset-default (form quote form))
  2672. (def-edebug-spec class-v form)
  2673. (def-edebug-spec class-p form)
  2674. (def-edebug-spec eieio-object-p form)
  2675. (def-edebug-spec class-constructor form)
  2676. (def-edebug-spec generic-p form)
  2677. (def-edebug-spec with-slots (list list def-body))
  2678. ;; I suspect this isn't the best way to do this, but when
  2679. ;; cust-print was used on my system all my objects
  2680. ;; appeared as "#1 =" which was not useful. This allows
  2681. ;; edebug to print my objects in the nice way they were
  2682. ;; meant to with `object-print' and `class-name'
  2683. ;; (defalias 'edebug-prin1-to-string 'eieio-edebug-prin1-to-string)
  2684. )
  2685. )
  2686. ;;; Interfacing with imenu in emacs lisp mode
  2687. ;; (Only if the expression is defined)
  2688. ;;
  2689. (if (eval-when-compile (boundp 'list-imenu-generic-expression))
  2690. (progn
  2691. (defun eieio-update-lisp-imenu-expression ()
  2692. "Examine `lisp-imenu-generic-expression' and modify it to find `defmethod'."
  2693. (let ((exp lisp-imenu-generic-expression))
  2694. (while exp
  2695. ;; it's of the form '( ( title expr indx ) ... )
  2696. (let* ((subcar (cdr (car exp)))
  2697. (substr (car subcar)))
  2698. (if (and (not (string-match "|method\\\\" substr))
  2699. (string-match "|advice\\\\" substr))
  2700. (setcar subcar
  2701. (replace-match "|advice\\|method\\" t t substr 0))))
  2702. (setq exp (cdr exp)))))
  2703. (eieio-update-lisp-imenu-expression)
  2704. ))
  2705. ;;; Autoloading some external symbols, and hooking into the help system
  2706. ;;
  2707. ;;; Start of automatically extracted autoloads.
  2708. ;;;### (autoloads (customize-object) "eieio-custom" "eieio-custom.el"
  2709. ;;;;;; "9cf80224540c52045d515a4c2c833543")
  2710. ;;; Generated autoloads from eieio-custom.el
  2711. (autoload 'customize-object "eieio-custom" "\
  2712. Customize OBJ in a custom buffer.
  2713. Optional argument GROUP is the sub-group of slots to display.
  2714. \(fn OBJ &optional GROUP)" nil nil)
  2715. ;;;***
  2716. ;;;### (autoloads (eieio-help-mode-augmentation-maybee eieio-describe-generic
  2717. ;;;;;; eieio-describe-constructor eieio-describe-class eieio-browse)
  2718. ;;;;;; "eieio-opt" "eieio-opt.el" "e2814881441ad23759409687502f0ee1")
  2719. ;;; Generated autoloads from eieio-opt.el
  2720. (autoload 'eieio-browse "eieio-opt" "\
  2721. Create an object browser window to show all objects.
  2722. If optional ROOT-CLASS, then start with that, otherwise start with
  2723. variable `eieio-default-superclass'.
  2724. \(fn &optional ROOT-CLASS)" t nil)
  2725. (defalias 'describe-class 'eieio-describe-class)
  2726. (autoload 'eieio-describe-class "eieio-opt" "\
  2727. Describe a CLASS defined by a string or symbol.
  2728. If CLASS is actually an object, then also display current values of that object.
  2729. Optional HEADERFCN should be called to insert a few bits of info first.
  2730. \(fn CLASS &optional HEADERFCN)" t nil)
  2731. (autoload 'eieio-describe-constructor "eieio-opt" "\
  2732. Describe the constructor function FCN.
  2733. Uses `eieio-describe-class' to describe the class being constructed.
  2734. \(fn FCN)" t nil)
  2735. (defalias 'describe-generic 'eieio-describe-generic)
  2736. (autoload 'eieio-describe-generic "eieio-opt" "\
  2737. Describe the generic function GENERIC.
  2738. Also extracts information about all methods specific to this generic.
  2739. \(fn GENERIC)" t nil)
  2740. (autoload 'eieio-help-mode-augmentation-maybee "eieio-opt" "\
  2741. For buffers thrown into help mode, augment for EIEIO.
  2742. Arguments UNUSED are not used.
  2743. \(fn &rest UNUSED)" nil nil)
  2744. ;;;***
  2745. ;;; End of automatically extracted autoloads.
  2746. (provide 'eieio)
  2747. ;;; eieio ends here