Another ridiculous test output workaround
[xuriella.git] / xslt.lisp
blob500431e6b1205d3141f3d6eb5c37bf4e9b915c4b
1 ;;; -*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
3 ;;; Copyright (c) 2007,2008 David Lichteblau, Ivan Shvedunov.
4 ;;; All rights reserved.
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; * Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; * Redistributions in binary form must reproduce the above
14 ;;; copyright notice, this list of conditions and the following
15 ;;; disclaimer in the documentation and/or other materials
16 ;;; provided with the distribution.
17 ;;;
18 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
19 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
22 ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
24 ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 (in-package :xuriella)
32 #+sbcl
33 (declaim (optimize (debug 2)))
36 (eval-when (:compile-toplevel :load-toplevel :execute)
37 (defvar *xsl* "http://www.w3.org/1999/XSL/Transform")
38 (defvar *xml* "http://www.w3.org/XML/1998/namespace")
39 (defvar *html* "http://www.w3.org/1999/xhtml"))
42 ;;;; XSLT-ERROR
44 (define-condition xslt-error (simple-error)
46 (:documentation "The class of all XSLT errors."))
48 (define-condition recoverable-xslt-error (xslt-error)
50 (:documentation "The class of recoverable XSLT errors."))
52 (defun xslt-error (fmt &rest args)
53 (error 'xslt-error :format-control fmt :format-arguments args))
55 (defun xslt-cerror (fmt &rest args)
56 (with-simple-restart (recover "recover")
57 (error 'recoverable-xslt-error
58 :format-control fmt
59 :format-arguments args)))
61 (defvar *debug* nil)
63 (defmacro handler-case* (form &rest clauses)
64 ;; like HANDLER-CASE if *DEBUG* is off. If it's on, don't establish
65 ;; a handler at all so that we see the real stack traces. (We could use
66 ;; HANDLER-BIND here and check at signalling time, but doesn't seem
67 ;; important.)
68 (let ((doit (gensym)))
69 `(flet ((,doit () ,form))
70 (if *debug*
71 (,doit)
72 (handler-case
73 (,doit)
74 ,@clauses)))))
76 (defun compile-xpath (xpath &optional env)
77 (handler-case*
78 (xpath:compile-xpath xpath env)
79 (xpath:xpath-error (c)
80 (xslt-error "~A" c))))
82 (defmacro with-stack-limit ((&optional) &body body)
83 `(invoke-with-stack-limit (lambda () ,@body)))
86 ;;;; Helper function and macro
88 (defun map-pipe-eagerly (fn pipe)
89 (xpath::enumerate pipe :key fn :result nil))
91 (defmacro do-pipe ((var pipe &optional result) &body body)
92 `(block nil
93 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
94 ,result))
97 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
99 (defparameter *namespaces* *initial-namespaces*)
101 (defvar *global-variable-declarations*)
102 (defvar *lexical-variable-declarations*)
104 (defvar *global-variable-values*)
105 (defvar *lexical-variable-values*)
107 (defclass xslt-environment () ())
109 (defun split-qname (str)
110 (handler-case
111 (multiple-value-bind (prefix local-name)
112 (cxml::split-qname str)
113 (unless
114 ;; FIXME: cxml should really offer a function that does
115 ;; checks for NCName and QName in a sensible way for user code.
116 ;; cxml::split-qname is tailored to the needs of the parser.
118 ;; For now, let's just check the syntax explicitly.
119 (and (or (null prefix) (xpath::nc-name-p prefix))
120 (xpath::nc-name-p local-name))
121 (xslt-error "not a qname: ~A" str))
122 (values prefix local-name))
123 (cxml:well-formedness-violation ()
124 (xslt-error "not a qname: ~A" str))))
126 (defun decode-qname (qname env attributep)
127 (multiple-value-bind (prefix local-name)
128 (split-qname qname)
129 (values local-name
130 (if (or prefix (not attributep))
131 (xpath-sys:environment-find-namespace env prefix)
133 prefix)))
135 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
136 (cdr (assoc prefix *namespaces* :test 'equal)))
138 (defun find-variable-index (local-name uri table)
139 (position (cons local-name uri) table :test 'equal))
141 (defun intern-global-variable (local-name uri)
142 (or (find-variable-index local-name uri *global-variable-declarations*)
143 (push-variable local-name uri *global-variable-declarations*)))
145 (defun push-variable (local-name uri table)
146 (prog1
147 (length table)
148 (vector-push-extend (cons local-name uri) table)))
150 (defun lexical-variable-value (index &optional (errorp t))
151 (let ((result (svref *lexical-variable-values* index)))
152 (when errorp
153 (assert (not (eq result 'unbound))))
154 result))
156 (defun (setf lexical-variable-value) (newval index)
157 (assert (not (eq newval 'unbound)))
158 (setf (svref *lexical-variable-values* index) newval))
160 (defun global-variable-value (index &optional (errorp t))
161 (let ((result (svref *global-variable-values* index)))
162 (when errorp
163 (assert (not (eq result 'unbound))))
164 result))
166 (defun (setf global-variable-value) (newval index)
167 (assert (not (eq newval 'unbound)))
168 (setf (svref *global-variable-values* index) newval))
170 (defmethod xpath-sys:environment-find-function
171 ((env xslt-environment) lname uri)
172 (if (string= uri "")
173 (or (xpath-sys:find-xpath-function lname *xsl*)
174 (xpath-sys:find-xpath-function lname uri))
175 (xpath-sys:find-xpath-function lname uri)))
177 (defmethod xpath-sys:environment-find-variable
178 ((env xslt-environment) lname uri)
179 (let ((index
180 (find-variable-index lname uri *lexical-variable-declarations*)))
181 (when index
182 (lambda (ctx)
183 (declare (ignore ctx))
184 (svref *lexical-variable-values* index)))))
186 (defclass lexical-xslt-environment (xslt-environment) ())
188 (defmethod xpath-sys:environment-find-variable
189 ((env lexical-xslt-environment) lname uri)
190 (or (call-next-method)
191 (let ((index
192 (find-variable-index lname uri *global-variable-declarations*)))
193 (when index
194 (xslt-trace-thunk
195 (lambda (ctx)
196 (declare (ignore ctx))
197 (svref *global-variable-values* index))
198 "global ~s (uri ~s) = ~s" lname uri :result)))))
200 (defclass global-variable-environment (xslt-environment)
201 ((initial-global-variable-thunks
202 :initarg :initial-global-variable-thunks
203 :accessor initial-global-variable-thunks)))
205 (defmethod xpath-sys:environment-find-variable
206 ((env global-variable-environment) lname uri)
207 (or (call-next-method)
208 (gethash (cons lname uri) (initial-global-variable-thunks env))))
211 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
212 ;;;;
213 ;;;; A sink that serializes only text not contained in any element.
215 (defmacro with-toplevel-text-output-sink ((var) &body body)
216 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
218 (defclass toplevel-text-output-sink (sax:default-handler)
219 ((target :initarg :target :accessor text-output-sink-target)
220 (depth :initform 0 :accessor textoutput-sink-depth)))
222 (defmethod sax:start-element ((sink toplevel-text-output-sink)
223 namespace-uri local-name qname attributes)
224 (declare (ignore namespace-uri local-name qname attributes))
225 (incf (textoutput-sink-depth sink)))
227 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
228 (when (zerop (textoutput-sink-depth sink))
229 (write-string data (text-output-sink-target sink))))
231 (defmethod sax:end-element ((sink toplevel-text-output-sink)
232 namespace-uri local-name qname)
233 (declare (ignore namespace-uri local-name qname))
234 (decf (textoutput-sink-depth sink)))
236 (defun invoke-with-toplevel-text-output-sink (fn)
237 (with-output-to-string (s)
238 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
241 ;;;; TEXT-FILTER
242 ;;;;
243 ;;;; A sink that passes through only text (at any level).
245 (defclass text-filter (sax:default-handler)
246 ((target :initarg :target :accessor text-filter-target)))
248 (defmethod sax:characters ((sink text-filter) data)
249 (sax:characters (text-filter-target sink) data))
251 (defmethod sax:end-document ((sink text-filter))
252 (sax:end-document (text-filter-target sink)))
254 (defun make-text-filter (target)
255 (make-instance 'text-filter :target target))
258 ;;;; Names
260 (defun of-name (local-name)
261 (stp:of-name local-name *xsl*))
263 (defun namep (node local-name)
264 (and (typep node '(or stp:element stp:attribute))
265 (equal (stp:namespace-uri node) *xsl*)
266 (equal (stp:local-name node) local-name)))
269 ;;;; PARSE-STYLESHEET
271 (defstruct stylesheet
272 (modes (make-hash-table :test 'equal))
273 (global-variables (make-empty-declaration-array))
274 (output-specification (make-output-specification))
275 (strip-tests nil)
276 (named-templates (make-hash-table :test 'equal))
277 (attribute-sets (make-hash-table :test 'equal))
278 (keys (make-hash-table :test 'equal))
279 (namespace-aliases (make-hash-table :test 'equal)))
281 (defstruct mode (templates nil))
283 (defun find-mode (stylesheet local-name &optional uri)
284 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
286 (defun ensure-mode (stylesheet &optional local-name uri)
287 (or (find-mode stylesheet local-name uri)
288 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
289 (make-mode))))
291 (defun ensure-mode/qname (stylesheet qname env)
292 (if qname
293 (multiple-value-bind (local-name uri)
294 (decode-qname qname env nil)
295 (ensure-mode stylesheet local-name uri))
296 (find-mode stylesheet nil)))
298 (defun acons-namespaces (element &optional (bindings *namespaces*))
299 (map-namespace-declarations (lambda (prefix uri)
300 (push (cons prefix uri) bindings))
301 element)
302 bindings)
304 (defun find-key (name stylesheet)
305 (or (gethash name (stylesheet-keys stylesheet))
306 (xslt-error "unknown key: ~a" name)))
308 (defun make-key (match use) (cons match use))
310 (defun key-match (key) (car key))
312 (defun key-use (key) (cdr key))
314 (defun add-key (stylesheet name match use)
315 (if (gethash name (stylesheet-keys stylesheet))
316 (xslt-error "duplicate key: ~a" name)
317 (setf (gethash name (stylesheet-keys stylesheet))
318 (make-key match use))))
320 (defvar *excluded-namespaces* (list *xsl*))
321 (defvar *empty-mode*)
322 (defvar *default-mode*)
324 (defvar *xsl-include-stack* nil)
326 (defun uri-to-pathname (uri)
327 (cxml::uri-to-pathname (puri:parse-uri uri)))
329 (defun parse-stylesheet-to-stp (input uri-resolver)
330 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
331 (<transform> (stp:document-element d)))
332 (strip-stylesheet <transform>)
333 ;; FIXME: handle embedded stylesheets
334 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
335 (or (equal (stp:local-name <transform>) "transform")
336 (equal (stp:local-name <transform>) "stylesheet")))
337 (xslt-error "not a stylesheet"))
338 (dolist (include (stp:filter-children (of-name "include") <transform>))
339 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
340 (stp:base-uri include)))
341 (uri (if uri-resolver
342 (funcall uri-resolver (puri:render-uri uri nil))
343 uri))
344 (str (puri:render-uri uri nil))
345 (pathname
346 (handler-case
347 (uri-to-pathname uri)
348 (cxml:xml-parse-error (c)
349 (xslt-error "cannot find included stylesheet ~A: ~A"
350 uri c)))))
351 (with-open-file
352 (stream pathname
353 :element-type '(unsigned-byte 8)
354 :if-does-not-exist nil)
355 (unless stream
356 (xslt-error "cannot find included stylesheet ~A at ~A"
357 uri pathname))
358 (when (find str *xsl-include-stack* :test #'equal)
359 (xslt-error "recursive inclusion of ~A" uri))
360 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
361 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
362 (stp:insert-child-after <transform>
363 (stp:copy <transform>2)
364 include)
365 (stp:detach include)))))
366 <transform>))
368 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
369 (defvar *apply-imports-limit*)
370 (defvar *import-priority*)
371 (defvar *extension-namespaces*)
373 (defmacro do-toplevel ((var xpath <transform>) &body body)
374 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
376 (defun map-toplevel (fn xpath <transform>)
377 (dolist (node (list-toplevel xpath <transform>))
378 (let ((*namespaces* *namespaces*))
379 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
380 (when (xpath-protocol:node-type-p ancestor :element)
381 (setf *namespaces* (acons-namespaces ancestor))))
382 (funcall fn node))))
384 (defun list-toplevel (xpath <transform>)
385 (labels ((recurse (sub)
386 (let ((subsubs
387 (xpath-sys:pipe-of
388 (xpath:evaluate "transform|stylesheet" sub))))
389 (xpath::append-pipes
390 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
391 (xpath::mappend-pipe #'recurse subsubs)))))
392 (xpath::sort-nodes (recurse <transform>))))
394 (defmacro with-parsed-prefixes ((node env) &body body)
395 `(invoke-with-parsed-prefixes (lambda () ,@body) ,node ,env))
397 (defun invoke-with-parsed-prefixes (fn node env)
398 (unless (or (namep node "stylesheet") (namep node "transform"))
399 (setf node (stp:parent node)))
400 (let ((*excluded-namespaces* (list *xsl*))
401 (*extension-namespaces* '()))
402 (parse-exclude-result-prefixes! node env)
403 (parse-extension-element-prefixes! node env)
404 (funcall fn)))
406 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
407 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
408 (instruction-base-uri (stp:base-uri <transform>))
409 (namespaces (acons-namespaces <transform>))
410 (apply-imports-limit (1+ *import-priority*))
411 (continuations '()))
412 (let ((*namespaces* namespaces))
413 (invoke-with-parsed-prefixes (constantly t) <transform> env))
414 (macrolet ((with-specials ((&optional) &body body)
415 `(let ((*instruction-base-uri* instruction-base-uri)
416 (*namespaces* namespaces)
417 (*apply-imports-limit* apply-imports-limit))
418 ,@body)))
419 (with-specials ()
420 (do-toplevel (import "import" <transform>)
421 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
422 (stp:base-uri import))))
423 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
424 continuations))))
425 (let ((import-priority
426 (incf *import-priority*))
427 (var-cont (prepare-global-variables stylesheet <transform>)))
428 ;; delay the rest of compilation until we've seen all global
429 ;; variables:
430 (lambda ()
431 (mapc #'funcall (nreverse continuations))
432 (with-specials ()
433 (let ((*import-priority* import-priority))
434 (funcall var-cont)
435 (parse-keys! stylesheet <transform> env)
436 (parse-templates! stylesheet <transform> env)
437 (parse-output! stylesheet <transform>)
438 (parse-strip/preserve-space! stylesheet <transform> env)
439 (parse-attribute-sets! stylesheet <transform> env)
440 (parse-namespace-aliases! stylesheet <transform> env))))))))
442 (defvar *xsl-import-stack* nil)
444 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
445 (let* ((uri (if uri-resolver
446 (funcall uri-resolver (puri:render-uri uri nil))
447 uri))
448 (str (puri:render-uri uri nil))
449 (pathname
450 (handler-case
451 (uri-to-pathname uri)
452 (cxml:xml-parse-error (c)
453 (xslt-error "cannot find imported stylesheet ~A: ~A"
454 uri c)))))
455 (with-open-file
456 (stream pathname
457 :element-type '(unsigned-byte 8)
458 :if-does-not-exist nil)
459 (unless stream
460 (xslt-error "cannot find imported stylesheet ~A at ~A"
461 uri pathname))
462 (when (find str *xsl-import-stack* :test #'equal)
463 (xslt-error "recursive inclusion of ~A" uri))
464 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
465 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
467 (defun parse-stylesheet (designator &key uri-resolver)
468 (xpath:with-namespaces ((nil #.*xsl*))
469 (let* ((*import-priority* 0)
470 (puri:*strict-parse* nil)
471 (stylesheet (make-stylesheet))
472 (env (make-instance 'lexical-xslt-environment))
473 (*excluded-namespaces* *excluded-namespaces*)
474 (*global-variable-declarations* (make-empty-declaration-array)))
475 (ensure-mode stylesheet nil)
476 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
477 ;; reverse attribute sets:
478 (let ((table (stylesheet-attribute-sets stylesheet)))
479 (maphash (lambda (k v)
480 (setf (gethash k table) (nreverse v)))
481 table))
482 stylesheet)))
484 (defun parse-attribute-sets! (stylesheet <transform> env)
485 (do-toplevel (elt "attribute-set" <transform>)
486 (with-parsed-prefixes (elt env)
487 (push (let* ((sets
488 (mapcar (lambda (qname)
489 (multiple-value-list (decode-qname qname env nil)))
490 (words
491 (stp:attribute-value elt "use-attribute-sets"))))
492 (instructions
493 (stp:map-children
494 'list
495 (lambda (child)
496 (unless (or (not (typep child 'stp:element))
497 (and (equal (stp:namespace-uri child) *xsl*)
498 (equal (stp:local-name child)
499 "attribute"))
500 (find (stp:namespace-uri child)
501 *extension-namespaces*
502 :test 'equal))
503 (xslt-error "non-attribute found in attribute set"))
504 (parse-instruction child))
505 elt))
506 (*lexical-variable-declarations*
507 (make-empty-declaration-array))
508 (thunk
509 (compile-instruction `(progn ,@instructions) env))
510 (n-variables (length *lexical-variable-declarations*)))
511 (lambda (ctx)
512 (with-stack-limit ()
513 (loop for (local-name uri nil) in sets do
514 (dolist (thunk (find-attribute-set local-name uri))
515 (funcall thunk ctx)))
516 (let ((*lexical-variable-values*
517 (make-variable-value-array n-variables)))
518 (funcall thunk ctx)))))
519 (gethash (multiple-value-bind (local-name uri)
520 (decode-qname (stp:attribute-value elt "name") env nil)
521 (cons local-name uri))
522 (stylesheet-attribute-sets stylesheet))))))
524 (defun parse-namespace-aliases! (stylesheet <transform> env)
525 (do-toplevel (elt "namespace-alias" <transform>)
526 (stp:with-attributes (stylesheet-prefix result-prefix) elt
527 (setf (gethash
528 (xpath-sys:environment-find-namespace env stylesheet-prefix)
529 (stylesheet-namespace-aliases stylesheet))
530 (xpath-sys:environment-find-namespace env result-prefix)))))
532 (defun parse-exclude-result-prefixes! (node env)
533 (stp:with-attributes (exclude-result-prefixes)
534 node
535 (dolist (prefix (words (or exclude-result-prefixes "")))
536 (if (equal prefix "#default")
537 (setf prefix nil)
538 (unless (cxml-stp-impl::nc-name-p prefix)
539 (xslt-error "invalid prefix: ~A" prefix)))
540 (push (or (xpath-sys:environment-find-namespace env prefix)
541 (xslt-error "namespace not found: ~A" prefix))
542 *excluded-namespaces*))))
544 (defun parse-extension-element-prefixes! (node env)
545 (stp:with-attributes (extension-element-prefixes)
546 node
547 (dolist (prefix (words (or extension-element-prefixes "")))
548 (if (equal prefix "#default")
549 (setf prefix nil)
550 (unless (cxml-stp-impl::nc-name-p prefix)
551 (xslt-error "invalid prefix: ~A" prefix)))
552 (let ((uri
553 (or (xpath-sys:environment-find-namespace env prefix)
554 (xslt-error "namespace not found: ~A" prefix))))
555 (unless (equal uri *xsl*)
556 (push uri *extension-namespaces*)
557 (push uri *excluded-namespaces*))))))
559 (defun parse-strip/preserve-space! (stylesheet <transform> env)
560 (xpath:with-namespaces ((nil #.*xsl*))
561 (do-toplevel (elt "strip-space|preserve-space" <transform>)
562 (let ((*namespaces* (acons-namespaces elt))
563 (mode
564 (if (equal (stp:local-name elt) "strip-space")
565 :strip
566 :preserve)))
567 (dolist (name-test (words (stp:attribute-value elt "elements")))
568 (let* ((pos (search ":*" name-test))
569 (test-function
570 (cond
571 ((eql pos (- (length name-test) 2))
572 (let* ((prefix (subseq name-test 0 pos))
573 (name-test-uri
574 (xpath-sys:environment-find-namespace env prefix)))
575 (unless (xpath::nc-name-p prefix)
576 (xslt-error "not an NCName: ~A" prefix))
577 (lambda (local-name uri)
578 (declare (ignore local-name))
579 (if (equal uri name-test-uri)
580 mode
581 nil))))
582 ((equal name-test "*")
583 (lambda (local-name uri)
584 (declare (ignore local-name uri))
585 mode))
587 (multiple-value-bind (name-test-local-name name-test-uri)
588 (decode-qname name-test env nil)
589 (lambda (local-name uri)
590 (if (and (equal local-name name-test-local-name)
591 (equal uri name-test-uri))
592 mode
593 nil)))))))
594 (push test-function (stylesheet-strip-tests stylesheet))))))))
596 (defstruct (output-specification
597 (:conc-name "OUTPUT-"))
598 method
599 indent
600 omit-xml-declaration
601 encoding)
603 (defun parse-output! (stylesheet <transform>)
604 (let ((outputs (list-toplevel "output" <transform>)))
605 (when outputs
606 (when (cdr outputs)
607 ;; FIXME:
608 ;; - concatenate cdata-section-elements
609 ;; - the others must not conflict
610 (error "oops, merging of output elements not supported yet"))
611 (let ((<output> (car outputs))
612 (spec (stylesheet-output-specification stylesheet)))
613 (stp:with-attributes (;; version
614 method
615 indent
616 encoding
617 ;;; media-type
618 ;;; doctype-system
619 ;;; doctype-public
620 omit-xml-declaration
621 ;;; standalone
622 ;;; cdata-section-elements
624 <output>
625 (setf (output-method spec) method)
626 (setf (output-indent spec) indent)
627 (setf (output-encoding spec) encoding)
628 (setf (output-omit-xml-declaration spec) omit-xml-declaration))))))
630 (defun make-empty-declaration-array ()
631 (make-array 1 :fill-pointer 0 :adjustable t))
633 (defun make-variable-value-array (n-lexical-variables)
634 (make-array n-lexical-variables :initial-element 'unbound))
636 (defun compile-global-variable (<variable> env) ;; also for <param>
637 (stp:with-attributes (name select) <variable>
638 (when (and select (stp:list-children <variable>))
639 (xslt-error "variable with select and body"))
640 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
641 (inner (cond
642 (select
643 (compile-xpath select env))
644 ((stp:list-children <variable>)
645 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
646 (inner-thunk (compile-instruction inner-sexpr env)))
647 (lambda (ctx)
648 (apply-to-result-tree-fragment ctx inner-thunk))))
650 (lambda (ctx)
651 (declare (ignore ctx))
652 ""))))
653 (n-lexical-variables (length *lexical-variable-declarations*)))
654 (xslt-trace-thunk
655 (lambda (ctx)
656 (let* ((*lexical-variable-values*
657 (make-variable-value-array n-lexical-variables)))
658 (funcall inner ctx)))
659 "global ~s (~s) = ~s" name select :result))))
661 (defstruct (variable-information
662 (:constructor make-variable)
663 (:conc-name "VARIABLE-"))
664 index
665 thunk
666 local-name
668 param-p
669 thunk-setter)
671 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
672 (let* ((*namespaces* (acons-namespaces <variable>))
673 (instruction-base-uri (stp:base-uri <variable>))
674 (*instruction-base-uri* instruction-base-uri)
675 (*excluded-namespaces* (list *xsl*))
676 (*extension-namespaces* '())
677 (qname (stp:attribute-value <variable> "name")))
678 (with-parsed-prefixes (<variable> global-env)
679 (unless qname
680 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
681 (multiple-value-bind (local-name uri)
682 (decode-qname qname global-env nil)
683 ;; For the normal compilation environment of templates, install it
684 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
685 (let ((index (intern-global-variable local-name uri)))
686 ;; For the evaluation of a global variable itself, build a thunk
687 ;; that lazily resolves other variables, stored into
688 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
689 (let* ((value-thunk :unknown)
690 (global-variable-thunk
691 (lambda (ctx)
692 (let ((v (global-variable-value index nil)))
693 (when (eq v 'seen)
694 (xslt-error "recursive variable definition"))
695 (cond
696 ((eq v 'unbound)
697 (setf (global-variable-value index) 'seen)
698 (setf (global-variable-value index)
699 (funcall value-thunk ctx)))
701 v)))))
702 (excluded-namespaces *excluded-namespaces*)
703 (extension-namespaces *extension-namespaces*)
704 (thunk-setter
705 (lambda ()
706 (let ((*instruction-base-uri* instruction-base-uri)
707 (*excluded-namespaces* excluded-namespaces)
708 (*extension-namespaces* extension-namespaces))
709 (setf value-thunk
710 (compile-global-variable <variable> global-env))))))
711 (setf (gethash (cons local-name uri)
712 (initial-global-variable-thunks global-env))
713 global-variable-thunk)
714 (make-variable :index index
715 :local-name local-name
716 :uri uri
717 :thunk global-variable-thunk
718 :param-p (namep <variable> "param")
719 :thunk-setter thunk-setter)))))))
721 (defun parse-keys! (stylesheet <transform> env)
722 (xpath:with-namespaces ((nil #.*xsl*))
723 (do-toplevel (<key> "key" <transform>)
724 (let ((*instruction-base-uri* (stp:base-uri <key>)))
725 (stp:with-attributes (name match use) <key>
726 (unless name (xslt-error "key name attribute not specified"))
727 (unless match (xslt-error "key match attribute not specified"))
728 (unless use (xslt-error "key use attribute not specified"))
729 (multiple-value-bind (local-name uri)
730 (decode-qname name env nil)
731 (add-key stylesheet
732 (cons local-name uri)
733 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
734 (compile-xpath use env))))))))
736 (defun prepare-global-variables (stylesheet <transform>)
737 (xpath:with-namespaces ((nil #.*xsl*))
738 (let* ((table (make-hash-table :test 'equal))
739 (global-env (make-instance 'global-variable-environment
740 :initial-global-variable-thunks table))
741 (specs '()))
742 (do-toplevel (<variable> "variable|param" <transform>)
743 (let ((var (parse-global-variable! <variable> global-env)))
744 (xslt-trace "parsing global variable ~s (uri ~s)"
745 (variable-local-name var)
746 (variable-uri var))
747 (when (find var
748 specs
749 :test (lambda (a b)
750 (and (equal (variable-local-name a)
751 (variable-local-name b))
752 (equal (variable-uri a)
753 (variable-uri b)))))
754 (xslt-error "duplicate definition for global variable ~A"
755 (variable-local-name var)))
756 (push var specs)))
757 (setf specs (nreverse specs))
758 (lambda ()
759 ;; now that the global environment knows about all variables, run the
760 ;; thunk setters to perform their compilation
761 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
762 (let ((table (stylesheet-global-variables stylesheet))
763 (newlen (length *global-variable-declarations*)))
764 (adjust-array table newlen :fill-pointer newlen)
765 (dolist (spec specs)
766 (setf (elt table (variable-index spec)) spec)))))))
768 (defun parse-templates! (stylesheet <transform> env)
769 (let ((i 0))
770 (do-toplevel (<template> "template" <transform>)
771 (let ((*namespaces* (acons-namespaces <template>))
772 (*instruction-base-uri* (stp:base-uri <template>)))
773 (with-parsed-prefixes (<template> env)
774 (dolist (template (compile-template <template> env i))
775 (let ((name (template-name template)))
776 (if name
777 (let* ((table (stylesheet-named-templates stylesheet))
778 (head (car (gethash name table))))
779 (when (and head (eql (template-import-priority head)
780 (template-import-priority template)))
781 ;; fixme: is this supposed to be a run-time error?
782 (xslt-error "conflicting templates for ~A" name))
783 (push template (gethash name table)))
784 (let ((mode (ensure-mode/qname stylesheet
785 (template-mode-qname template)
786 env)))
787 (setf (template-mode template) mode)
788 (push template (mode-templates mode))))))))
789 (incf i))))
792 ;;;; APPLY-STYLESHEET
794 (defvar *stylesheet*)
796 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
798 (defun unalias-uri (uri)
799 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
800 uri))
802 (defstruct (parameter
803 (:constructor make-parameter (value local-name &optional uri)))
804 (uri "")
805 local-name
806 value)
808 (defun find-parameter-value (local-name uri parameters)
809 (dolist (p parameters)
810 (when (and (equal (parameter-local-name p) local-name)
811 (equal (parameter-uri p) uri))
812 (return (parameter-value p)))))
814 (defvar *uri-resolver*)
816 (defun parse-allowing-microsoft-bom (pathname handler)
817 (with-open-file (s pathname :element-type '(unsigned-byte 8))
818 (unless (and (eql (read-byte s nil) #xef)
819 (eql (read-byte s nil) #xbb)
820 (eql (read-byte s nil) #xbf))
821 (file-position s 0))
822 (cxml:parse s handler)))
824 (defvar *documents*)
826 (defun %document (uri-string base-uri)
827 (let* ((absolute-uri
828 (puri:merge-uris uri-string (or base-uri "")))
829 (resolved-uri
830 (if *uri-resolver*
831 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
832 absolute-uri))
833 (pathname
834 (handler-case
835 (uri-to-pathname resolved-uri)
836 (cxml:xml-parse-error (c)
837 (xslt-error "cannot find referenced document ~A: ~A"
838 resolved-uri c))))
839 (xpath-root-node
840 (or (gethash pathname *documents*)
841 (setf (gethash pathname *documents*)
842 (make-whitespace-stripper
843 (handler-case
844 (parse-allowing-microsoft-bom pathname
845 (stp:make-builder))
846 ((or file-error cxml:xml-parse-error) (c)
847 (xslt-error "cannot parse referenced document ~A: ~A"
848 pathname c)))
849 (stylesheet-strip-tests *stylesheet*))))))
850 (when (puri:uri-fragment absolute-uri)
851 (xslt-error "use of fragment identifiers in document() not supported"))
852 xpath-root-node))
854 (xpath-sys:define-extension xslt *xsl*)
856 (defun document-base-uri (node)
857 (xpath-protocol:base-uri
858 (cond
859 ((xpath-protocol:node-type-p node :document)
860 (xpath::find-in-pipe-if
861 (lambda (x)
862 (xpath-protocol:node-type-p x :element))
863 (xpath-protocol:child-pipe node)))
864 ((xpath-protocol:node-type-p node :element)
865 node)
867 (xpath-protocol:parent-node node)))))
869 (xpath-sys:define-xpath-function/lazy
870 xslt :document
871 (object &optional node-set)
872 (let ((instruction-base-uri *instruction-base-uri*))
873 (lambda (ctx)
874 (let* ((object (funcall object ctx))
875 (node-set (and node-set (funcall node-set ctx)))
876 (base-uri
877 (if node-set
878 (document-base-uri (xpath::textually-first-node node-set))
879 instruction-base-uri)))
880 (xpath-sys:make-node-set
881 (if (xpath:node-set-p object)
882 (xpath:map-node-set->list
883 (lambda (node)
884 (%document (xpath:string-value node)
885 (if node-set
886 base-uri
887 (document-base-uri node))))
888 object)
889 (list (%document (xpath:string-value object) base-uri))))))))
891 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
892 (let ((namespaces *namespaces*))
893 (lambda (ctx)
894 (let* ((qname (xpath:string-value (funcall name ctx)))
895 (object (funcall object ctx))
896 (expanded-name
897 (multiple-value-bind (local-name uri)
898 (decode-qname/runtime qname namespaces nil)
899 (cons local-name uri)))
900 (key (find-key expanded-name *stylesheet*)))
901 (labels ((get-by-key (value)
902 (let ((value (xpath:string-value value)))
903 (xpath::filter-pipe
904 #'(lambda (node)
905 (let ((uses
906 (xpath:evaluate-compiled (key-use key) node)))
907 (if (xpath:node-set-p uses)
908 (xpath::find-in-pipe
909 value
910 (xpath-sys:pipe-of uses)
911 :key #'xpath:string-value
912 :test #'equal)
913 (equal value (xpath:string-value uses)))))
914 (xpath-sys:pipe-of
915 (xpath:node-set-value
916 (xpath:evaluate-compiled (key-match key) ctx)))))))
917 (xpath-sys:make-node-set
918 (xpath::sort-pipe
919 (if (xpath:node-set-p object)
920 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
921 (get-by-key object)))))))))
923 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
925 (xpath-sys:define-xpath-function/lazy xslt :current ()
926 #'(lambda (ctx)
927 (xpath-sys:make-node-set
928 (xpath-sys:make-pipe
929 (xpath:context-starting-node ctx)
930 nil))))
932 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
933 #'(lambda (ctx)
934 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
935 (funcall name ctx))
936 "")))
938 (defun %get-node-id (node)
939 (when (xpath:node-set-p node)
940 (setf node (xpath::textually-first-node node)))
941 (when node
942 (let ((id (xpath-sys:get-node-id node))
943 (highest-base-uri
944 (loop
945 for parent = node then next
946 for next = (xpath-protocol:parent-node parent)
947 for this-base-uri = (xpath-protocol:base-uri parent)
948 for highest-base-uri = (if (plusp (length this-base-uri))
949 this-base-uri
950 highest-base-uri)
951 while next
952 finally (return highest-base-uri))))
953 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
954 ;; checked only if everything else matches.
956 ;; This might be pointless premature optimization, but I like the idea :-)
957 (nreverse (concatenate 'string highest-base-uri "//" id)))))
959 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
960 (if node-set-thunk
961 #'(lambda (ctx)
962 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
963 #'(lambda (ctx)
964 (%get-node-id (xpath:context-node ctx)))))
966 (declaim (special *available-instructions*))
968 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
969 (let ((namespaces *namespaces*))
970 #'(lambda (ctx)
971 (let ((qname (funcall qname ctx)))
972 (multiple-value-bind (local-name uri)
973 (decode-qname/runtime qname namespaces nil)
974 (and (equal uri *xsl*)
975 (gethash local-name *available-instructions*)
976 t))))))
978 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
979 (let ((namespaces *namespaces*))
980 #'(lambda (ctx)
981 (let ((qname (funcall qname ctx)))
982 (multiple-value-bind (local-name uri)
983 (decode-qname/runtime qname namespaces nil)
984 (and (zerop (length uri))
985 (or (xpath-sys:find-xpath-function local-name *xsl*)
986 (xpath-sys:find-xpath-function local-name uri))
987 t))))))
989 (defun apply-stylesheet
990 (stylesheet source-designator
991 &key output parameters uri-resolver navigator)
992 (when (typep stylesheet 'xml-designator)
993 (setf stylesheet (parse-stylesheet stylesheet)))
994 (invoke-with-output-sink
995 (lambda ()
996 (handler-case*
997 (let* ((*documents* (make-hash-table :test 'equal))
998 (xpath:*navigator* (or navigator :default-navigator))
999 (puri:*strict-parse* nil)
1000 (*stylesheet* stylesheet)
1001 (*empty-mode* (make-mode))
1002 (*default-mode* (find-mode stylesheet nil))
1003 (global-variable-specs
1004 (stylesheet-global-variables stylesheet))
1005 (*global-variable-values*
1006 (make-variable-value-array (length global-variable-specs)))
1007 (*uri-resolver* uri-resolver)
1008 (source-document
1009 (if (typep source-designator 'xml-designator)
1010 (cxml:parse source-designator (stp:make-builder))
1011 source-designator))
1012 (xpath-root-node
1013 (make-whitespace-stripper
1014 source-document
1015 (stylesheet-strip-tests stylesheet)))
1016 (ctx (xpath:make-context xpath-root-node)))
1017 (when (pathnamep source-designator)
1018 (setf (gethash source-designator *documents*) xpath-root-node))
1019 (map nil
1020 (lambda (spec)
1021 (when (variable-param-p spec)
1022 (let ((value
1023 (find-parameter-value (variable-local-name spec)
1024 (variable-uri spec)
1025 parameters)))
1026 (when value
1027 (setf (global-variable-value (variable-index spec))
1028 value)))))
1029 global-variable-specs)
1030 (map nil
1031 (lambda (spec)
1032 (funcall (variable-thunk spec) ctx))
1033 global-variable-specs)
1034 ;; zzz we wouldn't have to mask float traps here if we used the
1035 ;; XPath API properly. Unfortunately I've been using FUNCALL
1036 ;; everywhere instead of EVALUATE, so let's paper over that
1037 ;; at a central place to be sure:
1038 (xpath::with-float-traps-masked ()
1039 (apply-templates ctx :mode *default-mode*)))
1040 (xpath:xpath-error (c)
1041 (xslt-error "~A" c))))
1042 (stylesheet-output-specification stylesheet)
1043 output))
1045 (defun find-attribute-set (local-name uri)
1046 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1047 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1049 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1050 (when sort-predicate
1051 (setf list (sort list sort-predicate)))
1052 (let* ((n (length list))
1053 (s/d (lambda () n)))
1054 (loop
1055 for i from 1
1056 for child in list
1058 (apply-templates (xpath:make-context child s/d i)
1059 :param-bindings param-bindings
1060 :mode mode))))
1062 (defvar *stack-limit* 200)
1064 (defun invoke-with-stack-limit (fn)
1065 (let ((*stack-limit* (1- *stack-limit*)))
1066 (unless (plusp *stack-limit*)
1067 (xslt-error "*stack-limit* reached; stack overflow"))
1068 (funcall fn)))
1070 (defun invoke-template (ctx template param-bindings)
1071 (let ((*lexical-variable-values*
1072 (make-variable-value-array (template-n-variables template))))
1073 (with-stack-limit ()
1074 (loop
1075 for (name-cons value) in param-bindings
1076 for (nil index nil) = (find name-cons
1077 (template-params template)
1078 :test #'equal
1079 :key #'car)
1081 (when index
1082 (setf (lexical-variable-value index) value)))
1083 (funcall (template-body template) ctx))))
1085 (defun apply-default-templates (ctx mode)
1086 (let ((node (xpath:context-node ctx)))
1087 (cond
1088 ((or (xpath-protocol:node-type-p node :processing-instruction)
1089 (xpath-protocol:node-type-p node :comment)))
1090 ((or (xpath-protocol:node-type-p node :text)
1091 (xpath-protocol:node-type-p node :attribute))
1092 (write-text (xpath-protocol:node-text node)))
1094 (apply-templates/list
1095 (xpath::force
1096 (xpath-protocol:child-pipe node))
1097 :mode mode)))))
1099 (defvar *apply-imports*)
1101 (defun apply-applicable-templates (ctx templates param-bindings finally)
1102 (labels ((apply-imports (&optional actual-param-bindings)
1103 (if templates
1104 (let* ((this (pop templates))
1105 (low (template-apply-imports-limit this))
1106 (high (template-import-priority this)))
1107 (setf templates
1108 (remove-if-not
1109 (lambda (x)
1110 (<= low (template-import-priority x) high))
1111 templates))
1112 (invoke-template ctx this actual-param-bindings))
1113 (funcall finally))))
1114 (let ((*apply-imports* #'apply-imports))
1115 (apply-imports param-bindings))))
1117 (defun apply-templates (ctx &key param-bindings mode)
1118 (apply-applicable-templates ctx
1119 (find-templates ctx (or mode *default-mode*))
1120 param-bindings
1121 (lambda ()
1122 (apply-default-templates ctx mode))))
1124 (defun call-template (ctx name &optional param-bindings)
1125 (apply-applicable-templates ctx
1126 (find-named-templates name)
1127 param-bindings
1128 (lambda ()
1129 (error "cannot find named template: ~s"
1130 name))))
1132 (defun find-templates (ctx mode)
1133 (let* ((matching-candidates
1134 (remove-if-not (lambda (template)
1135 (template-matches-p template ctx))
1136 (mode-templates mode)))
1137 (npriorities
1138 (if matching-candidates
1139 (1+ (reduce #'max
1140 matching-candidates
1141 :key #'template-import-priority))
1143 (priority-groups (make-array npriorities :initial-element nil)))
1144 (dolist (template matching-candidates)
1145 (push template
1146 (elt priority-groups (template-import-priority template))))
1147 (loop
1148 for i from (1- npriorities) downto 0
1149 for group = (elt priority-groups i)
1150 for template = (maximize #'template< group)
1151 when template
1152 collect template)))
1154 (defun find-named-templates (name)
1155 (gethash name (stylesheet-named-templates *stylesheet*)))
1157 (defun template< (a b) ;assuming same import priority
1158 (let ((p (template-priority a))
1159 (q (template-priority b)))
1160 (cond
1161 ((< p q) t)
1162 ((> p q) nil)
1164 (xslt-cerror "conflicting templates:~_~A,~_~A"
1165 (template-match-expression a)
1166 (template-match-expression b))
1167 (< (template-position a) (template-position b))))))
1169 (defun maximize (< things)
1170 (when things
1171 (let ((max (car things)))
1172 (dolist (other (cdr things))
1173 (when (funcall < max other)
1174 (setf max other)))
1175 max)))
1177 (defun template-matches-p (template ctx)
1178 (find (xpath:context-node ctx)
1179 (xpath:all-nodes (funcall (template-match-thunk template) ctx))))
1181 (defun invoke-with-output-sink (fn output-spec output)
1182 (etypecase output
1183 (pathname
1184 (with-open-file (s output
1185 :direction :output
1186 :element-type '(unsigned-byte 8)
1187 :if-exists :rename-and-delete)
1188 (invoke-with-output-sink fn output-spec s)))
1189 ((or stream null)
1190 (invoke-with-output-sink fn
1191 output-spec
1192 (make-output-sink output-spec output)))
1193 ((or hax:abstract-handler sax:abstract-handler)
1194 (with-xml-output output
1195 (funcall fn)))))
1197 (defun make-output-sink (output-spec stream)
1198 (let* ((ystream
1199 (if stream
1200 (let ((et (stream-element-type stream)))
1201 (cond
1202 ((or (null et) (subtypep et '(unsigned-byte 8)))
1203 (runes:make-octet-stream-ystream stream))
1204 ((subtypep et 'character)
1205 (runes:make-character-stream-ystream stream))))
1206 (runes:make-rod-ystream)))
1207 (omit-xml-declaration-p
1208 (equal (output-omit-xml-declaration output-spec) "yes"))
1209 (sax-target
1210 (make-instance 'cxml::sink
1211 :ystream ystream
1212 :omit-xml-declaration-p omit-xml-declaration-p)))
1213 (cond
1214 ((equalp (output-method output-spec) "HTML")
1215 (make-instance 'combi-sink
1216 :hax-target (make-instance 'chtml::sink
1217 :ystream ystream)
1218 :sax-target sax-target
1219 :encoding (output-encoding output-spec)))
1220 ((equalp (output-method output-spec) "TEXT")
1221 (make-text-filter sax-target))
1223 sax-target))))
1225 (defstruct template
1226 match-expression
1227 match-thunk
1228 name
1229 import-priority
1230 apply-imports-limit
1231 priority
1232 position
1233 mode
1234 mode-qname
1235 params
1236 body
1237 n-variables)
1239 (defun expression-priority (form)
1240 (let ((step (second form)))
1241 (if (and (null (cddr form))
1242 (listp step)
1243 (member (car step) '(:child :attribute))
1244 (null (cddr step)))
1245 (let ((name (second step)))
1246 (cond
1247 ((or (stringp name)
1248 (and (consp name)
1249 (or (eq (car name) :qname)
1250 (eq (car name) :processing-instruction))))
1251 0.0)
1252 ((and (consp name)
1253 (or (eq (car name) :namespace)
1254 (eq (car name) '*)))
1255 -0.25)
1257 -0.5)))
1258 0.5)))
1260 (defun valid-expression-p (expr)
1261 (cond
1262 ((atom expr) t)
1263 ((eq (first expr) :path)
1264 (every (lambda (x)
1265 (let ((filter (third x)))
1266 (or (null filter) (valid-expression-p filter))))
1267 (cdr expr)))
1268 ((eq (first expr) :variable) ;(!)
1269 nil)
1271 (every #'valid-expression-p (cdr expr)))))
1273 (defun parse-xpath (str)
1274 (handler-case
1275 (xpath:parse-xpath str)
1276 (xpath:xpath-error (c)
1277 (xslt-error "~A" c))))
1279 ;; zzz also use naive-pattern-expression here?
1280 (defun parse-key-pattern (str)
1281 (let ((parsed
1282 (mapcar #'(lambda (item)
1283 `(:path (:root :node)
1284 (:descendant-or-self *)
1285 ,@(cdr item)))
1286 (parse-pattern str))))
1287 (if (null (rest parsed))
1288 (first parsed)
1289 `(:union ,@parsed))))
1291 (defun parse-pattern (str)
1292 ;; zzz check here for anything not allowed as an XSLT pattern
1293 ;; zzz can we hack id() and key() here?
1294 (let ((form (parse-xpath str)))
1295 (unless (consp form)
1296 (xslt-error "not a valid pattern: ~A" str))
1297 (labels ((process-form (form)
1298 (cond ((eq (car form) :union)
1299 (alexandria:mappend #'process-form (rest form)))
1300 ((not (or (eq (car form) :path)
1301 (and (eq (car form) :filter)
1302 (let ((filter (second form)))
1303 (and (consp filter)
1304 (member (car filter)
1305 '(:key :id))))
1306 (equal (third form) '(:true)))
1307 (member (car form) '(:key :id))))
1308 (xslt-error "not a valid pattern: ~A ~A" str form))
1309 ((not (valid-expression-p form))
1310 (xslt-error "invalid filter"))
1311 (t (list form)))))
1312 (process-form form))))
1314 (defun naive-pattern-expression (x)
1315 (ecase (car x)
1316 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1317 ((:filter :key :id) x)))
1319 (defun compile-value-thunk (value env)
1320 (if (and (listp value) (eq (car value) 'progn))
1321 (let ((inner-thunk (compile-instruction value env)))
1322 (lambda (ctx)
1323 (apply-to-result-tree-fragment ctx inner-thunk)))
1324 (compile-xpath value env)))
1326 (defun compile-var-bindings/nointern (forms env)
1327 (loop
1328 for (name value) in forms
1329 collect (multiple-value-bind (local-name uri)
1330 (decode-qname name env nil)
1331 (list (cons local-name uri)
1332 (xslt-trace-thunk
1333 (compile-value-thunk value env)
1334 "local variable ~s = ~s" name :result)))))
1336 (defun compile-var-bindings (forms env)
1337 (loop
1338 for (cons thunk) in (compile-var-bindings/nointern forms env)
1339 for (local-name . uri) = cons
1340 collect (list cons
1341 (push-variable local-name
1343 *lexical-variable-declarations*)
1344 thunk)))
1346 (defun compile-template (<template> env position)
1347 (stp:with-attributes (match name priority mode) <template>
1348 (unless (or name match)
1349 (xslt-error "missing match in template"))
1350 (multiple-value-bind (params body-pos)
1351 (loop
1352 for i from 0
1353 for child in (stp:list-children <template>)
1354 while (namep child "param")
1355 collect (parse-param child) into params
1356 finally (return (values params i)))
1357 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1358 (param-bindings (compile-var-bindings params env))
1359 (body (parse-body <template> body-pos (mapcar #'car params)))
1360 (body-thunk (compile-instruction `(progn ,@body) env))
1361 (outer-body-thunk
1362 (xslt-trace-thunk
1363 #'(lambda (ctx)
1364 (unwind-protect
1365 (progn
1366 ;; set params that weren't initialized by apply-templates
1367 (loop for (name index param-thunk) in param-bindings
1368 when (eq (lexical-variable-value index nil) 'unbound)
1369 do (setf (lexical-variable-value index)
1370 (funcall param-thunk ctx)))
1371 (funcall body-thunk ctx))))
1372 "template: match = ~s name = ~s" match name))
1373 (n-variables (length *lexical-variable-declarations*)))
1374 (append
1375 (when name
1376 (multiple-value-bind (local-name uri)
1377 (decode-qname name env nil)
1378 (list
1379 (make-template :name (cons local-name uri)
1380 :import-priority *import-priority*
1381 :apply-imports-limit *apply-imports-limit*
1382 :params param-bindings
1383 :body outer-body-thunk
1384 :n-variables n-variables))))
1385 (when match
1386 (mapcar (lambda (expression)
1387 (let ((match-thunk
1388 (xslt-trace-thunk
1389 (compile-xpath
1390 `(xpath:xpath
1391 ,(naive-pattern-expression expression))
1392 env)
1393 "match-thunk for template (match ~s): ~s --> ~s"
1394 match expression :result))
1395 (p (if priority
1396 (parse-number:parse-number priority)
1397 (expression-priority expression))))
1398 (make-template :match-expression expression
1399 :match-thunk match-thunk
1400 :import-priority *import-priority*
1401 :apply-imports-limit *apply-imports-limit*
1402 :priority p
1403 :position position
1404 :mode-qname mode
1405 :params param-bindings
1406 :body outer-body-thunk
1407 :n-variables n-variables)))
1408 (parse-pattern match))))))))
1409 #+(or)
1410 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")