match.upstream.scm 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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. ;; 2012/05/23 - fixing combinatorial explosion of code in certain or patterns
  164. ;; 2011/09/25 - fixing bug when directly matching an identifier repeated in
  165. ;; the pattern (thanks to Stefan Israelsson Tampe)
  166. ;; 2011/01/27 - fixing bug when matching tail patterns against improper lists
  167. ;; 2010/09/26 - adding `..1' patterns (thanks to Ludovic Courtès)
  168. ;; 2010/09/07 - fixing identifier extraction in some `...' and `***' patterns
  169. ;; 2009/11/25 - adding `***' tree search patterns
  170. ;; 2008/03/20 - fixing bug where (a ...) matched non-lists
  171. ;; 2008/03/15 - removing redundant check in vector patterns
  172. ;; 2008/03/06 - you can use `...' portably now (thanks to Taylor Campbell)
  173. ;; 2007/09/04 - fixing quasiquote patterns
  174. ;; 2007/07/21 - allowing ellipse patterns in non-final list positions
  175. ;; 2007/04/10 - fixing potential hygiene issue in match-check-ellipse
  176. ;; (thanks to Taylor Campbell)
  177. ;; 2007/04/08 - clean up, commenting
  178. ;; 2006/12/24 - bugfixes
  179. ;; 2006/12/01 - non-linear patterns, shared variables in OR, get!/set!
  180. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  181. ;; force compile-time syntax errors with useful messages
  182. (define-syntax match-syntax-error
  183. (syntax-rules ()
  184. ((_) (match-syntax-error "invalid match-syntax-error usage"))))
  185. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  186. ;;> @subsubsection{Syntax}
  187. ;;> @subsubsubsection{@rawcode{(match expr (pattern . body) ...)@br{}
  188. ;;> (match expr (pattern (=> failure) . body) ...)}}
  189. ;;> The result of @var{expr} is matched against each @var{pattern} in
  190. ;;> turn, according to the pattern rules described in the previous
  191. ;;> section, until the the first @var{pattern} matches. When a match is
  192. ;;> found, the corresponding @var{body}s are evaluated in order,
  193. ;;> and the result of the last expression is returned as the result
  194. ;;> of the entire @scheme{match}. If a @var{failure} is provided,
  195. ;;> then it is bound to a procedure of no arguments which continues,
  196. ;;> processing at the next @var{pattern}. If no @var{pattern} matches,
  197. ;;> an error is signalled.
  198. ;; The basic interface. MATCH just performs some basic syntax
  199. ;; validation, binds the match expression to a temporary variable `v',
  200. ;; and passes it on to MATCH-NEXT. It's a constant throughout the
  201. ;; code below that the binding `v' is a direct variable reference, not
  202. ;; an expression.
  203. (define-syntax match
  204. (syntax-rules ()
  205. ((match)
  206. (match-syntax-error "missing match expression"))
  207. ((match atom)
  208. (match-syntax-error "no match clauses"))
  209. ((match (app ...) (pat . body) ...)
  210. (let ((v (app ...)))
  211. (match-next v ((app ...) (set! (app ...))) (pat . body) ...)))
  212. ((match #(vec ...) (pat . body) ...)
  213. (let ((v #(vec ...)))
  214. (match-next v (v (set! v)) (pat . body) ...)))
  215. ((match atom (pat . body) ...)
  216. (let ((v atom))
  217. (match-next v (atom (set! atom)) (pat . body) ...)))
  218. ))
  219. ;; MATCH-NEXT passes each clause to MATCH-ONE in turn with its failure
  220. ;; thunk, which is expanded by recursing MATCH-NEXT on the remaining
  221. ;; clauses. `g+s' is a list of two elements, the get! and set!
  222. ;; expressions respectively.
  223. (define-syntax match-next
  224. (syntax-rules (=>)
  225. ;; no more clauses, the match failed
  226. ((match-next v g+s)
  227. ;; Here we call error in non-tail context, so that the backtrace
  228. ;; can show the source location of the failing match form.
  229. (begin
  230. (error 'match "no matching pattern" v)
  231. #f))
  232. ;; named failure continuation
  233. ((match-next v g+s (pat (=> failure) . body) . rest)
  234. (let ((failure (lambda () (match-next v g+s . rest))))
  235. ;; match-one analyzes the pattern for us
  236. (match-one v pat g+s (match-drop-ids (begin . body)) (failure) ())))
  237. ;; anonymous failure continuation, give it a dummy name
  238. ((match-next v g+s (pat . body) . rest)
  239. (match-next v g+s (pat (=> failure) . body) . rest))))
  240. ;; MATCH-ONE first checks for ellipse patterns, otherwise passes on to
  241. ;; MATCH-TWO.
  242. (define-syntax match-one
  243. (syntax-rules ()
  244. ;; If it's a list of two or more values, check to see if the
  245. ;; second one is an ellipse and handle accordingly, otherwise go
  246. ;; to MATCH-TWO.
  247. ((match-one v (p q . r) g+s sk fk i)
  248. (match-check-ellipse
  249. q
  250. (match-extract-vars p (match-gen-ellipses v p r g+s sk fk i) i ())
  251. (match-two v (p q . r) g+s sk fk i)))
  252. ;; Go directly to MATCH-TWO.
  253. ((match-one . x)
  254. (match-two . x))))
  255. ;; This is the guts of the pattern matcher. We are passed a lot of
  256. ;; information in the form:
  257. ;;
  258. ;; (match-two var pattern getter setter success-k fail-k (ids ...))
  259. ;;
  260. ;; usually abbreviated
  261. ;;
  262. ;; (match-two v p g+s sk fk i)
  263. ;;
  264. ;; where VAR is the symbol name of the current variable we are
  265. ;; matching, PATTERN is the current pattern, getter and setter are the
  266. ;; corresponding accessors (e.g. CAR and SET-CAR! of the pair holding
  267. ;; VAR), SUCCESS-K is the success continuation, FAIL-K is the failure
  268. ;; continuation (which is just a thunk call and is thus safe to expand
  269. ;; multiple times) and IDS are the list of identifiers bound in the
  270. ;; pattern so far.
  271. (define-syntax match-two
  272. (syntax-rules (_ ___ ..1 *** quote quasiquote ? $ = and or not set! get!)
  273. ((match-two v () g+s (sk ...) fk i)
  274. (if (null? v) (sk ... i) fk))
  275. ((match-two v (quote p) g+s (sk ...) fk i)
  276. (if (equal? v 'p) (sk ... i) fk))
  277. ((match-two v (quasiquote p) . x)
  278. (match-quasiquote v p . x))
  279. ((match-two v (and) g+s (sk ...) fk i) (sk ... i))
  280. ((match-two v (and p q ...) g+s sk fk i)
  281. (match-one v p g+s (match-one v (and q ...) g+s sk fk) fk i))
  282. ((match-two v (or) g+s sk fk i) fk)
  283. ((match-two v (or p) . x)
  284. (match-one v p . x))
  285. ((match-two v (or p ...) g+s sk fk i)
  286. (match-extract-vars (or p ...) (match-gen-or v (p ...) g+s sk fk i) i ()))
  287. ((match-two v (not p) g+s (sk ...) fk i)
  288. (match-one v p g+s (match-drop-ids fk) (sk ... i) i))
  289. ((match-two v (get! getter) (g s) (sk ...) fk i)
  290. (let ((getter (lambda () g))) (sk ... i)))
  291. ((match-two v (set! setter) (g (s ...)) (sk ...) fk i)
  292. (let ((setter (lambda (x) (s ... x)))) (sk ... i)))
  293. ((match-two v (? pred . p) g+s sk fk i)
  294. (if (pred v) (match-one v (and . p) g+s sk fk i) fk))
  295. ((match-two v (= proc p) . x)
  296. (let ((w (proc v))) (match-one w p . x)))
  297. ((match-two v (p ___ . r) g+s sk fk i)
  298. (match-extract-vars p (match-gen-ellipses v p r g+s sk fk i) i ()))
  299. ((match-two v (p) g+s sk fk i)
  300. (if (and (pair? v) (null? (cdr v)))
  301. (let ((w (car v)))
  302. (match-one w p ((car v) (set-car! v)) sk fk i))
  303. fk))
  304. ((match-two v (p *** q) g+s sk fk i)
  305. (match-extract-vars p (match-gen-search v p q g+s sk fk i) i ()))
  306. ((match-two v (p *** . q) g+s sk fk i)
  307. (match-syntax-error "invalid use of ***" (p *** . q)))
  308. ((match-two v (p ..1) g+s sk fk i)
  309. (if (pair? v)
  310. (match-one v (p ___) g+s sk fk i)
  311. fk))
  312. ((match-two v ($ rec p ...) g+s sk fk i)
  313. (if (is-a? v rec)
  314. (match-record-refs v rec 0 (p ...) g+s sk fk i)
  315. fk))
  316. ((match-two v (p . q) g+s sk fk i)
  317. (if (pair? v)
  318. (let ((w (car v)) (x (cdr v)))
  319. (match-one w p ((car v) (set-car! v))
  320. (match-one x q ((cdr v) (set-cdr! v)) sk fk)
  321. fk
  322. i))
  323. fk))
  324. ((match-two v #(p ...) g+s . x)
  325. (match-vector v 0 () (p ...) . x))
  326. ((match-two v _ g+s (sk ...) fk i) (sk ... i))
  327. ;; Not a pair or vector or special literal, test to see if it's a
  328. ;; new symbol, in which case we just bind it, or if it's an
  329. ;; already bound symbol or some other literal, in which case we
  330. ;; compare it with EQUAL?.
  331. ((match-two v x g+s (sk ...) fk (id ...))
  332. (let-syntax
  333. ((new-sym?
  334. (syntax-rules (id ...)
  335. ((new-sym? x sk2 fk2) sk2)
  336. ((new-sym? y sk2 fk2) fk2))))
  337. (new-sym? random-sym-to-match
  338. (let ((x v)) (sk ... (id ... x)))
  339. (if (equal? v x) (sk ... (id ...)) fk))))
  340. ))
  341. ;; QUASIQUOTE patterns
  342. (define-syntax match-quasiquote
  343. (syntax-rules (unquote unquote-splicing quasiquote)
  344. ((_ v (unquote p) g+s sk fk i)
  345. (match-one v p g+s sk fk i))
  346. ((_ v ((unquote-splicing p) . rest) g+s sk fk i)
  347. (if (pair? v)
  348. (match-one v
  349. (p . tmp)
  350. (match-quasiquote tmp rest g+s sk fk)
  351. fk
  352. i)
  353. fk))
  354. ((_ v (quasiquote p) g+s sk fk i . depth)
  355. (match-quasiquote v p g+s sk fk i #f . depth))
  356. ((_ v (unquote p) g+s sk fk i x . depth)
  357. (match-quasiquote v p g+s sk fk i . depth))
  358. ((_ v (unquote-splicing p) g+s sk fk i x . depth)
  359. (match-quasiquote v p g+s sk fk i . depth))
  360. ((_ v (p . q) g+s sk fk i . depth)
  361. (if (pair? v)
  362. (let ((w (car v)) (x (cdr v)))
  363. (match-quasiquote
  364. w p g+s
  365. (match-quasiquote-step x q g+s sk fk depth)
  366. fk i . depth))
  367. fk))
  368. ((_ v #(elt ...) g+s sk fk i . depth)
  369. (if (vector? v)
  370. (let ((ls (vector->list v)))
  371. (match-quasiquote ls (elt ...) g+s sk fk i . depth))
  372. fk))
  373. ((_ v x g+s sk fk i . depth)
  374. (match-one v 'x g+s sk fk i))))
  375. (define-syntax match-quasiquote-step
  376. (syntax-rules ()
  377. ((match-quasiquote-step x q g+s sk fk depth i)
  378. (match-quasiquote x q g+s sk fk i . depth))))
  379. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  380. ;; Utilities
  381. ;; Takes two values and just expands into the first.
  382. (define-syntax match-drop-ids
  383. (syntax-rules ()
  384. ((_ expr ids ...) expr)))
  385. (define-syntax match-tuck-ids
  386. (syntax-rules ()
  387. ((_ (letish args (expr ...)) ids ...)
  388. (letish args (expr ... ids ...)))))
  389. (define-syntax match-drop-first-arg
  390. (syntax-rules ()
  391. ((_ arg expr) expr)))
  392. ;; To expand an OR group we try each clause in succession, passing the
  393. ;; first that succeeds to the success continuation. On failure for
  394. ;; any clause, we just try the next clause, finally resorting to the
  395. ;; failure continuation fk if all clauses fail. The only trick is
  396. ;; that we want to unify the identifiers, so that the success
  397. ;; continuation can refer to a variable from any of the OR clauses.
  398. (define-syntax match-gen-or
  399. (syntax-rules ()
  400. ((_ v p g+s (sk ...) fk (i ...) ((id id-ls) ...))
  401. (let ((sk2 (lambda (id ...) (sk ... (i ... id ...)))))
  402. (match-gen-or-step v p g+s (match-drop-ids (sk2 id ...)) fk (i ...))))))
  403. (define-syntax match-gen-or-step
  404. (syntax-rules ()
  405. ((_ v () g+s sk fk . x)
  406. ;; no OR clauses, call the failure continuation
  407. fk)
  408. ((_ v (p) . x)
  409. ;; last (or only) OR clause, just expand normally
  410. (match-one v p . x))
  411. ((_ v (p . q) g+s sk fk i)
  412. ;; match one and try the remaining on failure
  413. (let ((fk2 (lambda () (match-gen-or-step v q g+s sk fk i))))
  414. (match-one v p g+s sk (fk2) i)))
  415. ))
  416. ;; We match a pattern (p ...) by matching the pattern p in a loop on
  417. ;; each element of the variable, accumulating the bound ids into lists.
  418. ;; Look at the body of the simple case - it's just a named let loop,
  419. ;; matching each element in turn to the same pattern. The only trick
  420. ;; is that we want to keep track of the lists of each extracted id, so
  421. ;; when the loop recurses we cons the ids onto their respective list
  422. ;; variables, and on success we bind the ids (what the user input and
  423. ;; expects to see in the success body) to the reversed accumulated
  424. ;; list IDs.
  425. (define-syntax match-gen-ellipses
  426. (syntax-rules ()
  427. ((_ v p () g+s (sk ...) fk i ((id id-ls) ...))
  428. (match-check-identifier p
  429. ;; simplest case equivalent to (p ...), just bind the list
  430. (let ((p v))
  431. (if (list? p)
  432. (sk ... i)
  433. fk))
  434. ;; simple case, match all elements of the list
  435. (let loop ((ls v) (id-ls '()) ...)
  436. (cond
  437. ((null? ls)
  438. (let ((id (reverse id-ls)) ...) (sk ... i)))
  439. ((pair? ls)
  440. (let ((w (car ls)))
  441. (match-one w p ((car ls) (set-car! ls))
  442. (match-drop-ids (loop (cdr ls) (cons id id-ls) ...))
  443. fk i)))
  444. (else
  445. fk)))))
  446. ((_ v p r g+s (sk ...) fk i ((id id-ls) ...))
  447. ;; general case, trailing patterns to match, keep track of the
  448. ;; remaining list length so we don't need any backtracking
  449. (match-verify-no-ellipses
  450. r
  451. (let* ((tail-len (length 'r))
  452. (ls v)
  453. (len (and (list? ls) (length ls))))
  454. (if (or (not len) (< len tail-len))
  455. fk
  456. (let loop ((ls ls) (n len) (id-ls '()) ...)
  457. (cond
  458. ((= n tail-len)
  459. (let ((id (reverse id-ls)) ...)
  460. (match-one ls r (#f #f) (sk ...) fk i)))
  461. ((pair? ls)
  462. (let ((w (car ls)))
  463. (match-one w p ((car ls) (set-car! ls))
  464. (match-drop-ids
  465. (loop (cdr ls) (- n 1) (cons id id-ls) ...))
  466. fk
  467. i)))
  468. (else
  469. fk)))))))))
  470. ;; This is just a safety check. Although unlike syntax-rules we allow
  471. ;; trailing patterns after an ellipses, we explicitly disable multiple
  472. ;; ellipses at the same level. This is because in the general case
  473. ;; such patterns are exponential in the number of ellipses, and we
  474. ;; don't want to make it easy to construct very expensive operations
  475. ;; with simple looking patterns. For example, it would be O(n^2) for
  476. ;; patterns like (a ... b ...) because we must consider every trailing
  477. ;; element for every possible break for the leading "a ...".
  478. (define-syntax match-verify-no-ellipses
  479. (syntax-rules ()
  480. ((_ (x . y) sk)
  481. (match-check-ellipse
  482. x
  483. (match-syntax-error
  484. "multiple ellipse patterns not allowed at same level")
  485. (match-verify-no-ellipses y sk)))
  486. ((_ () sk)
  487. sk)
  488. ((_ x sk)
  489. (match-syntax-error "dotted tail not allowed after ellipse" x))))
  490. ;; To implement the tree search, we use two recursive procedures. TRY
  491. ;; attempts to match Y once, and on success it calls the normal SK on
  492. ;; the accumulated list ids as in MATCH-GEN-ELLIPSES. On failure, we
  493. ;; call NEXT which first checks if the current value is a list
  494. ;; beginning with X, then calls TRY on each remaining element of the
  495. ;; list. Since TRY will recursively call NEXT again on failure, this
  496. ;; effects a full depth-first search.
  497. ;;
  498. ;; The failure continuation throughout is a jump to the next step in
  499. ;; the tree search, initialized with the original failure continuation
  500. ;; FK.
  501. (define-syntax match-gen-search
  502. (syntax-rules ()
  503. ((match-gen-search v p q g+s sk fk i ((id id-ls) ...))
  504. (letrec ((try (lambda (w fail id-ls ...)
  505. (match-one w q g+s
  506. (match-tuck-ids
  507. (let ((id (reverse id-ls)) ...)
  508. sk))
  509. (next w fail id-ls ...) i)))
  510. (next (lambda (w fail id-ls ...)
  511. (if (not (pair? w))
  512. (fail)
  513. (let ((u (car w)))
  514. (match-one
  515. u p ((car w) (set-car! w))
  516. (match-drop-ids
  517. ;; accumulate the head variables from
  518. ;; the p pattern, and loop over the tail
  519. (let ((id-ls (cons id id-ls)) ...)
  520. (let lp ((ls (cdr w)))
  521. (if (pair? ls)
  522. (try (car ls)
  523. (lambda () (lp (cdr ls)))
  524. id-ls ...)
  525. (fail)))))
  526. (fail) i))))))
  527. ;; the initial id-ls binding here is a dummy to get the right
  528. ;; number of '()s
  529. (let ((id-ls '()) ...)
  530. (try v (lambda () fk) id-ls ...))))))
  531. ;; Vector patterns are just more of the same, with the slight
  532. ;; exception that we pass around the current vector index being
  533. ;; matched.
  534. (define-syntax match-vector
  535. (syntax-rules (___)
  536. ((_ v n pats (p q) . x)
  537. (match-check-ellipse q
  538. (match-gen-vector-ellipses v n pats p . x)
  539. (match-vector-two v n pats (p q) . x)))
  540. ((_ v n pats (p ___) sk fk i)
  541. (match-gen-vector-ellipses v n pats p sk fk i))
  542. ((_ . x)
  543. (match-vector-two . x))))
  544. ;; Check the exact vector length, then check each element in turn.
  545. (define-syntax match-vector-two
  546. (syntax-rules ()
  547. ((_ v n ((pat index) ...) () sk fk i)
  548. (if (vector? v)
  549. (let ((len (vector-length v)))
  550. (if (= len n)
  551. (match-vector-step v ((pat index) ...) sk fk i)
  552. fk))
  553. fk))
  554. ((_ v n (pats ...) (p . q) . x)
  555. (match-vector v (+ n 1) (pats ... (p n)) q . x))))
  556. (define-syntax match-vector-step
  557. (syntax-rules ()
  558. ((_ v () (sk ...) fk i) (sk ... i))
  559. ((_ v ((pat index) . rest) sk fk i)
  560. (let ((w (vector-ref v index)))
  561. (match-one w pat ((vector-ref v index) (vector-set! v index))
  562. (match-vector-step v rest sk fk)
  563. fk i)))))
  564. ;; With a vector ellipse pattern we first check to see if the vector
  565. ;; length is at least the required length.
  566. (define-syntax match-gen-vector-ellipses
  567. (syntax-rules ()
  568. ((_ v n ((pat index) ...) p sk fk i)
  569. (if (vector? v)
  570. (let ((len (vector-length v)))
  571. (if (>= len n)
  572. (match-vector-step v ((pat index) ...)
  573. (match-vector-tail v p n len sk fk)
  574. fk i)
  575. fk))
  576. fk))))
  577. (define-syntax match-vector-tail
  578. (syntax-rules ()
  579. ((_ v p n len sk fk i)
  580. (match-extract-vars p (match-vector-tail-two v p n len sk fk i) i ()))))
  581. (define-syntax match-vector-tail-two
  582. (syntax-rules ()
  583. ((_ v p n len (sk ...) fk i ((id id-ls) ...))
  584. (let loop ((j n) (id-ls '()) ...)
  585. (if (>= j len)
  586. (let ((id (reverse id-ls)) ...) (sk ... i))
  587. (let ((w (vector-ref v j)))
  588. (match-one w p ((vector-ref v j) (vetor-set! v j))
  589. (match-drop-ids (loop (+ j 1) (cons id id-ls) ...))
  590. fk i)))))))
  591. (define-syntax match-record-refs
  592. (syntax-rules ()
  593. ((_ v rec n (p . q) g+s sk fk i)
  594. (let ((w (slot-ref rec v n)))
  595. (match-one w p ((slot-ref rec v n) (slot-set! rec v n))
  596. (match-record-refs v rec (+ n 1) q g+s sk fk) fk i)))
  597. ((_ v rec n () g+s (sk ...) fk i)
  598. (sk ... i))))
  599. ;; Extract all identifiers in a pattern. A little more complicated
  600. ;; than just looking for symbols, we need to ignore special keywords
  601. ;; and non-pattern forms (such as the predicate expression in ?
  602. ;; patterns), and also ignore previously bound identifiers.
  603. ;;
  604. ;; Calls the continuation with all new vars as a list of the form
  605. ;; ((orig-var tmp-name) ...), where tmp-name can be used to uniquely
  606. ;; pair with the original variable (e.g. it's used in the ellipse
  607. ;; generation for list variables).
  608. ;;
  609. ;; (match-extract-vars pattern continuation (ids ...) (new-vars ...))
  610. (define-syntax match-extract-vars
  611. (syntax-rules (_ ___ ..1 *** ? $ = quote quasiquote and or not get! set!)
  612. ((match-extract-vars (? pred . p) . x)
  613. (match-extract-vars p . x))
  614. ((match-extract-vars ($ rec . p) . x)
  615. (match-extract-vars p . x))
  616. ((match-extract-vars (= proc p) . x)
  617. (match-extract-vars p . x))
  618. ((match-extract-vars (quote x) (k ...) i v)
  619. (k ... v))
  620. ((match-extract-vars (quasiquote x) k i v)
  621. (match-extract-quasiquote-vars x k i v (#t)))
  622. ((match-extract-vars (and . p) . x)
  623. (match-extract-vars p . x))
  624. ((match-extract-vars (or . p) . x)
  625. (match-extract-vars p . x))
  626. ((match-extract-vars (not . p) . x)
  627. (match-extract-vars p . x))
  628. ;; A non-keyword pair, expand the CAR with a continuation to
  629. ;; expand the CDR.
  630. ((match-extract-vars (p q . r) k i v)
  631. (match-check-ellipse
  632. q
  633. (match-extract-vars (p . r) k i v)
  634. (match-extract-vars p (match-extract-vars-step (q . r) k i v) i ())))
  635. ((match-extract-vars (p . q) k i v)
  636. (match-extract-vars p (match-extract-vars-step q k i v) i ()))
  637. ((match-extract-vars #(p ...) . x)
  638. (match-extract-vars (p ...) . x))
  639. ((match-extract-vars _ (k ...) i v) (k ... v))
  640. ((match-extract-vars ___ (k ...) i v) (k ... v))
  641. ((match-extract-vars *** (k ...) i v) (k ... v))
  642. ((match-extract-vars ..1 (k ...) i v) (k ... v))
  643. ;; This is the main part, the only place where we might add a new
  644. ;; var if it's an unbound symbol.
  645. ((match-extract-vars p (k ...) (i ...) v)
  646. (let-syntax
  647. ((new-sym?
  648. (syntax-rules (i ...)
  649. ((new-sym? p sk fk) sk)
  650. ((new-sym? any sk fk) fk))))
  651. (new-sym? random-sym-to-match
  652. (k ... ((p p-ls) . v))
  653. (k ... v))))
  654. ))
  655. ;; Stepper used in the above so it can expand the CAR and CDR
  656. ;; separately.
  657. (define-syntax match-extract-vars-step
  658. (syntax-rules ()
  659. ((_ p k i v ((v2 v2-ls) ...))
  660. (match-extract-vars p k (v2 ... . i) ((v2 v2-ls) ... . v)))
  661. ))
  662. (define-syntax match-extract-quasiquote-vars
  663. (syntax-rules (quasiquote unquote unquote-splicing)
  664. ((match-extract-quasiquote-vars (quasiquote x) k i v d)
  665. (match-extract-quasiquote-vars x k i v (#t . d)))
  666. ((match-extract-quasiquote-vars (unquote-splicing x) k i v d)
  667. (match-extract-quasiquote-vars (unquote x) k i v d))
  668. ((match-extract-quasiquote-vars (unquote x) k i v (#t))
  669. (match-extract-vars x k i v))
  670. ((match-extract-quasiquote-vars (unquote x) k i v (#t . d))
  671. (match-extract-quasiquote-vars x k i v d))
  672. ((match-extract-quasiquote-vars (x . y) k i v (#t . d))
  673. (match-extract-quasiquote-vars
  674. x
  675. (match-extract-quasiquote-vars-step y k i v d) i ()))
  676. ((match-extract-quasiquote-vars #(x ...) k i v (#t . d))
  677. (match-extract-quasiquote-vars (x ...) k i v d))
  678. ((match-extract-quasiquote-vars x (k ...) i v (#t . d))
  679. (k ... v))
  680. ))
  681. (define-syntax match-extract-quasiquote-vars-step
  682. (syntax-rules ()
  683. ((_ x k i v d ((v2 v2-ls) ...))
  684. (match-extract-quasiquote-vars x k (v2 ... . i) ((v2 v2-ls) ... . v) d))
  685. ))
  686. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  687. ;; Gimme some sugar baby.
  688. ;;> Shortcut for @scheme{lambda} + @scheme{match}. Creates a
  689. ;;> procedure of one argument, and matches that argument against each
  690. ;;> clause.
  691. (define-syntax match-lambda
  692. (syntax-rules ()
  693. ((_ (pattern . body) ...) (lambda (expr) (match expr (pattern . body) ...)))))
  694. ;;> Similar to @scheme{match-lambda}. Creates a procedure of any
  695. ;;> number of arguments, and matches the argument list against each
  696. ;;> clause.
  697. (define-syntax match-lambda*
  698. (syntax-rules ()
  699. ((_ (pattern . body) ...) (lambda expr (match expr (pattern . body) ...)))))
  700. ;;> Matches each var to the corresponding expression, and evaluates
  701. ;;> the body with all match variables in scope. Raises an error if
  702. ;;> any of the expressions fail to match. Syntax analogous to named
  703. ;;> let can also be used for recursive functions which match on their
  704. ;;> arguments as in @scheme{match-lambda*}.
  705. (define-syntax match-let
  706. (syntax-rules ()
  707. ((_ ((var value) ...) . body)
  708. (match-let/helper let () () ((var value) ...) . body))
  709. ((_ loop ((var init) ...) . body)
  710. (match-named-let loop ((var init) ...) . body))))
  711. ;;> Similar to @scheme{match-let}, but analogously to @scheme{letrec}
  712. ;;> matches and binds the variables with all match variables in scope.
  713. (define-syntax match-letrec
  714. (syntax-rules ()
  715. ((_ ((var value) ...) . body)
  716. (match-let/helper letrec () () ((var value) ...) . body))))
  717. (define-syntax match-let/helper
  718. (syntax-rules ()
  719. ((_ let ((var expr) ...) () () . body)
  720. (let ((var expr) ...) . body))
  721. ((_ let ((var expr) ...) ((pat tmp) ...) () . body)
  722. (let ((var expr) ...)
  723. (match-let* ((pat tmp) ...)
  724. . body)))
  725. ((_ let (v ...) (p ...) (((a . b) expr) . rest) . body)
  726. (match-let/helper
  727. let (v ... (tmp expr)) (p ... ((a . b) tmp)) rest . body))
  728. ((_ let (v ...) (p ...) ((#(a ...) expr) . rest) . body)
  729. (match-let/helper
  730. let (v ... (tmp expr)) (p ... (#(a ...) tmp)) rest . body))
  731. ((_ let (v ...) (p ...) ((a expr) . rest) . body)
  732. (match-let/helper let (v ... (a expr)) (p ...) rest . body))))
  733. (define-syntax match-named-let
  734. (syntax-rules ()
  735. ((_ loop ((pat expr var) ...) () . body)
  736. (let loop ((var expr) ...)
  737. (match-let ((pat var) ...)
  738. . body)))
  739. ((_ loop (v ...) ((pat expr) . rest) . body)
  740. (match-named-let loop (v ... (pat expr tmp)) rest . body))))
  741. ;;> @subsubsubsection{@rawcode{(match-let* ((var value) ...) body ...)}}
  742. ;;> Similar to @scheme{match-let}, but analogously to @scheme{let*}
  743. ;;> matches and binds the variables in sequence, with preceding match
  744. ;;> variables in scope.
  745. (define-syntax match-let*
  746. (syntax-rules ()
  747. ((_ () . body)
  748. (begin . body))
  749. ((_ ((pat expr) . rest) . body)
  750. (match expr (pat (match-let* rest . body))))))
  751. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  752. ;; Otherwise COND-EXPANDed bits.
  753. ;; This *should* work, but doesn't :(
  754. ;; (define-syntax match-check-ellipse
  755. ;; (syntax-rules (...)
  756. ;; ((_ ... sk fk) sk)
  757. ;; ((_ x sk fk) fk)))
  758. ;; This is a little more complicated, and introduces a new let-syntax,
  759. ;; but should work portably in any R[56]RS Scheme. Taylor Campbell
  760. ;; originally came up with the idea.
  761. (define-syntax match-check-ellipse
  762. (syntax-rules ()
  763. ;; these two aren't necessary but provide fast-case failures
  764. ((match-check-ellipse (a . b) success-k failure-k) failure-k)
  765. ((match-check-ellipse #(a ...) success-k failure-k) failure-k)
  766. ;; matching an atom
  767. ((match-check-ellipse id success-k failure-k)
  768. (let-syntax ((ellipse? (syntax-rules ()
  769. ;; iff `id' is `...' here then this will
  770. ;; match a list of any length
  771. ((ellipse? (foo id) sk fk) sk)
  772. ((ellipse? other sk fk) fk))))
  773. ;; this list of three elements will only many the (foo id) list
  774. ;; above if `id' is `...'
  775. (ellipse? (a b c) success-k failure-k)))))
  776. ;; This is portable but can be more efficient with non-portable
  777. ;; extensions. This trick was originally discovered by Oleg Kiselyov.
  778. (define-syntax match-check-identifier
  779. (syntax-rules ()
  780. ;; fast-case failures, lists and vectors are not identifiers
  781. ((_ (x . y) success-k failure-k) failure-k)
  782. ((_ #(x ...) success-k failure-k) failure-k)
  783. ;; x is an atom
  784. ((_ x success-k failure-k)
  785. (let-syntax
  786. ((sym?
  787. (syntax-rules ()
  788. ;; if the symbol `abracadabra' matches x, then x is a
  789. ;; symbol
  790. ((sym? x sk fk) sk)
  791. ;; otherwise x is a non-symbol datum
  792. ((sym? y sk fk) fk))))
  793. (sym? abracadabra success-k failure-k)))))