cl-macs.el 126 KB

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