match.upstream.scm 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. ;;;; match.scm -- portable hygienic pattern matcher -*- coding: utf-8 -*-
  2. ;;
  3. ;; This code is written by Alex Shinn and placed in the
  4. ;; Public Domain. All warranties are disclaimed.
  5. ;;> @example-import[(srfi 9)]
  6. ;;> This is a full superset of the popular @hyperlink[
  7. ;;> "http://www.cs.indiana.edu/scheme-repository/code.match.html"]{match}
  8. ;;> package by Andrew Wright, written in fully portable @scheme{syntax-rules}
  9. ;;> and thus preserving hygiene.
  10. ;;> The most notable extensions are the ability to use @emph{non-linear}
  11. ;;> patterns - patterns in which the same identifier occurs multiple
  12. ;;> times, tail patterns after ellipsis, and the experimental tree patterns.
  13. ;;> @subsubsection{Patterns}
  14. ;;> Patterns are written to look like the printed representation of
  15. ;;> the objects they match. The basic usage is
  16. ;;> @scheme{(match expr (pat body ...) ...)}
  17. ;;> where the result of @var{expr} is matched against each pattern in
  18. ;;> turn, and the corresponding body is evaluated for the first to
  19. ;;> succeed. Thus, a list of three elements matches a list of three
  20. ;;> elements.
  21. ;;> @example{(let ((ls (list 1 2 3))) (match ls ((1 2 3) #t)))}
  22. ;;> If no patterns match an error is signalled.
  23. ;;> Identifiers will match anything, and make the corresponding
  24. ;;> binding available in the body.
  25. ;;> @example{(match (list 1 2 3) ((a b c) b))}
  26. ;;> If the same identifier occurs multiple times, the first instance
  27. ;;> will match anything, but subsequent instances must match a value
  28. ;;> which is @scheme{equal?} to the first.
  29. ;;> @example{(match (list 1 2 1) ((a a b) 1) ((a b a) 2))}
  30. ;;> The special identifier @scheme{_} matches anything, no matter how
  31. ;;> many times it is used, and does not bind the result in the body.
  32. ;;> @example{(match (list 1 2 1) ((_ _ b) 1) ((a b a) 2))}
  33. ;;> To match a literal identifier (or list or any other literal), use
  34. ;;> @scheme{quote}.
  35. ;;> @example{(match 'a ('b 1) ('a 2))}
  36. ;;> Analogous to its normal usage in scheme, @scheme{quasiquote} can
  37. ;;> be used to quote a mostly literally matching object with selected
  38. ;;> parts unquoted.
  39. ;;> @example|{(match (list 1 2 3) (`(1 ,b ,c) (list b c)))}|
  40. ;;> Often you want to match any number of a repeated pattern. Inside
  41. ;;> a list pattern you can append @scheme{...} after an element to
  42. ;;> match zero or more of that pattern (like a regexp Kleene star).
  43. ;;> @example{(match (list 1 2) ((1 2 3 ...) #t))}
  44. ;;> @example{(match (list 1 2 3) ((1 2 3 ...) #t))}
  45. ;;> @example{(match (list 1 2 3 3 3) ((1 2 3 ...) #t))}
  46. ;;> Pattern variables matched inside the repeated pattern are bound to
  47. ;;> a list of each matching instance in the body.
  48. ;;> @example{(match (list 1 2) ((a b c ...) c))}
  49. ;;> @example{(match (list 1 2 3) ((a b c ...) c))}
  50. ;;> @example{(match (list 1 2 3 4 5) ((a b c ...) c))}
  51. ;;> More than one @scheme{...} may not be used in the same list, since
  52. ;;> this would require exponential backtracking in the general case.
  53. ;;> However, @scheme{...} need not be the final element in the list,
  54. ;;> and may be succeeded by a fixed number of patterns.
  55. ;;> @example{(match (list 1 2 3 4) ((a b c ... d e) c))}
  56. ;;> @example{(match (list 1 2 3 4 5) ((a b c ... d e) c))}
  57. ;;> @example{(match (list 1 2 3 4 5 6 7) ((a b c ... d e) c))}
  58. ;;> @scheme{___} is provided as an alias for @scheme{...} when it is
  59. ;;> inconvenient to use the ellipsis (as in a syntax-rules template).
  60. ;;> The @scheme{..1} syntax is exactly like the @scheme{...} except
  61. ;;> that it matches one or more repetitions (like a regexp "+").
  62. ;;> @example{(match (list 1 2) ((a b c ..1) c))}
  63. ;;> @example{(match (list 1 2 3) ((a b c ..1) c))}
  64. ;;> The boolean operators @scheme{and}, @scheme{or} and @scheme{not}
  65. ;;> can be used to group and negate patterns analogously to their
  66. ;;> Scheme counterparts.
  67. ;;> The @scheme{and} operator ensures that all subpatterns match.
  68. ;;> This operator is often used with the idiom @scheme{(and x pat)} to
  69. ;;> bind @var{x} to the entire value that matches @var{pat}
  70. ;;> (c.f. "as-patterns" in ML or Haskell). Another common use is in
  71. ;;> conjunction with @scheme{not} patterns to match a general case
  72. ;;> with certain exceptions.
  73. ;;> @example{(match 1 ((and) #t))}
  74. ;;> @example{(match 1 ((and x) x))}
  75. ;;> @example{(match 1 ((and x 1) x))}
  76. ;;> The @scheme{or} operator ensures that at least one subpattern
  77. ;;> matches. If the same identifier occurs in different subpatterns,
  78. ;;> it is matched independently. All identifiers from all subpatterns
  79. ;;> are bound if the @scheme{or} operator matches, but the binding is
  80. ;;> only defined for identifiers from the subpattern which matched.
  81. ;;> @example{(match 1 ((or) #t) (else #f))}
  82. ;;> @example{(match 1 ((or x) x))}
  83. ;;> @example{(match 1 ((or x 2) x))}
  84. ;;> The @scheme{not} operator succeeds if the given pattern doesn't
  85. ;;> match. None of the identifiers used are available in the body.
  86. ;;> @example{(match 1 ((not 2) #t))}
  87. ;;> The more general operator @scheme{?} can be used to provide a
  88. ;;> predicate. The usage is @scheme{(? predicate pat ...)} where
  89. ;;> @var{predicate} is a Scheme expression evaluating to a predicate
  90. ;;> called on the value to match, and any optional patterns after the
  91. ;;> predicate are then matched as in an @scheme{and} pattern.
  92. ;;> @example{(match 1 ((? odd? x) x))}
  93. ;;> The field operator @scheme{=} is used to extract an arbitrary
  94. ;;> field and match against it. It is useful for more complex or
  95. ;;> conditional destructuring that can't be more directly expressed in
  96. ;;> the pattern syntax. The usage is @scheme{(= field pat)}, where
  97. ;;> @var{field} can be any expression, and should result in a
  98. ;;> procedure of one argument, which is applied to the value to match
  99. ;;> to generate a new value to match against @var{pat}.
  100. ;;> Thus the pattern @scheme{(and (= car x) (= cdr y))} is equivalent
  101. ;;> to @scheme{(x . y)}, except it will result in an immediate error
  102. ;;> if the value isn't a pair.
  103. ;;> @example{(match '(1 . 2) ((= car x) x))}
  104. ;;> @example{(match 4 ((= sqrt x) x))}
  105. ;;> The record operator @scheme{$} is used as a concise way to match
  106. ;;> records defined by SRFI-9 (or SRFI-99). The usage is
  107. ;;> @scheme{($ rtd field ...)}, where @var{rtd} should be the record
  108. ;;> type descriptor specified as the first argument to
  109. ;;> @scheme{define-record-type}, and each @var{field} is a subpattern
  110. ;;> matched against the fields of the record in order. Not all fields
  111. ;;> must be present.
  112. ;;> @example{
  113. ;;> (let ()
  114. ;;> (define-record-type employee
  115. ;;> (make-employee name title)
  116. ;;> employee?
  117. ;;> (name get-name)
  118. ;;> (title get-title))
  119. ;;> (match (make-employee "Bob" "Doctor")
  120. ;;> (($ employee n t) (list t n))))
  121. ;;> }
  122. ;;> The @scheme{set!} and @scheme{get!} operators are used to bind an
  123. ;;> identifier to the setter and getter of a field, respectively. The
  124. ;;> setter is a procedure of one argument, which mutates the field to
  125. ;;> that argument. The getter is a procedure of no arguments which
  126. ;;> returns the current value of the field.
  127. ;;> @example{(let ((x (cons 1 2))) (match x ((1 . (set! s)) (s 3) x)))}
  128. ;;> @example{(match '(1 . 2) ((1 . (get! g)) (g)))}
  129. ;;> The new operator @scheme{***} can be used to search a tree for
  130. ;;> subpatterns. A pattern of the form @scheme{(x *** y)} represents
  131. ;;> the subpattern @var{y} located somewhere in a tree where the path
  132. ;;> from the current object to @var{y} can be seen as a list of the
  133. ;;> form @scheme{(x ...)}. @var{y} can immediately match the current
  134. ;;> object in which case the path is the empty list. In a sense it's
  135. ;;> a 2-dimensional version of the @scheme{...} pattern.
  136. ;;> As a common case the pattern @scheme{(_ *** y)} can be used to
  137. ;;> search for @var{y} anywhere in a tree, regardless of the path
  138. ;;> used.
  139. ;;> @example{(match '(a (a (a b))) ((x *** 'b) x))}
  140. ;;> @example{(match '(a (b) (c (d e) (f g))) ((x *** 'g) x))}
  141. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  142. ;; Notes
  143. ;; The implementation is a simple generative pattern matcher - each
  144. ;; pattern is expanded into the required tests, calling a failure
  145. ;; continuation if the tests fail. This makes the logic easy to
  146. ;; follow and extend, but produces sub-optimal code in cases where you
  147. ;; have many similar clauses due to repeating the same tests.
  148. ;; Nonetheless a smart compiler should be able to remove the redundant
  149. ;; tests. For MATCH-LET and DESTRUCTURING-BIND type uses there is no
  150. ;; performance hit.
  151. ;; The original version was written on 2006/11/29 and described in the
  152. ;; following Usenet post:
  153. ;; http://groups.google.com/group/comp.lang.scheme/msg/0941234de7112ffd
  154. ;; and is still available at
  155. ;; http://synthcode.com/scheme/match-simple.scm
  156. ;; It's just 80 lines for the core MATCH, and an extra 40 lines for
  157. ;; MATCH-LET, MATCH-LAMBDA and other syntactic sugar.
  158. ;;
  159. ;; A variant of this file which uses COND-EXPAND in a few places for
  160. ;; performance can be found at
  161. ;; http://synthcode.com/scheme/match-cond-expand.scm
  162. ;;
  163. ;; 2016/03/06 - fixing named match-let (thanks to Stefan Israelsson Tampe)
  164. ;; 2015/05/09 - fixing bug in var extraction of quasiquote patterns
  165. ;; 2014/11/24 - [OMITTED IN GUILE] adding Gauche's `@' pattern for named record field matching
  166. ;; 2012/12/26 - wrapping match-let&co body in lexical closure
  167. ;; 2012/11/28 - fixing typo s/vetor/vector in largely unused set! code
  168. ;; 2012/05/23 - fixing combinatorial explosion of code in certain or patterns
  169. ;; 2011/09/25 - fixing bug when directly matching an identifier repeated in
  170. ;; the pattern (thanks to Stefan Israelsson Tampe)
  171. ;; 2011/01/27 - fixing bug when matching tail patterns against improper lists
  172. ;; 2010/09/26 - adding `..1' patterns (thanks to Ludovic Courtès)
  173. ;; 2010/09/07 - fixing identifier extraction in some `...' and `***' patterns
  174. ;; 2009/11/25 - adding `***' tree search patterns
  175. ;; 2008/03/20 - fixing bug where (a ...) matched non-lists
  176. ;; 2008/03/15 - removing redundant check in vector patterns
  177. ;; 2008/03/06 - you can use `...' portably now (thanks to Taylor Campbell)
  178. ;; 2007/09/04 - fixing quasiquote patterns
  179. ;; 2007/07/21 - allowing ellipsis patterns in non-final list positions
  180. ;; 2007/04/10 - fixing potential hygiene issue in match-check-ellipsis
  181. ;; (thanks to Taylor Campbell)
  182. ;; 2007/04/08 - clean up, commenting
  183. ;; 2006/12/24 - bugfixes
  184. ;; 2006/12/01 - non-linear patterns, shared variables in OR, get!/set!
  185. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  186. ;; force compile-time syntax errors with useful messages
  187. (define-syntax match-syntax-error
  188. (syntax-rules ()
  189. ((_) (match-syntax-error "invalid match-syntax-error usage"))))
  190. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  191. ;;> @subsubsection{Syntax}
  192. ;;> @subsubsubsection{@rawcode{(match expr (pattern . body) ...)@br{}
  193. ;;> (match expr (pattern (=> failure) . body) ...)}}
  194. ;;> The result of @var{expr} is matched against each @var{pattern} in
  195. ;;> turn, according to the pattern rules described in the previous
  196. ;;> section, until the the first @var{pattern} matches. When a match is
  197. ;;> found, the corresponding @var{body}s are evaluated in order,
  198. ;;> and the result of the last expression is returned as the result
  199. ;;> of the entire @scheme{match}. If a @var{failure} is provided,
  200. ;;> then it is bound to a procedure of no arguments which continues,
  201. ;;> processing at the next @var{pattern}. If no @var{pattern} matches,
  202. ;;> an error is signalled.
  203. ;; The basic interface. MATCH just performs some basic syntax
  204. ;; validation, binds the match expression to a temporary variable `v',
  205. ;; and passes it on to MATCH-NEXT. It's a constant throughout the
  206. ;; code below that the binding `v' is a direct variable reference, not
  207. ;; an expression.
  208. (define-syntax match
  209. (syntax-rules ()
  210. ((match)
  211. (match-syntax-error "missing match expression"))
  212. ((match atom)
  213. (match-syntax-error "no match clauses"))
  214. ((match (app ...) (pat . body) ...)
  215. (let ((v (app ...)))
  216. (match-next v ((app ...) (set! (app ...))) (pat . body) ...)))
  217. ((match #(vec ...) (pat . body) ...)
  218. (let ((v #(vec ...)))
  219. (match-next v (v (set! v)) (pat . body) ...)))
  220. ((match atom (pat . body) ...)
  221. (let ((v atom))
  222. (match-next v (atom (set! atom)) (pat . body) ...)))
  223. ))
  224. ;; MATCH-NEXT passes each clause to MATCH-ONE in turn with its failure
  225. ;; thunk, which is expanded by recursing MATCH-NEXT on the remaining
  226. ;; clauses. `g+s' is a list of two elements, the get! and set!
  227. ;; expressions respectively.
  228. (define-syntax match-next
  229. (syntax-rules (=>)
  230. ;; no more clauses, the match failed
  231. ((match-next v g+s)
  232. ;; Here we call error in non-tail context, so that the backtrace
  233. ;; can show the source location of the failing match form.
  234. (begin
  235. (throw 'match-error "match" "no matching pattern" v)
  236. #f))
  237. ;; named failure continuation
  238. ((match-next v g+s (pat (=> failure) . body) . rest)
  239. (let ((failure (lambda () (match-next v g+s . rest))))
  240. ;; match-one analyzes the pattern for us
  241. (match-one v pat g+s (match-drop-ids (begin . body)) (failure) ())))
  242. ;; anonymous failure continuation, give it a dummy name
  243. ((match-next v g+s (pat . body) . rest)
  244. (match-next v g+s (pat (=> failure) . body) . rest))))
  245. ;; MATCH-ONE first checks for ellipsis patterns, otherwise passes on to
  246. ;; MATCH-TWO.
  247. (define-syntax match-one
  248. (syntax-rules ()
  249. ;; If it's a list of two or more values, check to see if the
  250. ;; second one is an ellipsis and handle accordingly, otherwise go
  251. ;; to MATCH-TWO.
  252. ((match-one v (p q . r) g+s sk fk i)
  253. (match-check-ellipsis
  254. q
  255. (match-extract-vars p (match-gen-ellipsis v p r g+s sk fk i) i ())
  256. (match-two v (p q . r) g+s sk fk i)))
  257. ;; Go directly to MATCH-TWO.
  258. ((match-one . x)
  259. (match-two . x))))
  260. ;; This is the guts of the pattern matcher. We are passed a lot of
  261. ;; information in the form:
  262. ;;
  263. ;; (match-two var pattern getter setter success-k fail-k (ids ...))
  264. ;;
  265. ;; usually abbreviated
  266. ;;
  267. ;; (match-two v p g+s sk fk i)
  268. ;;
  269. ;; where VAR is the symbol name of the current variable we are
  270. ;; matching, PATTERN is the current pattern, getter and setter are the
  271. ;; corresponding accessors (e.g. CAR and SET-CAR! of the pair holding
  272. ;; VAR), SUCCESS-K is the success continuation, FAIL-K is the failure
  273. ;; continuation (which is just a thunk call and is thus safe to expand
  274. ;; multiple times) and IDS are the list of identifiers bound in the
  275. ;; pattern so far.
  276. (define-syntax match-two
  277. (syntax-rules (_ ___ ..1 *** quote quasiquote ? $ = and or not set! get!)
  278. ((match-two v () g+s (sk ...) fk i)
  279. (if (null? v) (sk ... i) fk))
  280. ((match-two v (quote p) g+s (sk ...) fk i)
  281. (if (equal? v 'p) (sk ... i) fk))
  282. ((match-two v (quasiquote p) . x)
  283. (match-quasiquote v p . x))
  284. ((match-two v (and) g+s (sk ...) fk i) (sk ... i))
  285. ((match-two v (and p q ...) g+s sk fk i)
  286. (match-one v p g+s (match-one v (and q ...) g+s sk fk) fk i))
  287. ((match-two v (or) g+s sk fk i) fk)
  288. ((match-two v (or p) . x)
  289. (match-one v p . x))
  290. ((match-two v (or p ...) g+s sk fk i)
  291. (match-extract-vars (or p ...) (match-gen-or v (p ...) g+s sk fk i) i ()))
  292. ((match-two v (not p) g+s (sk ...) fk i)
  293. (match-one v p g+s (match-drop-ids fk) (sk ... i) i))
  294. ((match-two v (get! getter) (g s) (sk ...) fk i)
  295. (let ((getter (lambda () g))) (sk ... i)))
  296. ((match-two v (set! setter) (g (s ...)) (sk ...) fk i)
  297. (let ((setter (lambda (x) (s ... x)))) (sk ... i)))
  298. ((match-two v (? pred . p) g+s sk fk i)
  299. (if (pred v) (match-one v (and . p) g+s sk fk i) fk))
  300. ((match-two v (= proc p) . x)
  301. (let ((w (proc v))) (match-one w p . x)))
  302. ((match-two v (p ___ . r) g+s sk fk i)
  303. (match-extract-vars p (match-gen-ellipsis v p r g+s sk fk i) i ()))
  304. ((match-two v (p) g+s sk fk i)
  305. (if (and (pair? v) (null? (cdr v)))
  306. (let ((w (car v)))
  307. (match-one w p ((car v) (set-car! v)) sk fk i))
  308. fk))
  309. ((match-two v (p *** q) g+s sk fk i)
  310. (match-extract-vars p (match-gen-search v p q g+s sk fk i) i ()))
  311. ((match-two v (p *** . q) g+s sk fk i)
  312. (match-syntax-error "invalid use of ***" (p *** . q)))
  313. ((match-two v (p ..1) g+s sk fk i)
  314. (if (pair? v)
  315. (match-one v (p ___) g+s sk fk i)
  316. fk))
  317. ((match-two v ($ rec p ...) g+s sk fk i)
  318. (if (is-a? v rec)
  319. (match-record-refs v rec 0 (p ...) g+s sk fk i)
  320. fk))
  321. ((match-two v (p . q) g+s sk fk i)
  322. (if (pair? v)
  323. (let ((w (car v)) (x (cdr v)))
  324. (match-one w p ((car v) (set-car! v))
  325. (match-one x q ((cdr v) (set-cdr! v)) sk fk)
  326. fk
  327. i))
  328. fk))
  329. ((match-two v #(p ...) g+s . x)
  330. (match-vector v 0 () (p ...) . x))
  331. ((match-two v _ g+s (sk ...) fk i) (sk ... i))
  332. ;; Not a pair or vector or special literal, test to see if it's a
  333. ;; new symbol, in which case we just bind it, or if it's an
  334. ;; already bound symbol or some other literal, in which case we
  335. ;; compare it with EQUAL?.
  336. ((match-two v x g+s (sk ...) fk (id ...))
  337. (let-syntax
  338. ((new-sym?
  339. (syntax-rules (id ...)
  340. ((new-sym? x sk2 fk2) sk2)
  341. ((new-sym? y sk2 fk2) fk2))))
  342. (new-sym? random-sym-to-match
  343. (let ((x v)) (sk ... (id ... x)))
  344. (if (equal? v x) (sk ... (id ...)) fk))))
  345. ))
  346. ;; QUASIQUOTE patterns
  347. (define-syntax match-quasiquote
  348. (syntax-rules (unquote unquote-splicing quasiquote)
  349. ((_ v (unquote p) g+s sk fk i)
  350. (match-one v p g+s sk fk i))
  351. ((_ v ((unquote-splicing p) . rest) g+s sk fk i)
  352. (if (pair? v)
  353. (match-one v
  354. (p . tmp)
  355. (match-quasiquote tmp rest g+s sk fk)
  356. fk
  357. i)
  358. fk))
  359. ((_ v (quasiquote p) g+s sk fk i . depth)
  360. (match-quasiquote v p g+s sk fk i #f . depth))
  361. ((_ v (unquote p) g+s sk fk i x . depth)
  362. (match-quasiquote v p g+s sk fk i . depth))
  363. ((_ v (unquote-splicing p) g+s sk fk i x . depth)
  364. (match-quasiquote v p g+s sk fk i . depth))
  365. ((_ v (p . q) g+s sk fk i . depth)
  366. (if (pair? v)
  367. (let ((w (car v)) (x (cdr v)))
  368. (match-quasiquote
  369. w p g+s
  370. (match-quasiquote-step x q g+s sk fk depth)
  371. fk i . depth))
  372. fk))
  373. ((_ v #(elt ...) g+s sk fk i . depth)
  374. (if (vector? v)
  375. (let ((ls (vector->list v)))
  376. (match-quasiquote ls (elt ...) g+s sk fk i . depth))
  377. fk))
  378. ((_ v x g+s sk fk i . depth)
  379. (match-one v 'x g+s sk fk i))))
  380. (define-syntax match-quasiquote-step
  381. (syntax-rules ()
  382. ((match-quasiquote-step x q g+s sk fk depth i)
  383. (match-quasiquote x q g+s sk fk i . depth))))
  384. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  385. ;; Utilities
  386. ;; Takes two values and just expands into the first.
  387. (define-syntax match-drop-ids
  388. (syntax-rules ()
  389. ((_ expr ids ...) expr)))
  390. (define-syntax match-tuck-ids
  391. (syntax-rules ()
  392. ((_ (letish args (expr ...)) ids ...)
  393. (letish args (expr ... ids ...)))))
  394. (define-syntax match-drop-first-arg
  395. (syntax-rules ()
  396. ((_ arg expr) expr)))
  397. ;; To expand an OR group we try each clause in succession, passing the
  398. ;; first that succeeds to the success continuation. On failure for
  399. ;; any clause, we just try the next clause, finally resorting to the
  400. ;; failure continuation fk if all clauses fail. The only trick is
  401. ;; that we want to unify the identifiers, so that the success
  402. ;; continuation can refer to a variable from any of the OR clauses.
  403. (define-syntax match-gen-or
  404. (syntax-rules ()
  405. ((_ v p g+s (sk ...) fk (i ...) ((id id-ls) ...))
  406. (let ((sk2 (lambda (id ...) (sk ... (i ... id ...)))))
  407. (match-gen-or-step v p g+s (match-drop-ids (sk2 id ...)) fk (i ...))))))
  408. (define-syntax match-gen-or-step
  409. (syntax-rules ()
  410. ((_ v () g+s sk fk . x)
  411. ;; no OR clauses, call the failure continuation
  412. fk)
  413. ((_ v (p) . x)
  414. ;; last (or only) OR clause, just expand normally
  415. (match-one v p . x))
  416. ((_ v (p . q) g+s sk fk i)
  417. ;; match one and try the remaining on failure
  418. (let ((fk2 (lambda () (match-gen-or-step v q g+s sk fk i))))
  419. (match-one v p g+s sk (fk2) i)))
  420. ))
  421. ;; We match a pattern (p ...) by matching the pattern p in a loop on
  422. ;; each element of the variable, accumulating the bound ids into lists.
  423. ;; Look at the body of the simple case - it's just a named let loop,
  424. ;; matching each element in turn to the same pattern. The only trick
  425. ;; is that we want to keep track of the lists of each extracted id, so
  426. ;; when the loop recurses we cons the ids onto their respective list
  427. ;; variables, and on success we bind the ids (what the user input and
  428. ;; expects to see in the success body) to the reversed accumulated
  429. ;; list IDs.
  430. (define-syntax match-gen-ellipsis
  431. (syntax-rules ()
  432. ((_ v p () g+s (sk ...) fk i ((id id-ls) ...))
  433. (match-check-identifier p
  434. ;; simplest case equivalent to (p ...), just bind the list
  435. (let ((p v))
  436. (if (list? p)
  437. (sk ... i)
  438. fk))
  439. ;; simple case, match all elements of the list
  440. (let loop ((ls v) (id-ls '()) ...)
  441. (cond
  442. ((null? ls)
  443. (let ((id (reverse id-ls)) ...) (sk ... i)))
  444. ((pair? ls)
  445. (let ((w (car ls)))
  446. (match-one w p ((car ls) (set-car! ls))
  447. (match-drop-ids (loop (cdr ls) (cons id id-ls) ...))
  448. fk i)))
  449. (else
  450. fk)))))
  451. ((_ v p r g+s (sk ...) fk i ((id id-ls) ...))
  452. ;; general case, trailing patterns to match, keep track of the
  453. ;; remaining list length so we don't need any backtracking
  454. (match-verify-no-ellipsis
  455. r
  456. (let* ((tail-len (length 'r))
  457. (ls v)
  458. (len (and (list? ls) (length ls))))
  459. (if (or (not len) (< len tail-len))
  460. fk
  461. (let loop ((ls ls) (n len) (id-ls '()) ...)
  462. (cond
  463. ((= n tail-len)
  464. (let ((id (reverse id-ls)) ...)
  465. (match-one ls r (#f #f) (sk ...) fk i)))
  466. ((pair? ls)
  467. (let ((w (car ls)))
  468. (match-one w p ((car ls) (set-car! ls))
  469. (match-drop-ids
  470. (loop (cdr ls) (- n 1) (cons id id-ls) ...))
  471. fk
  472. i)))
  473. (else
  474. fk)))))))))
  475. ;; This is just a safety check. Although unlike syntax-rules we allow
  476. ;; trailing patterns after an ellipsis, we explicitly disable multiple
  477. ;; ellipses at the same level. This is because in the general case
  478. ;; such patterns are exponential in the number of ellipses, and we
  479. ;; don't want to make it easy to construct very expensive operations
  480. ;; with simple looking patterns. For example, it would be O(n^2) for
  481. ;; patterns like (a ... b ...) because we must consider every trailing
  482. ;; element for every possible break for the leading "a ...".
  483. (define-syntax match-verify-no-ellipsis
  484. (syntax-rules ()
  485. ((_ (x . y) sk)
  486. (match-check-ellipsis
  487. x
  488. (match-syntax-error
  489. "multiple ellipsis patterns not allowed at same level")
  490. (match-verify-no-ellipsis y sk)))
  491. ((_ () sk)
  492. sk)
  493. ((_ x sk)
  494. (match-syntax-error "dotted tail not allowed after ellipsis" x))))
  495. ;; To implement the tree search, we use two recursive procedures. TRY
  496. ;; attempts to match Y once, and on success it calls the normal SK on
  497. ;; the accumulated list ids as in MATCH-GEN-ELLIPSIS. On failure, we
  498. ;; call NEXT which first checks if the current value is a list
  499. ;; beginning with X, then calls TRY on each remaining element of the
  500. ;; list. Since TRY will recursively call NEXT again on failure, this
  501. ;; effects a full depth-first search.
  502. ;;
  503. ;; The failure continuation throughout is a jump to the next step in
  504. ;; the tree search, initialized with the original failure continuation
  505. ;; FK.
  506. (define-syntax match-gen-search
  507. (syntax-rules ()
  508. ((match-gen-search v p q g+s sk fk i ((id id-ls) ...))
  509. (letrec ((try (lambda (w fail id-ls ...)
  510. (match-one w q g+s
  511. (match-tuck-ids
  512. (let ((id (reverse id-ls)) ...)
  513. sk))
  514. (next w fail id-ls ...) i)))
  515. (next (lambda (w fail id-ls ...)
  516. (if (not (pair? w))
  517. (fail)
  518. (let ((u (car w)))
  519. (match-one
  520. u p ((car w) (set-car! w))
  521. (match-drop-ids
  522. ;; accumulate the head variables from
  523. ;; the p pattern, and loop over the tail
  524. (let ((id-ls (cons id id-ls)) ...)
  525. (let lp ((ls (cdr w)))
  526. (if (pair? ls)
  527. (try (car ls)
  528. (lambda () (lp (cdr ls)))
  529. id-ls ...)
  530. (fail)))))
  531. (fail) i))))))
  532. ;; the initial id-ls binding here is a dummy to get the right
  533. ;; number of '()s
  534. (let ((id-ls '()) ...)
  535. (try v (lambda () fk) id-ls ...))))))
  536. ;; Vector patterns are just more of the same, with the slight
  537. ;; exception that we pass around the current vector index being
  538. ;; matched.
  539. (define-syntax match-vector
  540. (syntax-rules (___)
  541. ((_ v n pats (p q) . x)
  542. (match-check-ellipsis q
  543. (match-gen-vector-ellipsis v n pats p . x)
  544. (match-vector-two v n pats (p q) . x)))
  545. ((_ v n pats (p ___) sk fk i)
  546. (match-gen-vector-ellipsis v n pats p sk fk i))
  547. ((_ . x)
  548. (match-vector-two . x))))
  549. ;; Check the exact vector length, then check each element in turn.
  550. (define-syntax match-vector-two
  551. (syntax-rules ()
  552. ((_ v n ((pat index) ...) () sk fk i)
  553. (if (vector? v)
  554. (let ((len (vector-length v)))
  555. (if (= len n)
  556. (match-vector-step v ((pat index) ...) sk fk i)
  557. fk))
  558. fk))
  559. ((_ v n (pats ...) (p . q) . x)
  560. (match-vector v (+ n 1) (pats ... (p n)) q . x))))
  561. (define-syntax match-vector-step
  562. (syntax-rules ()
  563. ((_ v () (sk ...) fk i) (sk ... i))
  564. ((_ v ((pat index) . rest) sk fk i)
  565. (let ((w (vector-ref v index)))
  566. (match-one w pat ((vector-ref v index) (vector-set! v index))
  567. (match-vector-step v rest sk fk)
  568. fk i)))))
  569. ;; With a vector ellipsis pattern we first check to see if the vector
  570. ;; length is at least the required length.
  571. (define-syntax match-gen-vector-ellipsis
  572. (syntax-rules ()
  573. ((_ v n ((pat index) ...) p sk fk i)
  574. (if (vector? v)
  575. (let ((len (vector-length v)))
  576. (if (>= len n)
  577. (match-vector-step v ((pat index) ...)
  578. (match-vector-tail v p n len sk fk)
  579. fk i)
  580. fk))
  581. fk))))
  582. (define-syntax match-vector-tail
  583. (syntax-rules ()
  584. ((_ v p n len sk fk i)
  585. (match-extract-vars p (match-vector-tail-two v p n len sk fk i) i ()))))
  586. (define-syntax match-vector-tail-two
  587. (syntax-rules ()
  588. ((_ v p n len (sk ...) fk i ((id id-ls) ...))
  589. (let loop ((j n) (id-ls '()) ...)
  590. (if (>= j len)
  591. (let ((id (reverse id-ls)) ...) (sk ... i))
  592. (let ((w (vector-ref v j)))
  593. (match-one w p ((vector-ref v j) (vector-set! v j))
  594. (match-drop-ids (loop (+ j 1) (cons id id-ls) ...))
  595. fk i)))))))
  596. (define-syntax match-record-refs
  597. (syntax-rules ()
  598. ((_ v rec n (p . q) g+s sk fk i)
  599. (let ((w (slot-ref rec v n)))
  600. (match-one w p ((slot-ref rec v n) (slot-set! rec v n))
  601. (match-record-refs v rec (+ n 1) q g+s sk fk) fk i)))
  602. ((_ v rec n () g+s (sk ...) fk i)
  603. (sk ... i))))
  604. ;; Extract all identifiers in a pattern. A little more complicated
  605. ;; than just looking for symbols, we need to ignore special keywords
  606. ;; and non-pattern forms (such as the predicate expression in ?
  607. ;; patterns), and also ignore previously bound identifiers.
  608. ;;
  609. ;; Calls the continuation with all new vars as a list of the form
  610. ;; ((orig-var tmp-name) ...), where tmp-name can be used to uniquely
  611. ;; pair with the original variable (e.g. it's used in the ellipsis
  612. ;; generation for list variables).
  613. ;;
  614. ;; (match-extract-vars pattern continuation (ids ...) (new-vars ...))
  615. (define-syntax match-extract-vars
  616. (syntax-rules (_ ___ ..1 *** ? $ = quote quasiquote and or not get! set!)
  617. ((match-extract-vars (? pred . p) . x)
  618. (match-extract-vars p . x))
  619. ((match-extract-vars ($ rec . p) . x)
  620. (match-extract-vars p . x))
  621. ((match-extract-vars (= proc p) . x)
  622. (match-extract-vars p . x))
  623. ((match-extract-vars (quote x) (k ...) i v)
  624. (k ... v))
  625. ((match-extract-vars (quasiquote x) k i v)
  626. (match-extract-quasiquote-vars x k i v (#t)))
  627. ((match-extract-vars (and . p) . x)
  628. (match-extract-vars p . x))
  629. ((match-extract-vars (or . p) . x)
  630. (match-extract-vars p . x))
  631. ((match-extract-vars (not . p) . x)
  632. (match-extract-vars p . x))
  633. ;; A non-keyword pair, expand the CAR with a continuation to
  634. ;; expand the CDR.
  635. ((match-extract-vars (p q . r) k i v)
  636. (match-check-ellipsis
  637. q
  638. (match-extract-vars (p . r) k i v)
  639. (match-extract-vars p (match-extract-vars-step (q . r) k i v) i ())))
  640. ((match-extract-vars (p . q) k i v)
  641. (match-extract-vars p (match-extract-vars-step q k i v) i ()))
  642. ((match-extract-vars #(p ...) . x)
  643. (match-extract-vars (p ...) . x))
  644. ((match-extract-vars _ (k ...) i v) (k ... v))
  645. ((match-extract-vars ___ (k ...) i v) (k ... v))
  646. ((match-extract-vars *** (k ...) i v) (k ... v))
  647. ((match-extract-vars ..1 (k ...) i v) (k ... v))
  648. ;; This is the main part, the only place where we might add a new
  649. ;; var if it's an unbound symbol.
  650. ((match-extract-vars p (k ...) (i ...) v)
  651. (let-syntax
  652. ((new-sym?
  653. (syntax-rules (i ...)
  654. ((new-sym? p sk fk) sk)
  655. ((new-sym? any sk fk) fk))))
  656. (new-sym? random-sym-to-match
  657. (k ... ((p p-ls) . v))
  658. (k ... v))))
  659. ))
  660. ;; Stepper used in the above so it can expand the CAR and CDR
  661. ;; separately.
  662. (define-syntax match-extract-vars-step
  663. (syntax-rules ()
  664. ((_ p k i v ((v2 v2-ls) ...))
  665. (match-extract-vars p k (v2 ... . i) ((v2 v2-ls) ... . v)))
  666. ))
  667. (define-syntax match-extract-quasiquote-vars
  668. (syntax-rules (quasiquote unquote unquote-splicing)
  669. ((match-extract-quasiquote-vars (quasiquote x) k i v d)
  670. (match-extract-quasiquote-vars x k i v (#t . d)))
  671. ((match-extract-quasiquote-vars (unquote-splicing x) k i v d)
  672. (match-extract-quasiquote-vars (unquote x) k i v d))
  673. ((match-extract-quasiquote-vars (unquote x) k i v (#t))
  674. (match-extract-vars x k i v))
  675. ((match-extract-quasiquote-vars (unquote x) k i v (#t . d))
  676. (match-extract-quasiquote-vars x k i v d))
  677. ((match-extract-quasiquote-vars (x . y) k i v d)
  678. (match-extract-quasiquote-vars
  679. x
  680. (match-extract-quasiquote-vars-step y k i v d) i () d))
  681. ((match-extract-quasiquote-vars #(x ...) k i v d)
  682. (match-extract-quasiquote-vars (x ...) k i v d))
  683. ((match-extract-quasiquote-vars x (k ...) i v d)
  684. (k ... v))
  685. ))
  686. (define-syntax match-extract-quasiquote-vars-step
  687. (syntax-rules ()
  688. ((_ x k i v d ((v2 v2-ls) ...))
  689. (match-extract-quasiquote-vars x k (v2 ... . i) ((v2 v2-ls) ... . v) d))
  690. ))
  691. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  692. ;; Gimme some sugar baby.
  693. ;;> Shortcut for @scheme{lambda} + @scheme{match}. Creates a
  694. ;;> procedure of one argument, and matches that argument against each
  695. ;;> clause.
  696. (define-syntax match-lambda
  697. (syntax-rules ()
  698. ((_ (pattern . body) ...) (lambda (expr) (match expr (pattern . body) ...)))))
  699. ;;> Similar to @scheme{match-lambda}. Creates a procedure of any
  700. ;;> number of arguments, and matches the argument list against each
  701. ;;> clause.
  702. (define-syntax match-lambda*
  703. (syntax-rules ()
  704. ((_ (pattern . body) ...) (lambda expr (match expr (pattern . body) ...)))))
  705. ;;> Matches each var to the corresponding expression, and evaluates
  706. ;;> the body with all match variables in scope. Raises an error if
  707. ;;> any of the expressions fail to match. Syntax analogous to named
  708. ;;> let can also be used for recursive functions which match on their
  709. ;;> arguments as in @scheme{match-lambda*}.
  710. (define-syntax match-let
  711. (syntax-rules ()
  712. ((_ ((var value) ...) . body)
  713. (match-let/helper let () () ((var value) ...) . body))
  714. ((_ loop ((var init) ...) . body)
  715. (match-named-let loop () ((var init) ...) . body))))
  716. ;;> Similar to @scheme{match-let}, but analogously to @scheme{letrec}
  717. ;;> matches and binds the variables with all match variables in scope.
  718. (define-syntax match-letrec
  719. (syntax-rules ()
  720. ((_ ((var value) ...) . body)
  721. (match-let/helper letrec () () ((var value) ...) . body))))
  722. (define-syntax match-let/helper
  723. (syntax-rules ()
  724. ((_ let ((var expr) ...) () () . body)
  725. (let ((var expr) ...) . body))
  726. ((_ let ((var expr) ...) ((pat tmp) ...) () . body)
  727. (let ((var expr) ...)
  728. (match-let* ((pat tmp) ...)
  729. . body)))
  730. ((_ let (v ...) (p ...) (((a . b) expr) . rest) . body)
  731. (match-let/helper
  732. let (v ... (tmp expr)) (p ... ((a . b) tmp)) rest . body))
  733. ((_ let (v ...) (p ...) ((#(a ...) expr) . rest) . body)
  734. (match-let/helper
  735. let (v ... (tmp expr)) (p ... (#(a ...) tmp)) rest . body))
  736. ((_ let (v ...) (p ...) ((a expr) . rest) . body)
  737. (match-let/helper let (v ... (a expr)) (p ...) rest . body))))
  738. (define-syntax match-named-let
  739. (syntax-rules ()
  740. ((_ loop ((pat expr var) ...) () . body)
  741. (let loop ((var expr) ...)
  742. (match-let ((pat var) ...)
  743. . body)))
  744. ((_ loop (v ...) ((pat expr) . rest) . body)
  745. (match-named-let loop (v ... (pat expr tmp)) rest . body))))
  746. ;;> @subsubsubsection{@rawcode{(match-let* ((var value) ...) body ...)}}
  747. ;;> Similar to @scheme{match-let}, but analogously to @scheme{let*}
  748. ;;> matches and binds the variables in sequence, with preceding match
  749. ;;> variables in scope.
  750. (define-syntax match-let*
  751. (syntax-rules ()
  752. ((_ () . body)
  753. (let () . body))
  754. ((_ ((pat expr) . rest) . body)
  755. (match expr (pat (match-let* rest . body))))))
  756. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  757. ;; Otherwise COND-EXPANDed bits.
  758. ;; This *should* work, but doesn't :(
  759. ;; (define-syntax match-check-ellipsis
  760. ;; (syntax-rules (...)
  761. ;; ((_ ... sk fk) sk)
  762. ;; ((_ x sk fk) fk)))
  763. ;; This is a little more complicated, and introduces a new let-syntax,
  764. ;; but should work portably in any R[56]RS Scheme. Taylor Campbell
  765. ;; originally came up with the idea.
  766. (define-syntax match-check-ellipsis
  767. (syntax-rules ()
  768. ;; these two aren't necessary but provide fast-case failures
  769. ((match-check-ellipsis (a . b) success-k failure-k) failure-k)
  770. ((match-check-ellipsis #(a ...) success-k failure-k) failure-k)
  771. ;; matching an atom
  772. ((match-check-ellipsis id success-k failure-k)
  773. (let-syntax ((ellipsis? (syntax-rules ()
  774. ;; iff `id' is `...' here then this will
  775. ;; match a list of any length
  776. ((ellipsis? (foo id) sk fk) sk)
  777. ((ellipsis? other sk fk) fk))))
  778. ;; this list of three elements will only match the (foo id) list
  779. ;; above if `id' is `...'
  780. (ellipsis? (a b c) success-k failure-k)))))
  781. ;; This is portable but can be more efficient with non-portable
  782. ;; extensions. This trick was originally discovered by Oleg Kiselyov.
  783. (define-syntax match-check-identifier
  784. (syntax-rules ()
  785. ;; fast-case failures, lists and vectors are not identifiers
  786. ((_ (x . y) success-k failure-k) failure-k)
  787. ((_ #(x ...) success-k failure-k) failure-k)
  788. ;; x is an atom
  789. ((_ x success-k failure-k)
  790. (let-syntax
  791. ((sym?
  792. (syntax-rules ()
  793. ;; if the symbol `abracadabra' matches x, then x is a
  794. ;; symbol
  795. ((sym? x sk fk) sk)
  796. ;; otherwise x is a non-symbol datum
  797. ((sym? y sk fk) fk))))
  798. (sym? abracadabra success-k failure-k)))))