cl-macs.el 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253
  1. ;;; cl-macs.el --- Common Lisp macros -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1993, 2001-2017 Free Software Foundation, Inc.
  3. ;; Author: Dave Gillespie <daveg@synaptics.com>
  4. ;; Old-Version: 2.02
  5. ;; Keywords: extensions
  6. ;; Package: emacs
  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. ;; These are extensions to Emacs Lisp that provide a degree of
  20. ;; Common Lisp compatibility, beyond what is already built-in
  21. ;; in Emacs Lisp.
  22. ;;
  23. ;; This package was written by Dave Gillespie; it is a complete
  24. ;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
  25. ;;
  26. ;; Bug reports, comments, and suggestions are welcome!
  27. ;; This file contains the portions of the Common Lisp extensions
  28. ;; package which should be autoloaded, but need only be present
  29. ;; if the compiler or interpreter is used---this file is not
  30. ;; necessary for executing compiled code.
  31. ;; See cl.el for Change Log.
  32. ;;; Code:
  33. (require 'cl-lib)
  34. (require 'macroexp)
  35. ;; `gv' is required here because cl-macs can be loaded before loaddefs.el.
  36. (require 'gv)
  37. (defmacro cl--pop2 (place)
  38. (declare (debug edebug-sexps))
  39. `(prog1 (car (cdr ,place))
  40. (setq ,place (cdr (cdr ,place)))))
  41. (defvar cl--optimize-safety)
  42. (defvar cl--optimize-speed)
  43. ;;; Initialization.
  44. ;; Place compiler macros at the beginning, otherwise uses of the corresponding
  45. ;; functions can lead to recursive-loads that prevent the calls from
  46. ;; being optimized.
  47. ;;;###autoload
  48. (defun cl--compiler-macro-list* (_form arg &rest others)
  49. (let* ((args (reverse (cons arg others)))
  50. (form (car args)))
  51. (while (setq args (cdr args))
  52. (setq form `(cons ,(car args) ,form)))
  53. form))
  54. ;; Note: `cl--compiler-macro-cXXr' has been copied to
  55. ;; `internal--compiler-macro-cXXr' in subr.el. If you amend either
  56. ;; one, you may want to amend the other, too.
  57. ;;;###autoload
  58. (define-obsolete-function-alias 'cl--compiler-macro-cXXr
  59. 'internal--compiler-macro-cXXr "25.1")
  60. ;;; Some predicates for analyzing Lisp forms.
  61. ;; These are used by various
  62. ;; macro expanders to optimize the results in certain common cases.
  63. (defconst cl--simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
  64. car-safe cdr-safe progn prog1 prog2))
  65. (defconst cl--safe-funcs '(* / % length memq list vector vectorp
  66. < > <= >= = error))
  67. (defun cl--simple-expr-p (x &optional size)
  68. "Check if no side effects, and executes quickly."
  69. (or size (setq size 10))
  70. (if (and (consp x) (not (memq (car x) '(quote function cl-function))))
  71. (and (symbolp (car x))
  72. (or (memq (car x) cl--simple-funcs)
  73. (get (car x) 'side-effect-free))
  74. (progn
  75. (setq size (1- size))
  76. (while (and (setq x (cdr x))
  77. (setq size (cl--simple-expr-p (car x) size))))
  78. (and (null x) (>= size 0) size)))
  79. (and (> size 0) (1- size))))
  80. (defun cl--simple-exprs-p (xs)
  81. (while (and xs (cl--simple-expr-p (car xs)))
  82. (setq xs (cdr xs)))
  83. (not xs))
  84. (defun cl--safe-expr-p (x)
  85. "Check if no side effects."
  86. (or (not (and (consp x) (not (memq (car x) '(quote function cl-function)))))
  87. (and (symbolp (car x))
  88. (or (memq (car x) cl--simple-funcs)
  89. (memq (car x) cl--safe-funcs)
  90. (get (car x) 'side-effect-free))
  91. (progn
  92. (while (and (setq x (cdr x)) (cl--safe-expr-p (car x))))
  93. (null x)))))
  94. ;;; Check if constant (i.e., no side effects or dependencies).
  95. (defun cl--const-expr-p (x)
  96. (cond ((consp x)
  97. (or (eq (car x) 'quote)
  98. (and (memq (car x) '(function cl-function))
  99. (or (symbolp (nth 1 x))
  100. (and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
  101. ((symbolp x) (and (memq x '(nil t)) t))
  102. (t t)))
  103. (defun cl--const-expr-val (x)
  104. "Return the value of X known at compile-time.
  105. If X is not known at compile time, return nil. Before testing
  106. whether X is known at compile time, macroexpand it completely in
  107. `macroexpand-all-environment'."
  108. (let ((x (macroexpand-all x macroexpand-all-environment)))
  109. (if (macroexp-const-p x)
  110. (if (consp x) (nth 1 x) x))))
  111. (defun cl--expr-contains (x y)
  112. "Count number of times X refers to Y. Return nil for 0 times."
  113. ;; FIXME: This is naive, and it will cl-count Y as referred twice in
  114. ;; (let ((Y 1)) Y) even though it should be 0. Also it is often called on
  115. ;; non-macroexpanded code, so it may also miss some occurrences that would
  116. ;; only appear in the expanded code.
  117. (cond ((equal y x) 1)
  118. ((and (consp x) (not (memq (car x) '(quote function cl-function))))
  119. (let ((sum 0))
  120. (while (consp x)
  121. (setq sum (+ sum (or (cl--expr-contains (pop x) y) 0))))
  122. (setq sum (+ sum (or (cl--expr-contains x y) 0)))
  123. (and (> sum 0) sum)))
  124. (t nil)))
  125. (defun cl--expr-contains-any (x y)
  126. (while (and y (not (cl--expr-contains x (car y)))) (pop y))
  127. y)
  128. (defun cl--expr-depends-p (x y)
  129. "Check whether X may depend on any of the symbols in Y."
  130. (and (not (macroexp-const-p x))
  131. (or (not (cl--safe-expr-p x)) (cl--expr-contains-any x y))))
  132. ;;; Symbols.
  133. (defvar cl--gensym-counter 0)
  134. ;;;###autoload
  135. (defun cl-gensym (&optional prefix)
  136. "Generate a new uninterned symbol.
  137. The name is made by appending a number to PREFIX, default \"G\"."
  138. (let ((pfix (if (stringp prefix) prefix "G"))
  139. (num (if (integerp prefix) prefix
  140. (prog1 cl--gensym-counter
  141. (setq cl--gensym-counter (1+ cl--gensym-counter))))))
  142. (make-symbol (format "%s%d" pfix num))))
  143. ;;;###autoload
  144. (defun cl-gentemp (&optional prefix)
  145. "Generate a new interned symbol with a unique name.
  146. The name is made by appending a number to PREFIX, default \"G\"."
  147. (let ((pfix (if (stringp prefix) prefix "G"))
  148. name)
  149. (while (intern-soft (setq name (format "%s%d" pfix cl--gensym-counter)))
  150. (setq cl--gensym-counter (1+ cl--gensym-counter)))
  151. (intern name)))
  152. ;;; Program structure.
  153. (def-edebug-spec cl-declarations
  154. (&rest ("cl-declare" &rest sexp)))
  155. (def-edebug-spec cl-declarations-or-string
  156. (&or stringp cl-declarations))
  157. (def-edebug-spec cl-lambda-list
  158. (([&rest arg]
  159. [&optional ["&optional" cl-&optional-arg &rest cl-&optional-arg]]
  160. [&optional ["&rest" arg]]
  161. [&optional ["&key" [cl-&key-arg &rest cl-&key-arg]
  162. &optional "&allow-other-keys"]]
  163. [&optional ["&aux" &rest
  164. &or (symbolp &optional def-form) symbolp]]
  165. )))
  166. (def-edebug-spec cl-&optional-arg
  167. (&or (arg &optional def-form arg) arg))
  168. (def-edebug-spec cl-&key-arg
  169. (&or ([&or (symbolp arg) arg] &optional def-form arg) arg))
  170. (def-edebug-spec cl-type-spec sexp)
  171. (defconst cl--lambda-list-keywords
  172. '(&optional &rest &key &allow-other-keys &aux &whole &body &environment))
  173. ;; Internal hacks used in formal arg lists:
  174. ;; - &cl-quote: Added to formal-arglists to mean that any default value
  175. ;; mentioned in the formal arglist should be considered as implicitly
  176. ;; quoted rather than evaluated. This is used in `cl-defsubst' when
  177. ;; performing compiler-macro-expansion, since at that time the
  178. ;; arguments hold expressions rather than values.
  179. ;; - &cl-defs (DEF . DEFS): Gives the default value to use for missing
  180. ;; optional arguments which don't have an explicit default value.
  181. ;; DEFS is an alist mapping vars to their default default value.
  182. ;; and DEF is the default default to use for all other vars.
  183. (defvar cl--bind-block) ;Name of surrounding block, only use for `signal' data.
  184. (defvar cl--bind-defs) ;(DEF . DEFS) giving the "default default" for optargs.
  185. (defvar cl--bind-enquote) ;Non-nil if &cl-quote was in the formal arglist!
  186. (defvar cl--bind-lets) (defvar cl--bind-forms)
  187. (defun cl--transform-lambda (form bind-block)
  188. "Transform a function form FORM of name BIND-BLOCK.
  189. BIND-BLOCK is the name of the symbol to which the function will be bound,
  190. and which will be used for the name of the `cl-block' surrounding the
  191. function's body.
  192. FORM is of the form (ARGS . BODY)."
  193. (let* ((args (car form)) (body (cdr form)) (orig-args args)
  194. (cl--bind-block bind-block) (cl--bind-defs nil) (cl--bind-enquote nil)
  195. (parsed-body (macroexp-parse-body body))
  196. (header (car parsed-body)) (simple-args nil))
  197. (setq body (cdr parsed-body))
  198. ;; "(. X) to (&rest X)" conversion already done in cl--do-arglist, but we
  199. ;; do it here as well, so as to be able to see if we can avoid
  200. ;; cl--do-arglist.
  201. (setq args (if (listp args) (cl-copy-list args) (list '&rest args)))
  202. (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
  203. (let ((cl-defs (memq '&cl-defs args)))
  204. (when cl-defs
  205. (setq cl--bind-defs (cadr cl-defs))
  206. ;; Remove "&cl-defs DEFS" from args.
  207. (setcdr cl-defs (cddr cl-defs))
  208. (setq args (delq '&cl-defs args))))
  209. (if (setq cl--bind-enquote (memq '&cl-quote args))
  210. (setq args (delq '&cl-quote args)))
  211. (if (memq '&whole args) (error "&whole not currently implemented"))
  212. (let* ((p (memq '&environment args))
  213. (v (cadr p)))
  214. (if p (setq args (nconc (delq (car p) (delq v args))
  215. `(&aux (,v macroexpand-all-environment))))))
  216. ;; Take away all the simple args whose parsing can be handled more
  217. ;; efficiently by a plain old `lambda' than the manual parsing generated
  218. ;; by `cl--do-arglist'.
  219. (let ((optional nil))
  220. (while (and args (symbolp (car args))
  221. (not (memq (car args) '(nil &rest &body &key &aux)))
  222. (or (not optional)
  223. ;; Optional args whose default is nil are simple.
  224. (null (nth 1 (assq (car args) (cdr cl--bind-defs)))))
  225. (not (and (eq (car args) '&optional) (setq optional t)
  226. (car cl--bind-defs))))
  227. (push (pop args) simple-args))
  228. (when optional
  229. (if args (push '&optional args))
  230. ;; Don't keep a dummy trailing &optional without actual optional args.
  231. (if (eq '&optional (car simple-args)) (pop simple-args))))
  232. (or (eq cl--bind-block 'cl-none)
  233. (setq body (list `(cl-block ,cl--bind-block ,@body))))
  234. (let* ((cl--bind-lets nil) (cl--bind-forms nil)
  235. (rest-args
  236. (cond
  237. ((null args) nil)
  238. ((eq (car args) '&aux)
  239. (cl--do-&aux args)
  240. (setq cl--bind-lets (nreverse cl--bind-lets))
  241. nil)
  242. (t ;; `simple-args' doesn't handle all the parsing that we need,
  243. ;; so we pass the rest to cl--do-arglist which will do
  244. ;; "manual" parsing.
  245. (let ((slen (length simple-args)))
  246. (when (memq '&optional simple-args)
  247. (cl-decf slen))
  248. (setq header
  249. ;; Macro expansion can take place in the middle of
  250. ;; apparently harmless computation, so it should not
  251. ;; touch the match-data.
  252. (save-match-data
  253. (cons (help-add-fundoc-usage
  254. (if (stringp (car header)) (pop header))
  255. ;; Be careful with make-symbol and (back)quote,
  256. ;; see bug#12884.
  257. (help--docstring-quote
  258. (let ((print-gensym nil) (print-quoted t)
  259. (print-escape-newlines t))
  260. (format "%S" (cons 'fn (cl--make-usage-args
  261. orig-args))))))
  262. header)))
  263. ;; FIXME: we'd want to choose an arg name for the &rest param
  264. ;; and pass that as `expr' to cl--do-arglist, but that ends up
  265. ;; generating code with a redundant let-binding, so we instead
  266. ;; pass a dummy and then look in cl--bind-lets to find what var
  267. ;; this was bound to.
  268. (cl--do-arglist args :dummy slen)
  269. (setq cl--bind-lets (nreverse cl--bind-lets))
  270. ;; (cl-assert (eq :dummy (nth 1 (car cl--bind-lets))))
  271. (list '&rest (car (pop cl--bind-lets))))))))
  272. `(nil
  273. (,@(nreverse simple-args) ,@rest-args)
  274. ,@header
  275. ,(macroexp-let* cl--bind-lets
  276. (macroexp-progn
  277. `(,@(nreverse cl--bind-forms)
  278. ,@body)))))))
  279. ;;;###autoload
  280. (defmacro cl-defun (name args &rest body)
  281. "Define NAME as a function.
  282. Like normal `defun', except ARGLIST allows full Common Lisp conventions,
  283. and BODY is implicitly surrounded by (cl-block NAME ...).
  284. The full form of a Common Lisp function argument list is
  285. (VAR...
  286. [&optional (VAR [INITFORM [SVAR]])...]
  287. [&rest|&body VAR]
  288. [&key (([KEYWORD] VAR) [INITFORM [SVAR]])... [&allow-other-keys]]
  289. [&aux (VAR [INITFORM])...])
  290. VAR maybe be replaced recursively with an argument list for
  291. destructing, `&whole' is supported within these sublists. If
  292. SVAR, INITFORM, and KEYWORD are all omitted, then `(VAR)' may be
  293. written simply `VAR'. See the Info node `(cl)Argument Lists' for
  294. more details.
  295. \(fn NAME ARGLIST [DOCSTRING] BODY...)"
  296. (declare (debug
  297. ;; Same as defun but use cl-lambda-list.
  298. (&define [&or name ("setf" :name setf name)]
  299. cl-lambda-list
  300. cl-declarations-or-string
  301. [&optional ("interactive" interactive)]
  302. def-body))
  303. (doc-string 3)
  304. (indent 2))
  305. (let* ((res (cl--transform-lambda (cons args body) name))
  306. (form `(defun ,name ,@(cdr res))))
  307. (if (car res) `(progn ,(car res) ,form) form)))
  308. ;;;###autoload
  309. (defmacro cl-iter-defun (name args &rest body)
  310. "Define NAME as a generator function.
  311. Like normal `iter-defun', except ARGLIST allows full Common Lisp conventions,
  312. and BODY is implicitly surrounded by (cl-block NAME ...).
  313. \(fn NAME ARGLIST [DOCSTRING] BODY...)"
  314. (declare (debug
  315. ;; Same as iter-defun but use cl-lambda-list.
  316. (&define [&or name ("setf" :name setf name)]
  317. cl-lambda-list
  318. cl-declarations-or-string
  319. [&optional ("interactive" interactive)]
  320. def-body))
  321. (doc-string 3)
  322. (indent 2))
  323. (require 'generator)
  324. (let* ((res (cl--transform-lambda (cons args body) name))
  325. (form `(iter-defun ,name ,@(cdr res))))
  326. (if (car res) `(progn ,(car res) ,form) form)))
  327. ;; The lambda list for macros is different from that of normal lambdas.
  328. ;; Note that &environment is only allowed as first or last items in the
  329. ;; top level list.
  330. (def-edebug-spec cl-macro-list
  331. (([&optional "&environment" arg]
  332. [&rest cl-macro-arg]
  333. [&optional ["&optional" &rest
  334. &or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
  335. [&optional [[&or "&rest" "&body"] cl-macro-arg]]
  336. [&optional ["&key" [&rest
  337. [&or ([&or (symbolp cl-macro-arg) arg]
  338. &optional def-form cl-macro-arg)
  339. arg]]
  340. &optional "&allow-other-keys"]]
  341. [&optional ["&aux" &rest
  342. &or (symbolp &optional def-form) symbolp]]
  343. [&optional "&environment" arg]
  344. )))
  345. (def-edebug-spec cl-macro-arg
  346. (&or arg cl-macro-list1))
  347. (def-edebug-spec cl-macro-list1
  348. (([&optional "&whole" arg] ;; only allowed at lower levels
  349. [&rest cl-macro-arg]
  350. [&optional ["&optional" &rest
  351. &or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
  352. [&optional [[&or "&rest" "&body"] cl-macro-arg]]
  353. [&optional ["&key" [&rest
  354. [&or ([&or (symbolp cl-macro-arg) arg]
  355. &optional def-form cl-macro-arg)
  356. arg]]
  357. &optional "&allow-other-keys"]]
  358. [&optional ["&aux" &rest
  359. &or (symbolp &optional def-form) symbolp]]
  360. . [&or arg nil])))
  361. ;;;###autoload
  362. (defmacro cl-defmacro (name args &rest body)
  363. "Define NAME as a macro.
  364. Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
  365. and BODY is implicitly surrounded by (cl-block NAME ...).
  366. The full form of a Common Lisp macro argument list is
  367. (VAR...
  368. [&optional (VAR [INITFORM [SVAR]])...]
  369. [&rest|&body VAR]
  370. [&key (([KEYWORD] VAR) [INITFORM [SVAR]])... [&allow-other-keys]]
  371. [&aux (VAR [INITFORM])...]
  372. [&environment VAR])
  373. VAR maybe be replaced recursively with an argument list for
  374. destructing, `&whole' is supported within these sublists. If
  375. SVAR, INITFORM, and KEYWORD are all omitted, then `(VAR)' may be
  376. written simply `VAR'. See the Info node `(cl)Argument Lists' for
  377. more details.
  378. \(fn NAME ARGLIST [DOCSTRING] BODY...)"
  379. (declare (debug
  380. (&define name cl-macro-list cl-declarations-or-string def-body))
  381. (doc-string 3)
  382. (indent 2))
  383. (let* ((res (cl--transform-lambda (cons args body) name))
  384. (form `(defmacro ,name ,@(cdr res))))
  385. (if (car res) `(progn ,(car res) ,form) form)))
  386. (def-edebug-spec cl-lambda-expr
  387. (&define ("lambda" cl-lambda-list
  388. ;;cl-declarations-or-string
  389. ;;[&optional ("interactive" interactive)]
  390. def-body)))
  391. ;; Redefine function-form to also match cl-function
  392. (def-edebug-spec function-form
  393. ;; form at the end could also handle "function",
  394. ;; but recognize it specially to avoid wrapping function forms.
  395. (&or ([&or "quote" "function"] &or symbolp lambda-expr)
  396. ("cl-function" cl-function)
  397. form))
  398. ;;;###autoload
  399. (defmacro cl-function (func)
  400. "Introduce a function.
  401. Like normal `function', except that if argument is a lambda form,
  402. its argument list allows full Common Lisp conventions."
  403. (declare (debug (&or symbolp cl-lambda-expr)))
  404. (if (eq (car-safe func) 'lambda)
  405. (let* ((res (cl--transform-lambda (cdr func) 'cl-none))
  406. (form `(function (lambda . ,(cdr res)))))
  407. (if (car res) `(progn ,(car res) ,form) form))
  408. `(function ,func)))
  409. (defun cl--make-usage-var (x)
  410. "X can be a var or a (destructuring) lambda-list."
  411. (cond
  412. ((symbolp x) (make-symbol (upcase (symbol-name x))))
  413. ((consp x) (cl--make-usage-args x))
  414. (t x)))
  415. (defun cl--make-usage-args (arglist)
  416. (let ((aux (ignore-errors (cl-position '&aux arglist))))
  417. (when aux
  418. ;; `&aux' args aren't arguments, so let's just drop them from the
  419. ;; usage info.
  420. (setq arglist (cl-subseq arglist 0 aux))))
  421. (if (cdr-safe (last arglist)) ;Not a proper list.
  422. (let* ((last (last arglist))
  423. (tail (cdr last)))
  424. (unwind-protect
  425. (progn
  426. (setcdr last nil)
  427. (nconc (cl--make-usage-args arglist) (cl--make-usage-var tail)))
  428. (setcdr last tail)))
  429. ;; `orig-args' can contain &cl-defs.
  430. (let ((x (memq '&cl-defs arglist)))
  431. (when x (setq arglist (delq (car x) (remq (cadr x) arglist)))))
  432. (let ((state nil))
  433. (mapcar (lambda (x)
  434. (cond
  435. ((symbolp x)
  436. (let ((first (aref (symbol-name x) 0)))
  437. (if (eq ?\& first)
  438. (setq state x)
  439. ;; Strip a leading underscore, since it only
  440. ;; means that this argument is unused.
  441. (make-symbol (upcase (if (eq ?_ first)
  442. (substring (symbol-name x) 1)
  443. (symbol-name x)))))))
  444. ((not (consp x)) x)
  445. ((memq state '(nil &rest)) (cl--make-usage-args x))
  446. (t ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
  447. (cl-list*
  448. (if (and (consp (car x)) (eq state '&key))
  449. (list (caar x) (cl--make-usage-var (nth 1 (car x))))
  450. (cl--make-usage-var (car x)))
  451. (nth 1 x) ;INITFORM.
  452. (cl--make-usage-args (nthcdr 2 x)) ;SVAR.
  453. ))))
  454. arglist))))
  455. (defun cl--do-&aux (args)
  456. (while (and (eq (car args) '&aux) (pop args))
  457. (while (and args (not (memq (car args) cl--lambda-list-keywords)))
  458. (if (consp (car args))
  459. (if (and cl--bind-enquote (cl-cadar args))
  460. (cl--do-arglist (caar args)
  461. `',(cadr (pop args)))
  462. (cl--do-arglist (caar args) (cadr (pop args))))
  463. (cl--do-arglist (pop args) nil))))
  464. (if args (error "Malformed argument list ends with: %S" args)))
  465. (defun cl--do-arglist (args expr &optional num) ; uses cl--bind-*
  466. (if (nlistp args)
  467. (if (or (memq args cl--lambda-list-keywords) (not (symbolp args)))
  468. (error "Invalid argument name: %s" args)
  469. (push (list args expr) cl--bind-lets))
  470. (setq args (cl-copy-list args))
  471. (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
  472. (let ((p (memq '&body args))) (if p (setcar p '&rest)))
  473. (if (memq '&environment args) (error "&environment used incorrectly"))
  474. (let ((restarg (memq '&rest args))
  475. (safety (if (cl--compiling-file) cl--optimize-safety 3))
  476. (keys nil)
  477. (laterarg nil) (exactarg nil) minarg)
  478. (or num (setq num 0))
  479. (setq restarg (if (listp (cadr restarg))
  480. (make-symbol "--cl-rest--")
  481. (cadr restarg)))
  482. (push (list restarg expr) cl--bind-lets)
  483. (if (eq (car args) '&whole)
  484. (push (list (cl--pop2 args) restarg) cl--bind-lets))
  485. (let ((p args))
  486. (setq minarg restarg)
  487. (while (and p (not (memq (car p) cl--lambda-list-keywords)))
  488. (or (eq p args) (setq minarg (list 'cdr minarg)))
  489. (setq p (cdr p)))
  490. (if (memq (car p) '(nil &aux))
  491. (setq minarg `(= (length ,restarg)
  492. ,(length (cl-ldiff args p)))
  493. exactarg (not (eq args p)))))
  494. (while (and args (not (memq (car args) cl--lambda-list-keywords)))
  495. (let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car)
  496. restarg)))
  497. (cl--do-arglist
  498. (pop args)
  499. (if (or laterarg (= safety 0)) poparg
  500. `(if ,minarg ,poparg
  501. (signal 'wrong-number-of-arguments
  502. (list ,(and (not (eq cl--bind-block 'cl-none))
  503. `',cl--bind-block)
  504. (length ,restarg)))))))
  505. (setq num (1+ num) laterarg t))
  506. (while (and (eq (car args) '&optional) (pop args))
  507. (while (and args (not (memq (car args) cl--lambda-list-keywords)))
  508. (let ((arg (pop args)))
  509. (or (consp arg) (setq arg (list arg)))
  510. (if (cddr arg) (cl--do-arglist (nth 2 arg) `(and ,restarg t)))
  511. (let ((def (if (cdr arg) (nth 1 arg)
  512. (or (car cl--bind-defs)
  513. (nth 1 (assq (car arg) cl--bind-defs)))))
  514. (poparg `(pop ,restarg)))
  515. (and def cl--bind-enquote (setq def `',def))
  516. (cl--do-arglist (car arg)
  517. (if def `(if ,restarg ,poparg ,def) poparg))
  518. (setq num (1+ num))))))
  519. (if (eq (car args) '&rest)
  520. (let ((arg (cl--pop2 args)))
  521. (if (consp arg) (cl--do-arglist arg restarg)))
  522. (or (eq (car args) '&key) (= safety 0) exactarg
  523. (push `(if ,restarg
  524. (signal 'wrong-number-of-arguments
  525. (list
  526. ,(and (not (eq cl--bind-block 'cl-none))
  527. `',cl--bind-block)
  528. (+ ,num (length ,restarg)))))
  529. cl--bind-forms)))
  530. (while (and (eq (car args) '&key) (pop args))
  531. (while (and args (not (memq (car args) cl--lambda-list-keywords)))
  532. (let ((arg (pop args)))
  533. (or (consp arg) (setq arg (list arg)))
  534. (let* ((karg (if (consp (car arg)) (caar arg)
  535. (let ((name (symbol-name (car arg))))
  536. ;; Strip a leading underscore, since it only
  537. ;; means that this argument is unused, but
  538. ;; shouldn't affect the key's name (bug#12367).
  539. (if (eq ?_ (aref name 0))
  540. (setq name (substring name 1)))
  541. (intern (format ":%s" name)))))
  542. (varg (if (consp (car arg)) (cl-cadar arg) (car arg)))
  543. (def (if (cdr arg) (cadr arg)
  544. ;; The ordering between those two or clauses is
  545. ;; irrelevant, since in practice only one of the two
  546. ;; is ever non-nil (the car is only used for
  547. ;; cl-deftype which doesn't use the cdr).
  548. (or (car cl--bind-defs)
  549. (cadr (assq varg cl--bind-defs)))))
  550. (look `(plist-member ,restarg ',karg)))
  551. (and def cl--bind-enquote (setq def `',def))
  552. (if (cddr arg)
  553. (let* ((temp (or (nth 2 arg) (make-symbol "--cl-var--")))
  554. (val `(car (cdr ,temp))))
  555. (cl--do-arglist temp look)
  556. (cl--do-arglist varg
  557. `(if ,temp
  558. (prog1 ,val (setq ,temp t))
  559. ,def)))
  560. (cl--do-arglist
  561. varg
  562. `(car (cdr ,(if (null def)
  563. look
  564. `(or ,look
  565. ,(if (eq (cl--const-expr-p def) t)
  566. `'(nil ,(cl--const-expr-val def))
  567. `(list nil ,def))))))))
  568. (push karg keys)))))
  569. (setq keys (nreverse keys))
  570. (or (and (eq (car args) '&allow-other-keys) (pop args))
  571. (null keys) (= safety 0)
  572. (let* ((var (make-symbol "--cl-keys--"))
  573. (allow '(:allow-other-keys))
  574. (check `(while ,var
  575. (cond
  576. ((memq (car ,var) ',(append keys allow))
  577. (setq ,var (cdr (cdr ,var))))
  578. ((car (cdr (memq (quote ,@allow) ,restarg)))
  579. (setq ,var nil))
  580. (t
  581. (error
  582. ,(format "Keyword argument %%s not one of %s"
  583. keys)
  584. (car ,var)))))))
  585. (push `(let ((,var ,restarg)) ,check) cl--bind-forms)))
  586. (cl--do-&aux args)
  587. nil)))
  588. (defun cl--arglist-args (args)
  589. (if (nlistp args) (list args)
  590. (let ((res nil) (kind nil) arg)
  591. (while (consp args)
  592. (setq arg (pop args))
  593. (if (memq arg cl--lambda-list-keywords) (setq kind arg)
  594. (if (eq arg '&cl-defs) (pop args)
  595. (and (consp arg) kind (setq arg (car arg)))
  596. (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
  597. (setq res (nconc res (cl--arglist-args arg))))))
  598. (nconc res (and args (list args))))))
  599. ;;;###autoload
  600. (defmacro cl-destructuring-bind (args expr &rest body)
  601. "Bind the variables in ARGS to the result of EXPR and execute BODY."
  602. (declare (indent 2)
  603. (debug (&define cl-macro-list def-form cl-declarations def-body)))
  604. (let* ((cl--bind-lets nil) (cl--bind-forms nil)
  605. (cl--bind-defs nil) (cl--bind-block 'cl-none) (cl--bind-enquote nil))
  606. (cl--do-arglist (or args '(&aux)) expr)
  607. (macroexp-let* (nreverse cl--bind-lets)
  608. (macroexp-progn (append (nreverse cl--bind-forms) body)))))
  609. ;;; The `cl-eval-when' form.
  610. (defvar cl--not-toplevel nil)
  611. ;;;###autoload
  612. (defmacro cl-eval-when (when &rest body)
  613. "Control when BODY is evaluated.
  614. If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
  615. If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
  616. If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level.
  617. \(fn (WHEN...) BODY...)"
  618. (declare (indent 1) (debug (sexp body)))
  619. (if (and (fboundp 'cl--compiling-file) (cl--compiling-file)
  620. (not cl--not-toplevel) (not (boundp 'for-effect))) ;Horrible kludge.
  621. (let ((comp (or (memq 'compile when) (memq :compile-toplevel when)))
  622. (cl--not-toplevel t))
  623. (if (or (memq 'load when) (memq :load-toplevel when))
  624. (if comp (cons 'progn (mapcar 'cl--compile-time-too body))
  625. `(if nil nil ,@body))
  626. (progn (if comp (eval (cons 'progn body))) nil)))
  627. (and (or (memq 'eval when) (memq :execute when))
  628. (cons 'progn body))))
  629. (defun cl--compile-time-too (form)
  630. (or (and (symbolp (car-safe form)) (get (car-safe form) 'byte-hunk-handler))
  631. (setq form (macroexpand
  632. form (cons '(cl-eval-when) byte-compile-macro-environment))))
  633. (cond ((eq (car-safe form) 'progn)
  634. (cons 'progn (mapcar 'cl--compile-time-too (cdr form))))
  635. ((eq (car-safe form) 'cl-eval-when)
  636. (let ((when (nth 1 form)))
  637. (if (or (memq 'eval when) (memq :execute when))
  638. `(cl-eval-when (compile ,@when) ,@(cddr form))
  639. form)))
  640. (t (eval form) form)))
  641. ;;;###autoload
  642. (defmacro cl-load-time-value (form &optional _read-only)
  643. "Like `progn', but evaluates the body at load time.
  644. The result of the body appears to the compiler as a quoted constant."
  645. (declare (debug (form &optional sexp)))
  646. (if (cl--compiling-file)
  647. (let* ((temp (cl-gentemp "--cl-load-time--"))
  648. (set `(setq ,temp ,form)))
  649. (if (and (fboundp 'byte-compile-file-form-defmumble)
  650. (boundp 'this-kind) (boundp 'that-one))
  651. ;; Else, we can't output right away, so we have to delay it to the
  652. ;; next time we're at the top-level.
  653. ;; FIXME: Use advice-add/remove.
  654. (fset 'byte-compile-file-form
  655. (let ((old (symbol-function 'byte-compile-file-form)))
  656. (lambda (form)
  657. (fset 'byte-compile-file-form old)
  658. (byte-compile-file-form set)
  659. (byte-compile-file-form form))))
  660. ;; If we're not in the middle of compiling something, we can
  661. ;; output directly to byte-compile-outbuffer, to make sure
  662. ;; temp is set before we use it.
  663. (print set byte-compile--outbuffer))
  664. temp)
  665. `',(eval form)))
  666. ;;; Conditional control structures.
  667. ;;;###autoload
  668. (defmacro cl-case (expr &rest clauses)
  669. "Eval EXPR and choose among clauses on that value.
  670. Each clause looks like (KEYLIST BODY...). EXPR is evaluated and compared
  671. against each key in each KEYLIST; the corresponding BODY is evaluated.
  672. If no clause succeeds, cl-case returns nil. A single atom may be used in
  673. place of a KEYLIST of one atom. A KEYLIST of t or `otherwise' is
  674. allowed only in the final clause, and matches if no other keys match.
  675. Key values are compared by `eql'.
  676. \n(fn EXPR (KEYLIST BODY...)...)"
  677. (declare (indent 1) (debug (form &rest (sexp body))))
  678. (macroexp-let2 macroexp-copyable-p temp expr
  679. (let* ((head-list nil))
  680. `(cond
  681. ,@(mapcar
  682. (lambda (c)
  683. (cons (cond ((memq (car c) '(t otherwise)) t)
  684. ((eq (car c) 'cl--ecase-error-flag)
  685. `(error "cl-ecase failed: %s, %s"
  686. ,temp ',(reverse head-list)))
  687. ((listp (car c))
  688. (setq head-list (append (car c) head-list))
  689. `(cl-member ,temp ',(car c)))
  690. (t
  691. (if (memq (car c) head-list)
  692. (error "Duplicate key in case: %s"
  693. (car c)))
  694. (push (car c) head-list)
  695. `(eql ,temp ',(car c))))
  696. (or (cdr c) '(nil))))
  697. clauses)))))
  698. ;;;###autoload
  699. (defmacro cl-ecase (expr &rest clauses)
  700. "Like `cl-case', but error if no case fits.
  701. `otherwise'-clauses are not allowed.
  702. \n(fn EXPR (KEYLIST BODY...)...)"
  703. (declare (indent 1) (debug cl-case))
  704. `(cl-case ,expr ,@clauses (cl--ecase-error-flag)))
  705. ;;;###autoload
  706. (defmacro cl-typecase (expr &rest clauses)
  707. "Evals EXPR, chooses among clauses on that value.
  708. Each clause looks like (TYPE BODY...). EXPR is evaluated and, if it
  709. satisfies TYPE, the corresponding BODY is evaluated. If no clause succeeds,
  710. cl-typecase returns nil. A TYPE of t or `otherwise' is allowed only in the
  711. final clause, and matches if no other keys match.
  712. \n(fn EXPR (TYPE BODY...)...)"
  713. (declare (indent 1)
  714. (debug (form &rest ([&or cl-type-spec "otherwise"] body))))
  715. (macroexp-let2 macroexp-copyable-p temp expr
  716. (let* ((type-list nil))
  717. (cons
  718. 'cond
  719. (mapcar
  720. (function
  721. (lambda (c)
  722. (cons (cond ((eq (car c) 'otherwise) t)
  723. ((eq (car c) 'cl--ecase-error-flag)
  724. `(error "cl-etypecase failed: %s, %s"
  725. ,temp ',(reverse type-list)))
  726. (t
  727. (push (car c) type-list)
  728. `(cl-typep ,temp ',(car c))))
  729. (or (cdr c) '(nil)))))
  730. clauses)))))
  731. ;;;###autoload
  732. (defmacro cl-etypecase (expr &rest clauses)
  733. "Like `cl-typecase', but error if no case fits.
  734. `otherwise'-clauses are not allowed.
  735. \n(fn EXPR (TYPE BODY...)...)"
  736. (declare (indent 1) (debug cl-typecase))
  737. `(cl-typecase ,expr ,@clauses (cl--ecase-error-flag)))
  738. ;;; Blocks and exits.
  739. ;;;###autoload
  740. (defmacro cl-block (name &rest body)
  741. "Define a lexically-scoped block named NAME.
  742. NAME may be any symbol. Code inside the BODY forms can call `cl-return-from'
  743. to jump prematurely out of the block. This differs from `catch' and `throw'
  744. in two respects: First, the NAME is an unevaluated symbol rather than a
  745. quoted symbol or other form; and second, NAME is lexically rather than
  746. dynamically scoped: Only references to it within BODY will work. These
  747. references may appear inside macro expansions, but not inside functions
  748. called from BODY."
  749. (declare (indent 1) (debug (symbolp body)))
  750. (if (cl--safe-expr-p `(progn ,@body)) `(progn ,@body)
  751. `(cl--block-wrapper
  752. (catch ',(intern (format "--cl-block-%s--" name))
  753. ,@body))))
  754. ;;;###autoload
  755. (defmacro cl-return (&optional result)
  756. "Return from the block named nil.
  757. This is equivalent to `(cl-return-from nil RESULT)'."
  758. (declare (debug (&optional form)))
  759. `(cl-return-from nil ,result))
  760. ;;;###autoload
  761. (defmacro cl-return-from (name &optional result)
  762. "Return from the block named NAME.
  763. This jumps out to the innermost enclosing `(cl-block NAME ...)' form,
  764. returning RESULT from that form (or nil if RESULT is omitted).
  765. This is compatible with Common Lisp, but note that `defun' and
  766. `defmacro' do not create implicit blocks as they do in Common Lisp."
  767. (declare (indent 1) (debug (symbolp &optional form)))
  768. (let ((name2 (intern (format "--cl-block-%s--" name))))
  769. `(cl--block-throw ',name2 ,result)))
  770. ;;; The "cl-loop" macro.
  771. (defvar cl--loop-args) (defvar cl--loop-accum-var) (defvar cl--loop-accum-vars)
  772. (defvar cl--loop-bindings) (defvar cl--loop-body)
  773. (defvar cl--loop-finally)
  774. (defvar cl--loop-finish-flag) ;Symbol set to nil to exit the loop?
  775. (defvar cl--loop-first-flag)
  776. (defvar cl--loop-initially) (defvar cl--loop-iterator-function)
  777. (defvar cl--loop-name)
  778. (defvar cl--loop-result) (defvar cl--loop-result-explicit)
  779. (defvar cl--loop-result-var) (defvar cl--loop-steps)
  780. (defvar cl--loop-symbol-macs)
  781. (defun cl--loop-set-iterator-function (kind iterator)
  782. (if cl--loop-iterator-function
  783. ;; FIXME: Of course, we could make it work, but why bother.
  784. (error "Iteration on %S does not support this combination" kind)
  785. (setq cl--loop-iterator-function iterator)))
  786. ;;;###autoload
  787. (defmacro cl-loop (&rest loop-args)
  788. "The Common Lisp `loop' macro.
  789. Valid clauses include:
  790. For clauses:
  791. for VAR from/upfrom/downfrom EXPR1 to/upto/downto/above/below EXPR2 [by EXPR3]
  792. for VAR = EXPR1 then EXPR2
  793. for VAR in/on/in-ref LIST [by FUNC]
  794. for VAR across/across-ref ARRAY
  795. for VAR being:
  796. the elements of/of-ref SEQUENCE [using (index VAR2)]
  797. the symbols [of OBARRAY]
  798. the hash-keys/hash-values of HASH-TABLE [using (hash-values/hash-keys V2)]
  799. the key-codes/key-bindings/key-seqs of KEYMAP [using (key-bindings VAR2)]
  800. the overlays/intervals [of BUFFER] [from POS1] [to POS2]
  801. the frames/buffers
  802. the windows [of FRAME]
  803. Iteration clauses:
  804. repeat INTEGER
  805. while/until/always/never/thereis CONDITION
  806. Accumulation clauses:
  807. collect/append/nconc/concat/vconcat/count/sum/maximize/minimize FORM
  808. [into VAR]
  809. Miscellaneous clauses:
  810. with VAR = INIT
  811. if/when/unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...]
  812. named NAME
  813. initially/finally [do] EXPRS...
  814. do EXPRS...
  815. [finally] return EXPR
  816. For more details, see Info node `(cl)Loop Facility'.
  817. \(fn CLAUSE...)"
  818. (declare (debug (&rest &or
  819. ;; These are usually followed by a symbol, but it can
  820. ;; actually be any destructuring-bind pattern, which
  821. ;; would erroneously match `form'.
  822. [[&or "for" "as" "with" "and"] sexp]
  823. ;; These are followed by expressions which could
  824. ;; erroneously match `symbolp'.
  825. [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
  826. "above" "below" "by" "in" "on" "=" "across"
  827. "repeat" "while" "until" "always" "never"
  828. "thereis" "collect" "append" "nconc" "sum"
  829. "count" "maximize" "minimize" "if" "unless"
  830. "return"]
  831. form]
  832. ["using" (symbolp symbolp)]
  833. ;; Simple default, which covers 99% of the cases.
  834. symbolp form)))
  835. (if (not (memq t (mapcar #'symbolp
  836. (delq nil (delq t (cl-copy-list loop-args))))))
  837. `(cl-block nil (while t ,@loop-args))
  838. (let ((cl--loop-args loop-args) (cl--loop-name nil) (cl--loop-bindings nil)
  839. (cl--loop-body nil) (cl--loop-steps nil)
  840. (cl--loop-result nil) (cl--loop-result-explicit nil)
  841. (cl--loop-result-var nil) (cl--loop-finish-flag nil)
  842. (cl--loop-accum-var nil) (cl--loop-accum-vars nil)
  843. (cl--loop-initially nil) (cl--loop-finally nil)
  844. (cl--loop-iterator-function nil) (cl--loop-first-flag nil)
  845. (cl--loop-symbol-macs nil))
  846. ;; Here is more or less how those dynbind vars are used after looping
  847. ;; over cl--parse-loop-clause:
  848. ;;
  849. ;; (cl-block ,cl--loop-name
  850. ;; (cl-symbol-macrolet ,cl--loop-symbol-macs
  851. ;; (foldl #'cl--loop-let
  852. ;; `((,cl--loop-result-var)
  853. ;; ((,cl--loop-first-flag t))
  854. ;; ((,cl--loop-finish-flag t))
  855. ;; ,@cl--loop-bindings)
  856. ;; ,@(nreverse cl--loop-initially)
  857. ;; (while ;(well: cl--loop-iterator-function)
  858. ;; ,(car (cl--loop-build-ands (nreverse cl--loop-body)))
  859. ;; ,@(cadr (cl--loop-build-ands (nreverse cl--loop-body)))
  860. ;; ,@(nreverse cl--loop-steps)
  861. ;; (setq ,cl--loop-first-flag nil))
  862. ;; (if (not ,cl--loop-finish-flag) ;FIXME: Why `if' vs `progn'?
  863. ;; ,cl--loop-result-var
  864. ;; ,@(nreverse cl--loop-finally)
  865. ;; ,(or cl--loop-result-explicit
  866. ;; cl--loop-result)))))
  867. ;;
  868. (setq cl--loop-args (append cl--loop-args '(cl-end-loop)))
  869. (while (not (eq (car cl--loop-args) 'cl-end-loop))
  870. (cl--parse-loop-clause))
  871. (if cl--loop-finish-flag
  872. (push `((,cl--loop-finish-flag t)) cl--loop-bindings))
  873. (if cl--loop-first-flag
  874. (progn (push `((,cl--loop-first-flag t)) cl--loop-bindings)
  875. (push `(setq ,cl--loop-first-flag nil) cl--loop-steps)))
  876. (let* ((epilogue (nconc (nreverse cl--loop-finally)
  877. (list (or cl--loop-result-explicit
  878. cl--loop-result))))
  879. (ands (cl--loop-build-ands (nreverse cl--loop-body)))
  880. (while-body (nconc (cadr ands) (nreverse cl--loop-steps)))
  881. (body (append
  882. (nreverse cl--loop-initially)
  883. (list (if cl--loop-iterator-function
  884. `(cl-block --cl-finish--
  885. ,(funcall cl--loop-iterator-function
  886. (if (eq (car ands) t) while-body
  887. (cons `(or ,(car ands)
  888. (cl-return-from
  889. --cl-finish--
  890. nil))
  891. while-body))))
  892. `(while ,(car ands) ,@while-body)))
  893. (if cl--loop-finish-flag
  894. (if (equal epilogue '(nil)) (list cl--loop-result-var)
  895. `((if ,cl--loop-finish-flag
  896. (progn ,@epilogue) ,cl--loop-result-var)))
  897. epilogue))))
  898. (if cl--loop-result-var
  899. (push (list cl--loop-result-var) cl--loop-bindings))
  900. (while cl--loop-bindings
  901. (if (cdar cl--loop-bindings)
  902. (setq body (list (cl--loop-let (pop cl--loop-bindings) body t)))
  903. (let ((lets nil))
  904. (while (and cl--loop-bindings
  905. (not (cdar cl--loop-bindings)))
  906. (push (car (pop cl--loop-bindings)) lets))
  907. (setq body (list (cl--loop-let lets body nil))))))
  908. (if cl--loop-symbol-macs
  909. (setq body
  910. (list `(cl-symbol-macrolet ,cl--loop-symbol-macs ,@body))))
  911. `(cl-block ,cl--loop-name ,@body)))))
  912. ;; Below is a complete spec for cl-loop, in several parts that correspond
  913. ;; to the syntax given in CLtL2. The specs do more than specify where
  914. ;; the forms are; it also specifies, as much as Edebug allows, all the
  915. ;; syntactically valid cl-loop clauses. The disadvantage of this
  916. ;; completeness is rigidity, but the "for ... being" clause allows
  917. ;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].
  918. ;; (def-edebug-spec cl-loop
  919. ;; ([&optional ["named" symbolp]]
  920. ;; [&rest
  921. ;; &or
  922. ;; ["repeat" form]
  923. ;; loop-for-as
  924. ;; loop-with
  925. ;; loop-initial-final]
  926. ;; [&rest loop-clause]
  927. ;; ))
  928. ;; (def-edebug-spec loop-with
  929. ;; ("with" loop-var
  930. ;; loop-type-spec
  931. ;; [&optional ["=" form]]
  932. ;; &rest ["and" loop-var
  933. ;; loop-type-spec
  934. ;; [&optional ["=" form]]]))
  935. ;; (def-edebug-spec loop-for-as
  936. ;; ([&or "for" "as"] loop-for-as-subclause
  937. ;; &rest ["and" loop-for-as-subclause]))
  938. ;; (def-edebug-spec loop-for-as-subclause
  939. ;; (loop-var
  940. ;; loop-type-spec
  941. ;; &or
  942. ;; [[&or "in" "on" "in-ref" "across-ref"]
  943. ;; form &optional ["by" function-form]]
  944. ;; ["=" form &optional ["then" form]]
  945. ;; ["across" form]
  946. ;; ["being"
  947. ;; [&or "the" "each"]
  948. ;; &or
  949. ;; [[&or "element" "elements"]
  950. ;; [&or "of" "in" "of-ref"] form
  951. ;; &optional "using" ["index" symbolp]];; is this right?
  952. ;; [[&or "hash-key" "hash-keys"
  953. ;; "hash-value" "hash-values"]
  954. ;; [&or "of" "in"]
  955. ;; hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
  956. ;; "hash-key" "hash-keys"] sexp)]]
  957. ;; [[&or "symbol" "present-symbol" "external-symbol"
  958. ;; "symbols" "present-symbols" "external-symbols"]
  959. ;; [&or "in" "of"] package-p]
  960. ;; ;; Extensions for Emacs Lisp, including Lucid Emacs.
  961. ;; [[&or "frame" "frames"
  962. ;; "screen" "screens"
  963. ;; "buffer" "buffers"]]
  964. ;; [[&or "window" "windows"]
  965. ;; [&or "of" "in"] form]
  966. ;; [[&or "overlay" "overlays"
  967. ;; "extent" "extents"]
  968. ;; [&or "of" "in"] form
  969. ;; &optional [[&or "from" "to"] form]]
  970. ;; [[&or "interval" "intervals"]
  971. ;; [&or "in" "of"] form
  972. ;; &optional [[&or "from" "to"] form]
  973. ;; ["property" form]]
  974. ;; [[&or "key-code" "key-codes"
  975. ;; "key-seq" "key-seqs"
  976. ;; "key-binding" "key-bindings"]
  977. ;; [&or "in" "of"] form
  978. ;; &optional ["using" ([&or "key-code" "key-codes"
  979. ;; "key-seq" "key-seqs"
  980. ;; "key-binding" "key-bindings"]
  981. ;; sexp)]]
  982. ;; ;; For arbitrary extensions, recognize anything else.
  983. ;; [symbolp &rest &or symbolp form]
  984. ;; ]
  985. ;; ;; arithmetic - must be last since all parts are optional.
  986. ;; [[&optional [[&or "from" "downfrom" "upfrom"] form]]
  987. ;; [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
  988. ;; [&optional ["by" form]]
  989. ;; ]))
  990. ;; (def-edebug-spec loop-initial-final
  991. ;; (&or ["initially"
  992. ;; ;; [&optional &or "do" "doing"] ;; CLtL2 doesn't allow this.
  993. ;; &rest loop-non-atomic-expr]
  994. ;; ["finally" &or
  995. ;; [[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
  996. ;; ["return" form]]))
  997. ;; (def-edebug-spec loop-and-clause
  998. ;; (loop-clause &rest ["and" loop-clause]))
  999. ;; (def-edebug-spec loop-clause
  1000. ;; (&or
  1001. ;; [[&or "while" "until" "always" "never" "thereis"] form]
  1002. ;; [[&or "collect" "collecting"
  1003. ;; "append" "appending"
  1004. ;; "nconc" "nconcing"
  1005. ;; "concat" "vconcat"] form
  1006. ;; [&optional ["into" loop-var]]]
  1007. ;; [[&or "count" "counting"
  1008. ;; "sum" "summing"
  1009. ;; "maximize" "maximizing"
  1010. ;; "minimize" "minimizing"] form
  1011. ;; [&optional ["into" loop-var]]
  1012. ;; loop-type-spec]
  1013. ;; [[&or "if" "when" "unless"]
  1014. ;; form loop-and-clause
  1015. ;; [&optional ["else" loop-and-clause]]
  1016. ;; [&optional "end"]]
  1017. ;; [[&or "do" "doing"] &rest loop-non-atomic-expr]
  1018. ;; ["return" form]
  1019. ;; loop-initial-final
  1020. ;; ))
  1021. ;; (def-edebug-spec loop-non-atomic-expr
  1022. ;; ([&not atom] form))
  1023. ;; (def-edebug-spec loop-var
  1024. ;; ;; The symbolp must be last alternative to recognize e.g. (a b . c)
  1025. ;; ;; loop-var =>
  1026. ;; ;; (loop-var . [&or nil loop-var])
  1027. ;; ;; (symbolp . [&or nil loop-var])
  1028. ;; ;; (symbolp . loop-var)
  1029. ;; ;; (symbolp . (symbolp . [&or nil loop-var]))
  1030. ;; ;; (symbolp . (symbolp . loop-var))
  1031. ;; ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
  1032. ;; (&or (loop-var . [&or nil loop-var]) [gate symbolp]))
  1033. ;; (def-edebug-spec loop-type-spec
  1034. ;; (&optional ["of-type" loop-d-type-spec]))
  1035. ;; (def-edebug-spec loop-d-type-spec
  1036. ;; (&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))
  1037. (defun cl--parse-loop-clause () ; uses loop-*
  1038. (let ((word (pop cl--loop-args))
  1039. (hash-types '(hash-key hash-keys hash-value hash-values))
  1040. (key-types '(key-code key-codes key-seq key-seqs
  1041. key-binding key-bindings)))
  1042. (cond
  1043. ((null cl--loop-args)
  1044. (error "Malformed `cl-loop' macro"))
  1045. ((eq word 'named)
  1046. (setq cl--loop-name (pop cl--loop-args)))
  1047. ((eq word 'initially)
  1048. (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
  1049. (or (consp (car cl--loop-args))
  1050. (error "Syntax error on `initially' clause"))
  1051. (while (consp (car cl--loop-args))
  1052. (push (pop cl--loop-args) cl--loop-initially)))
  1053. ((eq word 'finally)
  1054. (if (eq (car cl--loop-args) 'return)
  1055. (setq cl--loop-result-explicit
  1056. (or (cl--pop2 cl--loop-args) '(quote nil)))
  1057. (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
  1058. (or (consp (car cl--loop-args))
  1059. (error "Syntax error on `finally' clause"))
  1060. (if (and (eq (caar cl--loop-args) 'return) (null cl--loop-name))
  1061. (setq cl--loop-result-explicit
  1062. (or (nth 1 (pop cl--loop-args)) '(quote nil)))
  1063. (while (consp (car cl--loop-args))
  1064. (push (pop cl--loop-args) cl--loop-finally)))))
  1065. ((memq word '(for as))
  1066. (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
  1067. (ands nil))
  1068. (while
  1069. ;; Use `cl-gensym' rather than `make-symbol'. It's important that
  1070. ;; (not (eq (symbol-name var1) (symbol-name var2))) because
  1071. ;; these vars get added to the macro-environment.
  1072. (let ((var (or (pop cl--loop-args) (cl-gensym "--cl-var--"))))
  1073. (setq word (pop cl--loop-args))
  1074. (if (eq word 'being) (setq word (pop cl--loop-args)))
  1075. (if (memq word '(the each)) (setq word (pop cl--loop-args)))
  1076. (if (memq word '(buffer buffers))
  1077. (setq word 'in
  1078. cl--loop-args (cons '(buffer-list) cl--loop-args)))
  1079. (cond
  1080. ((memq word '(from downfrom upfrom to downto upto
  1081. above below by))
  1082. (push word cl--loop-args)
  1083. (if (memq (car cl--loop-args) '(downto above))
  1084. (error "Must specify `from' value for downward cl-loop"))
  1085. (let* ((down (or (eq (car cl--loop-args) 'downfrom)
  1086. (memq (nth 2 cl--loop-args)
  1087. '(downto above))))
  1088. (excl (or (memq (car cl--loop-args) '(above below))
  1089. (memq (nth 2 cl--loop-args)
  1090. '(above below))))
  1091. (start (and (memq (car cl--loop-args)
  1092. '(from upfrom downfrom))
  1093. (cl--pop2 cl--loop-args)))
  1094. (end (and (memq (car cl--loop-args)
  1095. '(to upto downto above below))
  1096. (cl--pop2 cl--loop-args)))
  1097. (step (and (eq (car cl--loop-args) 'by)
  1098. (cl--pop2 cl--loop-args)))
  1099. (end-var (and (not (macroexp-const-p end))
  1100. (make-symbol "--cl-var--")))
  1101. (step-var (and (not (macroexp-const-p step))
  1102. (make-symbol "--cl-var--"))))
  1103. (and step (numberp step) (<= step 0)
  1104. (error "Loop `by' value is not positive: %s" step))
  1105. (push (list var (or start 0)) loop-for-bindings)
  1106. (if end-var (push (list end-var end) loop-for-bindings))
  1107. (if step-var (push (list step-var step)
  1108. loop-for-bindings))
  1109. (if end
  1110. (push (list
  1111. (if down (if excl '> '>=) (if excl '< '<=))
  1112. var (or end-var end))
  1113. cl--loop-body))
  1114. (push (list var (list (if down '- '+) var
  1115. (or step-var step 1)))
  1116. loop-for-steps)))
  1117. ((memq word '(in in-ref on))
  1118. (let* ((on (eq word 'on))
  1119. (temp (if (and on (symbolp var))
  1120. var (make-symbol "--cl-var--"))))
  1121. (push (list temp (pop cl--loop-args)) loop-for-bindings)
  1122. (push `(consp ,temp) cl--loop-body)
  1123. (if (eq word 'in-ref)
  1124. (push (list var `(car ,temp)) cl--loop-symbol-macs)
  1125. (or (eq temp var)
  1126. (progn
  1127. (push (list var nil) loop-for-bindings)
  1128. (push (list var (if on temp `(car ,temp)))
  1129. loop-for-sets))))
  1130. (push (list temp
  1131. (if (eq (car cl--loop-args) 'by)
  1132. (let ((step (cl--pop2 cl--loop-args)))
  1133. (if (and (memq (car-safe step)
  1134. '(quote function
  1135. cl-function))
  1136. (symbolp (nth 1 step)))
  1137. (list (nth 1 step) temp)
  1138. `(funcall ,step ,temp)))
  1139. `(cdr ,temp)))
  1140. loop-for-steps)))
  1141. ((eq word '=)
  1142. (let* ((start (pop cl--loop-args))
  1143. (then (if (eq (car cl--loop-args) 'then)
  1144. (cl--pop2 cl--loop-args) start)))
  1145. (push (list var nil) loop-for-bindings)
  1146. (if (or ands (eq (car cl--loop-args) 'and))
  1147. (progn
  1148. (push `(,var
  1149. (if ,(or cl--loop-first-flag
  1150. (setq cl--loop-first-flag
  1151. (make-symbol "--cl-var--")))
  1152. ,start ,var))
  1153. loop-for-sets)
  1154. (push (list var then) loop-for-steps))
  1155. (push (list var
  1156. (if (eq start then) start
  1157. `(if ,(or cl--loop-first-flag
  1158. (setq cl--loop-first-flag
  1159. (make-symbol "--cl-var--")))
  1160. ,start ,then)))
  1161. loop-for-sets))))
  1162. ((memq word '(across across-ref))
  1163. (let ((temp-vec (make-symbol "--cl-vec--"))
  1164. (temp-idx (make-symbol "--cl-idx--")))
  1165. (push (list temp-vec (pop cl--loop-args)) loop-for-bindings)
  1166. (push (list temp-idx -1) loop-for-bindings)
  1167. (push `(< (setq ,temp-idx (1+ ,temp-idx))
  1168. (length ,temp-vec))
  1169. cl--loop-body)
  1170. (if (eq word 'across-ref)
  1171. (push (list var `(aref ,temp-vec ,temp-idx))
  1172. cl--loop-symbol-macs)
  1173. (push (list var nil) loop-for-bindings)
  1174. (push (list var `(aref ,temp-vec ,temp-idx))
  1175. loop-for-sets))))
  1176. ((memq word '(element elements))
  1177. (let ((ref (or (memq (car cl--loop-args) '(in-ref of-ref))
  1178. (and (not (memq (car cl--loop-args) '(in of)))
  1179. (error "Expected `of'"))))
  1180. (seq (cl--pop2 cl--loop-args))
  1181. (temp-seq (make-symbol "--cl-seq--"))
  1182. (temp-idx
  1183. (if (eq (car cl--loop-args) 'using)
  1184. (if (and (= (length (cadr cl--loop-args)) 2)
  1185. (eq (cl-caadr cl--loop-args) 'index))
  1186. (cadr (cl--pop2 cl--loop-args))
  1187. (error "Bad `using' clause"))
  1188. (make-symbol "--cl-idx--"))))
  1189. (push (list temp-seq seq) loop-for-bindings)
  1190. (push (list temp-idx 0) loop-for-bindings)
  1191. (if ref
  1192. (let ((temp-len (make-symbol "--cl-len--")))
  1193. (push (list temp-len `(length ,temp-seq))
  1194. loop-for-bindings)
  1195. (push (list var `(elt ,temp-seq ,temp-idx))
  1196. cl--loop-symbol-macs)
  1197. (push `(< ,temp-idx ,temp-len) cl--loop-body))
  1198. (push (list var nil) loop-for-bindings)
  1199. (push `(and ,temp-seq
  1200. (or (consp ,temp-seq)
  1201. (< ,temp-idx (length ,temp-seq))))
  1202. cl--loop-body)
  1203. (push (list var `(if (consp ,temp-seq)
  1204. (pop ,temp-seq)
  1205. (aref ,temp-seq ,temp-idx)))
  1206. loop-for-sets))
  1207. (push (list temp-idx `(1+ ,temp-idx))
  1208. loop-for-steps)))
  1209. ((memq word hash-types)
  1210. (or (memq (car cl--loop-args) '(in of))
  1211. (error "Expected `of'"))
  1212. (let* ((table (cl--pop2 cl--loop-args))
  1213. (other
  1214. (if (eq (car cl--loop-args) 'using)
  1215. (if (and (= (length (cadr cl--loop-args)) 2)
  1216. (memq (cl-caadr cl--loop-args) hash-types)
  1217. (not (eq (cl-caadr cl--loop-args) word)))
  1218. (cadr (cl--pop2 cl--loop-args))
  1219. (error "Bad `using' clause"))
  1220. (make-symbol "--cl-var--"))))
  1221. (if (memq word '(hash-value hash-values))
  1222. (setq var (prog1 other (setq other var))))
  1223. (cl--loop-set-iterator-function
  1224. 'hash-tables (lambda (body)
  1225. `(maphash (lambda (,var ,other) . ,body)
  1226. ,table)))))
  1227. ((memq word '(symbol present-symbol external-symbol
  1228. symbols present-symbols external-symbols))
  1229. (let ((ob (and (memq (car cl--loop-args) '(in of))
  1230. (cl--pop2 cl--loop-args))))
  1231. (cl--loop-set-iterator-function
  1232. 'symbols (lambda (body)
  1233. `(mapatoms (lambda (,var) . ,body) ,ob)))))
  1234. ((memq word '(overlay overlays extent extents))
  1235. (let ((buf nil) (from nil) (to nil))
  1236. (while (memq (car cl--loop-args) '(in of from to))
  1237. (cond ((eq (car cl--loop-args) 'from)
  1238. (setq from (cl--pop2 cl--loop-args)))
  1239. ((eq (car cl--loop-args) 'to)
  1240. (setq to (cl--pop2 cl--loop-args)))
  1241. (t (setq buf (cl--pop2 cl--loop-args)))))
  1242. (cl--loop-set-iterator-function
  1243. 'overlays (lambda (body)
  1244. `(cl--map-overlays
  1245. (lambda (,var ,(make-symbol "--cl-var--"))
  1246. (progn . ,body) nil)
  1247. ,buf ,from ,to)))))
  1248. ((memq word '(interval intervals))
  1249. (let ((buf nil) (prop nil) (from nil) (to nil)
  1250. (var1 (make-symbol "--cl-var1--"))
  1251. (var2 (make-symbol "--cl-var2--")))
  1252. (while (memq (car cl--loop-args) '(in of property from to))
  1253. (cond ((eq (car cl--loop-args) 'from)
  1254. (setq from (cl--pop2 cl--loop-args)))
  1255. ((eq (car cl--loop-args) 'to)
  1256. (setq to (cl--pop2 cl--loop-args)))
  1257. ((eq (car cl--loop-args) 'property)
  1258. (setq prop (cl--pop2 cl--loop-args)))
  1259. (t (setq buf (cl--pop2 cl--loop-args)))))
  1260. (if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
  1261. (setq var1 (car var) var2 (cdr var))
  1262. (push (list var `(cons ,var1 ,var2)) loop-for-sets))
  1263. (cl--loop-set-iterator-function
  1264. 'intervals (lambda (body)
  1265. `(cl--map-intervals
  1266. (lambda (,var1 ,var2) . ,body)
  1267. ,buf ,prop ,from ,to)))))
  1268. ((memq word key-types)
  1269. (or (memq (car cl--loop-args) '(in of))
  1270. (error "Expected `of'"))
  1271. (let ((cl-map (cl--pop2 cl--loop-args))
  1272. (other
  1273. (if (eq (car cl--loop-args) 'using)
  1274. (if (and (= (length (cadr cl--loop-args)) 2)
  1275. (memq (cl-caadr cl--loop-args) key-types)
  1276. (not (eq (cl-caadr cl--loop-args) word)))
  1277. (cadr (cl--pop2 cl--loop-args))
  1278. (error "Bad `using' clause"))
  1279. (make-symbol "--cl-var--"))))
  1280. (if (memq word '(key-binding key-bindings))
  1281. (setq var (prog1 other (setq other var))))
  1282. (cl--loop-set-iterator-function
  1283. 'keys (lambda (body)
  1284. `(,(if (memq word '(key-seq key-seqs))
  1285. 'cl--map-keymap-recursively 'map-keymap)
  1286. (lambda (,var ,other) . ,body) ,cl-map)))))
  1287. ((memq word '(frame frames screen screens))
  1288. (let ((temp (make-symbol "--cl-var--")))
  1289. (push (list var '(selected-frame))
  1290. loop-for-bindings)
  1291. (push (list temp nil) loop-for-bindings)
  1292. (push `(prog1 (not (eq ,var ,temp))
  1293. (or ,temp (setq ,temp ,var)))
  1294. cl--loop-body)
  1295. (push (list var `(next-frame ,var))
  1296. loop-for-steps)))
  1297. ((memq word '(window windows))
  1298. (let ((scr (and (memq (car cl--loop-args) '(in of))
  1299. (cl--pop2 cl--loop-args)))
  1300. (temp (make-symbol "--cl-var--"))
  1301. (minip (make-symbol "--cl-minip--")))
  1302. (push (list var (if scr
  1303. `(frame-selected-window ,scr)
  1304. '(selected-window)))
  1305. loop-for-bindings)
  1306. ;; If we started in the minibuffer, we need to
  1307. ;; ensure that next-window will bring us back there
  1308. ;; at some point. (Bug#7492).
  1309. ;; (Consider using walk-windows instead of cl-loop if
  1310. ;; you care about such things.)
  1311. (push (list minip `(minibufferp (window-buffer ,var)))
  1312. loop-for-bindings)
  1313. (push (list temp nil) loop-for-bindings)
  1314. (push `(prog1 (not (eq ,var ,temp))
  1315. (or ,temp (setq ,temp ,var)))
  1316. cl--loop-body)
  1317. (push (list var `(next-window ,var ,minip))
  1318. loop-for-steps)))
  1319. (t
  1320. ;; This is an advertised interface: (info "(cl)Other Clauses").
  1321. (let ((handler (and (symbolp word)
  1322. (get word 'cl-loop-for-handler))))
  1323. (if handler
  1324. (funcall handler var)
  1325. (error "Expected a `for' preposition, found %s" word)))))
  1326. (eq (car cl--loop-args) 'and))
  1327. (setq ands t)
  1328. (pop cl--loop-args))
  1329. (if (and ands loop-for-bindings)
  1330. (push (nreverse loop-for-bindings) cl--loop-bindings)
  1331. (setq cl--loop-bindings (nconc (mapcar 'list loop-for-bindings)
  1332. cl--loop-bindings)))
  1333. (if loop-for-sets
  1334. (push `(progn
  1335. ,(cl--loop-let (nreverse loop-for-sets) 'setq ands)
  1336. t)
  1337. cl--loop-body))
  1338. (if loop-for-steps
  1339. (push (cons (if ands 'cl-psetq 'setq)
  1340. (apply 'append (nreverse loop-for-steps)))
  1341. cl--loop-steps))))
  1342. ((eq word 'repeat)
  1343. (let ((temp (make-symbol "--cl-var--")))
  1344. (push (list (list temp (pop cl--loop-args))) cl--loop-bindings)
  1345. (push `(>= (setq ,temp (1- ,temp)) 0) cl--loop-body)))
  1346. ((memq word '(collect collecting))
  1347. (let ((what (pop cl--loop-args))
  1348. (var (cl--loop-handle-accum nil 'nreverse)))
  1349. (if (eq var cl--loop-accum-var)
  1350. (push `(progn (push ,what ,var) t) cl--loop-body)
  1351. (push `(progn
  1352. (setq ,var (nconc ,var (list ,what)))
  1353. t)
  1354. cl--loop-body))))
  1355. ((memq word '(nconc nconcing append appending))
  1356. (let ((what (pop cl--loop-args))
  1357. (var (cl--loop-handle-accum nil 'nreverse)))
  1358. (push `(progn
  1359. (setq ,var
  1360. ,(if (eq var cl--loop-accum-var)
  1361. `(nconc
  1362. (,(if (memq word '(nconc nconcing))
  1363. #'nreverse #'reverse)
  1364. ,what)
  1365. ,var)
  1366. `(,(if (memq word '(nconc nconcing))
  1367. #'nconc #'append)
  1368. ,var ,what)))
  1369. t)
  1370. cl--loop-body)))
  1371. ((memq word '(concat concating))
  1372. (let ((what (pop cl--loop-args))
  1373. (var (cl--loop-handle-accum "")))
  1374. (push `(progn (cl-callf concat ,var ,what) t) cl--loop-body)))
  1375. ((memq word '(vconcat vconcating))
  1376. (let ((what (pop cl--loop-args))
  1377. (var (cl--loop-handle-accum [])))
  1378. (push `(progn (cl-callf vconcat ,var ,what) t) cl--loop-body)))
  1379. ((memq word '(sum summing))
  1380. (let ((what (pop cl--loop-args))
  1381. (var (cl--loop-handle-accum 0)))
  1382. (push `(progn (cl-incf ,var ,what) t) cl--loop-body)))
  1383. ((memq word '(count counting))
  1384. (let ((what (pop cl--loop-args))
  1385. (var (cl--loop-handle-accum 0)))
  1386. (push `(progn (if ,what (cl-incf ,var)) t) cl--loop-body)))
  1387. ((memq word '(minimize minimizing maximize maximizing))
  1388. (push `(progn ,(macroexp-let2 macroexp-copyable-p temp
  1389. (pop cl--loop-args)
  1390. (let* ((var (cl--loop-handle-accum nil))
  1391. (func (intern (substring (symbol-name word)
  1392. 0 3))))
  1393. `(setq ,var (if ,var (,func ,var ,temp) ,temp))))
  1394. t)
  1395. cl--loop-body))
  1396. ((eq word 'with)
  1397. (let ((bindings nil))
  1398. (while (progn (push (list (pop cl--loop-args)
  1399. (and (eq (car cl--loop-args) '=)
  1400. (cl--pop2 cl--loop-args)))
  1401. bindings)
  1402. (eq (car cl--loop-args) 'and))
  1403. (pop cl--loop-args))
  1404. (push (nreverse bindings) cl--loop-bindings)))
  1405. ((eq word 'while)
  1406. (push (pop cl--loop-args) cl--loop-body))
  1407. ((eq word 'until)
  1408. (push `(not ,(pop cl--loop-args)) cl--loop-body))
  1409. ((eq word 'always)
  1410. (or cl--loop-finish-flag
  1411. (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
  1412. (push `(setq ,cl--loop-finish-flag ,(pop cl--loop-args)) cl--loop-body)
  1413. (setq cl--loop-result t))
  1414. ((eq word 'never)
  1415. (or cl--loop-finish-flag
  1416. (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
  1417. (push `(setq ,cl--loop-finish-flag (not ,(pop cl--loop-args)))
  1418. cl--loop-body)
  1419. (setq cl--loop-result t))
  1420. ((eq word 'thereis)
  1421. (or cl--loop-finish-flag
  1422. (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
  1423. (or cl--loop-result-var
  1424. (setq cl--loop-result-var (make-symbol "--cl-var--")))
  1425. (push `(setq ,cl--loop-finish-flag
  1426. (not (setq ,cl--loop-result-var ,(pop cl--loop-args))))
  1427. cl--loop-body))
  1428. ((memq word '(if when unless))
  1429. (let* ((cond (pop cl--loop-args))
  1430. (then (let ((cl--loop-body nil))
  1431. (cl--parse-loop-clause)
  1432. (cl--loop-build-ands (nreverse cl--loop-body))))
  1433. (else (let ((cl--loop-body nil))
  1434. (if (eq (car cl--loop-args) 'else)
  1435. (progn (pop cl--loop-args) (cl--parse-loop-clause)))
  1436. (cl--loop-build-ands (nreverse cl--loop-body))))
  1437. (simple (and (eq (car then) t) (eq (car else) t))))
  1438. (if (eq (car cl--loop-args) 'end) (pop cl--loop-args))
  1439. (if (eq word 'unless) (setq then (prog1 else (setq else then))))
  1440. (let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
  1441. (if simple (nth 1 else) (list (nth 2 else))))))
  1442. (setq form (if (cl--expr-contains form 'it)
  1443. `(let ((it ,cond)) (if it ,@form))
  1444. `(if ,cond ,@form)))
  1445. (push (if simple `(progn ,form t) form) cl--loop-body))))
  1446. ((memq word '(do doing))
  1447. (let ((body nil))
  1448. (or (consp (car cl--loop-args)) (error "Syntax error on `do' clause"))
  1449. (while (consp (car cl--loop-args)) (push (pop cl--loop-args) body))
  1450. (push (cons 'progn (nreverse (cons t body))) cl--loop-body)))
  1451. ((eq word 'return)
  1452. (or cl--loop-finish-flag
  1453. (setq cl--loop-finish-flag (make-symbol "--cl-var--")))
  1454. (or cl--loop-result-var
  1455. (setq cl--loop-result-var (make-symbol "--cl-var--")))
  1456. (push `(setq ,cl--loop-result-var ,(pop cl--loop-args)
  1457. ,cl--loop-finish-flag nil)
  1458. cl--loop-body))
  1459. (t
  1460. ;; This is an advertised interface: (info "(cl)Other Clauses").
  1461. (let ((handler (and (symbolp word) (get word 'cl-loop-handler))))
  1462. (or handler (error "Expected a cl-loop keyword, found %s" word))
  1463. (funcall handler))))
  1464. (if (eq (car cl--loop-args) 'and)
  1465. (progn (pop cl--loop-args) (cl--parse-loop-clause)))))
  1466. (defun cl--unused-var-p (sym)
  1467. (or (null sym) (eq ?_ (aref (symbol-name sym) 0))))
  1468. (defun cl--loop-let (specs body par) ; modifies cl--loop-bindings
  1469. "Build an expression equivalent to (let SPECS BODY).
  1470. SPECS can include bindings using `cl-loop's destructuring (not to be
  1471. confused with the patterns of `cl-destructuring-bind').
  1472. If PAR is nil, do the bindings step by step, like `let*'.
  1473. If BODY is `setq', then use SPECS for assignments rather than for bindings."
  1474. (let ((temps nil) (new nil))
  1475. (when par
  1476. (let ((p specs))
  1477. (while (and p (or (symbolp (car-safe (car p))) (null (cl-cadar p))))
  1478. (setq p (cdr p)))
  1479. (when p
  1480. (setq par nil)
  1481. (dolist (spec specs)
  1482. (or (macroexp-const-p (cadr spec))
  1483. (let ((temp (make-symbol "--cl-var--")))
  1484. (push (list temp (cadr spec)) temps)
  1485. (setcar (cdr spec) temp)))))))
  1486. (while specs
  1487. (let* ((binding (pop specs))
  1488. (spec (car-safe binding)))
  1489. (if (and (consp binding) (or (consp spec) (cl--unused-var-p spec)))
  1490. (let* ((nspecs nil)
  1491. (expr (car (cdr-safe binding)))
  1492. (temp (last spec 0)))
  1493. (if (and (cl--unused-var-p temp) (null expr))
  1494. nil ;; Don't bother declaring/setting `temp' since it won't
  1495. ;; be used when `expr' is nil, anyway.
  1496. (when (or (null temp)
  1497. (and (eq body 'setq) (cl--unused-var-p temp)))
  1498. ;; Prefer a fresh uninterned symbol over "_to", to avoid
  1499. ;; warnings that we set an unused variable.
  1500. (setq temp (make-symbol "--cl-var--"))
  1501. ;; Make sure this temp variable is locally declared.
  1502. (when (eq body 'setq)
  1503. (push (list (list temp)) cl--loop-bindings)))
  1504. (push (list temp expr) new))
  1505. (while (consp spec)
  1506. (push (list (pop spec)
  1507. (and expr (list (if spec 'pop 'car) temp)))
  1508. nspecs))
  1509. (setq specs (nconc (nreverse nspecs) specs)))
  1510. (push binding new))))
  1511. (if (eq body 'setq)
  1512. (let ((set (cons (if par 'cl-psetq 'setq)
  1513. (apply 'nconc (nreverse new)))))
  1514. (if temps `(let* ,(nreverse temps) ,set) set))
  1515. `(,(if par 'let 'let*)
  1516. ,(nconc (nreverse temps) (nreverse new)) ,@body))))
  1517. (defun cl--loop-handle-accum (def &optional func) ; uses loop-*
  1518. (if (eq (car cl--loop-args) 'into)
  1519. (let ((var (cl--pop2 cl--loop-args)))
  1520. (or (memq var cl--loop-accum-vars)
  1521. (progn (push (list (list var def)) cl--loop-bindings)
  1522. (push var cl--loop-accum-vars)))
  1523. var)
  1524. (or cl--loop-accum-var
  1525. (progn
  1526. (push (list (list
  1527. (setq cl--loop-accum-var (make-symbol "--cl-var--"))
  1528. def))
  1529. cl--loop-bindings)
  1530. (setq cl--loop-result (if func (list func cl--loop-accum-var)
  1531. cl--loop-accum-var))
  1532. cl--loop-accum-var))))
  1533. (defun cl--loop-build-ands (clauses)
  1534. "Return various representations of (and . CLAUSES).
  1535. CLAUSES is a list of Elisp expressions, where clauses of the form
  1536. \(progn E1 E2 E3 .. t) are the focus of particular optimizations.
  1537. The return value has shape (COND BODY COMBO)
  1538. such that COMBO is equivalent to (and . CLAUSES)."
  1539. (let ((ands nil)
  1540. (body nil))
  1541. ;; Look through `clauses', trying to optimize (progn ,@A t) (progn ,@B) ,@C
  1542. ;; into (progn ,@A ,@B) ,@C.
  1543. (while clauses
  1544. (if (and (eq (car-safe (car clauses)) 'progn)
  1545. (eq (car (last (car clauses))) t))
  1546. (if (cdr clauses)
  1547. (setq clauses (cons (nconc (butlast (car clauses))
  1548. (if (eq (car-safe (cadr clauses))
  1549. 'progn)
  1550. (cl-cdadr clauses)
  1551. (list (cadr clauses))))
  1552. (cddr clauses)))
  1553. ;; A final (progn ,@A t) is moved outside of the `and'.
  1554. (setq body (cdr (butlast (pop clauses)))))
  1555. (push (pop clauses) ands)))
  1556. (setq ands (or (nreverse ands) (list t)))
  1557. (list (if (cdr ands) (cons 'and ands) (car ands))
  1558. body
  1559. (let ((full (if body
  1560. (append ands (list (cons 'progn (append body '(t)))))
  1561. ands)))
  1562. (if (cdr full) (cons 'and full) (car full))))))
  1563. ;;; Other iteration control structures.
  1564. ;;;###autoload
  1565. (defmacro cl-do (steps endtest &rest body)
  1566. "The Common Lisp `do' loop.
  1567. \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
  1568. (declare (indent 2)
  1569. (debug
  1570. ((&rest &or symbolp (symbolp &optional form form))
  1571. (form body)
  1572. cl-declarations body)))
  1573. (cl--expand-do-loop steps endtest body nil))
  1574. ;;;###autoload
  1575. (defmacro cl-do* (steps endtest &rest body)
  1576. "The Common Lisp `do*' loop.
  1577. \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
  1578. (declare (indent 2) (debug cl-do))
  1579. (cl--expand-do-loop steps endtest body t))
  1580. (defun cl--expand-do-loop (steps endtest body star)
  1581. `(cl-block nil
  1582. (,(if star 'let* 'let)
  1583. ,(mapcar (lambda (c) (if (consp c) (list (car c) (nth 1 c)) c))
  1584. steps)
  1585. (while (not ,(car endtest))
  1586. ,@body
  1587. ,@(let ((sets (mapcar (lambda (c)
  1588. (and (consp c) (cdr (cdr c))
  1589. (list (car c) (nth 2 c))))
  1590. steps)))
  1591. (setq sets (delq nil sets))
  1592. (and sets
  1593. (list (cons (if (or star (not (cdr sets)))
  1594. 'setq 'cl-psetq)
  1595. (apply 'append sets))))))
  1596. ,@(or (cdr endtest) '(nil)))))
  1597. ;;;###autoload
  1598. (defmacro cl-dolist (spec &rest body)
  1599. "Loop over a list.
  1600. Evaluate BODY with VAR bound to each `car' from LIST, in turn.
  1601. Then evaluate RESULT to get return value, default nil.
  1602. An implicit nil block is established around the loop.
  1603. \(fn (VAR LIST [RESULT]) BODY...)"
  1604. (declare (debug ((symbolp form &optional form) cl-declarations body))
  1605. (indent 1))
  1606. (let ((loop `(dolist ,spec ,@body)))
  1607. (if (advice-member-p 'cl--wrap-in-nil-block 'dolist)
  1608. loop `(cl-block nil ,loop))))
  1609. ;;;###autoload
  1610. (defmacro cl-dotimes (spec &rest body)
  1611. "Loop a certain number of times.
  1612. Evaluate BODY with VAR bound to successive integers from 0, inclusive,
  1613. to COUNT, exclusive. Then evaluate RESULT to get return value, default
  1614. nil.
  1615. \(fn (VAR COUNT [RESULT]) BODY...)"
  1616. (declare (debug cl-dolist) (indent 1))
  1617. (let ((loop `(dotimes ,spec ,@body)))
  1618. (if (advice-member-p 'cl--wrap-in-nil-block 'dotimes)
  1619. loop `(cl-block nil ,loop))))
  1620. (defvar cl--tagbody-alist nil)
  1621. ;;;###autoload
  1622. (defmacro cl-tagbody (&rest labels-or-stmts)
  1623. "Execute statements while providing for control transfers to labels.
  1624. Each element of LABELS-OR-STMTS can be either a label (integer or symbol)
  1625. or a `cons' cell, in which case it's taken to be a statement.
  1626. This distinction is made before performing macroexpansion.
  1627. Statements are executed in sequence left to right, discarding any return value,
  1628. stopping only when reaching the end of LABELS-OR-STMTS.
  1629. Any statement can transfer control at any time to the statements that follow
  1630. one of the labels with the special form (go LABEL).
  1631. Labels have lexical scope and dynamic extent."
  1632. (let ((blocks '())
  1633. (first-label (if (consp (car labels-or-stmts))
  1634. 'cl--preamble (pop labels-or-stmts))))
  1635. (let ((block (list first-label)))
  1636. (dolist (label-or-stmt labels-or-stmts)
  1637. (if (consp label-or-stmt) (push label-or-stmt block)
  1638. ;; Add a "go to next block" to implement the fallthrough.
  1639. (unless (eq 'go (car-safe (car-safe block)))
  1640. (push `(go ,label-or-stmt) block))
  1641. (push (nreverse block) blocks)
  1642. (setq block (list label-or-stmt))))
  1643. (unless (eq 'go (car-safe (car-safe block)))
  1644. (push `(go cl--exit) block))
  1645. (push (nreverse block) blocks))
  1646. (let ((catch-tag (make-symbol "cl--tagbody-tag"))
  1647. (cl--tagbody-alist cl--tagbody-alist))
  1648. (push (cons 'cl--exit catch-tag) cl--tagbody-alist)
  1649. (dolist (block blocks)
  1650. (push (cons (car block) catch-tag) cl--tagbody-alist))
  1651. (macroexpand-all
  1652. `(let ((next-label ',first-label))
  1653. (while
  1654. (not (eq (setq next-label
  1655. (catch ',catch-tag
  1656. (cl-case next-label
  1657. ,@blocks)))
  1658. 'cl--exit))))
  1659. `((go . ,(lambda (label)
  1660. (let ((catch-tag (cdr (assq label cl--tagbody-alist))))
  1661. (unless catch-tag
  1662. (error "Unknown cl-tagbody go label `%S'" label))
  1663. `(throw ',catch-tag ',label))))
  1664. ,@macroexpand-all-environment)))))
  1665. (defun cl--prog (binder bindings body)
  1666. (let (decls)
  1667. (while (eq 'declare (car-safe (car body)))
  1668. (push (pop body) decls))
  1669. `(cl-block nil
  1670. (,binder ,bindings
  1671. ,@(nreverse decls)
  1672. (cl-tagbody . ,body)))))
  1673. ;;;###autoload
  1674. (defmacro cl-prog (bindings &rest body)
  1675. "Run BODY like a `cl-tagbody' after setting up the BINDINGS.
  1676. Shorthand for (cl-block nil (let BINDINGS (cl-tagbody BODY)))"
  1677. (cl--prog 'let bindings body))
  1678. ;;;###autoload
  1679. (defmacro cl-prog* (bindings &rest body)
  1680. "Run BODY like a `cl-tagbody' after setting up the BINDINGS.
  1681. Shorthand for (cl-block nil (let* BINDINGS (cl-tagbody BODY)))"
  1682. (cl--prog 'let* bindings body))
  1683. ;;;###autoload
  1684. (defmacro cl-do-symbols (spec &rest body)
  1685. "Loop over all symbols.
  1686. Evaluate BODY with VAR bound to each interned symbol, or to each symbol
  1687. from OBARRAY.
  1688. \(fn (VAR [OBARRAY [RESULT]]) BODY...)"
  1689. (declare (indent 1)
  1690. (debug ((symbolp &optional form form) cl-declarations body)))
  1691. ;; Apparently this doesn't have an implicit block.
  1692. `(cl-block nil
  1693. (let (,(car spec))
  1694. (mapatoms #'(lambda (,(car spec)) ,@body)
  1695. ,@(and (cadr spec) (list (cadr spec))))
  1696. ,(nth 2 spec))))
  1697. ;;;###autoload
  1698. (defmacro cl-do-all-symbols (spec &rest body)
  1699. "Like `cl-do-symbols', but use the default obarray.
  1700. \(fn (VAR [RESULT]) BODY...)"
  1701. (declare (indent 1) (debug ((symbolp &optional form) cl-declarations body)))
  1702. `(cl-do-symbols (,(car spec) nil ,(cadr spec)) ,@body))
  1703. ;;; Assignments.
  1704. ;;;###autoload
  1705. (defmacro cl-psetq (&rest args)
  1706. "Set SYMs to the values VALs in parallel.
  1707. This is like `setq', except that all VAL forms are evaluated (in order)
  1708. before assigning any symbols SYM to the corresponding values.
  1709. \(fn SYM VAL SYM VAL ...)"
  1710. (declare (debug setq))
  1711. (cons 'cl-psetf args))
  1712. ;;; Binding control structures.
  1713. ;;;###autoload
  1714. (defmacro cl-progv (symbols values &rest body)
  1715. "Bind SYMBOLS to VALUES dynamically in BODY.
  1716. The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
  1717. Each symbol in the first list is bound to the corresponding value in the
  1718. second list (or to nil if VALUES is shorter than SYMBOLS); then the
  1719. BODY forms are executed and their result is returned. This is much like
  1720. a `let' form, except that the list of symbols can be computed at run-time."
  1721. (declare (indent 2) (debug (form form body)))
  1722. (let ((bodyfun (make-symbol "body"))
  1723. (binds (make-symbol "binds"))
  1724. (syms (make-symbol "syms"))
  1725. (vals (make-symbol "vals")))
  1726. `(progn
  1727. (let* ((,syms ,symbols)
  1728. (,vals ,values)
  1729. (,bodyfun (lambda () ,@body))
  1730. (,binds ()))
  1731. (while ,syms
  1732. (push (list (pop ,syms) (list 'quote (pop ,vals))) ,binds))
  1733. (eval (list 'let ,binds (list 'funcall (list 'quote ,bodyfun))))))))
  1734. (defconst cl--labels-magic (make-symbol "cl--labels-magic"))
  1735. (defvar cl--labels-convert-cache nil)
  1736. (defun cl--labels-convert (f)
  1737. "Special macro-expander to rename (function F) references in `cl-labels'."
  1738. (cond
  1739. ;; ¡¡Big Ugly Hack!! We can't use a compiler-macro because those are checked
  1740. ;; *after* handling `function', but we want to stop macroexpansion from
  1741. ;; being applied infinitely, so we use a cache to return the exact `form'
  1742. ;; being expanded even though we don't receive it.
  1743. ((eq f (car cl--labels-convert-cache)) (cdr cl--labels-convert-cache))
  1744. (t
  1745. (let* ((found (assq f macroexpand-all-environment))
  1746. (replacement (and found
  1747. (ignore-errors
  1748. (funcall (cdr found) cl--labels-magic)))))
  1749. (if (and replacement (eq cl--labels-magic (car replacement)))
  1750. (nth 1 replacement)
  1751. (let ((res `(function ,f)))
  1752. (setq cl--labels-convert-cache (cons f res))
  1753. res))))))
  1754. ;;;###autoload
  1755. (defmacro cl-flet (bindings &rest body)
  1756. "Make local function definitions.
  1757. Like `cl-labels' but the definitions are not recursive.
  1758. Each binding can take the form (FUNC EXP) where
  1759. FUNC is the function name, and EXP is an expression that returns the
  1760. function value to which it should be bound, or it can take the more common
  1761. form \(FUNC ARGLIST BODY...) which is a shorthand
  1762. for (FUNC (lambda ARGLIST BODY)).
  1763. \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
  1764. (declare (indent 1) (debug ((&rest (cl-defun)) cl-declarations body)))
  1765. (let ((binds ()) (newenv macroexpand-all-environment))
  1766. (dolist (binding bindings)
  1767. (let ((var (make-symbol (format "--cl-%s--" (car binding))))
  1768. (args-and-body (cdr binding)))
  1769. (if (and (= (length args-and-body) 1) (symbolp (car args-and-body)))
  1770. ;; Optimize (cl-flet ((fun var)) body).
  1771. (setq var (car args-and-body))
  1772. (push (list var (if (= (length args-and-body) 1)
  1773. (car args-and-body)
  1774. `(cl-function (lambda . ,args-and-body))))
  1775. binds))
  1776. (push (cons (car binding)
  1777. (lambda (&rest args)
  1778. (if (eq (car args) cl--labels-magic)
  1779. (list cl--labels-magic var)
  1780. `(funcall ,var ,@args))))
  1781. newenv)))
  1782. ;; FIXME: Eliminate those functions which aren't referenced.
  1783. (macroexp-let* (nreverse binds)
  1784. (macroexpand-all
  1785. `(progn ,@body)
  1786. ;; Don't override lexical-let's macro-expander.
  1787. (if (assq 'function newenv) newenv
  1788. (cons (cons 'function #'cl--labels-convert) newenv))))))
  1789. ;;;###autoload
  1790. (defmacro cl-flet* (bindings &rest body)
  1791. "Make local function definitions.
  1792. Like `cl-flet' but the definitions can refer to previous ones.
  1793. \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
  1794. (declare (indent 1) (debug cl-flet))
  1795. (cond
  1796. ((null bindings) (macroexp-progn body))
  1797. ((null (cdr bindings)) `(cl-flet ,bindings ,@body))
  1798. (t `(cl-flet (,(pop bindings)) (cl-flet* ,bindings ,@body)))))
  1799. ;;;###autoload
  1800. (defmacro cl-labels (bindings &rest body)
  1801. "Make temporary function bindings.
  1802. The bindings can be recursive and the scoping is lexical, but capturing them
  1803. in closures will only work if `lexical-binding' is in use.
  1804. \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
  1805. (declare (indent 1) (debug cl-flet))
  1806. (let ((binds ()) (newenv macroexpand-all-environment))
  1807. (dolist (binding bindings)
  1808. (let ((var (make-symbol (format "--cl-%s--" (car binding)))))
  1809. (push (list var `(cl-function (lambda . ,(cdr binding)))) binds)
  1810. (push (cons (car binding)
  1811. (lambda (&rest args)
  1812. (if (eq (car args) cl--labels-magic)
  1813. (list cl--labels-magic var)
  1814. (cl-list* 'funcall var args))))
  1815. newenv)))
  1816. (macroexpand-all `(letrec ,(nreverse binds) ,@body)
  1817. ;; Don't override lexical-let's macro-expander.
  1818. (if (assq 'function newenv) newenv
  1819. (cons (cons 'function #'cl--labels-convert) newenv)))))
  1820. ;; The following ought to have a better definition for use with newer
  1821. ;; byte compilers.
  1822. ;;;###autoload
  1823. (defmacro cl-macrolet (bindings &rest body)
  1824. "Make temporary macro definitions.
  1825. This is like `cl-flet', but for macros instead of functions.
  1826. \(fn ((NAME ARGLIST BODY...) ...) FORM...)"
  1827. (declare (indent 1)
  1828. (debug
  1829. ((&rest (&define name (&rest arg) cl-declarations-or-string
  1830. def-body))
  1831. cl-declarations body)))
  1832. (if (cdr bindings)
  1833. `(cl-macrolet (,(car bindings)) (cl-macrolet ,(cdr bindings) ,@body))
  1834. (if (null bindings) (macroexp-progn body)
  1835. (let* ((name (caar bindings))
  1836. (res (cl--transform-lambda (cdar bindings) name)))
  1837. (eval (car res))
  1838. (macroexpand-all (macroexp-progn body)
  1839. (cons (cons name
  1840. (eval `(cl-function (lambda ,@(cdr res))) t))
  1841. macroexpand-all-environment))))))
  1842. (defconst cl--old-macroexpand
  1843. (if (and (boundp 'cl--old-macroexpand)
  1844. (eq (symbol-function 'macroexpand)
  1845. #'cl--sm-macroexpand))
  1846. cl--old-macroexpand
  1847. (symbol-function 'macroexpand)))
  1848. (defun cl--sm-macroexpand (exp &optional env)
  1849. "Special macro expander used inside `cl-symbol-macrolet'.
  1850. This function replaces `macroexpand' during macro expansion
  1851. of `cl-symbol-macrolet', and does the same thing as `macroexpand'
  1852. except that it additionally expands symbol macros."
  1853. (let ((macroexpand-all-environment env)
  1854. (venv (alist-get :cl-symbol-macros env)))
  1855. (while
  1856. (progn
  1857. (setq exp (funcall cl--old-macroexpand exp env))
  1858. (pcase exp
  1859. ((pred symbolp)
  1860. ;; Perform symbol-macro expansion.
  1861. (let ((symval (assq exp venv)))
  1862. (when symval
  1863. (setq exp (cadr symval)))))
  1864. (`(setq . ,_)
  1865. ;; Convert setq to setf if required by symbol-macro expansion.
  1866. (let* ((args (mapcar (lambda (f) (cl--sm-macroexpand f env))
  1867. (cdr exp)))
  1868. (p args))
  1869. (while (and p (symbolp (car p))) (setq p (cddr p)))
  1870. (if p (setq exp (cons 'setf args))
  1871. (setq exp (cons 'setq args))
  1872. ;; Don't loop further.
  1873. nil)))
  1874. (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
  1875. ;; CL's symbol-macrolet treats re-bindings as candidates for
  1876. ;; expansion (turning the let into a letf if needed), contrary to
  1877. ;; Common-Lisp where such re-bindings hide the symbol-macro.
  1878. (let ((letf nil) (found nil) (nbs ()))
  1879. (dolist (binding bindings)
  1880. (let* ((var (if (symbolp binding) binding (car binding)))
  1881. (sm (assq var venv)))
  1882. (push (if (not (cdr sm))
  1883. binding
  1884. (let ((nexp (cadr sm)))
  1885. (setq found t)
  1886. (unless (symbolp nexp) (setq letf t))
  1887. (cons nexp (cdr-safe binding))))
  1888. nbs)))
  1889. (when found
  1890. (setq exp `(,(if letf
  1891. (if (eq (car exp) 'let) 'cl-letf 'cl-letf*)
  1892. (car exp))
  1893. ,(nreverse nbs)
  1894. ,@body)))))
  1895. ;; FIXME: The behavior of CL made sense in a dynamically scoped
  1896. ;; language, but for lexical scoping, Common-Lisp's behavior might
  1897. ;; make more sense (and indeed, CL behaves like Common-Lisp w.r.t
  1898. ;; lexical-let), so maybe we should adjust the behavior based on
  1899. ;; the use of lexical-binding.
  1900. ;; (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
  1901. ;; (let ((nbs ()) (found nil))
  1902. ;; (dolist (binding bindings)
  1903. ;; (let* ((var (if (symbolp binding) binding (car binding)))
  1904. ;; (name (symbol-name var))
  1905. ;; (val (and found (consp binding) (eq 'let* (car exp))
  1906. ;; (list (macroexpand-all (cadr binding)
  1907. ;; env)))))
  1908. ;; (push (if (assq name env)
  1909. ;; ;; This binding should hide its symbol-macro,
  1910. ;; ;; but given the way macroexpand-all works, we
  1911. ;; ;; can't prevent application of `env' to the
  1912. ;; ;; sub-expressions, so we need to α-rename this
  1913. ;; ;; variable instead.
  1914. ;; (let ((nvar (make-symbol
  1915. ;; (copy-sequence name))))
  1916. ;; (setq found t)
  1917. ;; (push (list name nvar) env)
  1918. ;; (cons nvar (or val (cdr-safe binding))))
  1919. ;; (if val (cons var val) binding))
  1920. ;; nbs)))
  1921. ;; (when found
  1922. ;; (setq exp `(,(car exp)
  1923. ;; ,(nreverse nbs)
  1924. ;; ,@(macroexp-unprogn
  1925. ;; (macroexpand-all (macroexp-progn body)
  1926. ;; env)))))
  1927. ;; nil))
  1928. )))
  1929. exp))
  1930. ;;;###autoload
  1931. (defmacro cl-symbol-macrolet (bindings &rest body)
  1932. "Make symbol macro definitions.
  1933. Within the body FORMs, references to the variable NAME will be replaced
  1934. by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...).
  1935. \(fn ((NAME EXPANSION) ...) FORM...)"
  1936. (declare (indent 1) (debug ((&rest (symbolp sexp)) cl-declarations body)))
  1937. (let ((previous-macroexpand (symbol-function 'macroexpand))
  1938. (malformed-bindings nil))
  1939. (dolist (binding bindings)
  1940. (unless (and (consp binding) (symbolp (car binding))
  1941. (consp (cdr binding)) (null (cddr binding)))
  1942. (push binding malformed-bindings)))
  1943. (unwind-protect
  1944. (progn
  1945. (fset 'macroexpand #'cl--sm-macroexpand)
  1946. (let* ((venv (cdr (assq :cl-symbol-macros macroexpand-all-environment)))
  1947. (expansion
  1948. (macroexpand-all (macroexp-progn body)
  1949. (cons (cons :cl-symbol-macros
  1950. (append bindings venv))
  1951. macroexpand-all-environment))))
  1952. (if malformed-bindings
  1953. (macroexp--warn-and-return
  1954. (format-message "Malformed `cl-symbol-macrolet' binding(s): %S"
  1955. (nreverse malformed-bindings))
  1956. expansion)
  1957. expansion)))
  1958. (fset 'macroexpand previous-macroexpand))))
  1959. ;;; Multiple values.
  1960. ;;;###autoload
  1961. (defmacro cl-multiple-value-bind (vars form &rest body)
  1962. "Collect multiple return values.
  1963. FORM must return a list; the BODY is then executed with the first N elements
  1964. of this list bound (`let'-style) to each of the symbols SYM in turn. This
  1965. is analogous to the Common Lisp `multiple-value-bind' macro, using lists to
  1966. simulate true multiple return values. For compatibility, (cl-values A B C) is
  1967. a synonym for (list A B C).
  1968. \(fn (SYM...) FORM BODY)"
  1969. (declare (indent 2) (debug ((&rest symbolp) form body)))
  1970. (let ((temp (make-symbol "--cl-var--")) (n -1))
  1971. `(let* ((,temp ,form)
  1972. ,@(mapcar (lambda (v)
  1973. (list v `(nth ,(setq n (1+ n)) ,temp)))
  1974. vars))
  1975. ,@body)))
  1976. ;;;###autoload
  1977. (defmacro cl-multiple-value-setq (vars form)
  1978. "Collect multiple return values.
  1979. FORM must return a list; the first N elements of this list are stored in
  1980. each of the symbols SYM in turn. This is analogous to the Common Lisp
  1981. `multiple-value-setq' macro, using lists to simulate true multiple return
  1982. values. For compatibility, (cl-values A B C) is a synonym for (list A B C).
  1983. \(fn (SYM...) FORM)"
  1984. (declare (indent 1) (debug ((&rest symbolp) form)))
  1985. (cond ((null vars) `(progn ,form nil))
  1986. ((null (cdr vars)) `(setq ,(car vars) (car ,form)))
  1987. (t
  1988. (let* ((temp (make-symbol "--cl-var--")) (n 0))
  1989. `(let ((,temp ,form))
  1990. (prog1 (setq ,(pop vars) (car ,temp))
  1991. (setq ,@(apply #'nconc
  1992. (mapcar (lambda (v)
  1993. (list v `(nth ,(setq n (1+ n))
  1994. ,temp)))
  1995. vars)))))))))
  1996. ;;; Declarations.
  1997. ;;;###autoload
  1998. (defmacro cl-locally (&rest body)
  1999. "Equivalent to `progn'."
  2000. (declare (debug t))
  2001. (cons 'progn body))
  2002. ;;;###autoload
  2003. (defmacro cl-the (type form)
  2004. "Return FORM. If type-checking is enabled, assert that it is of TYPE."
  2005. (declare (indent 1) (debug (cl-type-spec form)))
  2006. (if (not (or (not (cl--compiling-file))
  2007. (< cl--optimize-speed 3)
  2008. (= cl--optimize-safety 3)))
  2009. form
  2010. (macroexp-let2 macroexp-copyable-p temp form
  2011. `(progn (unless (cl-typep ,temp ',type)
  2012. (signal 'wrong-type-argument
  2013. (list ',type ,temp ',form)))
  2014. ,temp))))
  2015. (defvar cl--proclaim-history t) ; for future compilers
  2016. (defvar cl--declare-stack t) ; for future compilers
  2017. (defun cl--do-proclaim (spec hist)
  2018. (and hist (listp cl--proclaim-history) (push spec cl--proclaim-history))
  2019. (cond ((eq (car-safe spec) 'special)
  2020. (if (boundp 'byte-compile-bound-variables)
  2021. (setq byte-compile-bound-variables
  2022. (append (cdr spec) byte-compile-bound-variables))))
  2023. ((eq (car-safe spec) 'inline)
  2024. (while (setq spec (cdr spec))
  2025. (or (memq (get (car spec) 'byte-optimizer)
  2026. '(nil byte-compile-inline-expand))
  2027. (error "%s already has a byte-optimizer, can't make it inline"
  2028. (car spec)))
  2029. (put (car spec) 'byte-optimizer 'byte-compile-inline-expand)))
  2030. ((eq (car-safe spec) 'notinline)
  2031. (while (setq spec (cdr spec))
  2032. (if (eq (get (car spec) 'byte-optimizer)
  2033. 'byte-compile-inline-expand)
  2034. (put (car spec) 'byte-optimizer nil))))
  2035. ((eq (car-safe spec) 'optimize)
  2036. (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
  2037. '((0 nil) (1 t) (2 t) (3 t))))
  2038. (safety (assq (nth 1 (assq 'safety (cdr spec)))
  2039. '((0 t) (1 t) (2 t) (3 nil)))))
  2040. (if speed (setq cl--optimize-speed (car speed)
  2041. byte-optimize (nth 1 speed)))
  2042. (if safety (setq cl--optimize-safety (car safety)
  2043. byte-compile-delete-errors (nth 1 safety)))))
  2044. ((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
  2045. (while (setq spec (cdr spec))
  2046. (if (consp (car spec))
  2047. (if (eq (cl-cadar spec) 0)
  2048. (byte-compile-disable-warning (caar spec))
  2049. (byte-compile-enable-warning (caar spec)))))))
  2050. nil)
  2051. ;;; Process any proclamations made before cl-macs was loaded.
  2052. (defvar cl--proclaims-deferred)
  2053. (let ((p (reverse cl--proclaims-deferred)))
  2054. (while p (cl--do-proclaim (pop p) t))
  2055. (setq cl--proclaims-deferred nil))
  2056. ;;;###autoload
  2057. (defmacro cl-declare (&rest specs)
  2058. "Declare SPECS about the current function while compiling.
  2059. For instance
  2060. (cl-declare (warn 0))
  2061. will turn off byte-compile warnings in the function.
  2062. See Info node `(cl)Declarations' for details."
  2063. (if (cl--compiling-file)
  2064. (while specs
  2065. (if (listp cl--declare-stack) (push (car specs) cl--declare-stack))
  2066. (cl--do-proclaim (pop specs) nil)))
  2067. nil)
  2068. ;;; The standard modify macros.
  2069. ;; `setf' is now part of core Elisp, defined in gv.el.
  2070. ;;;###autoload
  2071. (defmacro cl-psetf (&rest args)
  2072. "Set PLACEs to the values VALs in parallel.
  2073. This is like `setf', except that all VAL forms are evaluated (in order)
  2074. before assigning any PLACEs to the corresponding values.
  2075. \(fn PLACE VAL PLACE VAL ...)"
  2076. (declare (debug setf))
  2077. (let ((p args) (simple t) (vars nil))
  2078. (while p
  2079. (if (or (not (symbolp (car p))) (cl--expr-depends-p (nth 1 p) vars))
  2080. (setq simple nil))
  2081. (if (memq (car p) vars)
  2082. (error "Destination duplicated in psetf: %s" (car p)))
  2083. (push (pop p) vars)
  2084. (or p (error "Odd number of arguments to cl-psetf"))
  2085. (pop p))
  2086. (if simple
  2087. `(progn (setq ,@args) nil)
  2088. (setq args (reverse args))
  2089. (let ((expr `(setf ,(cadr args) ,(car args))))
  2090. (while (setq args (cddr args))
  2091. (setq expr `(setf ,(cadr args) (prog1 ,(car args) ,expr))))
  2092. `(progn ,expr nil)))))
  2093. ;;;###autoload
  2094. (defmacro cl-remf (place tag)
  2095. "Remove TAG from property list PLACE.
  2096. PLACE may be a symbol, or any generalized variable allowed by `setf'.
  2097. The form returns true if TAG was found and removed, nil otherwise."
  2098. (declare (debug (place form)))
  2099. (gv-letplace (tval setter) place
  2100. (macroexp-let2 macroexp-copyable-p ttag tag
  2101. `(if (eq ,ttag (car ,tval))
  2102. (progn ,(funcall setter `(cddr ,tval))
  2103. t)
  2104. (cl--do-remf ,tval ,ttag)))))
  2105. ;;;###autoload
  2106. (defmacro cl-shiftf (place &rest args)
  2107. "Shift left among PLACEs.
  2108. Example: (cl-shiftf A B C) sets A to B, B to C, and returns the old A.
  2109. Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
  2110. \(fn PLACE... VAL)"
  2111. (declare (debug (&rest place)))
  2112. (cond
  2113. ((null args) place)
  2114. ((symbolp place) `(prog1 ,place (setq ,place (cl-shiftf ,@args))))
  2115. (t
  2116. (gv-letplace (getter setter) place
  2117. `(prog1 ,getter
  2118. ,(funcall setter `(cl-shiftf ,@args)))))))
  2119. ;;;###autoload
  2120. (defmacro cl-rotatef (&rest args)
  2121. "Rotate left among PLACEs.
  2122. Example: (cl-rotatef A B C) sets A to B, B to C, and C to A. It returns nil.
  2123. Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
  2124. \(fn PLACE...)"
  2125. (declare (debug (&rest place)))
  2126. (if (not (memq nil (mapcar 'symbolp args)))
  2127. (and (cdr args)
  2128. (let ((sets nil)
  2129. (first (car args)))
  2130. (while (cdr args)
  2131. (setq sets (nconc sets (list (pop args) (car args)))))
  2132. `(cl-psetf ,@sets ,(car args) ,first)))
  2133. (let* ((places (reverse args))
  2134. (temp (make-symbol "--cl-rotatef--"))
  2135. (form temp))
  2136. (while (cdr places)
  2137. (setq form
  2138. (gv-letplace (getter setter) (pop places)
  2139. `(prog1 ,getter ,(funcall setter form)))))
  2140. (gv-letplace (getter setter) (car places)
  2141. (macroexp-let* `((,temp ,getter))
  2142. `(progn ,(funcall setter form) nil))))))
  2143. ;; FIXME: `letf' is unsatisfactory because it does not really "restore" the
  2144. ;; previous state. If the getter/setter loses information, that info is
  2145. ;; not recovered.
  2146. (defun cl--letf (bindings simplebinds binds body)
  2147. ;; It's not quite clear what the semantics of cl-letf should be.
  2148. ;; E.g. in (cl-letf ((PLACE1 VAL1) (PLACE2 VAL2)) BODY), while it's clear
  2149. ;; that the actual assignments ("bindings") should only happen after
  2150. ;; evaluating VAL1 and VAL2, it's not clear when the sub-expressions of
  2151. ;; PLACE1 and PLACE2 should be evaluated. Should we have
  2152. ;; PLACE1; VAL1; PLACE2; VAL2; bind1; bind2
  2153. ;; or
  2154. ;; VAL1; VAL2; PLACE1; PLACE2; bind1; bind2
  2155. ;; or
  2156. ;; VAL1; VAL2; PLACE1; bind1; PLACE2; bind2
  2157. ;; Common-Lisp's `psetf' does the first, so we'll do the same.
  2158. (if (null bindings)
  2159. (if (and (null binds) (null simplebinds)) (macroexp-progn body)
  2160. `(let* (,@(mapcar (lambda (x)
  2161. (pcase-let ((`(,vold ,getter ,_setter ,_vnew) x))
  2162. (list vold getter)))
  2163. binds)
  2164. ,@simplebinds)
  2165. (unwind-protect
  2166. ,(macroexp-progn
  2167. (append
  2168. (delq nil
  2169. (mapcar (lambda (x)
  2170. (pcase x
  2171. ;; If there's no vnew, do nothing.
  2172. (`(,_vold ,_getter ,setter ,vnew)
  2173. (funcall setter vnew))))
  2174. binds))
  2175. body))
  2176. ,@(mapcar (lambda (x)
  2177. (pcase-let ((`(,vold ,_getter ,setter ,_vnew) x))
  2178. (funcall setter vold)))
  2179. binds))))
  2180. (let ((binding (car bindings)))
  2181. (gv-letplace (getter setter) (car binding)
  2182. (macroexp-let2 nil vnew (cadr binding)
  2183. (if (symbolp (car binding))
  2184. ;; Special-case for simple variables.
  2185. (cl--letf (cdr bindings)
  2186. (cons `(,getter ,(if (cdr binding) vnew getter))
  2187. simplebinds)
  2188. binds body)
  2189. (cl--letf (cdr bindings) simplebinds
  2190. (cons `(,(make-symbol "old") ,getter ,setter
  2191. ,@(if (cdr binding) (list vnew)))
  2192. binds)
  2193. body)))))))
  2194. ;;;###autoload
  2195. (defmacro cl-letf (bindings &rest body)
  2196. "Temporarily bind to PLACEs.
  2197. This is the analogue of `let', but with generalized variables (in the
  2198. sense of `setf') for the PLACEs. Each PLACE is set to the corresponding
  2199. VALUE, then the BODY forms are executed. On exit, either normally or
  2200. because of a `throw' or error, the PLACEs are set back to their original
  2201. values. Note that this macro is *not* available in Common Lisp.
  2202. As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
  2203. the PLACE is not modified before executing BODY.
  2204. \(fn ((PLACE VALUE) ...) BODY...)"
  2205. (declare (indent 1) (debug ((&rest (gate gv-place &optional form)) body)))
  2206. (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
  2207. `(let ,bindings ,@body)
  2208. (cl--letf bindings () () body)))
  2209. ;;;###autoload
  2210. (defmacro cl-letf* (bindings &rest body)
  2211. "Temporarily bind to PLACEs.
  2212. Like `cl-letf' but where the bindings are performed one at a time,
  2213. rather than all at the end (i.e. like `let*' rather than like `let')."
  2214. (declare (indent 1) (debug cl-letf))
  2215. (dolist (binding (reverse bindings))
  2216. (setq body (list `(cl-letf (,binding) ,@body))))
  2217. (macroexp-progn body))
  2218. ;;;###autoload
  2219. (defmacro cl-callf (func place &rest args)
  2220. "Set PLACE to (FUNC PLACE ARGS...).
  2221. FUNC should be an unquoted function name. PLACE may be a symbol,
  2222. or any generalized variable allowed by `setf'."
  2223. (declare (indent 2) (debug (cl-function place &rest form)))
  2224. (gv-letplace (getter setter) place
  2225. (let* ((rargs (cons getter args)))
  2226. (funcall setter
  2227. (if (symbolp func) (cons func rargs)
  2228. `(funcall #',func ,@rargs))))))
  2229. ;;;###autoload
  2230. (defmacro cl-callf2 (func arg1 place &rest args)
  2231. "Set PLACE to (FUNC ARG1 PLACE ARGS...).
  2232. Like `cl-callf', but PLACE is the second argument of FUNC, not the first.
  2233. \(fn FUNC ARG1 PLACE ARGS...)"
  2234. (declare (indent 3) (debug (cl-function form place &rest form)))
  2235. (if (and (cl--safe-expr-p arg1) (cl--simple-expr-p place) (symbolp func))
  2236. `(setf ,place (,func ,arg1 ,place ,@args))
  2237. (macroexp-let2 nil a1 arg1
  2238. (gv-letplace (getter setter) place
  2239. (let* ((rargs (cl-list* a1 getter args)))
  2240. (funcall setter
  2241. (if (symbolp func) (cons func rargs)
  2242. `(funcall #',func ,@rargs))))))))
  2243. ;;;###autoload
  2244. (defmacro cl-defsubst (name args &rest body)
  2245. "Define NAME as a function.
  2246. Like `defun', except the function is automatically declared `inline' and
  2247. the arguments are immutable.
  2248. ARGLIST allows full Common Lisp conventions, and BODY is implicitly
  2249. surrounded by (cl-block NAME ...).
  2250. The function's arguments should be treated as immutable.
  2251. \(fn NAME ARGLIST [DOCSTRING] BODY...)"
  2252. (declare (debug cl-defun) (indent 2))
  2253. (let* ((argns (cl--arglist-args args))
  2254. (real-args (if (eq '&cl-defs (car args)) (cddr args) args))
  2255. (p argns)
  2256. ;; (pbody (cons 'progn body))
  2257. )
  2258. (while (and p (eq (cl--expr-contains real-args (car p)) 1)) (pop p))
  2259. `(progn
  2260. ,(if p nil ; give up if defaults refer to earlier args
  2261. `(cl-define-compiler-macro ,name
  2262. ,(if (memq '&key args)
  2263. `(&whole cl-whole &cl-quote ,@args)
  2264. (cons '&cl-quote args))
  2265. (cl--defsubst-expand
  2266. ',argns '(cl-block ,name ,@body)
  2267. ;; We used to pass `simple' as
  2268. ;; (not (or unsafe (cl-expr-access-order pbody argns)))
  2269. ;; But this is much too simplistic since it
  2270. ;; does not pay attention to the argvs (and
  2271. ;; cl-expr-access-order itself is also too naive).
  2272. nil
  2273. ,(and (memq '&key args) 'cl-whole) nil ,@argns)))
  2274. (cl-defun ,name ,args ,@body))))
  2275. (defun cl--defsubst-expand (argns body simple whole _unsafe &rest argvs)
  2276. (if (and whole (not (cl--safe-expr-p (cons 'progn argvs)))) whole
  2277. (if (cl--simple-exprs-p argvs) (setq simple t))
  2278. (let* ((substs ())
  2279. (lets (delq nil
  2280. (cl-mapcar (lambda (argn argv)
  2281. (if (or simple (macroexp-const-p argv))
  2282. (progn (push (cons argn argv) substs)
  2283. nil)
  2284. (list argn argv)))
  2285. argns argvs))))
  2286. ;; FIXME: `sublis/subst' will happily substitute the symbol
  2287. ;; `argn' in places where it's not used as a reference
  2288. ;; to a variable.
  2289. ;; FIXME: `sublis/subst' will happily copy `argv' to a different
  2290. ;; scope, leading to name capture.
  2291. (setq body (cond ((null substs) body)
  2292. ((null (cdr substs))
  2293. (cl-subst (cdar substs) (caar substs) body))
  2294. (t (cl--sublis substs body))))
  2295. (if lets `(let ,lets ,body) body))))
  2296. (defun cl--sublis (alist tree)
  2297. "Perform substitutions indicated by ALIST in TREE (non-destructively)."
  2298. (let ((x (assq tree alist)))
  2299. (cond
  2300. (x (cdr x))
  2301. ((consp tree)
  2302. (cons (cl--sublis alist (car tree)) (cl--sublis alist (cdr tree))))
  2303. (t tree))))
  2304. ;;; Structures.
  2305. (defmacro cl--find-class (type)
  2306. `(get ,type 'cl--class))
  2307. ;; Rather than hard code cl-structure-object, we indirect through this variable
  2308. ;; for bootstrapping reasons.
  2309. (defvar cl--struct-default-parent nil)
  2310. ;;;###autoload
  2311. (defmacro cl-defstruct (struct &rest descs)
  2312. "Define a struct type.
  2313. This macro defines a new data type called NAME that stores data
  2314. in SLOTs. It defines a `make-NAME' constructor, a `copy-NAME'
  2315. copier, a `NAME-p' predicate, and slot accessors named `NAME-SLOT'.
  2316. You can use the accessors to set the corresponding slots, via `setf'.
  2317. NAME may instead take the form (NAME OPTIONS...), where each
  2318. OPTION is either a single keyword or (KEYWORD VALUE) where
  2319. KEYWORD can be one of :conc-name, :constructor, :copier, :predicate,
  2320. :type, :named, :initial-offset, :print-function, or :include.
  2321. Each SLOT may instead take the form (SNAME SDEFAULT SOPTIONS...), where
  2322. SDEFAULT is the default value of that slot and SOPTIONS are keyword-value
  2323. pairs for that slot.
  2324. Currently, only one keyword is supported, `:read-only'. If this has a
  2325. non-nil value, that slot cannot be set via `setf'.
  2326. \(fn NAME SLOTS...)"
  2327. (declare (doc-string 2) (indent 1)
  2328. (debug
  2329. (&define ;Makes top-level form not be wrapped.
  2330. [&or symbolp
  2331. (gate
  2332. symbolp &rest
  2333. [&or symbolp
  2334. (&or [":conc-name" symbolp]
  2335. [":constructor" symbolp &optional cl-lambda-list]
  2336. [":copier" symbolp]
  2337. [":predicate" symbolp]
  2338. [":include" symbolp &rest sexp] ;; Not finished.
  2339. [":print-function" sexp]
  2340. [":type" symbolp]
  2341. [":named"]
  2342. [":initial-offset" natnump])])]
  2343. [&optional stringp]
  2344. ;; All the above is for the following def-form.
  2345. &rest &or symbolp (symbolp &optional def-form &rest sexp))))
  2346. (let* ((name (if (consp struct) (car struct) struct))
  2347. (opts (cdr-safe struct))
  2348. (slots nil)
  2349. (defaults nil)
  2350. (conc-name (concat (symbol-name name) "-"))
  2351. (constructor (intern (format "make-%s" name)))
  2352. (constrs nil)
  2353. (copier (intern (format "copy-%s" name)))
  2354. (predicate (intern (format "%s-p" name)))
  2355. (print-func nil) (print-auto nil)
  2356. (safety (if (cl--compiling-file) cl--optimize-safety 3))
  2357. (include nil)
  2358. ;; There are 4 types of structs:
  2359. ;; - `vector' type: means we should use a vector, which can come
  2360. ;; with or without a tag `name', which is usually in slot 0
  2361. ;; but obeys :initial-offset.
  2362. ;; - `list' type: same as `vector' but using lists.
  2363. ;; - `record' type: means we should use a record, which necessarily
  2364. ;; comes tagged in slot 0. Currently we'll use the `name' as
  2365. ;; the tag, but we may want to change it so that the class object
  2366. ;; is used as the tag.
  2367. ;; - nil type: this is the "pre-record default", which uses a vector
  2368. ;; with a tag in slot 0 which is a symbol of the form
  2369. ;; `cl-struct-NAME'. We need to still support this for backward
  2370. ;; compatibility with old .elc files.
  2371. (tag name)
  2372. (tag-symbol (intern (format "cl-struct-%s-tags" name)))
  2373. (include-descs nil)
  2374. (include-name nil)
  2375. (type nil) ;nil here means not specified explicitly.
  2376. (named nil)
  2377. (forms nil)
  2378. (docstring (if (stringp (car descs)) (pop descs)))
  2379. pred-form pred-check)
  2380. (setq descs (cons '(cl-tag-slot)
  2381. (mapcar (function (lambda (x) (if (consp x) x (list x))))
  2382. descs)))
  2383. (while opts
  2384. (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
  2385. (args (cdr-safe (pop opts))))
  2386. (cond ((eq opt :conc-name)
  2387. (if args
  2388. (setq conc-name (if (car args)
  2389. (symbol-name (car args)) ""))))
  2390. ((eq opt :constructor)
  2391. (if (cdr args)
  2392. (progn
  2393. ;; If this defines a constructor of the same name as
  2394. ;; the default one, don't define the default.
  2395. (if (eq (car args) constructor)
  2396. (setq constructor nil))
  2397. (push args constrs))
  2398. (if args (setq constructor (car args)))))
  2399. ((eq opt :copier)
  2400. (if args (setq copier (car args))))
  2401. ((eq opt :predicate)
  2402. (if args (setq predicate (car args))))
  2403. ((eq opt :include)
  2404. ;; FIXME: Actually, we can include more than once as long as
  2405. ;; we include EIEIO classes rather than cl-structs!
  2406. (when include-name (error "Can't :include more than once"))
  2407. (setq include-name (car args))
  2408. (setq include-descs (mapcar (function
  2409. (lambda (x)
  2410. (if (consp x) x (list x))))
  2411. (cdr args))))
  2412. ((eq opt :print-function)
  2413. (setq print-func (car args)))
  2414. ((eq opt :type)
  2415. (setq type (car args))
  2416. (unless (memq type '(vector list))
  2417. (error "Invalid :type specifier: %s" type)))
  2418. ((eq opt :named)
  2419. (setq named t))
  2420. ((eq opt :initial-offset)
  2421. (setq descs (nconc (make-list (car args) '(cl-skip-slot))
  2422. descs)))
  2423. (t
  2424. (error "Structure option %s unrecognized" opt)))))
  2425. (unless (or include-name type)
  2426. (setq include-name cl--struct-default-parent))
  2427. (when include-name (setq include (cl--struct-get-class include-name)))
  2428. (if print-func
  2429. (setq print-func
  2430. `(progn (funcall #',print-func cl-x cl-s cl-n) t))
  2431. (or type (and include (not (cl--struct-class-print include)))
  2432. (setq print-auto t
  2433. print-func (and (or (not (or include type)) (null print-func))
  2434. `(progn
  2435. (princ ,(format "#S(%s" name) cl-s))))))
  2436. (if include
  2437. (let* ((inc-type (cl--struct-class-type include))
  2438. (old-descs (cl-struct-slot-info include)))
  2439. (and type (not (eq inc-type type))
  2440. (error ":type disagrees with :include for %s" name))
  2441. (while include-descs
  2442. (setcar (memq (or (assq (caar include-descs) old-descs)
  2443. (error "No slot %s in included struct %s"
  2444. (caar include-descs) include))
  2445. old-descs)
  2446. (pop include-descs)))
  2447. (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
  2448. type inc-type
  2449. named (if (memq type '(vector list))
  2450. (assq 'cl-tag-slot descs)
  2451. 'true))
  2452. (if (cl--struct-class-named include) (setq named t)))
  2453. (unless type
  2454. (setq named 'true)))
  2455. (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
  2456. (when (and (null predicate) named)
  2457. (setq predicate (intern (format "cl--struct-%s-p" name))))
  2458. (setq pred-form (and named
  2459. (let ((pos (- (length descs)
  2460. (length (memq (assq 'cl-tag-slot descs)
  2461. descs)))))
  2462. (cond
  2463. ((null type) ;Record type.
  2464. `(memq (type-of cl-x) ,tag-symbol))
  2465. ((eq type 'vector)
  2466. `(and (vectorp cl-x)
  2467. (>= (length cl-x) ,(length descs))
  2468. (memq (aref cl-x ,pos) ,tag-symbol)))
  2469. ((= pos 0) `(memq (car-safe cl-x) ,tag-symbol))
  2470. (t `(and (consp cl-x)
  2471. (memq (nth ,pos cl-x) ,tag-symbol))))))
  2472. pred-check (and pred-form (> safety 0)
  2473. (if (and (eq (cl-caadr pred-form) 'vectorp)
  2474. (= safety 1))
  2475. (cons 'and (cl-cdddr pred-form))
  2476. `(,predicate cl-x))))
  2477. (when pred-form
  2478. (push `(cl-defsubst ,predicate (cl-x)
  2479. (declare (side-effect-free error-free))
  2480. ,(if (eq (car pred-form) 'and)
  2481. (append pred-form '(t))
  2482. `(and ,pred-form t)))
  2483. forms)
  2484. (push `(put ',name 'cl-deftype-satisfies ',predicate) forms))
  2485. (let ((pos 0) (descp descs))
  2486. (while descp
  2487. (let* ((desc (pop descp))
  2488. (slot (pop desc)))
  2489. (if (memq slot '(cl-tag-slot cl-skip-slot))
  2490. (progn
  2491. (push nil slots)
  2492. (push (and (eq slot 'cl-tag-slot) `',tag)
  2493. defaults))
  2494. (if (assq slot descp)
  2495. (error "Duplicate slots named %s in %s" slot name))
  2496. (let ((accessor (intern (format "%s%s" conc-name slot))))
  2497. (push slot slots)
  2498. (push (pop desc) defaults)
  2499. ;; The arg "cl-x" is referenced by name in eg pred-form
  2500. ;; and pred-check, so changing it is not straightforward.
  2501. (push `(cl-defsubst ,accessor (cl-x)
  2502. ,(format "Access slot \"%s\" of `%s' struct CL-X."
  2503. slot struct)
  2504. (declare (side-effect-free t))
  2505. ,@(and pred-check
  2506. (list `(or ,pred-check
  2507. (signal 'wrong-type-argument
  2508. (list ',name cl-x)))))
  2509. ,(if (memq type '(nil vector)) `(aref cl-x ,pos)
  2510. (if (= pos 0) '(car cl-x)
  2511. `(nth ,pos cl-x))))
  2512. forms)
  2513. (when (cl-oddp (length desc))
  2514. (push
  2515. (macroexp--warn-and-return
  2516. (format "Missing value for option `%S' of slot `%s' in struct %s!"
  2517. (car (last desc)) slot name)
  2518. 'nil)
  2519. forms)
  2520. (when (and (keywordp (car defaults))
  2521. (not (keywordp (car desc))))
  2522. (let ((kw (car defaults)))
  2523. (push
  2524. (macroexp--warn-and-return
  2525. (format " I'll take `%s' to be an option rather than a default value."
  2526. kw)
  2527. 'nil)
  2528. forms)
  2529. (push kw desc)
  2530. (setcar defaults nil))))
  2531. (if (plist-get desc ':read-only)
  2532. (push `(gv-define-expander ,accessor
  2533. (lambda (_cl-do _cl-x)
  2534. (error "%s is a read-only slot" ',accessor)))
  2535. forms)
  2536. ;; For normal slots, we don't need to define a setf-expander,
  2537. ;; since gv-get can use the compiler macro to get the
  2538. ;; same result.
  2539. ;; (push `(gv-define-setter ,accessor (cl-val cl-x)
  2540. ;; ;; If cl is loaded only for compilation,
  2541. ;; ;; the call to cl--struct-setf-expander would
  2542. ;; ;; cause a warning because it may not be
  2543. ;; ;; defined at run time. Suppress that warning.
  2544. ;; (progn
  2545. ;; (declare-function
  2546. ;; cl--struct-setf-expander "cl-macs"
  2547. ;; (x name accessor pred-form pos))
  2548. ;; (cl--struct-setf-expander
  2549. ;; cl-val cl-x ',name ',accessor
  2550. ;; ,(and pred-check `',pred-check)
  2551. ;; ,pos)))
  2552. ;; forms)
  2553. )
  2554. (if print-auto
  2555. (nconc print-func
  2556. (list `(princ ,(format " %s" slot) cl-s)
  2557. `(prin1 (,accessor cl-x) cl-s)))))))
  2558. (setq pos (1+ pos))))
  2559. (setq slots (nreverse slots)
  2560. defaults (nreverse defaults))
  2561. (and copier
  2562. (push `(defalias ',copier #'copy-sequence)
  2563. forms))
  2564. (if constructor
  2565. (push (list constructor
  2566. (cons '&key (delq nil (copy-sequence slots))))
  2567. constrs))
  2568. (pcase-dolist (`(,cname ,args ,doc) constrs)
  2569. (let* ((anames (cl--arglist-args args))
  2570. (make (cl-mapcar (function (lambda (s d) (if (memq s anames) s d)))
  2571. slots defaults)))
  2572. (push `(cl-defsubst ,cname
  2573. (&cl-defs (nil ,@descs) ,@args)
  2574. ,(if (stringp doc) doc
  2575. (format "Constructor for objects of type `%s'." name))
  2576. ,@(if (cl--safe-expr-p `(progn ,@(mapcar #'cl-second descs)))
  2577. '((declare (side-effect-free t))))
  2578. (,(or type #'record) ,@make))
  2579. forms)))
  2580. (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
  2581. ;; Don't bother adding to cl-custom-print-functions since it's not used
  2582. ;; by anything anyway!
  2583. ;;(if print-func
  2584. ;; (push `(if (boundp 'cl-custom-print-functions)
  2585. ;; (push
  2586. ;; ;; The auto-generated function does not pay attention to
  2587. ;; ;; the depth argument cl-n.
  2588. ;; (lambda (cl-x cl-s ,(if print-auto '_cl-n 'cl-n))
  2589. ;; (and ,pred-form ,print-func))
  2590. ;; cl-custom-print-functions))
  2591. ;; forms))
  2592. `(progn
  2593. (defvar ,tag-symbol)
  2594. ,@(nreverse forms)
  2595. ;; Call cl-struct-define during compilation as well, so that
  2596. ;; a subsequent cl-defstruct in the same file can correctly include this
  2597. ;; struct as a parent.
  2598. (eval-and-compile
  2599. (cl-struct-define ',name ,docstring ',include-name
  2600. ',(or type 'record) ,(eq named t) ',descs
  2601. ',tag-symbol ',tag ',print-auto))
  2602. ',name)))
  2603. ;;; Add cl-struct support to pcase
  2604. (defun cl--struct-all-parents (class)
  2605. (when (cl--struct-class-p class)
  2606. (let ((res ())
  2607. (classes (list class)))
  2608. ;; BFS precedence.
  2609. (while (let ((class (pop classes)))
  2610. (push class res)
  2611. (setq classes
  2612. (append classes
  2613. (cl--class-parents class)))))
  2614. (nreverse res))))
  2615. ;;;###autoload
  2616. (pcase-defmacro cl-struct (type &rest fields)
  2617. "Pcase patterns to match cl-structs.
  2618. Elements of FIELDS can be of the form (NAME PAT) in which case the contents of
  2619. field NAME is matched against PAT, or they can be of the form NAME which
  2620. is a shorthand for (NAME NAME)."
  2621. (declare (debug (sexp &rest [&or (sexp pcase-PAT) sexp])))
  2622. `(and (pred (pcase--flip cl-typep ',type))
  2623. ,@(mapcar
  2624. (lambda (field)
  2625. (let* ((name (if (consp field) (car field) field))
  2626. (pat (if (consp field) (cadr field) field)))
  2627. `(app ,(if (eq (cl-struct-sequence-type type) 'list)
  2628. `(nth ,(cl-struct-slot-offset type name))
  2629. `(pcase--flip aref ,(cl-struct-slot-offset type name)))
  2630. ,pat)))
  2631. fields)))
  2632. (defun cl--defstruct-predicate (type)
  2633. (let ((cons (assq (cl-struct-sequence-type type)
  2634. `((list . consp)
  2635. (vector . vectorp)
  2636. (nil . recordp)))))
  2637. (if cons
  2638. (cdr cons)
  2639. 'recordp)))
  2640. (defun cl--pcase-mutually-exclusive-p (orig pred1 pred2)
  2641. "Extra special cases for `cl-typep' predicates."
  2642. (let* ((x1 pred1) (x2 pred2)
  2643. (t1
  2644. (and (eq 'pcase--flip (car-safe x1)) (setq x1 (cdr x1))
  2645. (eq 'cl-typep (car-safe x1)) (setq x1 (cdr x1))
  2646. (null (cdr-safe x1)) (setq x1 (car x1))
  2647. (eq 'quote (car-safe x1)) (cadr x1)))
  2648. (t2
  2649. (and (eq 'pcase--flip (car-safe x2)) (setq x2 (cdr x2))
  2650. (eq 'cl-typep (car-safe x2)) (setq x2 (cdr x2))
  2651. (null (cdr-safe x2)) (setq x2 (car x2))
  2652. (eq 'quote (car-safe x2)) (cadr x2))))
  2653. (or
  2654. (and (symbolp t1) (symbolp t2)
  2655. (let ((c1 (cl--find-class t1))
  2656. (c2 (cl--find-class t2)))
  2657. (and c1 c2
  2658. (not (or (memq c1 (cl--struct-all-parents c2))
  2659. (memq c2 (cl--struct-all-parents c1)))))))
  2660. (let ((c1 (and (symbolp t1) (cl--find-class t1))))
  2661. (and c1 (cl--struct-class-p c1)
  2662. (funcall orig (cl--defstruct-predicate t1)
  2663. pred2)))
  2664. (let ((c2 (and (symbolp t2) (cl--find-class t2))))
  2665. (and c2 (cl--struct-class-p c2)
  2666. (funcall orig pred1
  2667. (cl--defstruct-predicate t2))))
  2668. (funcall orig pred1 pred2))))
  2669. (advice-add 'pcase--mutually-exclusive-p
  2670. :around #'cl--pcase-mutually-exclusive-p)
  2671. (defun cl-struct-sequence-type (struct-type)
  2672. "Return the sequence used to build STRUCT-TYPE.
  2673. STRUCT-TYPE is a symbol naming a struct type. Return `record',
  2674. `vector`, or `list' if STRUCT-TYPE is a struct type, nil otherwise."
  2675. (declare (side-effect-free t) (pure t))
  2676. (cl--struct-class-type (cl--struct-get-class struct-type)))
  2677. (defun cl-struct-slot-info (struct-type)
  2678. "Return a list of slot names of struct STRUCT-TYPE.
  2679. Each entry is a list (SLOT-NAME . OPTS), where SLOT-NAME is a
  2680. slot name symbol and OPTS is a list of slot options given to
  2681. `cl-defstruct'. Dummy slots that represent the struct name and
  2682. slots skipped by :initial-offset may appear in the list."
  2683. (declare (side-effect-free t) (pure t))
  2684. (let* ((class (cl--struct-get-class struct-type))
  2685. (slots (cl--struct-class-slots class))
  2686. (type (cl--struct-class-type class))
  2687. (descs (if type () (list '(cl-tag-slot)))))
  2688. (dotimes (i (length slots))
  2689. (let ((slot (aref slots i)))
  2690. (push `(,(cl--slot-descriptor-name slot)
  2691. ,(cl--slot-descriptor-initform slot)
  2692. ,@(if (not (eq (cl--slot-descriptor-type slot) t))
  2693. `(:type ,(cl--slot-descriptor-type slot)))
  2694. ,@(cl--slot-descriptor-props slot))
  2695. descs)))
  2696. (nreverse descs)))
  2697. (define-error 'cl-struct-unknown-slot "struct %S has no slot %S")
  2698. (defun cl-struct-slot-offset (struct-type slot-name)
  2699. "Return the offset of slot SLOT-NAME in STRUCT-TYPE.
  2700. The returned zero-based slot index is relative to the start of
  2701. the structure data type and is adjusted for any structure name
  2702. and :initial-offset slots. Signal error if struct STRUCT-TYPE
  2703. does not contain SLOT-NAME."
  2704. (declare (side-effect-free t) (pure t))
  2705. (or (gethash slot-name
  2706. (cl--class-index-table (cl--struct-get-class struct-type)))
  2707. (signal 'cl-struct-unknown-slot (list struct-type slot-name))))
  2708. (defvar byte-compile-function-environment)
  2709. (defvar byte-compile-macro-environment)
  2710. (defun cl--macroexp-fboundp (sym)
  2711. "Return non-nil if SYM will be bound when we run the code.
  2712. Of course, we really can't know that for sure, so it's just a heuristic."
  2713. (or (fboundp sym)
  2714. (and (cl--compiling-file)
  2715. (or (cdr (assq sym byte-compile-function-environment))
  2716. (cdr (assq sym byte-compile-macro-environment))))))
  2717. (put 'null 'cl-deftype-satisfies #'null)
  2718. (put 'atom 'cl-deftype-satisfies #'atom)
  2719. (put 'real 'cl-deftype-satisfies #'numberp)
  2720. (put 'fixnum 'cl-deftype-satisfies #'integerp)
  2721. (put 'base-char 'cl-deftype-satisfies #'characterp)
  2722. (put 'character 'cl-deftype-satisfies #'natnump)
  2723. ;;;###autoload
  2724. (define-inline cl-typep (val type)
  2725. (inline-letevals (val)
  2726. (pcase (inline-const-val type)
  2727. ((and `(,name . ,args) (guard (get name 'cl-deftype-handler)))
  2728. (inline-quote
  2729. (cl-typep ,val ',(apply (get name 'cl-deftype-handler) args))))
  2730. (`(,(and name (or 'integer 'float 'real 'number))
  2731. . ,(or `(,min ,max) pcase--dontcare))
  2732. (inline-quote
  2733. (and (cl-typep ,val ',name)
  2734. ,(if (memq min '(* nil)) t
  2735. (if (consp min)
  2736. (inline-quote (> ,val ',(car min)))
  2737. (inline-quote (>= ,val ',min))))
  2738. ,(if (memq max '(* nil)) t
  2739. (if (consp max)
  2740. (inline-quote (< ,val ',(car max)))
  2741. (inline-quote (<= ,val ',max)))))))
  2742. (`(not ,type) (inline-quote (not (cl-typep ,val ',type))))
  2743. (`(,(and name (or 'and 'or)) . ,types)
  2744. (cond
  2745. ((null types) (inline-quote ',(eq name 'and)))
  2746. ((null (cdr types))
  2747. (inline-quote (cl-typep ,val ',(car types))))
  2748. (t
  2749. (let ((head (car types))
  2750. (rest `(,name . ,(cdr types))))
  2751. (cond
  2752. ((eq name 'and)
  2753. (inline-quote (and (cl-typep ,val ',head)
  2754. (cl-typep ,val ',rest))))
  2755. (t
  2756. (inline-quote (or (cl-typep ,val ',head)
  2757. (cl-typep ,val ',rest)))))))))
  2758. (`(eql ,v) (inline-quote (and (eql ,val ',v) t)))
  2759. (`(member . ,args) (inline-quote (and (memql ,val ',args) t)))
  2760. (`(satisfies ,pred) (inline-quote (funcall #',pred ,val)))
  2761. ((and (pred symbolp) type (guard (get type 'cl-deftype-handler)))
  2762. (inline-quote
  2763. (cl-typep ,val ',(funcall (get type 'cl-deftype-handler)))))
  2764. ((and (pred symbolp) type (guard (get type 'cl-deftype-satisfies)))
  2765. (inline-quote (funcall #',(get type 'cl-deftype-satisfies) ,val)))
  2766. ((and (or 'nil 't) type) (inline-quote ',type))
  2767. ((and (pred symbolp) type)
  2768. (let* ((name (symbol-name type))
  2769. (namep (intern (concat name "p"))))
  2770. (cond
  2771. ((cl--macroexp-fboundp namep) (inline-quote (funcall #',namep ,val)))
  2772. ((cl--macroexp-fboundp
  2773. (setq namep (intern (concat name "-p"))))
  2774. (inline-quote (funcall #',namep ,val)))
  2775. ((cl--macroexp-fboundp type) (inline-quote (funcall #',type ,val)))
  2776. (t (error "Unknown type %S" type)))))
  2777. (type (error "Bad type spec: %s" type)))))
  2778. ;;;###autoload
  2779. (defmacro cl-check-type (form type &optional string)
  2780. "Verify that FORM is of type TYPE; signal an error if not.
  2781. STRING is an optional description of the desired type."
  2782. (declare (debug (place cl-type-spec &optional stringp)))
  2783. (and (or (not (cl--compiling-file))
  2784. (< cl--optimize-speed 3) (= cl--optimize-safety 3))
  2785. (macroexp-let2 macroexp-copyable-p temp form
  2786. `(progn (or (cl-typep ,temp ',type)
  2787. (signal 'wrong-type-argument
  2788. (list ,(or string `',type) ,temp ',form)))
  2789. nil))))
  2790. ;;;###autoload
  2791. (defmacro cl-assert (form &optional show-args string &rest args)
  2792. ;; FIXME: This is actually not compatible with Common-Lisp's `assert'.
  2793. "Verify that FORM returns non-nil; signal an error if not.
  2794. Second arg SHOW-ARGS means to include arguments of FORM in message.
  2795. Other args STRING and ARGS... are arguments to be passed to `error'.
  2796. They are not evaluated unless the assertion fails. If STRING is
  2797. omitted, a default message listing FORM itself is used."
  2798. (declare (debug (form &rest form)))
  2799. (and (or (not (cl--compiling-file))
  2800. (< cl--optimize-speed 3) (= cl--optimize-safety 3))
  2801. (let ((sargs (and show-args
  2802. (delq nil (mapcar (lambda (x)
  2803. (unless (macroexp-const-p x)
  2804. x))
  2805. (cdr-safe form))))))
  2806. `(progn
  2807. (or ,form
  2808. (cl--assertion-failed
  2809. ',form ,@(if (or string sargs args)
  2810. `(,string (list ,@sargs) (list ,@args)))))
  2811. nil))))
  2812. ;;; Compiler macros.
  2813. ;;;###autoload
  2814. (defmacro cl-define-compiler-macro (func args &rest body)
  2815. "Define a compiler-only macro.
  2816. This is like `defmacro', but macro expansion occurs only if the call to
  2817. FUNC is compiled (i.e., not interpreted). Compiler macros should be used
  2818. for optimizing the way calls to FUNC are compiled; the form returned by
  2819. BODY should do the same thing as a call to the normal function called
  2820. FUNC, though possibly more efficiently. Note that, like regular macros,
  2821. compiler macros are expanded repeatedly until no further expansions are
  2822. possible. Unlike regular macros, BODY can decide to \"punt\" and leave the
  2823. original function call alone by declaring an initial `&whole foo' parameter
  2824. and then returning foo."
  2825. (declare (debug cl-defmacro) (indent 2))
  2826. (let ((p args) (res nil))
  2827. (while (consp p) (push (pop p) res))
  2828. (setq args (nconc (nreverse res) (and p (list '&rest p)))))
  2829. ;; FIXME: The code in bytecomp mishandles top-level expressions that define
  2830. ;; uninterned functions. E.g. it would generate code like:
  2831. ;; (defalias '#1=#:foo--cmacro #[514 ...])
  2832. ;; (put 'foo 'compiler-macro '#:foo--cmacro)
  2833. ;; So we circumvent this by using an interned name.
  2834. (let ((fname (intern (concat (symbol-name func) "--cmacro"))))
  2835. `(eval-and-compile
  2836. ;; Name the compiler-macro function, so that `symbol-file' can find it.
  2837. (cl-defun ,fname ,(if (memq '&whole args) (delq '&whole args)
  2838. (cons '_cl-whole-arg args))
  2839. ,@body)
  2840. (put ',func 'compiler-macro #',fname))))
  2841. ;;;###autoload
  2842. (defun cl-compiler-macroexpand (form)
  2843. "Like `macroexpand', but for compiler macros.
  2844. Expands FORM repeatedly until no further expansion is possible.
  2845. Returns FORM unchanged if it has no compiler macro, or if it has a
  2846. macro that returns its `&whole' argument."
  2847. (while
  2848. (let ((func (car-safe form)) (handler nil))
  2849. (while (and (symbolp func)
  2850. (not (setq handler (get func 'compiler-macro)))
  2851. (fboundp func)
  2852. (or (not (autoloadp (symbol-function func)))
  2853. (autoload-do-load (symbol-function func) func)))
  2854. (setq func (symbol-function func)))
  2855. (and handler
  2856. (not (eq form (setq form (apply handler form (cdr form))))))))
  2857. form)
  2858. ;; Optimize away unused block-wrappers.
  2859. (defvar cl--active-block-names nil)
  2860. (cl-define-compiler-macro cl--block-wrapper (cl-form)
  2861. (let* ((cl-entry (cons (nth 1 (nth 1 cl-form)) nil))
  2862. (cl--active-block-names (cons cl-entry cl--active-block-names))
  2863. (cl-body (macroexpand-all ;Performs compiler-macro expansions.
  2864. (macroexp-progn (cddr cl-form))
  2865. macroexpand-all-environment)))
  2866. ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
  2867. ;; to indicate that this return value is already fully expanded.
  2868. (if (cdr cl-entry)
  2869. `(catch ,(nth 1 cl-form) ,@(macroexp-unprogn cl-body))
  2870. cl-body)))
  2871. (cl-define-compiler-macro cl--block-throw (cl-tag cl-value)
  2872. (let ((cl-found (assq (nth 1 cl-tag) cl--active-block-names)))
  2873. (if cl-found (setcdr cl-found t)))
  2874. `(throw ,cl-tag ,cl-value))
  2875. ;; Compile-time optimizations for some functions defined in this package.
  2876. (defun cl--compiler-macro-member (form a list &rest keys)
  2877. (let ((test (and (= (length keys) 2) (eq (car keys) :test)
  2878. (cl--const-expr-val (nth 1 keys)))))
  2879. (cond ((eq test 'eq) `(memq ,a ,list))
  2880. ((eq test 'equal) `(member ,a ,list))
  2881. ((or (null keys) (eq test 'eql)) `(memql ,a ,list))
  2882. (t form))))
  2883. (defun cl--compiler-macro-assoc (form a list &rest keys)
  2884. (let ((test (and (= (length keys) 2) (eq (car keys) :test)
  2885. (cl--const-expr-val (nth 1 keys)))))
  2886. (cond ((eq test 'eq) `(assq ,a ,list))
  2887. ((eq test 'equal) `(assoc ,a ,list))
  2888. ((and (macroexp-const-p a) (or (null keys) (eq test 'eql)))
  2889. (if (floatp (cl--const-expr-val a))
  2890. `(assoc ,a ,list) `(assq ,a ,list)))
  2891. (t form))))
  2892. ;;;###autoload
  2893. (defun cl--compiler-macro-adjoin (form a list &rest keys)
  2894. (if (memq :key keys) form
  2895. (macroexp-let2* macroexp-copyable-p ((va a) (vlist list))
  2896. `(if (cl-member ,va ,vlist ,@keys) ,vlist (cons ,va ,vlist)))))
  2897. (defun cl--compiler-macro-get (_form sym prop &optional def)
  2898. (if def
  2899. `(cl-getf (symbol-plist ,sym) ,prop ,def)
  2900. `(get ,sym ,prop)))
  2901. (dolist (y '(cl-first cl-second cl-third cl-fourth
  2902. cl-fifth cl-sixth cl-seventh
  2903. cl-eighth cl-ninth cl-tenth
  2904. cl-rest cl-endp cl-plusp cl-minusp
  2905. cl-caaar cl-caadr cl-cadar
  2906. cl-caddr cl-cdaar cl-cdadr
  2907. cl-cddar cl-cdddr cl-caaaar
  2908. cl-caaadr cl-caadar cl-caaddr
  2909. cl-cadaar cl-cadadr cl-caddar
  2910. cl-cadddr cl-cdaaar cl-cdaadr
  2911. cl-cdadar cl-cdaddr cl-cddaar
  2912. cl-cddadr cl-cdddar cl-cddddr))
  2913. (put y 'side-effect-free t))
  2914. ;;; Things that are inline.
  2915. (cl-proclaim '(inline cl-acons cl-map cl-concatenate cl-notany
  2916. cl-notevery cl-revappend cl-nreconc gethash))
  2917. ;;; Things that are side-effect-free.
  2918. (mapc (lambda (x) (function-put x 'side-effect-free t))
  2919. '(cl-oddp cl-evenp cl-signum last butlast cl-ldiff cl-pairlis cl-gcd
  2920. cl-lcm cl-isqrt cl-floor cl-ceiling cl-truncate cl-round cl-mod cl-rem
  2921. cl-subseq cl-list-length cl-get cl-getf))
  2922. ;;; Things that are side-effect-and-error-free.
  2923. (mapc (lambda (x) (function-put x 'side-effect-free 'error-free))
  2924. '(eql cl-list* cl-subst cl-acons cl-equalp
  2925. cl-random-state-p copy-tree cl-sublis))
  2926. ;;; Types and assertions.
  2927. ;;;###autoload
  2928. (defmacro cl-deftype (name arglist &rest body)
  2929. "Define NAME as a new data type.
  2930. The type name can then be used in `cl-typecase', `cl-check-type', etc."
  2931. (declare (debug cl-defmacro) (doc-string 3) (indent 2))
  2932. `(cl-eval-when (compile load eval)
  2933. (put ',name 'cl-deftype-handler
  2934. (cl-function (lambda (&cl-defs ('*) ,@arglist) ,@body)))))
  2935. (cl-deftype extended-char () `(and character (not base-char)))
  2936. ;;; Additional functions that we can now define because we've defined
  2937. ;;; `cl-defsubst' and `cl-typep'.
  2938. (define-inline cl-struct-slot-value (struct-type slot-name inst)
  2939. "Return the value of slot SLOT-NAME in INST of STRUCT-TYPE.
  2940. STRUCT and SLOT-NAME are symbols. INST is a structure instance."
  2941. (declare (side-effect-free t))
  2942. (inline-letevals (struct-type slot-name inst)
  2943. (inline-quote
  2944. (progn
  2945. (unless (cl-typep ,inst ,struct-type)
  2946. (signal 'wrong-type-argument (list ,struct-type ,inst)))
  2947. ;; We could use `elt', but since the byte compiler will resolve the
  2948. ;; branch below at compile time, it's more efficient to use the
  2949. ;; type-specific accessor.
  2950. (if (eq (cl-struct-sequence-type ,struct-type) 'list)
  2951. (nth (cl-struct-slot-offset ,struct-type ,slot-name) ,inst)
  2952. (aref ,inst (cl-struct-slot-offset ,struct-type ,slot-name)))))))
  2953. (run-hooks 'cl-macs-load-hook)
  2954. ;; Local variables:
  2955. ;; byte-compile-dynamic: t
  2956. ;; generated-autoload-file: "cl-loaddefs.el"
  2957. ;; End:
  2958. (provide 'cl-macs)
  2959. ;;; cl-macs.el ends here