Check for disallowed attributes on <stylesheet>
[xuriella.git] / xslt.lisp
blob94e2abf4bce86c8dec22ca488cdad41d43297fb8
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 (dolist (include (stp:filter-children (of-name "include") <transform>))
422 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
423 (stp:base-uri include)))
424 (uri (if uri-resolver
425 (funcall uri-resolver (puri:render-uri uri nil))
426 uri))
427 (str (puri:render-uri uri nil))
428 (pathname
429 (handler-case
430 (uri-to-pathname uri)
431 (cxml:xml-parse-error (c)
432 (xslt-error "cannot find included stylesheet ~A: ~A"
433 uri c)))))
434 (with-open-file
435 (stream pathname
436 :element-type '(unsigned-byte 8)
437 :if-does-not-exist nil)
438 (unless stream
439 (xslt-error "cannot find included stylesheet ~A at ~A"
440 uri pathname))
441 (when (find str *xsl-include-stack* :test #'equal)
442 (xslt-error "recursive inclusion of ~A" uri))
443 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
444 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
445 (stp:insert-child-after <transform>
446 (stp:copy <transform>2)
447 include)
448 (stp:detach include)))))
449 <transform>))
451 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
452 (defvar *apply-imports-limit*)
453 (defvar *import-priority*)
454 (defvar *extension-namespaces*)
455 (defvar *forwards-compatible-p*)
457 (defmacro do-toplevel ((var xpath <transform>) &body body)
458 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
460 (defun map-toplevel (fn xpath <transform>)
461 (dolist (node (list-toplevel xpath <transform>))
462 (let ((*namespaces* *namespaces*))
463 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
464 (when (xpath-protocol:node-type-p ancestor :element)
465 (setf *namespaces* (acons-namespaces ancestor))))
466 (funcall fn node))))
468 (defun list-toplevel (xpath <transform>)
469 (labels ((recurse (sub)
470 (let ((subsubs
471 (xpath-sys:pipe-of
472 (xpath:evaluate "transform|stylesheet" sub))))
473 (xpath::append-pipes
474 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
475 (xpath::mappend-pipe #'recurse subsubs)))))
476 (xpath::sort-nodes (recurse <transform>))))
478 (defmacro with-import-magic ((node env) &body body)
479 `(invoke-with-import-magic (lambda () ,@body) ,node ,env))
481 (defun invoke-with-import-magic (fn node env)
482 (unless (or (namep node "stylesheet") (namep node "transform"))
483 (setf node (stp:parent node)))
484 (let ((*excluded-namespaces* (list *xsl*))
485 (*extension-namespaces* '())
486 (*forwards-compatible-p*
487 (not (equal (stp:attribute-value node "version") "1.0"))))
488 (parse-exclude-result-prefixes! node env)
489 (parse-extension-element-prefixes! node env)
490 (funcall fn)))
492 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
493 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
494 (instruction-base-uri (stp:base-uri <transform>))
495 (namespaces (acons-namespaces <transform>))
496 (apply-imports-limit (1+ *import-priority*))
497 (continuations '()))
498 (let ((*namespaces* namespaces))
499 (invoke-with-import-magic (constantly t) <transform> env))
500 (macrolet ((with-specials ((&optional) &body body)
501 `(let ((*instruction-base-uri* instruction-base-uri)
502 (*namespaces* namespaces)
503 (*apply-imports-limit* apply-imports-limit))
504 ,@body)))
505 (with-specials ()
506 (do-toplevel (import "import" <transform>)
507 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
508 (stp:base-uri import))))
509 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
510 continuations))))
511 (let ((import-priority
512 (incf *import-priority*))
513 (var-cont (prepare-global-variables stylesheet <transform>)))
514 ;; delay the rest of compilation until we've seen all global
515 ;; variables:
516 (lambda ()
517 (mapc #'funcall (nreverse continuations))
518 (with-specials ()
519 (let ((*import-priority* import-priority))
520 (funcall var-cont)
521 (parse-keys! stylesheet <transform> env)
522 (parse-templates! stylesheet <transform> env)
523 (parse-output! stylesheet <transform>)
524 (parse-strip/preserve-space! stylesheet <transform> env)
525 (parse-attribute-sets! stylesheet <transform> env)
526 (parse-namespace-aliases! stylesheet <transform> env)
527 (parse-decimal-formats! stylesheet <transform> env))))))))
529 (defvar *xsl-import-stack* nil)
531 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
532 (let* ((uri (if uri-resolver
533 (funcall uri-resolver (puri:render-uri uri nil))
534 uri))
535 (str (puri:render-uri uri nil))
536 (pathname
537 (handler-case
538 (uri-to-pathname uri)
539 (cxml:xml-parse-error (c)
540 (xslt-error "cannot find imported stylesheet ~A: ~A"
541 uri c)))))
542 (with-open-file
543 (stream pathname
544 :element-type '(unsigned-byte 8)
545 :if-does-not-exist nil)
546 (unless stream
547 (xslt-error "cannot find imported stylesheet ~A at ~A"
548 uri pathname))
549 (when (find str *xsl-import-stack* :test #'equal)
550 (xslt-error "recursive inclusion of ~A" uri))
551 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
552 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
554 (defun parse-stylesheet (designator &key uri-resolver)
555 (xpath:with-namespaces ((nil #.*xsl*))
556 (let* ((*import-priority* 0)
557 (puri:*strict-parse* nil)
558 (stylesheet (make-stylesheet))
559 (env (make-instance 'lexical-xslt-environment))
560 (*excluded-namespaces* *excluded-namespaces*)
561 (*global-variable-declarations* (make-empty-declaration-array)))
562 (ensure-mode stylesheet nil)
563 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
564 ;; reverse attribute sets:
565 (let ((table (stylesheet-attribute-sets stylesheet)))
566 (maphash (lambda (k v)
567 (setf (gethash k table) (nreverse v)))
568 table))
569 ;; add default df
570 (unless (find-decimal-format "" "" stylesheet nil)
571 (setf (find-decimal-format "" "" stylesheet)
572 (make-decimal-format)))
573 stylesheet)))
575 (defun parse-attribute-sets! (stylesheet <transform> env)
576 (do-toplevel (elt "attribute-set" <transform>)
577 (with-import-magic (elt env)
578 (push (let* ((sets
579 (mapcar (lambda (qname)
580 (multiple-value-list (decode-qname qname env nil)))
581 (words
582 (stp:attribute-value elt "use-attribute-sets"))))
583 (instructions
584 (stp:map-children
585 'list
586 (lambda (child)
587 (unless
588 (and (typep child 'stp:element)
589 (or (and (equal (stp:namespace-uri child) *xsl*)
590 (equal (stp:local-name child)
591 "attribute"))
592 (find (stp:namespace-uri child)
593 *extension-namespaces*
594 :test 'equal)))
595 (xslt-error "non-attribute found in attribute set"))
596 (parse-instruction child))
597 elt))
598 (*lexical-variable-declarations*
599 (make-empty-declaration-array))
600 (thunk
601 (compile-instruction `(progn ,@instructions) env))
602 (n-variables (length *lexical-variable-declarations*)))
603 (lambda (ctx)
604 (with-stack-limit ()
605 (loop for (local-name uri nil) in sets do
606 (dolist (thunk (find-attribute-set local-name uri))
607 (funcall thunk ctx)))
608 (let ((*lexical-variable-values*
609 (make-variable-value-array n-variables)))
610 (funcall thunk ctx)))))
611 (gethash (multiple-value-bind (local-name uri)
612 (decode-qname (stp:attribute-value elt "name") env nil)
613 (cons local-name uri))
614 (stylesheet-attribute-sets stylesheet))))))
616 (defun parse-namespace-aliases! (stylesheet <transform> env)
617 (do-toplevel (elt "namespace-alias" <transform>)
618 (stp:with-attributes (stylesheet-prefix result-prefix) elt
619 (setf (gethash
620 (xpath-sys:environment-find-namespace env stylesheet-prefix)
621 (stylesheet-namespace-aliases stylesheet))
622 (xpath-sys:environment-find-namespace
624 (if (equal result-prefix "#default")
626 result-prefix))))))
628 (defun parse-decimal-formats! (stylesheet <transform> env)
629 (do-toplevel (elt "decimal-format" <transform>)
630 (stp:with-attributes (name
631 ;; strings
632 infinity
633 (nan "NaN")
634 ;; characters:
635 decimal-separator
636 grouping-separator
637 zero-digit
638 percent
639 per-mille
640 digit
641 pattern-separator
642 minus-sign)
644 (multiple-value-bind (local-name uri)
645 (if name
646 (decode-qname name env nil)
647 (values "" ""))
648 (unless (find-decimal-format local-name uri stylesheet nil)
649 (setf (find-decimal-format local-name uri stylesheet)
650 (let ((seen '()))
651 (flet ((chr (key x)
652 (when x
653 (unless (eql (length x) 1)
654 (xslt-error "not a single character: ~A" x))
655 (let ((chr (elt x 0)))
656 (when (find chr seen)
657 (xslt-error
658 "conflicting decimal format characters: ~A"
659 chr))
660 (push chr seen)
661 (list key chr))))
662 (str (key x)
663 (when x
664 (list key x))))
665 (apply #'make-decimal-format
666 (append (str :infinity infinity)
667 (str :nan nan)
668 (chr :decimal-separator decimal-separator)
669 (chr :grouping-separator grouping-separator)
670 (chr :zero-digit zero-digit)
671 (chr :percent percent)
672 (chr :per-mille per-mille)
673 (chr :digit digit)
674 (chr :pattern-separator pattern-separator)
675 (chr :minus-sign minus-sign)))))))))))
677 (defun parse-exclude-result-prefixes! (node env)
678 (stp:with-attributes (exclude-result-prefixes)
679 node
680 (dolist (prefix (words (or exclude-result-prefixes "")))
681 (if (equal prefix "#default")
682 (setf prefix nil)
683 (unless (cxml-stp-impl::nc-name-p prefix)
684 (xslt-error "invalid prefix: ~A" prefix)))
685 (push (or (xpath-sys:environment-find-namespace env prefix)
686 (xslt-error "namespace not found: ~A" prefix))
687 *excluded-namespaces*))))
689 (defun parse-extension-element-prefixes! (node env)
690 (stp:with-attributes (extension-element-prefixes)
691 node
692 (dolist (prefix (words (or extension-element-prefixes "")))
693 (if (equal prefix "#default")
694 (setf prefix nil)
695 (unless (cxml-stp-impl::nc-name-p prefix)
696 (xslt-error "invalid prefix: ~A" prefix)))
697 (let ((uri
698 (or (xpath-sys:environment-find-namespace env prefix)
699 (xslt-error "namespace not found: ~A" prefix))))
700 (unless (equal uri *xsl*)
701 (push uri *extension-namespaces*)
702 (push uri *excluded-namespaces*))))))
704 (defun parse-strip/preserve-space! (stylesheet <transform> env)
705 (xpath:with-namespaces ((nil #.*xsl*))
706 (do-toplevel (elt "strip-space|preserve-space" <transform>)
707 (let ((*namespaces* (acons-namespaces elt))
708 (mode
709 (if (equal (stp:local-name elt) "strip-space")
710 :strip
711 :preserve)))
712 (dolist (name-test (words (stp:attribute-value elt "elements")))
713 (let* ((pos (search ":*" name-test))
714 (test-function
715 (cond
716 ((eql pos (- (length name-test) 2))
717 (let* ((prefix (subseq name-test 0 pos))
718 (name-test-uri
719 (xpath-sys:environment-find-namespace env prefix)))
720 (unless (xpath::nc-name-p prefix)
721 (xslt-error "not an NCName: ~A" prefix))
722 (lambda (local-name uri)
723 (declare (ignore local-name))
724 (if (equal uri name-test-uri)
725 mode
726 nil))))
727 ((equal name-test "*")
728 (lambda (local-name uri)
729 (declare (ignore local-name uri))
730 mode))
732 (multiple-value-bind (name-test-local-name name-test-uri)
733 (decode-qname name-test env nil)
734 (lambda (local-name uri)
735 (if (and (equal local-name name-test-local-name)
736 (equal uri name-test-uri))
737 mode
738 nil)))))))
739 (push test-function (stylesheet-strip-tests stylesheet))))))))
741 (defstruct (output-specification
742 (:conc-name "OUTPUT-"))
743 method
744 indent
745 omit-xml-declaration
746 encoding
747 doctype-system
748 doctype-public)
750 (defun parse-output! (stylesheet <transform>)
751 (dolist (<output> (list-toplevel "output" <transform>))
752 (let ((spec (stylesheet-output-specification stylesheet)))
753 (stp:with-attributes ( ;; version
754 method
755 indent
756 encoding
757 ;;; media-type
758 doctype-system
759 doctype-public
760 omit-xml-declaration
761 ;;; standalone
762 ;;; cdata-section-elements
764 <output>
765 (when method
766 (setf (output-method spec) method))
767 (when indent
768 (setf (output-indent spec) indent))
769 (when encoding
770 (setf (output-encoding spec) encoding))
771 (when doctype-system
772 (setf (output-doctype-system spec) doctype-system))
773 (when doctype-public
774 (setf (output-doctype-public spec) doctype-public))
775 (when omit-xml-declaration
776 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
777 ;;; (when cdata-section-elements
778 ;;; (setf (output-cdata-section-elements spec)
779 ;;; (concatenate 'string
780 ;;; (output-cdata-section-elements spec)
781 ;;; " "
782 ;;; cdata-section-elements)))
783 ))))
785 (defun make-empty-declaration-array ()
786 (make-array 1 :fill-pointer 0 :adjustable t))
788 (defun make-variable-value-array (n-lexical-variables)
789 (make-array n-lexical-variables :initial-element 'unbound))
791 (defun compile-global-variable (<variable> env) ;; also for <param>
792 (stp:with-attributes (name select) <variable>
793 (when (and select (stp:list-children <variable>))
794 (xslt-error "variable with select and body"))
795 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
796 (inner (cond
797 (select
798 (compile-xpath select env))
799 ((stp:list-children <variable>)
800 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
801 (inner-thunk (compile-instruction inner-sexpr env)))
802 (lambda (ctx)
803 (apply-to-result-tree-fragment ctx inner-thunk))))
805 (lambda (ctx)
806 (declare (ignore ctx))
807 ""))))
808 (n-lexical-variables (length *lexical-variable-declarations*)))
809 (xslt-trace-thunk
810 (lambda (ctx)
811 (let* ((*lexical-variable-values*
812 (make-variable-value-array n-lexical-variables)))
813 (funcall inner ctx)))
814 "global ~s (~s) = ~s" name select :result))))
816 (defstruct (variable-information
817 (:constructor make-variable)
818 (:conc-name "VARIABLE-"))
819 index
820 thunk
821 local-name
823 param-p
824 thunk-setter)
826 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
827 (let* ((*namespaces* (acons-namespaces <variable>))
828 (instruction-base-uri (stp:base-uri <variable>))
829 (*instruction-base-uri* instruction-base-uri)
830 (*excluded-namespaces* (list *xsl*))
831 (*extension-namespaces* '())
832 (qname (stp:attribute-value <variable> "name")))
833 (with-import-magic (<variable> global-env)
834 (unless qname
835 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
836 (multiple-value-bind (local-name uri)
837 (decode-qname qname global-env nil)
838 ;; For the normal compilation environment of templates, install it
839 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
840 (let ((index (intern-global-variable local-name uri)))
841 ;; For the evaluation of a global variable itself, build a thunk
842 ;; that lazily resolves other variables, stored into
843 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
844 (let* ((value-thunk :unknown)
845 (global-variable-thunk
846 (lambda (ctx)
847 (let ((v (global-variable-value index nil)))
848 (when (eq v 'seen)
849 (xslt-error "recursive variable definition"))
850 (cond
851 ((eq v 'unbound)
852 (setf (global-variable-value index) 'seen)
853 (setf (global-variable-value index)
854 (funcall value-thunk ctx)))
856 v)))))
857 (excluded-namespaces *excluded-namespaces*)
858 (extension-namespaces *extension-namespaces*)
859 (thunk-setter
860 (lambda ()
861 (let ((*instruction-base-uri* instruction-base-uri)
862 (*excluded-namespaces* excluded-namespaces)
863 (*extension-namespaces* extension-namespaces))
864 (setf value-thunk
865 (compile-global-variable <variable> global-env))))))
866 (setf (gethash (cons local-name uri)
867 (initial-global-variable-thunks global-env))
868 global-variable-thunk)
869 (make-variable :index index
870 :local-name local-name
871 :uri uri
872 :thunk global-variable-thunk
873 :param-p (namep <variable> "param")
874 :thunk-setter thunk-setter)))))))
876 (defun parse-keys! (stylesheet <transform> env)
877 (xpath:with-namespaces ((nil #.*xsl*))
878 (do-toplevel (<key> "key" <transform>)
879 (let ((*instruction-base-uri* (stp:base-uri <key>)))
880 (stp:with-attributes (name match use) <key>
881 (unless name (xslt-error "key name attribute not specified"))
882 (unless match (xslt-error "key match attribute not specified"))
883 (unless use (xslt-error "key use attribute not specified"))
884 (multiple-value-bind (local-name uri)
885 (decode-qname name env nil)
886 (add-key stylesheet
887 (cons local-name uri)
888 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
889 (compile-xpath use env))))))))
891 (defun prepare-global-variables (stylesheet <transform>)
892 (xpath:with-namespaces ((nil #.*xsl*))
893 (let* ((table (make-hash-table :test 'equal))
894 (global-env (make-instance 'global-variable-environment
895 :initial-global-variable-thunks table))
896 (specs '()))
897 (do-toplevel (<variable> "variable|param" <transform>)
898 (let ((var (parse-global-variable! <variable> global-env)))
899 (xslt-trace "parsing global variable ~s (uri ~s)"
900 (variable-local-name var)
901 (variable-uri var))
902 (when (find var
903 specs
904 :test (lambda (a b)
905 (and (equal (variable-local-name a)
906 (variable-local-name b))
907 (equal (variable-uri a)
908 (variable-uri b)))))
909 (xslt-error "duplicate definition for global variable ~A"
910 (variable-local-name var)))
911 (push var specs)))
912 (setf specs (nreverse specs))
913 (lambda ()
914 ;; now that the global environment knows about all variables, run the
915 ;; thunk setters to perform their compilation
916 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
917 (let ((table (stylesheet-global-variables stylesheet))
918 (newlen (length *global-variable-declarations*)))
919 (adjust-array table newlen :fill-pointer newlen)
920 (dolist (spec specs)
921 (setf (elt table (variable-index spec)) spec)))))))
923 (defun parse-templates! (stylesheet <transform> env)
924 (let ((i 0))
925 (do-toplevel (<template> "template" <transform>)
926 (let ((*namespaces* (acons-namespaces <template>))
927 (*instruction-base-uri* (stp:base-uri <template>)))
928 (with-import-magic (<template> env)
929 (dolist (template (compile-template <template> env i))
930 (let ((name (template-name template)))
931 (if name
932 (let* ((table (stylesheet-named-templates stylesheet))
933 (head (car (gethash name table))))
934 (when (and head (eql (template-import-priority head)
935 (template-import-priority template)))
936 ;; fixme: is this supposed to be a run-time error?
937 (xslt-error "conflicting templates for ~A" name))
938 (push template (gethash name table)))
939 (let ((mode (ensure-mode/qname stylesheet
940 (template-mode-qname template)
941 env)))
942 (setf (template-mode template) mode)
943 (push template (mode-templates mode))))))))
944 (incf i))))
947 ;;;; APPLY-STYLESHEET
949 (defvar *stylesheet*)
951 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
953 (defun unalias-uri (uri)
954 (let ((result
955 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
956 uri)))
957 (check-type result string)
958 result))
960 (defstruct (parameter
961 (:constructor make-parameter (value local-name &optional uri)))
962 (uri "")
963 local-name
964 value)
966 (defun find-parameter-value (local-name uri parameters)
967 (dolist (p parameters)
968 (when (and (equal (parameter-local-name p) local-name)
969 (equal (parameter-uri p) uri))
970 (return (parameter-value p)))))
972 (defvar *uri-resolver*)
974 (defun parse-allowing-microsoft-bom (pathname handler)
975 (with-open-file (s pathname :element-type '(unsigned-byte 8))
976 (unless (and (eql (read-byte s nil) #xef)
977 (eql (read-byte s nil) #xbb)
978 (eql (read-byte s nil) #xbf))
979 (file-position s 0))
980 (cxml:parse s handler)))
982 (defvar *documents*)
984 (defun %document (uri-string base-uri)
985 (let* ((absolute-uri
986 (puri:merge-uris uri-string (or base-uri "")))
987 (resolved-uri
988 (if *uri-resolver*
989 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
990 absolute-uri))
991 (pathname
992 (handler-case
993 (uri-to-pathname resolved-uri)
994 (cxml:xml-parse-error (c)
995 (xslt-error "cannot find referenced document ~A: ~A"
996 resolved-uri c))))
997 (xpath-root-node
998 (or (gethash pathname *documents*)
999 (setf (gethash pathname *documents*)
1000 (make-whitespace-stripper
1001 (handler-case
1002 (parse-allowing-microsoft-bom pathname
1003 (stp:make-builder))
1004 ((or file-error cxml:xml-parse-error) (c)
1005 (xslt-error "cannot parse referenced document ~A: ~A"
1006 pathname c)))
1007 (stylesheet-strip-tests *stylesheet*))))))
1008 (when (puri:uri-fragment absolute-uri)
1009 (xslt-error "use of fragment identifiers in document() not supported"))
1010 xpath-root-node))
1012 (xpath-sys:define-extension xslt *xsl*)
1014 (defun document-base-uri (node)
1015 (xpath-protocol:base-uri
1016 (cond
1017 ((xpath-protocol:node-type-p node :document)
1018 (xpath::find-in-pipe-if
1019 (lambda (x)
1020 (xpath-protocol:node-type-p x :element))
1021 (xpath-protocol:child-pipe node)))
1022 ((xpath-protocol:node-type-p node :element)
1023 node)
1025 (xpath-protocol:parent-node node)))))
1027 (xpath-sys:define-xpath-function/lazy
1028 xslt :document
1029 (object &optional node-set)
1030 (let ((instruction-base-uri *instruction-base-uri*))
1031 (lambda (ctx)
1032 (let* ((object (funcall object ctx))
1033 (node-set (and node-set (funcall node-set ctx)))
1034 (base-uri
1035 (if node-set
1036 (document-base-uri (xpath::textually-first-node node-set))
1037 instruction-base-uri)))
1038 (xpath-sys:make-node-set
1039 (if (xpath:node-set-p object)
1040 (xpath:map-node-set->list
1041 (lambda (node)
1042 (%document (xpath:string-value node)
1043 (if node-set
1044 base-uri
1045 (document-base-uri node))))
1046 object)
1047 (list (%document (xpath:string-value object) base-uri))))))))
1049 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1050 (let ((namespaces *namespaces*))
1051 (lambda (ctx)
1052 (let* ((qname (xpath:string-value (funcall name ctx)))
1053 (object (funcall object ctx))
1054 (expanded-name
1055 (multiple-value-bind (local-name uri)
1056 (decode-qname/runtime qname namespaces nil)
1057 (cons local-name uri)))
1058 (key (find-key expanded-name *stylesheet*)))
1059 (labels ((get-by-key (value)
1060 (let ((value (xpath:string-value value)))
1061 (xpath::filter-pipe
1062 #'(lambda (node)
1063 (let ((uses
1064 (xpath:evaluate-compiled (key-use key) node)))
1065 (if (xpath:node-set-p uses)
1066 (xpath::find-in-pipe
1067 value
1068 (xpath-sys:pipe-of uses)
1069 :key #'xpath:string-value
1070 :test #'equal)
1071 (equal value (xpath:string-value uses)))))
1072 (xpath-sys:pipe-of
1073 (xpath:node-set-value
1074 (xpath:evaluate-compiled (key-match key) ctx)))))))
1075 (xpath-sys:make-node-set
1076 (xpath::sort-pipe
1077 (if (xpath:node-set-p object)
1078 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1079 (get-by-key object)))))))))
1081 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1083 (xpath-sys:define-xpath-function/lazy xslt :current ()
1084 #'(lambda (ctx)
1085 (xpath-sys:make-node-set
1086 (xpath-sys:make-pipe
1087 (xpath:context-starting-node ctx)
1088 nil))))
1090 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1091 #'(lambda (ctx)
1092 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1093 (funcall name ctx))
1094 "")))
1096 (defun %get-node-id (node)
1097 (when (xpath:node-set-p node)
1098 (setf node (xpath::textually-first-node node)))
1099 (when node
1100 (let ((id (xpath-sys:get-node-id node))
1101 (highest-base-uri
1102 (loop
1103 for parent = node then next
1104 for next = (xpath-protocol:parent-node parent)
1105 for this-base-uri = (xpath-protocol:base-uri parent)
1106 for highest-base-uri = (if (plusp (length this-base-uri))
1107 this-base-uri
1108 highest-base-uri)
1109 while next
1110 finally (return highest-base-uri))))
1111 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1112 ;; checked only if everything else matches.
1114 ;; This might be pointless premature optimization, but I like the idea :-)
1115 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1117 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1118 (if node-set-thunk
1119 #'(lambda (ctx)
1120 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1121 #'(lambda (ctx)
1122 (%get-node-id (xpath:context-node ctx)))))
1124 (declaim (special *available-instructions*))
1126 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1127 (let ((namespaces *namespaces*))
1128 #'(lambda (ctx)
1129 (let ((qname (funcall qname ctx)))
1130 (multiple-value-bind (local-name uri)
1131 (decode-qname/runtime qname namespaces nil)
1132 (and (equal uri *xsl*)
1133 (gethash local-name *available-instructions*)
1134 t))))))
1136 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1137 (let ((namespaces *namespaces*))
1138 #'(lambda (ctx)
1139 (let ((qname (funcall qname ctx)))
1140 (multiple-value-bind (local-name uri)
1141 (decode-qname/runtime qname namespaces nil)
1142 (and (zerop (length uri))
1143 (or (xpath-sys:find-xpath-function local-name *xsl*)
1144 (xpath-sys:find-xpath-function local-name uri))
1145 t))))))
1147 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1148 (let ((namespaces *namespaces*))
1149 (lambda (ctx)
1150 (let ((qname (funcall qname ctx)))
1151 (multiple-value-bind (local-name uri)
1152 (decode-qname/runtime qname namespaces nil)
1153 (if (equal uri *xsl*)
1154 (cond
1155 ((equal local-name "version")
1156 "1")
1157 ((equal local-name "vendor")
1158 "Xuriella")
1159 ((equal local-name "vendor-uri")
1160 "http://repo.or.cz/w/xuriella.git")
1162 ""))
1163 ""))))))
1165 (defun apply-stylesheet
1166 (stylesheet source-designator
1167 &key output parameters uri-resolver navigator)
1168 (when (typep stylesheet 'xml-designator)
1169 (setf stylesheet
1170 (handler-bind
1171 ((cxml:xml-parse-error
1172 (lambda (c)
1173 (xslt-error "cannot parse stylesheet: ~A" c))))
1174 (parse-stylesheet stylesheet))))
1175 (invoke-with-output-sink
1176 (lambda ()
1177 (handler-case*
1178 (let* ((*documents* (make-hash-table :test 'equal))
1179 (xpath:*navigator* (or navigator :default-navigator))
1180 (puri:*strict-parse* nil)
1181 (*stylesheet* stylesheet)
1182 (*empty-mode* (make-mode))
1183 (*default-mode* (find-mode stylesheet nil))
1184 (global-variable-specs
1185 (stylesheet-global-variables stylesheet))
1186 (*global-variable-values*
1187 (make-variable-value-array (length global-variable-specs)))
1188 (*uri-resolver* uri-resolver)
1189 (source-document
1190 (if (typep source-designator 'xml-designator)
1191 (cxml:parse source-designator (stp:make-builder))
1192 source-designator))
1193 (xpath-root-node
1194 (make-whitespace-stripper
1195 source-document
1196 (stylesheet-strip-tests stylesheet)))
1197 (ctx (xpath:make-context xpath-root-node)))
1198 (when (pathnamep source-designator)
1199 (setf (gethash source-designator *documents*) xpath-root-node))
1200 (map nil
1201 (lambda (spec)
1202 (when (variable-param-p spec)
1203 (let ((value
1204 (find-parameter-value (variable-local-name spec)
1205 (variable-uri spec)
1206 parameters)))
1207 (when value
1208 (setf (global-variable-value (variable-index spec))
1209 value)))))
1210 global-variable-specs)
1211 (map nil
1212 (lambda (spec)
1213 (funcall (variable-thunk spec) ctx))
1214 global-variable-specs)
1215 ;; zzz we wouldn't have to mask float traps here if we used the
1216 ;; XPath API properly. Unfortunately I've been using FUNCALL
1217 ;; everywhere instead of EVALUATE, so let's paper over that
1218 ;; at a central place to be sure:
1219 (xpath::with-float-traps-masked ()
1220 (apply-templates ctx :mode *default-mode*)))
1221 (xpath:xpath-error (c)
1222 (xslt-error "~A" c))))
1223 (stylesheet-output-specification stylesheet)
1224 output))
1226 (defun find-attribute-set (local-name uri)
1227 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1228 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1230 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1231 (when sort-predicate
1232 (setf list
1233 (mapcar #'xpath:context-node
1234 (stable-sort (contextify-node-list list)
1235 sort-predicate))))
1236 (let* ((n (length list))
1237 (s/d (lambda () n)))
1238 (loop
1239 for i from 1
1240 for child in list
1242 (apply-templates (xpath:make-context child s/d i)
1243 :param-bindings param-bindings
1244 :mode mode))))
1246 (defvar *stack-limit* 200)
1248 (defun invoke-with-stack-limit (fn)
1249 (let ((*stack-limit* (1- *stack-limit*)))
1250 (unless (plusp *stack-limit*)
1251 (xslt-error "*stack-limit* reached; stack overflow"))
1252 (funcall fn)))
1254 (defun invoke-template (ctx template param-bindings)
1255 (let ((*lexical-variable-values*
1256 (make-variable-value-array (template-n-variables template))))
1257 (with-stack-limit ()
1258 (loop
1259 for (name-cons value) in param-bindings
1260 for (nil index nil) = (find name-cons
1261 (template-params template)
1262 :test #'equal
1263 :key #'car)
1265 (when index
1266 (setf (lexical-variable-value index) value)))
1267 (funcall (template-body template) ctx))))
1269 (defun apply-default-templates (ctx mode)
1270 (let ((node (xpath:context-node ctx)))
1271 (cond
1272 ((or (xpath-protocol:node-type-p node :processing-instruction)
1273 (xpath-protocol:node-type-p node :comment)))
1274 ((or (xpath-protocol:node-type-p node :text)
1275 (xpath-protocol:node-type-p node :attribute))
1276 (write-text (xpath-protocol:node-text node)))
1278 (apply-templates/list
1279 (xpath::force
1280 (xpath-protocol:child-pipe node))
1281 :mode mode)))))
1283 (defvar *apply-imports*)
1285 (defun apply-applicable-templates (ctx templates param-bindings finally)
1286 (labels ((apply-imports (&optional actual-param-bindings)
1287 (if templates
1288 (let* ((this (pop templates))
1289 (low (template-apply-imports-limit this))
1290 (high (template-import-priority this)))
1291 (setf templates
1292 (remove-if-not
1293 (lambda (x)
1294 (<= low (template-import-priority x) high))
1295 templates))
1296 (invoke-template ctx this actual-param-bindings))
1297 (funcall finally))))
1298 (let ((*apply-imports* #'apply-imports))
1299 (apply-imports param-bindings))))
1301 (defun apply-templates (ctx &key param-bindings mode)
1302 (apply-applicable-templates ctx
1303 (find-templates ctx (or mode *default-mode*))
1304 param-bindings
1305 (lambda ()
1306 (apply-default-templates ctx mode))))
1308 (defun call-template (ctx name &optional param-bindings)
1309 (apply-applicable-templates ctx
1310 (find-named-templates name)
1311 param-bindings
1312 (lambda ()
1313 (error "cannot find named template: ~s"
1314 name))))
1316 (defun find-templates (ctx mode)
1317 (let* ((matching-candidates
1318 (remove-if-not (lambda (template)
1319 (template-matches-p template ctx))
1320 (mode-templates mode)))
1321 (npriorities
1322 (if matching-candidates
1323 (1+ (reduce #'max
1324 matching-candidates
1325 :key #'template-import-priority))
1327 (priority-groups (make-array npriorities :initial-element nil)))
1328 (dolist (template matching-candidates)
1329 (push template
1330 (elt priority-groups (template-import-priority template))))
1331 (loop
1332 for i from (1- npriorities) downto 0
1333 for group = (elt priority-groups i)
1334 for template = (maximize #'template< group)
1335 when template
1336 collect template)))
1338 (defun find-named-templates (name)
1339 (gethash name (stylesheet-named-templates *stylesheet*)))
1341 (defun template< (a b) ;assuming same import priority
1342 (let ((p (template-priority a))
1343 (q (template-priority b)))
1344 (cond
1345 ((< p q) t)
1346 ((> p q) nil)
1348 (xslt-cerror "conflicting templates:~_~A,~_~A"
1349 (template-match-expression a)
1350 (template-match-expression b))
1351 (< (template-position a) (template-position b))))))
1353 (defun maximize (< things)
1354 (when things
1355 (let ((max (car things)))
1356 (dolist (other (cdr things))
1357 (when (funcall < max other)
1358 (setf max other)))
1359 max)))
1361 (defun template-matches-p (template ctx)
1362 (find (xpath:context-node ctx)
1363 (xpath:all-nodes (funcall (template-match-thunk template) ctx))
1364 :test #'xpath-protocol:node-equal))
1366 (defun invoke-with-output-sink (fn output-spec output)
1367 (etypecase output
1368 (pathname
1369 (with-open-file (s output
1370 :direction :output
1371 :element-type '(unsigned-byte 8)
1372 :if-exists :rename-and-delete)
1373 (invoke-with-output-sink fn output-spec s)))
1374 ((or stream null)
1375 (invoke-with-output-sink fn
1376 output-spec
1377 (make-output-sink output-spec output)))
1378 ((or hax:abstract-handler sax:abstract-handler)
1379 (with-xml-output output
1380 (when (typep output '(or combi-sink auto-detect-sink))
1381 (sax:start-dtd output
1382 :autodetect-me-please
1383 (output-doctype-public output-spec)
1384 (output-doctype-system output-spec)))
1385 (funcall fn)))))
1387 (defun make-output-sink (output-spec stream)
1388 (let* ((ystream
1389 (if stream
1390 (let ((et (stream-element-type stream)))
1391 (cond
1392 ((or (null et) (subtypep et '(unsigned-byte 8)))
1393 (runes:make-octet-stream-ystream stream))
1394 ((subtypep et 'character)
1395 (runes:make-character-stream-ystream stream))))
1396 (runes:make-rod-ystream)))
1397 (omit-xml-declaration-p
1398 (equal (output-omit-xml-declaration output-spec) "yes"))
1399 (sax-target
1400 (make-instance 'cxml::sink
1401 :ystream ystream
1402 :omit-xml-declaration-p omit-xml-declaration-p)))
1403 (flet ((make-combi-sink ()
1404 (make-instance 'combi-sink
1405 :hax-target (make-instance 'chtml::sink
1406 :ystream ystream)
1407 :sax-target sax-target
1408 :encoding (output-encoding output-spec))))
1409 (let ((method-key
1410 (cond
1411 ((equalp (output-method output-spec) "HTML") :html)
1412 ((equalp (output-method output-spec) "TEXT") :text)
1413 ((equalp (output-method output-spec) "XML") :xml)
1414 (t nil))))
1415 (cond
1416 ((and (eq method-key :html)
1417 (null (output-doctype-system output-spec))
1418 (null (output-doctype-public output-spec)))
1419 (make-combi-sink))
1420 ((eq method-key :text)
1421 (make-text-filter sax-target))
1422 ((and (eq method-key :xml)
1423 (null (output-doctype-system output-spec)))
1424 sax-target)
1426 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1428 (defstruct template
1429 match-expression
1430 match-thunk
1431 name
1432 import-priority
1433 apply-imports-limit
1434 priority
1435 position
1436 mode
1437 mode-qname
1438 params
1439 body
1440 n-variables)
1442 (defun expression-priority (form)
1443 (let ((step (second form)))
1444 (if (and (null (cddr form))
1445 (listp step)
1446 (member (car step) '(:child :attribute))
1447 (null (cddr step)))
1448 (let ((name (second step)))
1449 (cond
1450 ((or (stringp name)
1451 (and (consp name)
1452 (or (eq (car name) :qname)
1453 (eq (car name) :processing-instruction))))
1454 0.0)
1455 ((and (consp name)
1456 (or (eq (car name) :namespace)
1457 (eq (car name) '*)))
1458 -0.25)
1460 -0.5)))
1461 0.5)))
1463 (defun valid-expression-p (expr)
1464 (cond
1465 ((atom expr) t)
1466 ((eq (first expr) :path)
1467 (every (lambda (x)
1468 (let ((filter (third x)))
1469 (or (null filter) (valid-expression-p filter))))
1470 (cdr expr)))
1471 ((eq (first expr) :variable) ;(!)
1472 nil)
1474 (every #'valid-expression-p (cdr expr)))))
1476 (defun parse-xpath (str)
1477 (handler-case
1478 (xpath:parse-xpath str)
1479 (xpath:xpath-error (c)
1480 (xslt-error "~A" c))))
1482 ;; zzz also use naive-pattern-expression here?
1483 (defun parse-key-pattern (str)
1484 (let ((parsed
1485 (mapcar #'(lambda (item)
1486 `(:path (:root :node)
1487 (:descendant-or-self *)
1488 ,@(cdr item)))
1489 (parse-pattern str))))
1490 (if (null (rest parsed))
1491 (first parsed)
1492 `(:union ,@parsed))))
1494 (defun parse-pattern (str)
1495 ;; zzz check here for anything not allowed as an XSLT pattern
1496 ;; zzz can we hack id() and key() here?
1497 (let ((form (parse-xpath str)))
1498 (unless (consp form)
1499 (xslt-error "not a valid pattern: ~A" str))
1500 (labels ((process-form (form)
1501 (cond ((eq (car form) :union)
1502 (alexandria:mappend #'process-form (rest form)))
1503 ((not (or (eq (car form) :path)
1504 (and (eq (car form) :filter)
1505 (let ((filter (second form)))
1506 (and (consp filter)
1507 (member (car filter)
1508 '(:key :id))))
1509 (equal (third form) '(:true)))
1510 (member (car form) '(:key :id))))
1511 (xslt-error "not a valid pattern: ~A ~A" str form))
1512 ((not (valid-expression-p form))
1513 (xslt-error "invalid filter"))
1514 (t (list form)))))
1515 (process-form form))))
1517 (defun naive-pattern-expression (x)
1518 (ecase (car x)
1519 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1520 ((:filter :key :id) x)))
1522 (defun compile-value-thunk (value env)
1523 (if (and (listp value) (eq (car value) 'progn))
1524 (let ((inner-thunk (compile-instruction value env)))
1525 (lambda (ctx)
1526 (apply-to-result-tree-fragment ctx inner-thunk)))
1527 (compile-xpath value env)))
1529 (defun compile-var-binding (name value env)
1530 (multiple-value-bind (local-name uri)
1531 (decode-qname name env nil)
1532 (let ((thunk (xslt-trace-thunk
1533 (compile-value-thunk value env)
1534 "local variable ~s = ~s" name :result)))
1535 (list (cons local-name uri)
1536 (push-variable local-name
1538 *lexical-variable-declarations*)
1539 thunk))))
1541 (defun compile-var-bindings (forms env)
1542 (loop
1543 for (name value) in forms
1544 collect (compile-var-binding name value env)))
1546 (defun compile-template (<template> env position)
1547 (stp:with-attributes (match name priority mode) <template>
1548 (unless (or name match)
1549 (xslt-error "missing match in template"))
1550 (multiple-value-bind (params body-pos)
1551 (loop
1552 for i from 0
1553 for child in (stp:list-children <template>)
1554 while (namep child "param")
1555 collect (parse-param child) into params
1556 finally (return (values params i)))
1557 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1558 (param-bindings (compile-var-bindings params env))
1559 (body (parse-body <template> body-pos (mapcar #'car params)))
1560 (body-thunk (compile-instruction `(progn ,@body) env))
1561 (outer-body-thunk
1562 (xslt-trace-thunk
1563 #'(lambda (ctx)
1564 (unwind-protect
1565 (progn
1566 ;; set params that weren't initialized by apply-templates
1567 (loop for (name index param-thunk) in param-bindings
1568 when (eq (lexical-variable-value index nil) 'unbound)
1569 do (setf (lexical-variable-value index)
1570 (funcall param-thunk ctx)))
1571 (funcall body-thunk ctx))))
1572 "template: match = ~s name = ~s" match name))
1573 (n-variables (length *lexical-variable-declarations*)))
1574 (append
1575 (when name
1576 (multiple-value-bind (local-name uri)
1577 (decode-qname name env nil)
1578 (list
1579 (make-template :name (cons local-name uri)
1580 :import-priority *import-priority*
1581 :apply-imports-limit *apply-imports-limit*
1582 :params param-bindings
1583 :body outer-body-thunk
1584 :n-variables n-variables))))
1585 (when match
1586 (mapcar (lambda (expression)
1587 (let ((match-thunk
1588 (xslt-trace-thunk
1589 (compile-xpath
1590 `(xpath:xpath
1591 ,(naive-pattern-expression expression))
1592 env)
1593 "match-thunk for template (match ~s): ~s --> ~s"
1594 match expression :result))
1595 (p (if priority
1596 (parse-number:parse-number priority)
1597 (expression-priority expression))))
1598 (make-template :match-expression expression
1599 :match-thunk match-thunk
1600 :import-priority *import-priority*
1601 :apply-imports-limit *apply-imports-limit*
1602 :priority p
1603 :position position
1604 :mode-qname mode
1605 :params param-bindings
1606 :body outer-body-thunk
1607 :n-variables n-variables)))
1608 (parse-pattern match))))))))
1609 #+(or)
1610 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")