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