Check apply-templates child nodes
[xuriella.git] / xslt.lisp
blob62a77fd874144012da4e50c9c6ca63ff15f54827
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 functions and macros
88 (defun check-for-invalid-attributes (valid-names node)
89 (labels ((check-attribute (a)
90 (unless
91 (let ((uri (stp:namespace-uri a)))
92 (or (and (plusp (length uri)) (not (equal uri *xsl*)))
93 (find (cons (stp:local-name a) uri)
94 valid-names
95 :test #'equal)))
96 (xslt-error "attribute ~A not allowed on ~A"
97 (stp:local-name a)
98 (stp:local-name node)))))
99 (stp:map-attributes nil #'check-attribute node)))
101 (defmacro only-with-attributes ((&rest specs) node &body body)
102 (let ((valid-names
103 (mapcar (lambda (entry)
104 (if (and (listp entry) (cdr entry))
105 (destructuring-bind (name &optional (uri ""))
106 (cdr entry)
107 (cons name uri))
108 (cons (string-downcase
109 (princ-to-string
110 (symbol-name entry)))
111 "")))
112 specs))
113 (%node (gensym)))
114 `(let ((,%NODE ,node))
115 (check-for-invalid-attributes ',valid-names ,%NODE)
116 (stp:with-attributes ,specs ,%NODE
117 ,@body))))
119 (defun map-pipe-eagerly (fn pipe)
120 (xpath::enumerate pipe :key fn :result nil))
122 (defmacro do-pipe ((var pipe &optional result) &body body)
123 `(block nil
124 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
125 ,result))
128 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
130 (defparameter *namespaces*
131 '((nil . "")
132 ("xmlns" . #"http://www.w3.org/2000/xmlns/")
133 ("xml" . #"http://www.w3.org/XML/1998/namespace")))
135 (defvar *global-variable-declarations*)
136 (defvar *lexical-variable-declarations*)
138 (defvar *global-variable-values*)
139 (defvar *lexical-variable-values*)
141 (defclass xslt-environment () ())
143 (defun split-qname (str)
144 (handler-case
145 (multiple-value-bind (prefix local-name)
146 (cxml::split-qname str)
147 (unless
148 ;; FIXME: cxml should really offer a function that does
149 ;; checks for NCName and QName in a sensible way for user code.
150 ;; cxml::split-qname is tailored to the needs of the parser.
152 ;; For now, let's just check the syntax explicitly.
153 (and (or (null prefix) (xpath::nc-name-p prefix))
154 (xpath::nc-name-p local-name))
155 (xslt-error "not a qname: ~A" str))
156 (values prefix local-name))
157 (cxml:well-formedness-violation ()
158 (xslt-error "not a qname: ~A" str))))
160 (defun decode-qname (qname env attributep)
161 (multiple-value-bind (prefix local-name)
162 (split-qname qname)
163 (values local-name
164 (if (or prefix (not attributep))
165 (xpath-sys:environment-find-namespace env (or prefix ""))
167 prefix)))
169 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
170 (or (cdr (assoc prefix *namespaces* :test 'equal))
171 ;; zzz gross hack.
172 ;; Change the entire code base to represent "no prefix" as the
173 ;; empty string consistently. unparse.lisp has already been changed.
174 (and (equal prefix "")
175 (cdr (assoc nil *namespaces* :test 'equal)))
176 (and (eql prefix nil)
177 (cdr (assoc "" *namespaces* :test 'equal)))))
179 (defun find-variable-index (local-name uri table)
180 (position (cons local-name uri) table :test 'equal))
182 (defun intern-global-variable (local-name uri)
183 (or (find-variable-index local-name uri *global-variable-declarations*)
184 (push-variable local-name uri *global-variable-declarations*)))
186 (defun push-variable (local-name uri table)
187 (prog1
188 (length table)
189 (vector-push-extend (cons local-name uri) table)))
191 (defun lexical-variable-value (index &optional (errorp t))
192 (let ((result (svref *lexical-variable-values* index)))
193 (when errorp
194 (assert (not (eq result 'unbound))))
195 result))
197 (defun (setf lexical-variable-value) (newval index)
198 (assert (not (eq newval 'unbound)))
199 (setf (svref *lexical-variable-values* index) newval))
201 (defun global-variable-value (index &optional (errorp t))
202 (let ((result (svref *global-variable-values* index)))
203 (when errorp
204 (assert (not (eq result 'unbound))))
205 result))
207 (defun (setf global-variable-value) (newval index)
208 (assert (not (eq newval 'unbound)))
209 (setf (svref *global-variable-values* index) newval))
211 (defmethod xpath-sys:environment-find-function
212 ((env xslt-environment) lname uri)
213 (if (string= uri "")
214 (or (xpath-sys:find-xpath-function lname *xsl*)
215 (xpath-sys:find-xpath-function lname uri))
216 (xpath-sys:find-xpath-function lname uri)))
218 (defmethod xpath-sys:environment-find-variable
219 ((env xslt-environment) lname uri)
220 (let ((index
221 (find-variable-index lname uri *lexical-variable-declarations*)))
222 (when index
223 (lambda (ctx)
224 (declare (ignore ctx))
225 (svref *lexical-variable-values* index)))))
227 (defclass lexical-xslt-environment (xslt-environment) ())
229 (defmethod xpath-sys:environment-find-variable
230 ((env lexical-xslt-environment) lname uri)
231 (or (call-next-method)
232 (let ((index
233 (find-variable-index lname uri *global-variable-declarations*)))
234 (when index
235 (xslt-trace-thunk
236 (lambda (ctx)
237 (declare (ignore ctx))
238 (svref *global-variable-values* index))
239 "global ~s (uri ~s) = ~s" lname uri :result)))))
241 (defclass global-variable-environment (xslt-environment)
242 ((initial-global-variable-thunks
243 :initarg :initial-global-variable-thunks
244 :accessor initial-global-variable-thunks)))
246 (defmethod xpath-sys:environment-find-variable
247 ((env global-variable-environment) lname uri)
248 (or (call-next-method)
249 (gethash (cons lname uri) (initial-global-variable-thunks env))))
252 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
253 ;;;;
254 ;;;; A sink that serializes only text not contained in any element.
256 (defmacro with-toplevel-text-output-sink ((var) &body body)
257 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
259 (defclass toplevel-text-output-sink (sax:default-handler)
260 ((target :initarg :target :accessor text-output-sink-target)
261 (depth :initform 0 :accessor textoutput-sink-depth)))
263 (defmethod sax:start-element ((sink toplevel-text-output-sink)
264 namespace-uri local-name qname attributes)
265 (declare (ignore namespace-uri local-name qname attributes))
266 (incf (textoutput-sink-depth sink)))
268 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
269 (when (zerop (textoutput-sink-depth sink))
270 (write-string data (text-output-sink-target sink))))
272 (defmethod sax:unescaped ((sink toplevel-text-output-sink) data)
273 (sax:characters sink data))
275 (defmethod sax:end-element ((sink toplevel-text-output-sink)
276 namespace-uri local-name qname)
277 (declare (ignore namespace-uri local-name qname))
278 (decf (textoutput-sink-depth sink)))
280 (defun invoke-with-toplevel-text-output-sink (fn)
281 (with-output-to-string (s)
282 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
285 ;;;; TEXT-FILTER
286 ;;;;
287 ;;;; A sink that passes through only text (at any level) and turns to
288 ;;;; into unescaped characters.
290 (defclass text-filter (sax:default-handler)
291 ((target :initarg :target :accessor text-filter-target)))
293 (defmethod sax:characters ((sink text-filter) data)
294 (sax:unescaped (text-filter-target sink) data))
296 (defmethod sax:unescaped ((sink text-filter) data)
297 (sax:unescaped (text-filter-target sink) data))
299 (defmethod sax:end-document ((sink text-filter))
300 (sax:end-document (text-filter-target sink)))
302 (defun make-text-filter (target)
303 (make-instance 'text-filter :target target))
306 ;;;; ESCAPER
307 ;;;;
308 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
309 ;;;; XSLT 16.4.
311 (defclass escaper (cxml:broadcast-handler)
314 (defmethod sax:unescaped ((sink escaper) data)
315 (sax:characters sink data))
317 (defun make-escaper (target)
318 (make-instance 'escaper :handlers (list target)))
321 ;;;; Names
323 (defun of-name (local-name)
324 (stp:of-name local-name *xsl*))
326 (defun namep (node local-name)
327 (and (typep node '(or stp:element stp:attribute))
328 (equal (stp:namespace-uri node) *xsl*)
329 (equal (stp:local-name node) local-name)))
332 ;;;; PARSE-STYLESHEET
334 (defstruct stylesheet
335 (modes (make-hash-table :test 'equal))
336 (global-variables (make-empty-declaration-array))
337 (output-specification (make-output-specification))
338 (strip-tests nil)
339 (named-templates (make-hash-table :test 'equal))
340 (attribute-sets (make-hash-table :test 'equal))
341 (keys (make-hash-table :test 'equal))
342 (namespace-aliases (make-hash-table :test 'equal))
343 (decimal-formats (make-hash-table :test 'equal)))
345 (defstruct mode (templates nil))
347 (defun find-mode (stylesheet local-name &optional uri)
348 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
350 (defun ensure-mode (stylesheet &optional local-name uri)
351 (or (find-mode stylesheet local-name uri)
352 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
353 (make-mode))))
355 (defun ensure-mode/qname (stylesheet qname env)
356 (if qname
357 (multiple-value-bind (local-name uri)
358 (decode-qname qname env nil)
359 (ensure-mode stylesheet local-name uri))
360 (find-mode stylesheet nil)))
362 (defun acons-namespaces (element &optional (bindings *namespaces*))
363 (map-namespace-declarations (lambda (prefix uri)
364 (push (cons prefix uri) bindings))
365 element)
366 bindings)
368 (defun find-key (name stylesheet)
369 (or (gethash name (stylesheet-keys stylesheet))
370 (xslt-error "unknown key: ~a" name)))
372 (defun make-key (match use) (cons match use))
374 (defun key-match (key) (car key))
376 (defun key-use (key) (cdr key))
378 (defun add-key (stylesheet name match use)
379 (if (gethash name (stylesheet-keys stylesheet))
380 (xslt-error "duplicate key: ~a" name)
381 (setf (gethash name (stylesheet-keys stylesheet))
382 (make-key match use))))
384 (defvar *excluded-namespaces* (list *xsl*))
385 (defvar *empty-mode*)
386 (defvar *default-mode*)
388 (defvar *xsl-include-stack* nil)
390 (defun uri-to-pathname (uri)
391 (cxml::uri-to-pathname (puri:parse-uri uri)))
393 (defun unwrap-2.3 (document)
394 (let ((literal-result-element (stp:document-element document))
395 (new-template (stp:make-element "template" *xsl*))
396 (new-document-element (stp:make-element "stylesheet" *xsl*)))
397 (setf (stp:attribute-value new-document-element "version")
398 (or (stp:attribute-value literal-result-element "version" *xsl*)
399 (xslt-error "not a stylesheet: root element lacks xsl:version")))
400 (setf (stp:attribute-value new-template "match") "/")
401 (setf (stp:document-element document) new-document-element)
402 (stp:append-child new-document-element new-template)
403 (stp:append-child new-template literal-result-element)
404 new-document-element))
406 (defun parse-stylesheet-to-stp (input uri-resolver)
407 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
408 (<transform> (stp:document-element d)))
409 (unless (equal (stp:namespace-uri <transform>) *xsl*)
410 (setf <transform> (unwrap-2.3 d)))
411 (strip-stylesheet <transform>)
412 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
413 (or (equal (stp:local-name <transform>) "transform")
414 (equal (stp:local-name <transform>) "stylesheet")))
415 (xslt-error "not a stylesheet"))
416 (check-for-invalid-attributes '(("version" . "")
417 ("exclude-result-prefixes" . "")
418 ("extension-element-prefixes" . ""))
419 <transform>)
420 (let ((invalid
421 (or (stp:find-child-if (of-name "stylesheet") <transform>)
422 (stp:find-child-if (of-name "transform") <transform>))))
423 (when invalid
424 (xslt-error "invalid top-level element ~A" (stp:local-name invalid))))
425 (dolist (include (stp:filter-children (of-name "include") <transform>))
426 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
427 (stp:base-uri include)))
428 (uri (if uri-resolver
429 (funcall uri-resolver (puri:render-uri uri nil))
430 uri))
431 (str (puri:render-uri uri nil))
432 (pathname
433 (handler-case
434 (uri-to-pathname uri)
435 (cxml:xml-parse-error (c)
436 (xslt-error "cannot find included stylesheet ~A: ~A"
437 uri c)))))
438 (with-open-file
439 (stream pathname
440 :element-type '(unsigned-byte 8)
441 :if-does-not-exist nil)
442 (unless stream
443 (xslt-error "cannot find included stylesheet ~A at ~A"
444 uri pathname))
445 (when (find str *xsl-include-stack* :test #'equal)
446 (xslt-error "recursive inclusion of ~A" uri))
447 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
448 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
449 (stp:insert-child-after <transform>
450 (stp:copy <transform>2)
451 include)
452 (stp:detach include)))))
453 <transform>))
455 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
456 (defvar *apply-imports-limit*)
457 (defvar *import-priority*)
458 (defvar *extension-namespaces*)
459 (defvar *forwards-compatible-p*)
461 (defmacro do-toplevel ((var xpath <transform>) &body body)
462 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
464 (defun map-toplevel (fn xpath <transform>)
465 (dolist (node (list-toplevel xpath <transform>))
466 (let ((*namespaces* *namespaces*))
467 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
468 (when (xpath-protocol:node-type-p ancestor :element)
469 (setf *namespaces* (acons-namespaces ancestor))))
470 (funcall fn node))))
472 (defun list-toplevel (xpath <transform>)
473 (labels ((recurse (sub)
474 (let ((subsubs
475 (xpath-sys:pipe-of
476 (xpath:evaluate "transform|stylesheet" sub))))
477 (xpath::append-pipes
478 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
479 (xpath::mappend-pipe #'recurse subsubs)))))
480 (xpath::sort-nodes (recurse <transform>))))
482 (defmacro with-import-magic ((node env) &body body)
483 `(invoke-with-import-magic (lambda () ,@body) ,node ,env))
485 (defun invoke-with-import-magic (fn node env)
486 (unless (or (namep node "stylesheet") (namep node "transform"))
487 (setf node (stp:parent node)))
488 (let ((*excluded-namespaces* (list *xsl*))
489 (*extension-namespaces* '())
490 (*forwards-compatible-p*
491 (not (equal (stp:attribute-value node "version") "1.0"))))
492 (parse-exclude-result-prefixes! node env)
493 (parse-extension-element-prefixes! node env)
494 (funcall fn)))
496 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
497 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
498 (instruction-base-uri (stp:base-uri <transform>))
499 (namespaces (acons-namespaces <transform>))
500 (apply-imports-limit (1+ *import-priority*))
501 (continuations '()))
502 (let ((*namespaces* namespaces))
503 (invoke-with-import-magic (constantly t) <transform> env))
504 (do-toplevel (elt "node()" <transform>)
505 (when (equal (stp:attribute-value (stp:parent elt) "version") "1.0")
506 (if (typep elt 'stp:element)
507 (when (or (equal (stp:namespace-uri elt) "")
508 (and (equal (stp:namespace-uri elt) *xsl*)
509 (not (find (stp:local-name elt)
510 '("key" "template" "output" "strip-space"
511 "preserve-space" "attribute-set"
512 "namespace-alias" "decimal-format"
513 "variable" "param" "import" "include"
514 ;; for include handling:
515 "stylesheet" "transform")
516 :test #'equal))))
517 (xslt-error "unknown top-level element ~A" (stp:local-name elt)))
518 (xslt-error "text at top-level"))))
519 (macrolet ((with-specials ((&optional) &body body)
520 `(let ((*instruction-base-uri* instruction-base-uri)
521 (*namespaces* namespaces)
522 (*apply-imports-limit* apply-imports-limit))
523 ,@body)))
524 (with-specials ()
525 (do-toplevel (import "import" <transform>)
526 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
527 (stp:base-uri import))))
528 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
529 continuations))))
530 (let ((import-priority
531 (incf *import-priority*))
532 (var-cont (prepare-global-variables stylesheet <transform>)))
533 ;; delay the rest of compilation until we've seen all global
534 ;; variables:
535 (lambda ()
536 (mapc #'funcall (nreverse continuations))
537 (with-specials ()
538 (let ((*import-priority* import-priority))
539 (funcall var-cont)
540 (parse-keys! stylesheet <transform> env)
541 (parse-templates! stylesheet <transform> env)
542 (parse-output! stylesheet <transform>)
543 (parse-strip/preserve-space! stylesheet <transform> env)
544 (parse-attribute-sets! stylesheet <transform> env)
545 (parse-namespace-aliases! stylesheet <transform> env)
546 (parse-decimal-formats! stylesheet <transform> env))))))))
548 (defvar *xsl-import-stack* nil)
550 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
551 (let* ((uri (if uri-resolver
552 (funcall uri-resolver (puri:render-uri uri nil))
553 uri))
554 (str (puri:render-uri uri nil))
555 (pathname
556 (handler-case
557 (uri-to-pathname uri)
558 (cxml:xml-parse-error (c)
559 (xslt-error "cannot find imported stylesheet ~A: ~A"
560 uri c)))))
561 (with-open-file
562 (stream pathname
563 :element-type '(unsigned-byte 8)
564 :if-does-not-exist nil)
565 (unless stream
566 (xslt-error "cannot find imported stylesheet ~A at ~A"
567 uri pathname))
568 (when (find str *xsl-import-stack* :test #'equal)
569 (xslt-error "recursive inclusion of ~A" uri))
570 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
571 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
573 (defun parse-stylesheet (designator &key uri-resolver)
574 (xpath:with-namespaces ((nil #.*xsl*))
575 (let* ((*import-priority* 0)
576 (puri:*strict-parse* nil)
577 (stylesheet (make-stylesheet))
578 (env (make-instance 'lexical-xslt-environment))
579 (*excluded-namespaces* *excluded-namespaces*)
580 (*global-variable-declarations* (make-empty-declaration-array)))
581 (ensure-mode stylesheet nil)
582 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
583 ;; reverse attribute sets:
584 (let ((table (stylesheet-attribute-sets stylesheet)))
585 (maphash (lambda (k v)
586 (setf (gethash k table) (nreverse v)))
587 table))
588 ;; add default df
589 (unless (find-decimal-format "" "" stylesheet nil)
590 (setf (find-decimal-format "" "" stylesheet)
591 (make-decimal-format)))
592 stylesheet)))
594 (defun parse-attribute-sets! (stylesheet <transform> env)
595 (do-toplevel (elt "attribute-set" <transform>)
596 (with-import-magic (elt env)
597 (push (let* ((sets
598 (mapcar (lambda (qname)
599 (multiple-value-list (decode-qname qname env nil)))
600 (words
601 (stp:attribute-value elt "use-attribute-sets"))))
602 (instructions
603 (stp:map-children
604 'list
605 (lambda (child)
606 (unless
607 (and (typep child 'stp:element)
608 (or (and (equal (stp:namespace-uri child) *xsl*)
609 (equal (stp:local-name child)
610 "attribute"))
611 (find (stp:namespace-uri child)
612 *extension-namespaces*
613 :test 'equal)))
614 (xslt-error "non-attribute found in attribute set"))
615 (parse-instruction child))
616 elt))
617 (*lexical-variable-declarations*
618 (make-empty-declaration-array))
619 (thunk
620 (compile-instruction `(progn ,@instructions) env))
621 (n-variables (length *lexical-variable-declarations*)))
622 (lambda (ctx)
623 (with-stack-limit ()
624 (loop for (local-name uri nil) in sets do
625 (dolist (thunk (find-attribute-set local-name uri))
626 (funcall thunk ctx)))
627 (let ((*lexical-variable-values*
628 (make-variable-value-array n-variables)))
629 (funcall thunk ctx)))))
630 (gethash (multiple-value-bind (local-name uri)
631 (decode-qname (stp:attribute-value elt "name") env nil)
632 (cons local-name uri))
633 (stylesheet-attribute-sets stylesheet))))))
635 (defun parse-namespace-aliases! (stylesheet <transform> env)
636 (do-toplevel (elt "namespace-alias" <transform>)
637 (stp:with-attributes (stylesheet-prefix result-prefix) elt
638 (setf (gethash
639 (xpath-sys:environment-find-namespace env stylesheet-prefix)
640 (stylesheet-namespace-aliases stylesheet))
641 (xpath-sys:environment-find-namespace
643 (if (equal result-prefix "#default")
645 result-prefix))))))
647 (defun parse-decimal-formats! (stylesheet <transform> env)
648 (do-toplevel (elt "decimal-format" <transform>)
649 (stp:with-attributes (name
650 ;; strings
651 infinity
652 (nan "NaN")
653 ;; characters:
654 decimal-separator
655 grouping-separator
656 zero-digit
657 percent
658 per-mille
659 digit
660 pattern-separator
661 minus-sign)
663 (multiple-value-bind (local-name uri)
664 (if name
665 (decode-qname name env nil)
666 (values "" ""))
667 (unless (find-decimal-format local-name uri stylesheet nil)
668 (setf (find-decimal-format local-name uri stylesheet)
669 (let ((seen '()))
670 (flet ((chr (key x)
671 (when x
672 (unless (eql (length x) 1)
673 (xslt-error "not a single character: ~A" x))
674 (let ((chr (elt x 0)))
675 (when (find chr seen)
676 (xslt-error
677 "conflicting decimal format characters: ~A"
678 chr))
679 (push chr seen)
680 (list key chr))))
681 (str (key x)
682 (when x
683 (list key x))))
684 (apply #'make-decimal-format
685 (append (str :infinity infinity)
686 (str :nan nan)
687 (chr :decimal-separator decimal-separator)
688 (chr :grouping-separator grouping-separator)
689 (chr :zero-digit zero-digit)
690 (chr :percent percent)
691 (chr :per-mille per-mille)
692 (chr :digit digit)
693 (chr :pattern-separator pattern-separator)
694 (chr :minus-sign minus-sign)))))))))))
696 (defun parse-exclude-result-prefixes! (node env)
697 (stp:with-attributes (exclude-result-prefixes)
698 node
699 (dolist (prefix (words (or exclude-result-prefixes "")))
700 (if (equal prefix "#default")
701 (setf prefix nil)
702 (unless (cxml-stp-impl::nc-name-p prefix)
703 (xslt-error "invalid prefix: ~A" prefix)))
704 (push (or (xpath-sys:environment-find-namespace env prefix)
705 (xslt-error "namespace not found: ~A" prefix))
706 *excluded-namespaces*))))
708 (defun parse-extension-element-prefixes! (node env)
709 (stp:with-attributes (extension-element-prefixes)
710 node
711 (dolist (prefix (words (or extension-element-prefixes "")))
712 (if (equal prefix "#default")
713 (setf prefix nil)
714 (unless (cxml-stp-impl::nc-name-p prefix)
715 (xslt-error "invalid prefix: ~A" prefix)))
716 (let ((uri
717 (or (xpath-sys:environment-find-namespace env prefix)
718 (xslt-error "namespace not found: ~A" prefix))))
719 (unless (equal uri *xsl*)
720 (push uri *extension-namespaces*)
721 (push uri *excluded-namespaces*))))))
723 (defun parse-strip/preserve-space! (stylesheet <transform> env)
724 (xpath:with-namespaces ((nil #.*xsl*))
725 (do-toplevel (elt "strip-space|preserve-space" <transform>)
726 (let ((*namespaces* (acons-namespaces elt))
727 (mode
728 (if (equal (stp:local-name elt) "strip-space")
729 :strip
730 :preserve)))
731 (dolist (name-test (words (stp:attribute-value elt "elements")))
732 (let* ((pos (search ":*" name-test))
733 (test-function
734 (cond
735 ((eql pos (- (length name-test) 2))
736 (let* ((prefix (subseq name-test 0 pos))
737 (name-test-uri
738 (xpath-sys:environment-find-namespace env prefix)))
739 (unless (xpath::nc-name-p prefix)
740 (xslt-error "not an NCName: ~A" prefix))
741 (lambda (local-name uri)
742 (declare (ignore local-name))
743 (if (equal uri name-test-uri)
744 mode
745 nil))))
746 ((equal name-test "*")
747 (lambda (local-name uri)
748 (declare (ignore local-name uri))
749 mode))
751 (multiple-value-bind (name-test-local-name name-test-uri)
752 (decode-qname name-test env nil)
753 (lambda (local-name uri)
754 (if (and (equal local-name name-test-local-name)
755 (equal uri name-test-uri))
756 mode
757 nil)))))))
758 (push test-function (stylesheet-strip-tests stylesheet))))))))
760 (defstruct (output-specification
761 (:conc-name "OUTPUT-"))
762 method
763 indent
764 omit-xml-declaration
765 encoding
766 doctype-system
767 doctype-public)
769 (defun parse-output! (stylesheet <transform>)
770 (dolist (<output> (list-toplevel "output" <transform>))
771 (let ((spec (stylesheet-output-specification stylesheet)))
772 (stp:with-attributes ( ;; version
773 method
774 indent
775 encoding
776 ;;; media-type
777 doctype-system
778 doctype-public
779 omit-xml-declaration
780 ;;; standalone
781 ;;; cdata-section-elements
783 <output>
784 (when method
785 (setf (output-method spec) method))
786 (when indent
787 (setf (output-indent spec) indent))
788 (when encoding
789 (setf (output-encoding spec) encoding))
790 (when doctype-system
791 (setf (output-doctype-system spec) doctype-system))
792 (when doctype-public
793 (setf (output-doctype-public spec) doctype-public))
794 (when omit-xml-declaration
795 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
796 ;;; (when cdata-section-elements
797 ;;; (setf (output-cdata-section-elements spec)
798 ;;; (concatenate 'string
799 ;;; (output-cdata-section-elements spec)
800 ;;; " "
801 ;;; cdata-section-elements)))
802 ))))
804 (defun make-empty-declaration-array ()
805 (make-array 1 :fill-pointer 0 :adjustable t))
807 (defun make-variable-value-array (n-lexical-variables)
808 (make-array n-lexical-variables :initial-element 'unbound))
810 (defun compile-global-variable (<variable> env) ;; also for <param>
811 (stp:with-attributes (name select) <variable>
812 (when (and select (stp:list-children <variable>))
813 (xslt-error "variable with select and body"))
814 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
815 (inner (cond
816 (select
817 (compile-xpath select env))
818 ((stp:list-children <variable>)
819 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
820 (inner-thunk (compile-instruction inner-sexpr env)))
821 (lambda (ctx)
822 (apply-to-result-tree-fragment ctx inner-thunk))))
824 (lambda (ctx)
825 (declare (ignore ctx))
826 ""))))
827 (n-lexical-variables (length *lexical-variable-declarations*)))
828 (xslt-trace-thunk
829 (lambda (ctx)
830 (let* ((*lexical-variable-values*
831 (make-variable-value-array n-lexical-variables)))
832 (funcall inner ctx)))
833 "global ~s (~s) = ~s" name select :result))))
835 (defstruct (variable-information
836 (:constructor make-variable)
837 (:conc-name "VARIABLE-"))
838 index
839 thunk
840 local-name
842 param-p
843 thunk-setter)
845 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
846 (let* ((*namespaces* (acons-namespaces <variable>))
847 (instruction-base-uri (stp:base-uri <variable>))
848 (*instruction-base-uri* instruction-base-uri)
849 (*excluded-namespaces* (list *xsl*))
850 (*extension-namespaces* '())
851 (qname (stp:attribute-value <variable> "name")))
852 (with-import-magic (<variable> global-env)
853 (unless qname
854 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
855 (multiple-value-bind (local-name uri)
856 (decode-qname qname global-env nil)
857 ;; For the normal compilation environment of templates, install it
858 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
859 (let ((index (intern-global-variable local-name uri)))
860 ;; For the evaluation of a global variable itself, build a thunk
861 ;; that lazily resolves other variables, stored into
862 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
863 (let* ((value-thunk :unknown)
864 (global-variable-thunk
865 (lambda (ctx)
866 (let ((v (global-variable-value index nil)))
867 (when (eq v 'seen)
868 (xslt-error "recursive variable definition"))
869 (cond
870 ((eq v 'unbound)
871 (setf (global-variable-value index) 'seen)
872 (setf (global-variable-value index)
873 (funcall value-thunk ctx)))
875 v)))))
876 (excluded-namespaces *excluded-namespaces*)
877 (extension-namespaces *extension-namespaces*)
878 (thunk-setter
879 (lambda ()
880 (let ((*instruction-base-uri* instruction-base-uri)
881 (*excluded-namespaces* excluded-namespaces)
882 (*extension-namespaces* extension-namespaces))
883 (setf value-thunk
884 (compile-global-variable <variable> global-env))))))
885 (setf (gethash (cons local-name uri)
886 (initial-global-variable-thunks global-env))
887 global-variable-thunk)
888 (make-variable :index index
889 :local-name local-name
890 :uri uri
891 :thunk global-variable-thunk
892 :param-p (namep <variable> "param")
893 :thunk-setter thunk-setter)))))))
895 (defun parse-keys! (stylesheet <transform> env)
896 (xpath:with-namespaces ((nil #.*xsl*))
897 (do-toplevel (<key> "key" <transform>)
898 (let ((*instruction-base-uri* (stp:base-uri <key>)))
899 (stp:with-attributes (name match use) <key>
900 (unless name (xslt-error "key name attribute not specified"))
901 (unless match (xslt-error "key match attribute not specified"))
902 (unless use (xslt-error "key use attribute not specified"))
903 (multiple-value-bind (local-name uri)
904 (decode-qname name env nil)
905 (add-key stylesheet
906 (cons local-name uri)
907 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
908 (compile-xpath use env))))))))
910 (defun prepare-global-variables (stylesheet <transform>)
911 (xpath:with-namespaces ((nil #.*xsl*))
912 (let* ((table (make-hash-table :test 'equal))
913 (global-env (make-instance 'global-variable-environment
914 :initial-global-variable-thunks table))
915 (specs '()))
916 (do-toplevel (<variable> "variable|param" <transform>)
917 (let ((var (parse-global-variable! <variable> global-env)))
918 (xslt-trace "parsing global variable ~s (uri ~s)"
919 (variable-local-name var)
920 (variable-uri var))
921 (when (find var
922 specs
923 :test (lambda (a b)
924 (and (equal (variable-local-name a)
925 (variable-local-name b))
926 (equal (variable-uri a)
927 (variable-uri b)))))
928 (xslt-error "duplicate definition for global variable ~A"
929 (variable-local-name var)))
930 (push var specs)))
931 (setf specs (nreverse specs))
932 (lambda ()
933 ;; now that the global environment knows about all variables, run the
934 ;; thunk setters to perform their compilation
935 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
936 (let ((table (stylesheet-global-variables stylesheet))
937 (newlen (length *global-variable-declarations*)))
938 (adjust-array table newlen :fill-pointer newlen)
939 (dolist (spec specs)
940 (setf (elt table (variable-index spec)) spec)))))))
942 (defun parse-templates! (stylesheet <transform> env)
943 (let ((i 0))
944 (do-toplevel (<template> "template" <transform>)
945 (let ((*namespaces* (acons-namespaces <template>))
946 (*instruction-base-uri* (stp:base-uri <template>)))
947 (with-import-magic (<template> env)
948 (dolist (template (compile-template <template> env i))
949 (let ((name (template-name template)))
950 (if name
951 (let* ((table (stylesheet-named-templates stylesheet))
952 (head (car (gethash name table))))
953 (when (and head (eql (template-import-priority head)
954 (template-import-priority template)))
955 ;; fixme: is this supposed to be a run-time error?
956 (xslt-error "conflicting templates for ~A" name))
957 (push template (gethash name table)))
958 (let ((mode (ensure-mode/qname stylesheet
959 (template-mode-qname template)
960 env)))
961 (setf (template-mode template) mode)
962 (push template (mode-templates mode))))))))
963 (incf i))))
966 ;;;; APPLY-STYLESHEET
968 (defvar *stylesheet*)
970 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
972 (defun unalias-uri (uri)
973 (let ((result
974 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
975 uri)))
976 (check-type result string)
977 result))
979 (defstruct (parameter
980 (:constructor make-parameter (value local-name &optional uri)))
981 (uri "")
982 local-name
983 value)
985 (defun find-parameter-value (local-name uri parameters)
986 (dolist (p parameters)
987 (when (and (equal (parameter-local-name p) local-name)
988 (equal (parameter-uri p) uri))
989 (return (parameter-value p)))))
991 (defvar *uri-resolver*)
993 (defun parse-allowing-microsoft-bom (pathname handler)
994 (with-open-file (s pathname :element-type '(unsigned-byte 8))
995 (unless (and (eql (read-byte s nil) #xef)
996 (eql (read-byte s nil) #xbb)
997 (eql (read-byte s nil) #xbf))
998 (file-position s 0))
999 (cxml:parse s handler)))
1001 (defvar *documents*)
1003 (defun %document (uri-string base-uri)
1004 (let* ((absolute-uri
1005 (puri:merge-uris uri-string (or base-uri "")))
1006 (resolved-uri
1007 (if *uri-resolver*
1008 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
1009 absolute-uri))
1010 (pathname
1011 (handler-case
1012 (uri-to-pathname resolved-uri)
1013 (cxml:xml-parse-error (c)
1014 (xslt-error "cannot find referenced document ~A: ~A"
1015 resolved-uri c))))
1016 (xpath-root-node
1017 (or (gethash pathname *documents*)
1018 (setf (gethash pathname *documents*)
1019 (make-whitespace-stripper
1020 (handler-case
1021 (parse-allowing-microsoft-bom pathname
1022 (stp:make-builder))
1023 ((or file-error cxml:xml-parse-error) (c)
1024 (xslt-error "cannot parse referenced document ~A: ~A"
1025 pathname c)))
1026 (stylesheet-strip-tests *stylesheet*))))))
1027 (when (puri:uri-fragment absolute-uri)
1028 (xslt-error "use of fragment identifiers in document() not supported"))
1029 xpath-root-node))
1031 (xpath-sys:define-extension xslt *xsl*)
1033 (defun document-base-uri (node)
1034 (xpath-protocol:base-uri
1035 (cond
1036 ((xpath-protocol:node-type-p node :document)
1037 (xpath::find-in-pipe-if
1038 (lambda (x)
1039 (xpath-protocol:node-type-p x :element))
1040 (xpath-protocol:child-pipe node)))
1041 ((xpath-protocol:node-type-p node :element)
1042 node)
1044 (xpath-protocol:parent-node node)))))
1046 (xpath-sys:define-xpath-function/lazy
1047 xslt :document
1048 (object &optional node-set)
1049 (let ((instruction-base-uri *instruction-base-uri*))
1050 (lambda (ctx)
1051 (let* ((object (funcall object ctx))
1052 (node-set (and node-set (funcall node-set ctx)))
1053 (base-uri
1054 (if node-set
1055 (document-base-uri (xpath::textually-first-node node-set))
1056 instruction-base-uri)))
1057 (xpath-sys:make-node-set
1058 (if (xpath:node-set-p object)
1059 (xpath:map-node-set->list
1060 (lambda (node)
1061 (%document (xpath:string-value node)
1062 (if node-set
1063 base-uri
1064 (document-base-uri node))))
1065 object)
1066 (list (%document (xpath:string-value object) base-uri))))))))
1068 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1069 (let ((namespaces *namespaces*))
1070 (lambda (ctx)
1071 (let* ((qname (xpath:string-value (funcall name ctx)))
1072 (object (funcall object ctx))
1073 (expanded-name
1074 (multiple-value-bind (local-name uri)
1075 (decode-qname/runtime qname namespaces nil)
1076 (cons local-name uri)))
1077 (key (find-key expanded-name *stylesheet*)))
1078 (labels ((get-by-key (value)
1079 (let ((value (xpath:string-value value)))
1080 (xpath::filter-pipe
1081 #'(lambda (node)
1082 (let ((uses
1083 (xpath:evaluate-compiled (key-use key) node)))
1084 (if (xpath:node-set-p uses)
1085 (xpath::find-in-pipe
1086 value
1087 (xpath-sys:pipe-of uses)
1088 :key #'xpath:string-value
1089 :test #'equal)
1090 (equal value (xpath:string-value uses)))))
1091 (xpath-sys:pipe-of
1092 (xpath:node-set-value
1093 (xpath:evaluate-compiled (key-match key) ctx)))))))
1094 (xpath-sys:make-node-set
1095 (xpath::sort-pipe
1096 (if (xpath:node-set-p object)
1097 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1098 (get-by-key object)))))))))
1100 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1102 (xpath-sys:define-xpath-function/lazy xslt :current ()
1103 #'(lambda (ctx)
1104 (xpath-sys:make-node-set
1105 (xpath-sys:make-pipe
1106 (xpath:context-starting-node ctx)
1107 nil))))
1109 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1110 #'(lambda (ctx)
1111 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1112 (funcall name ctx))
1113 "")))
1115 (defun %get-node-id (node)
1116 (when (xpath:node-set-p node)
1117 (setf node (xpath::textually-first-node node)))
1118 (when node
1119 (let ((id (xpath-sys:get-node-id node))
1120 (highest-base-uri
1121 (loop
1122 for parent = node then next
1123 for next = (xpath-protocol:parent-node parent)
1124 for this-base-uri = (xpath-protocol:base-uri parent)
1125 for highest-base-uri = (if (plusp (length this-base-uri))
1126 this-base-uri
1127 highest-base-uri)
1128 while next
1129 finally (return highest-base-uri))))
1130 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1131 ;; checked only if everything else matches.
1133 ;; This might be pointless premature optimization, but I like the idea :-)
1134 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1136 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1137 (if node-set-thunk
1138 #'(lambda (ctx)
1139 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1140 #'(lambda (ctx)
1141 (%get-node-id (xpath:context-node ctx)))))
1143 (declaim (special *available-instructions*))
1145 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1146 (let ((namespaces *namespaces*))
1147 #'(lambda (ctx)
1148 (let ((qname (funcall qname ctx)))
1149 (multiple-value-bind (local-name uri)
1150 (decode-qname/runtime qname namespaces nil)
1151 (and (equal uri *xsl*)
1152 (gethash local-name *available-instructions*)
1153 t))))))
1155 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1156 (let ((namespaces *namespaces*))
1157 #'(lambda (ctx)
1158 (let ((qname (funcall qname ctx)))
1159 (multiple-value-bind (local-name uri)
1160 (decode-qname/runtime qname namespaces nil)
1161 (and (zerop (length uri))
1162 (or (xpath-sys:find-xpath-function local-name *xsl*)
1163 (xpath-sys:find-xpath-function local-name uri))
1164 t))))))
1166 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1167 (let ((namespaces *namespaces*))
1168 (lambda (ctx)
1169 (let ((qname (funcall qname ctx)))
1170 (multiple-value-bind (local-name uri)
1171 (decode-qname/runtime qname namespaces nil)
1172 (if (equal uri *xsl*)
1173 (cond
1174 ((equal local-name "version")
1175 "1")
1176 ((equal local-name "vendor")
1177 "Xuriella")
1178 ((equal local-name "vendor-uri")
1179 "http://repo.or.cz/w/xuriella.git")
1181 ""))
1182 ""))))))
1184 (defun apply-stylesheet
1185 (stylesheet source-designator
1186 &key output parameters uri-resolver navigator)
1187 (when (typep stylesheet 'xml-designator)
1188 (setf stylesheet
1189 (handler-bind
1190 ((cxml:xml-parse-error
1191 (lambda (c)
1192 (xslt-error "cannot parse stylesheet: ~A" c))))
1193 (parse-stylesheet stylesheet))))
1194 (invoke-with-output-sink
1195 (lambda ()
1196 (handler-case*
1197 (let* ((*documents* (make-hash-table :test 'equal))
1198 (xpath:*navigator* (or navigator :default-navigator))
1199 (puri:*strict-parse* nil)
1200 (*stylesheet* stylesheet)
1201 (*empty-mode* (make-mode))
1202 (*default-mode* (find-mode stylesheet nil))
1203 (global-variable-specs
1204 (stylesheet-global-variables stylesheet))
1205 (*global-variable-values*
1206 (make-variable-value-array (length global-variable-specs)))
1207 (*uri-resolver* uri-resolver)
1208 (source-document
1209 (if (typep source-designator 'xml-designator)
1210 (cxml:parse source-designator (stp:make-builder))
1211 source-designator))
1212 (xpath-root-node
1213 (make-whitespace-stripper
1214 source-document
1215 (stylesheet-strip-tests stylesheet)))
1216 (ctx (xpath:make-context xpath-root-node)))
1217 (when (pathnamep source-designator)
1218 (setf (gethash source-designator *documents*) xpath-root-node))
1219 (map nil
1220 (lambda (spec)
1221 (when (variable-param-p spec)
1222 (let ((value
1223 (find-parameter-value (variable-local-name spec)
1224 (variable-uri spec)
1225 parameters)))
1226 (when value
1227 (setf (global-variable-value (variable-index spec))
1228 value)))))
1229 global-variable-specs)
1230 (map nil
1231 (lambda (spec)
1232 (funcall (variable-thunk spec) ctx))
1233 global-variable-specs)
1234 ;; zzz we wouldn't have to mask float traps here if we used the
1235 ;; XPath API properly. Unfortunately I've been using FUNCALL
1236 ;; everywhere instead of EVALUATE, so let's paper over that
1237 ;; at a central place to be sure:
1238 (xpath::with-float-traps-masked ()
1239 (apply-templates ctx :mode *default-mode*)))
1240 (xpath:xpath-error (c)
1241 (xslt-error "~A" c))))
1242 (stylesheet-output-specification stylesheet)
1243 output))
1245 (defun find-attribute-set (local-name uri)
1246 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1247 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1249 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1250 (when sort-predicate
1251 (setf list
1252 (mapcar #'xpath:context-node
1253 (stable-sort (contextify-node-list list)
1254 sort-predicate))))
1255 (let* ((n (length list))
1256 (s/d (lambda () n)))
1257 (loop
1258 for i from 1
1259 for child in list
1261 (apply-templates (xpath:make-context child s/d i)
1262 :param-bindings param-bindings
1263 :mode mode))))
1265 (defvar *stack-limit* 200)
1267 (defun invoke-with-stack-limit (fn)
1268 (let ((*stack-limit* (1- *stack-limit*)))
1269 (unless (plusp *stack-limit*)
1270 (xslt-error "*stack-limit* reached; stack overflow"))
1271 (funcall fn)))
1273 (defun invoke-template (ctx template param-bindings)
1274 (let ((*lexical-variable-values*
1275 (make-variable-value-array (template-n-variables template))))
1276 (with-stack-limit ()
1277 (loop
1278 for (name-cons value) in param-bindings
1279 for (nil index nil) = (find name-cons
1280 (template-params template)
1281 :test #'equal
1282 :key #'car)
1284 (when index
1285 (setf (lexical-variable-value index) value)))
1286 (funcall (template-body template) ctx))))
1288 (defun apply-default-templates (ctx mode)
1289 (let ((node (xpath:context-node ctx)))
1290 (cond
1291 ((or (xpath-protocol:node-type-p node :processing-instruction)
1292 (xpath-protocol:node-type-p node :comment)))
1293 ((or (xpath-protocol:node-type-p node :text)
1294 (xpath-protocol:node-type-p node :attribute))
1295 (write-text (xpath-protocol:node-text node)))
1297 (apply-templates/list
1298 (xpath::force
1299 (xpath-protocol:child-pipe node))
1300 :mode mode)))))
1302 (defvar *apply-imports*)
1304 (defun apply-applicable-templates (ctx templates param-bindings finally)
1305 (labels ((apply-imports (&optional actual-param-bindings)
1306 (if templates
1307 (let* ((this (pop templates))
1308 (low (template-apply-imports-limit this))
1309 (high (template-import-priority this)))
1310 (setf templates
1311 (remove-if-not
1312 (lambda (x)
1313 (<= low (template-import-priority x) high))
1314 templates))
1315 (invoke-template ctx this actual-param-bindings))
1316 (funcall finally))))
1317 (let ((*apply-imports* #'apply-imports))
1318 (apply-imports param-bindings))))
1320 (defun apply-templates (ctx &key param-bindings mode)
1321 (apply-applicable-templates ctx
1322 (find-templates ctx (or mode *default-mode*))
1323 param-bindings
1324 (lambda ()
1325 (apply-default-templates ctx mode))))
1327 (defun call-template (ctx name &optional param-bindings)
1328 (apply-applicable-templates ctx
1329 (find-named-templates name)
1330 param-bindings
1331 (lambda ()
1332 (error "cannot find named template: ~s"
1333 name))))
1335 (defun find-templates (ctx mode)
1336 (let* ((matching-candidates
1337 (remove-if-not (lambda (template)
1338 (template-matches-p template ctx))
1339 (mode-templates mode)))
1340 (npriorities
1341 (if matching-candidates
1342 (1+ (reduce #'max
1343 matching-candidates
1344 :key #'template-import-priority))
1346 (priority-groups (make-array npriorities :initial-element nil)))
1347 (dolist (template matching-candidates)
1348 (push template
1349 (elt priority-groups (template-import-priority template))))
1350 (loop
1351 for i from (1- npriorities) downto 0
1352 for group = (elt priority-groups i)
1353 for template = (maximize #'template< group)
1354 when template
1355 collect template)))
1357 (defun find-named-templates (name)
1358 (gethash name (stylesheet-named-templates *stylesheet*)))
1360 (defun template< (a b) ;assuming same import priority
1361 (let ((p (template-priority a))
1362 (q (template-priority b)))
1363 (cond
1364 ((< p q) t)
1365 ((> p q) nil)
1367 (xslt-cerror "conflicting templates:~_~A,~_~A"
1368 (template-match-expression a)
1369 (template-match-expression b))
1370 (< (template-position a) (template-position b))))))
1372 (defun maximize (< things)
1373 (when things
1374 (let ((max (car things)))
1375 (dolist (other (cdr things))
1376 (when (funcall < max other)
1377 (setf max other)))
1378 max)))
1380 (defun template-matches-p (template ctx)
1381 (find (xpath:context-node ctx)
1382 (xpath:all-nodes (funcall (template-match-thunk template) ctx))
1383 :test #'xpath-protocol:node-equal))
1385 (defun invoke-with-output-sink (fn output-spec output)
1386 (etypecase output
1387 (pathname
1388 (with-open-file (s output
1389 :direction :output
1390 :element-type '(unsigned-byte 8)
1391 :if-exists :rename-and-delete)
1392 (invoke-with-output-sink fn output-spec s)))
1393 ((or stream null)
1394 (invoke-with-output-sink fn
1395 output-spec
1396 (make-output-sink output-spec output)))
1397 ((or hax:abstract-handler sax:abstract-handler)
1398 (with-xml-output output
1399 (when (typep output '(or combi-sink auto-detect-sink))
1400 (sax:start-dtd output
1401 :autodetect-me-please
1402 (output-doctype-public output-spec)
1403 (output-doctype-system output-spec)))
1404 (funcall fn)))))
1406 (defun make-output-sink (output-spec stream)
1407 (let* ((ystream
1408 (if stream
1409 (let ((et (stream-element-type stream)))
1410 (cond
1411 ((or (null et) (subtypep et '(unsigned-byte 8)))
1412 (runes:make-octet-stream-ystream stream))
1413 ((subtypep et 'character)
1414 (runes:make-character-stream-ystream stream))))
1415 (runes:make-rod-ystream)))
1416 (omit-xml-declaration-p
1417 (equal (output-omit-xml-declaration output-spec) "yes"))
1418 (sax-target
1419 (make-instance 'cxml::sink
1420 :ystream ystream
1421 :omit-xml-declaration-p omit-xml-declaration-p)))
1422 (flet ((make-combi-sink ()
1423 (make-instance 'combi-sink
1424 :hax-target (make-instance 'chtml::sink
1425 :ystream ystream)
1426 :sax-target sax-target
1427 :encoding (output-encoding output-spec))))
1428 (let ((method-key
1429 (cond
1430 ((equalp (output-method output-spec) "HTML") :html)
1431 ((equalp (output-method output-spec) "TEXT") :text)
1432 ((equalp (output-method output-spec) "XML") :xml)
1433 (t nil))))
1434 (cond
1435 ((and (eq method-key :html)
1436 (null (output-doctype-system output-spec))
1437 (null (output-doctype-public output-spec)))
1438 (make-combi-sink))
1439 ((eq method-key :text)
1440 (make-text-filter sax-target))
1441 ((and (eq method-key :xml)
1442 (null (output-doctype-system output-spec)))
1443 sax-target)
1445 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1447 (defstruct template
1448 match-expression
1449 match-thunk
1450 name
1451 import-priority
1452 apply-imports-limit
1453 priority
1454 position
1455 mode
1456 mode-qname
1457 params
1458 body
1459 n-variables)
1461 (defun expression-priority (form)
1462 (let ((step (second form)))
1463 (if (and (null (cddr form))
1464 (listp step)
1465 (member (car step) '(:child :attribute))
1466 (null (cddr step)))
1467 (let ((name (second step)))
1468 (cond
1469 ((or (stringp name)
1470 (and (consp name)
1471 (or (eq (car name) :qname)
1472 (eq (car name) :processing-instruction))))
1473 0.0)
1474 ((and (consp name)
1475 (or (eq (car name) :namespace)
1476 (eq (car name) '*)))
1477 -0.25)
1479 -0.5)))
1480 0.5)))
1482 (defun valid-expression-p (expr)
1483 (cond
1484 ((atom expr) t)
1485 ((eq (first expr) :path)
1486 (every (lambda (x)
1487 (let ((filter (third x)))
1488 (or (null filter) (valid-expression-p filter))))
1489 (cdr expr)))
1490 ((eq (first expr) :variable) ;(!)
1491 nil)
1493 (every #'valid-expression-p (cdr expr)))))
1495 (defun parse-xpath (str)
1496 (handler-case
1497 (xpath:parse-xpath str)
1498 (xpath:xpath-error (c)
1499 (xslt-error "~A" c))))
1501 ;; zzz also use naive-pattern-expression here?
1502 (defun parse-key-pattern (str)
1503 (let ((parsed
1504 (mapcar #'(lambda (item)
1505 `(:path (:root :node)
1506 (:descendant-or-self *)
1507 ,@(cdr item)))
1508 (parse-pattern str))))
1509 (if (null (rest parsed))
1510 (first parsed)
1511 `(:union ,@parsed))))
1513 (defun parse-pattern (str)
1514 ;; zzz check here for anything not allowed as an XSLT pattern
1515 ;; zzz can we hack id() and key() here?
1516 (let ((form (parse-xpath str)))
1517 (unless (consp form)
1518 (xslt-error "not a valid pattern: ~A" str))
1519 (labels ((process-form (form)
1520 (cond ((eq (car form) :union)
1521 (alexandria:mappend #'process-form (rest form)))
1522 ((not (or (eq (car form) :path)
1523 (and (eq (car form) :filter)
1524 (let ((filter (second form)))
1525 (and (consp filter)
1526 (member (car filter)
1527 '(:key :id))))
1528 (equal (third form) '(:true)))
1529 (member (car form) '(:key :id))))
1530 (xslt-error "not a valid pattern: ~A ~A" str form))
1531 ((not (valid-expression-p form))
1532 (xslt-error "invalid filter"))
1533 (t (list form)))))
1534 (process-form form))))
1536 (defun naive-pattern-expression (x)
1537 (ecase (car x)
1538 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1539 ((:filter :key :id) x)))
1541 (defun compile-value-thunk (value env)
1542 (if (and (listp value) (eq (car value) 'progn))
1543 (let ((inner-thunk (compile-instruction value env)))
1544 (lambda (ctx)
1545 (apply-to-result-tree-fragment ctx inner-thunk)))
1546 (compile-xpath value env)))
1548 (defun compile-var-binding (name value env)
1549 (multiple-value-bind (local-name uri)
1550 (decode-qname name env nil)
1551 (let ((thunk (xslt-trace-thunk
1552 (compile-value-thunk value env)
1553 "local variable ~s = ~s" name :result)))
1554 (list (cons local-name uri)
1555 (push-variable local-name
1557 *lexical-variable-declarations*)
1558 thunk))))
1560 (defun compile-var-bindings (forms env)
1561 (loop
1562 for (name value) in forms
1563 collect (compile-var-binding name value env)))
1565 (defun compile-template (<template> env position)
1566 (stp:with-attributes (match name priority mode) <template>
1567 (unless (or name match)
1568 (xslt-error "missing match in template"))
1569 (multiple-value-bind (params body-pos)
1570 (loop
1571 for i from 0
1572 for child in (stp:list-children <template>)
1573 while (namep child "param")
1574 collect (parse-param child) into params
1575 finally (return (values params i)))
1576 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1577 (param-bindings (compile-var-bindings params env))
1578 (body (parse-body <template> body-pos (mapcar #'car params)))
1579 (body-thunk (compile-instruction `(progn ,@body) env))
1580 (outer-body-thunk
1581 (xslt-trace-thunk
1582 #'(lambda (ctx)
1583 (unwind-protect
1584 (progn
1585 ;; set params that weren't initialized by apply-templates
1586 (loop for (name index param-thunk) in param-bindings
1587 when (eq (lexical-variable-value index nil) 'unbound)
1588 do (setf (lexical-variable-value index)
1589 (funcall param-thunk ctx)))
1590 (funcall body-thunk ctx))))
1591 "template: match = ~s name = ~s" match name))
1592 (n-variables (length *lexical-variable-declarations*)))
1593 (append
1594 (when name
1595 (multiple-value-bind (local-name uri)
1596 (decode-qname name env nil)
1597 (list
1598 (make-template :name (cons local-name uri)
1599 :import-priority *import-priority*
1600 :apply-imports-limit *apply-imports-limit*
1601 :params param-bindings
1602 :body outer-body-thunk
1603 :n-variables n-variables))))
1604 (when match
1605 (mapcar (lambda (expression)
1606 (let ((match-thunk
1607 (xslt-trace-thunk
1608 (compile-xpath
1609 `(xpath:xpath
1610 ,(naive-pattern-expression expression))
1611 env)
1612 "match-thunk for template (match ~s): ~s --> ~s"
1613 match expression :result))
1614 (p (if priority
1615 (parse-number:parse-number priority)
1616 (expression-priority expression))))
1617 (make-template :match-expression expression
1618 :match-thunk match-thunk
1619 :import-priority *import-priority*
1620 :apply-imports-limit *apply-imports-limit*
1621 :priority p
1622 :position position
1623 :mode-qname mode
1624 :params param-bindings
1625 :body outer-body-thunk
1626 :n-variables n-variables)))
1627 (parse-pattern match))))))))
1628 #+(or)
1629 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")