Fixed variable import
[xuriella.git] / xslt.lisp
blob4335868785c2cf188ac00a8a990893ac139f7f74
1 ;;; -*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
3 ;;; Copyright (c) 2007,2008 David Lichteblau, Ivan Shvedunov.
4 ;;; All rights reserved.
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; * Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; * Redistributions in binary form must reproduce the above
14 ;;; copyright notice, this list of conditions and the following
15 ;;; disclaimer in the documentation and/or other materials
16 ;;; provided with the distribution.
17 ;;;
18 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
19 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
22 ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
24 ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 (in-package :xuriella)
32 #+sbcl
33 (declaim (optimize (debug 2)))
36 (eval-when (:compile-toplevel :load-toplevel :execute)
37 (defvar *xsl* "http://www.w3.org/1999/XSL/Transform")
38 (defvar *xml* "http://www.w3.org/XML/1998/namespace")
39 (defvar *html* "http://www.w3.org/1999/xhtml"))
42 ;;;; XSLT-ERROR
44 (define-condition xslt-error (simple-error)
46 (:documentation "The class of all XSLT errors."))
48 (define-condition recoverable-xslt-error (xslt-error)
50 (:documentation "The class of recoverable XSLT errors."))
52 (defun xslt-error (fmt &rest args)
53 (error 'xslt-error :format-control fmt :format-arguments args))
55 (defun xslt-cerror (fmt &rest args)
56 (with-simple-restart (recover "recover")
57 (error 'recoverable-xslt-error
58 :format-control fmt
59 :format-arguments args)))
61 (defvar *debug* nil)
63 (defmacro handler-case* (form &rest clauses)
64 ;; like HANDLER-CASE if *DEBUG* is off. If it's on, don't establish
65 ;; a handler at all so that we see the real stack traces. (We could use
66 ;; HANDLER-BIND here and check at signalling time, but doesn't seem
67 ;; important.)
68 (let ((doit (gensym)))
69 `(flet ((,doit () ,form))
70 (if *debug*
71 (,doit)
72 (handler-case
73 (,doit)
74 ,@clauses)))))
76 (defun compile-xpath (xpath &optional env)
77 (handler-case*
78 (xpath:compile-xpath xpath env)
79 (xpath:xpath-error (c)
80 (xslt-error "~A" c))))
82 (defmacro with-stack-limit ((&optional) &body body)
83 `(invoke-with-stack-limit (lambda () ,@body)))
86 ;;;; Helper functions and macros
88 (defun check-for-invalid-attributes (valid-names node)
89 (labels ((check-attribute (a)
90 (unless
91 (let ((uri (stp:namespace-uri a)))
92 (or (and (plusp (length uri)) (not (equal uri *xsl*)))
93 (find (cons (stp:local-name a) uri)
94 valid-names
95 :test #'equal)))
96 (xslt-error "attribute ~A not allowed on ~A"
97 (stp:local-name a)
98 (stp:local-name node)))))
99 (stp:map-attributes nil #'check-attribute node)))
101 (defmacro only-with-attributes ((&rest specs) node &body body)
102 (let ((valid-names
103 (mapcar (lambda (entry)
104 (if (and (listp entry) (cdr entry))
105 (destructuring-bind (name &optional (uri ""))
106 (cdr entry)
107 (cons name uri))
108 (cons (string-downcase
109 (princ-to-string
110 (symbol-name entry)))
111 "")))
112 specs))
113 (%node (gensym)))
114 `(let ((,%NODE ,node))
115 (check-for-invalid-attributes ',valid-names ,%NODE)
116 (stp:with-attributes ,specs ,%NODE
117 ,@body))))
119 (defun map-pipe-eagerly (fn pipe)
120 (xpath::enumerate pipe :key fn :result nil))
122 (defmacro do-pipe ((var pipe &optional result) &body body)
123 `(block nil
124 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
125 ,result))
128 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
130 (defparameter *namespaces*
131 '((nil . "")
132 ("xmlns" . #"http://www.w3.org/2000/xmlns/")
133 ("xml" . #"http://www.w3.org/XML/1998/namespace")))
135 (defvar *global-variable-declarations*)
136 (defvar *lexical-variable-declarations*)
138 (defvar *global-variable-values*)
139 (defvar *lexical-variable-values*)
141 (defclass xslt-environment () ())
143 (defun split-qname (str)
144 (handler-case
145 (multiple-value-bind (prefix local-name)
146 (cxml::split-qname str)
147 (unless
148 ;; FIXME: cxml should really offer a function that does
149 ;; checks for NCName and QName in a sensible way for user code.
150 ;; cxml::split-qname is tailored to the needs of the parser.
152 ;; For now, let's just check the syntax explicitly.
153 (and (or (null prefix) (xpath::nc-name-p prefix))
154 (xpath::nc-name-p local-name))
155 (xslt-error "not a qname: ~A" str))
156 (values prefix local-name))
157 (cxml:well-formedness-violation ()
158 (xslt-error "not a qname: ~A" str))))
160 (defun decode-qname (qname env attributep)
161 (multiple-value-bind (prefix local-name)
162 (split-qname qname)
163 (values local-name
164 (if (or prefix (not attributep))
165 (xpath-sys:environment-find-namespace env (or prefix ""))
167 prefix)))
169 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
170 (or (cdr (assoc prefix *namespaces* :test 'equal))
171 ;; zzz gross hack.
172 ;; Change the entire code base to represent "no prefix" as the
173 ;; empty string consistently. unparse.lisp has already been changed.
174 (and (equal prefix "")
175 (cdr (assoc nil *namespaces* :test 'equal)))
176 (and (eql prefix nil)
177 (cdr (assoc "" *namespaces* :test 'equal)))))
179 (defun find-variable-index (local-name uri table)
180 (position (cons local-name uri) table :test 'equal))
182 (defun intern-global-variable (local-name uri)
183 (or (find-variable-index local-name uri *global-variable-declarations*)
184 (push-variable local-name uri *global-variable-declarations*)))
186 (defun push-variable (local-name uri table)
187 (prog1
188 (length table)
189 (vector-push-extend (cons local-name uri) table)))
191 (defun lexical-variable-value (index &optional (errorp t))
192 (let ((result (svref *lexical-variable-values* index)))
193 (when errorp
194 (assert (not (eq result 'unbound))))
195 result))
197 (defun (setf lexical-variable-value) (newval index)
198 (assert (not (eq newval 'unbound)))
199 (setf (svref *lexical-variable-values* index) newval))
201 (defun global-variable-value (index &optional (errorp t))
202 (let ((result (svref *global-variable-values* index)))
203 (when errorp
204 (assert (not (eq result 'unbound))))
205 result))
207 (defun (setf global-variable-value) (newval index)
208 (assert (not (eq newval 'unbound)))
209 (setf (svref *global-variable-values* index) newval))
211 (defmethod xpath-sys:environment-find-function
212 ((env xslt-environment) lname uri)
213 (if (string= uri "")
214 (or (xpath-sys:find-xpath-function lname *xsl*)
215 (xpath-sys:find-xpath-function lname uri))
216 (xpath-sys:find-xpath-function lname uri)))
218 (defmethod xpath-sys:environment-find-variable
219 ((env xslt-environment) lname uri)
220 (let ((index
221 (find-variable-index lname uri *lexical-variable-declarations*)))
222 (when index
223 (lambda (ctx)
224 (declare (ignore ctx))
225 (svref *lexical-variable-values* index)))))
227 (defclass lexical-xslt-environment (xslt-environment) ())
229 (defmethod xpath-sys:environment-find-variable
230 ((env lexical-xslt-environment) lname uri)
231 (or (call-next-method)
232 (let ((index
233 (find-variable-index lname uri *global-variable-declarations*)))
234 (when index
235 (xslt-trace-thunk
236 (lambda (ctx)
237 (declare (ignore ctx))
238 (svref *global-variable-values* index))
239 "global ~s (uri ~s) = ~s" lname uri :result)))))
241 (defclass global-variable-environment (xslt-environment)
242 ((initial-global-variable-thunks
243 :initarg :initial-global-variable-thunks
244 :accessor initial-global-variable-thunks)))
246 (defmethod xpath-sys:environment-find-variable
247 ((env global-variable-environment) lname uri)
248 (or (call-next-method)
249 (gethash (cons lname uri) (initial-global-variable-thunks env))))
252 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
253 ;;;;
254 ;;;; A sink that serializes only text not contained in any element.
256 (defmacro with-toplevel-text-output-sink ((var) &body body)
257 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
259 (defclass toplevel-text-output-sink (sax:default-handler)
260 ((target :initarg :target :accessor text-output-sink-target)
261 (depth :initform 0 :accessor textoutput-sink-depth)))
263 (defmethod sax:start-element ((sink toplevel-text-output-sink)
264 namespace-uri local-name qname attributes)
265 (declare (ignore namespace-uri local-name qname attributes))
266 (incf (textoutput-sink-depth sink)))
268 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
269 (when (zerop (textoutput-sink-depth sink))
270 (write-string data (text-output-sink-target sink))))
272 (defmethod sax:unescaped ((sink toplevel-text-output-sink) data)
273 (sax:characters sink data))
275 (defmethod sax:end-element ((sink toplevel-text-output-sink)
276 namespace-uri local-name qname)
277 (declare (ignore namespace-uri local-name qname))
278 (decf (textoutput-sink-depth sink)))
280 (defun invoke-with-toplevel-text-output-sink (fn)
281 (with-output-to-string (s)
282 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
285 ;;;; TEXT-FILTER
286 ;;;;
287 ;;;; A sink that passes through only text (at any level) and turns to
288 ;;;; into unescaped characters.
290 (defclass text-filter (sax:default-handler)
291 ((target :initarg :target :accessor text-filter-target)))
293 (defmethod sax:characters ((sink text-filter) data)
294 (sax:unescaped (text-filter-target sink) data))
296 (defmethod sax:unescaped ((sink text-filter) data)
297 (sax:unescaped (text-filter-target sink) data))
299 (defmethod sax:end-document ((sink text-filter))
300 (sax:end-document (text-filter-target sink)))
302 (defun make-text-filter (target)
303 (make-instance 'text-filter :target target))
306 ;;;; ESCAPER
307 ;;;;
308 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
309 ;;;; XSLT 16.4.
311 (defclass escaper (cxml:broadcast-handler)
314 (defmethod sax:unescaped ((sink escaper) data)
315 (sax:characters sink data))
317 (defun make-escaper (target)
318 (make-instance 'escaper :handlers (list target)))
321 ;;;; Names
323 (defun of-name (local-name)
324 (stp:of-name local-name *xsl*))
326 (defun namep (node local-name)
327 (and (typep node '(or stp:element stp:attribute))
328 (equal (stp:namespace-uri node) *xsl*)
329 (equal (stp:local-name node) local-name)))
332 ;;;; PARSE-STYLESHEET
334 (defstruct stylesheet
335 (modes (make-hash-table :test 'equal))
336 (global-variables (make-empty-declaration-array))
337 (output-specification (make-output-specification))
338 (strip-tests nil)
339 (named-templates (make-hash-table :test 'equal))
340 (attribute-sets (make-hash-table :test 'equal))
341 (keys (make-hash-table :test 'equal))
342 (namespace-aliases (make-hash-table :test 'equal))
343 (decimal-formats (make-hash-table :test 'equal))
344 (initial-global-variable-thunks (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 (let ((current (find-decimal-format local-name uri stylesheet nil))
669 (new
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)))))))
696 (if current
697 (unless (decimal-format= current new)
698 (xslt-error "decimal format mismatch for ~S" local-name))
699 (setf (find-decimal-format local-name uri stylesheet) new)))))))
701 (defun parse-exclude-result-prefixes! (node env)
702 (stp:with-attributes (exclude-result-prefixes)
703 node
704 (dolist (prefix (words (or exclude-result-prefixes "")))
705 (if (equal prefix "#default")
706 (setf prefix nil)
707 (unless (cxml-stp-impl::nc-name-p prefix)
708 (xslt-error "invalid prefix: ~A" prefix)))
709 (push (or (xpath-sys:environment-find-namespace env prefix)
710 (xslt-error "namespace not found: ~A" prefix))
711 *excluded-namespaces*))))
713 (defun parse-extension-element-prefixes! (node env)
714 (stp:with-attributes (extension-element-prefixes)
715 node
716 (dolist (prefix (words (or extension-element-prefixes "")))
717 (if (equal prefix "#default")
718 (setf prefix nil)
719 (unless (cxml-stp-impl::nc-name-p prefix)
720 (xslt-error "invalid prefix: ~A" prefix)))
721 (let ((uri
722 (or (xpath-sys:environment-find-namespace env prefix)
723 (xslt-error "namespace not found: ~A" prefix))))
724 (unless (equal uri *xsl*)
725 (push uri *extension-namespaces*)
726 (push uri *excluded-namespaces*))))))
728 (defun parse-strip/preserve-space! (stylesheet <transform> env)
729 (xpath:with-namespaces ((nil #.*xsl*))
730 (do-toplevel (elt "strip-space|preserve-space" <transform>)
731 (let ((*namespaces* (acons-namespaces elt))
732 (mode
733 (if (equal (stp:local-name elt) "strip-space")
734 :strip
735 :preserve)))
736 (dolist (name-test (words (stp:attribute-value elt "elements")))
737 (let* ((pos (search ":*" name-test))
738 (test-function
739 (cond
740 ((eql pos (- (length name-test) 2))
741 (let* ((prefix (subseq name-test 0 pos))
742 (name-test-uri
743 (xpath-sys:environment-find-namespace env prefix)))
744 (unless (xpath::nc-name-p prefix)
745 (xslt-error "not an NCName: ~A" prefix))
746 (lambda (local-name uri)
747 (declare (ignore local-name))
748 (if (equal uri name-test-uri)
749 mode
750 nil))))
751 ((equal name-test "*")
752 (lambda (local-name uri)
753 (declare (ignore local-name uri))
754 mode))
756 (multiple-value-bind (name-test-local-name name-test-uri)
757 (decode-qname name-test env nil)
758 (lambda (local-name uri)
759 (if (and (equal local-name name-test-local-name)
760 (equal uri name-test-uri))
761 mode
762 nil)))))))
763 (push test-function (stylesheet-strip-tests stylesheet))))))))
765 (defstruct (output-specification
766 (:conc-name "OUTPUT-"))
767 method
768 indent
769 omit-xml-declaration
770 encoding
771 doctype-system
772 doctype-public)
774 (defun parse-output! (stylesheet <transform>)
775 (dolist (<output> (list-toplevel "output" <transform>))
776 (let ((spec (stylesheet-output-specification stylesheet)))
777 (stp:with-attributes ( ;; version
778 method
779 indent
780 encoding
781 ;;; media-type
782 doctype-system
783 doctype-public
784 omit-xml-declaration
785 ;;; standalone
786 ;;; cdata-section-elements
788 <output>
789 (when method
790 (setf (output-method spec) method))
791 (when indent
792 (setf (output-indent spec) indent))
793 (when encoding
794 (setf (output-encoding spec) encoding))
795 (when doctype-system
796 (setf (output-doctype-system spec) doctype-system))
797 (when doctype-public
798 (setf (output-doctype-public spec) doctype-public))
799 (when omit-xml-declaration
800 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
801 ;;; (when cdata-section-elements
802 ;;; (setf (output-cdata-section-elements spec)
803 ;;; (concatenate 'string
804 ;;; (output-cdata-section-elements spec)
805 ;;; " "
806 ;;; cdata-section-elements)))
807 ))))
809 (defun make-empty-declaration-array ()
810 (make-array 1 :fill-pointer 0 :adjustable t))
812 (defun make-variable-value-array (n-lexical-variables)
813 (make-array n-lexical-variables :initial-element 'unbound))
815 (defun compile-global-variable (<variable> env) ;; also for <param>
816 (stp:with-attributes (name select) <variable>
817 (when (and select (stp:list-children <variable>))
818 (xslt-error "variable with select and body"))
819 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
820 (inner (cond
821 (select
822 (compile-xpath select env))
823 ((stp:list-children <variable>)
824 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
825 (inner-thunk (compile-instruction inner-sexpr env)))
826 (lambda (ctx)
827 (apply-to-result-tree-fragment ctx inner-thunk))))
829 (lambda (ctx)
830 (declare (ignore ctx))
831 ""))))
832 (n-lexical-variables (length *lexical-variable-declarations*)))
833 (xslt-trace-thunk
834 (lambda (ctx)
835 (let* ((*lexical-variable-values*
836 (make-variable-value-array n-lexical-variables)))
837 (funcall inner ctx)))
838 "global ~s (~s) = ~s" name select :result))))
840 (defstruct (variable-chain
841 (:constructor make-variable-chain)
842 (:conc-name "VARIABLE-CHAIN-"))
843 definitions
844 index
845 local-name
846 thunk
847 uri)
849 (defstruct (import-variable
850 (:constructor make-variable)
851 (:conc-name "VARIABLE-"))
852 value-thunk
853 value-thunk-setter
854 param-p)
856 (defun parse-global-variable! (stylesheet <variable> global-env)
857 (let* ((*namespaces* (acons-namespaces <variable>))
858 (instruction-base-uri (stp:base-uri <variable>))
859 (*instruction-base-uri* instruction-base-uri)
860 (*excluded-namespaces* (list *xsl*))
861 (*extension-namespaces* '())
862 (qname (stp:attribute-value <variable> "name")))
863 (with-import-magic (<variable> global-env)
864 (unless qname
865 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
866 (multiple-value-bind (local-name uri)
867 (decode-qname qname global-env nil)
868 ;; For the normal compilation environment of templates, install it
869 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
870 (let ((index (intern-global-variable local-name uri)))
871 ;; For the evaluation of a global variable itself, build a thunk
872 ;; that lazily resolves other variables, stored into
873 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
874 (let* ((value-thunk :unknown)
875 (sgv (stylesheet-global-variables stylesheet))
876 (chain
877 (if (< index (length sgv))
878 (elt sgv index)
879 (make-variable-chain
880 :index index
881 :local-name local-name
882 :uri uri)))
883 (next (car (variable-chain-definitions chain)))
884 (global-variable-thunk
885 (lambda (ctx)
886 (let ((v (global-variable-value index nil)))
887 (cond
888 ((eq v 'seen)
889 (unless next
890 (xslt-error "no next definition for: ~A"
891 local-name))
892 (funcall (variable-value-thunk next) ctx))
893 ((eq v 'unbound)
894 (setf (global-variable-value index) 'seen)
895 (setf (global-variable-value index)
896 (funcall value-thunk ctx)))
898 v)))))
899 (excluded-namespaces *excluded-namespaces*)
900 (extension-namespaces *extension-namespaces*)
901 (variable
902 (make-variable :param-p (namep <variable> "param")))
903 (value-thunk-setter
904 (lambda ()
905 (let* ((*instruction-base-uri* instruction-base-uri)
906 (*excluded-namespaces* excluded-namespaces)
907 (*extension-namespaces* extension-namespaces)
909 (compile-global-variable <variable> global-env)))
910 (setf value-thunk fn)
911 (setf (variable-value-thunk variable) fn)))))
912 (setf (variable-value-thunk-setter variable)
913 value-thunk-setter)
914 (setf (gethash (cons local-name uri)
915 (initial-global-variable-thunks global-env))
916 global-variable-thunk)
917 (setf (variable-chain-thunk chain) global-variable-thunk)
918 (push variable (variable-chain-definitions chain))
919 chain))))))
921 (defun parse-keys! (stylesheet <transform> env)
922 (xpath:with-namespaces ((nil #.*xsl*))
923 (do-toplevel (<key> "key" <transform>)
924 (let ((*instruction-base-uri* (stp:base-uri <key>)))
925 (stp:with-attributes (name match use) <key>
926 (unless name (xslt-error "key name attribute not specified"))
927 (unless match (xslt-error "key match attribute not specified"))
928 (unless use (xslt-error "key use attribute not specified"))
929 (multiple-value-bind (local-name uri)
930 (decode-qname name env nil)
931 (add-key stylesheet
932 (cons local-name uri)
933 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
934 (compile-xpath use env))))))))
936 (defun prepare-global-variables (stylesheet <transform>)
937 (xpath:with-namespaces ((nil #.*xsl*))
938 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet))
939 (global-env (make-instance 'global-variable-environment
940 :initial-global-variable-thunks igvt))
941 (chains '()))
942 (do-toplevel (<variable> "variable|param" <transform>)
943 (let ((chain
944 (parse-global-variable! stylesheet <variable> global-env)))
945 (xslt-trace "parsing global variable ~s (uri ~s)"
946 (variable-chain-local-name chain)
947 (variable-chain-uri chain))
948 (when (find chain
949 chains
950 :test (lambda (a b)
951 (and (equal (variable-chain-local-name a)
952 (variable-chain-local-name b))
953 (equal (variable-chain-uri a)
954 (variable-chain-uri b)))))
955 (xslt-error "duplicate definition for global variable ~A"
956 (variable-chain-local-name chain)))
957 (push chain chains)))
958 (setf chains (nreverse chains))
959 (let ((table (stylesheet-global-variables stylesheet))
960 (newlen (length *global-variable-declarations*)))
961 (adjust-array table newlen :fill-pointer newlen)
962 (dolist (chain chains)
963 (setf (elt table (variable-chain-index chain)) chain)))
964 (lambda ()
965 ;; now that the global environment knows about all variables, run the
966 ;; thunk setters to perform their compilation
967 (mapc (lambda (chain)
968 (dolist (var (variable-chain-definitions chain))
969 (funcall (variable-value-thunk-setter var))))
970 chains)))))
972 (defun parse-templates! (stylesheet <transform> env)
973 (let ((i 0))
974 (do-toplevel (<template> "template" <transform>)
975 (let ((*namespaces* (acons-namespaces <template>))
976 (*instruction-base-uri* (stp:base-uri <template>)))
977 (with-import-magic (<template> env)
978 (dolist (template (compile-template <template> env i))
979 (let ((name (template-name template)))
980 (if name
981 (let* ((table (stylesheet-named-templates stylesheet))
982 (head (car (gethash name table))))
983 (when (and head (eql (template-import-priority head)
984 (template-import-priority template)))
985 ;; fixme: is this supposed to be a run-time error?
986 (xslt-error "conflicting templates for ~A" name))
987 (push template (gethash name table)))
988 (let ((mode (ensure-mode/qname stylesheet
989 (template-mode-qname template)
990 env)))
991 (setf (template-mode template) mode)
992 (push template (mode-templates mode))))))))
993 (incf i))))
996 ;;;; APPLY-STYLESHEET
998 (defvar *stylesheet*)
1000 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
1002 (defun unalias-uri (uri)
1003 (let ((result
1004 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
1005 uri)))
1006 (check-type result string)
1007 result))
1009 (defstruct (parameter
1010 (:constructor make-parameter (value local-name &optional uri)))
1011 (uri "")
1012 local-name
1013 value)
1015 (defun find-parameter-value (local-name uri parameters)
1016 (dolist (p parameters)
1017 (when (and (equal (parameter-local-name p) local-name)
1018 (equal (parameter-uri p) uri))
1019 (return (parameter-value p)))))
1021 (defvar *uri-resolver*)
1023 (defun parse-allowing-microsoft-bom (pathname handler)
1024 (with-open-file (s pathname :element-type '(unsigned-byte 8))
1025 (unless (and (eql (read-byte s nil) #xef)
1026 (eql (read-byte s nil) #xbb)
1027 (eql (read-byte s nil) #xbf))
1028 (file-position s 0))
1029 (cxml:parse s handler)))
1031 (defvar *documents*)
1033 (defun %document (uri-string base-uri)
1034 (let* ((absolute-uri
1035 (puri:merge-uris uri-string (or base-uri "")))
1036 (resolved-uri
1037 (if *uri-resolver*
1038 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
1039 absolute-uri))
1040 (pathname
1041 (handler-case
1042 (uri-to-pathname resolved-uri)
1043 (cxml:xml-parse-error (c)
1044 (xslt-error "cannot find referenced document ~A: ~A"
1045 resolved-uri c))))
1046 (xpath-root-node
1047 (or (gethash pathname *documents*)
1048 (setf (gethash pathname *documents*)
1049 (make-whitespace-stripper
1050 (handler-case
1051 (parse-allowing-microsoft-bom pathname
1052 (stp:make-builder))
1053 ((or file-error cxml:xml-parse-error) (c)
1054 (xslt-error "cannot parse referenced document ~A: ~A"
1055 pathname c)))
1056 (stylesheet-strip-tests *stylesheet*))))))
1057 (when (puri:uri-fragment absolute-uri)
1058 (xslt-error "use of fragment identifiers in document() not supported"))
1059 xpath-root-node))
1061 (xpath-sys:define-extension xslt *xsl*)
1063 (defun document-base-uri (node)
1064 (xpath-protocol:base-uri
1065 (cond
1066 ((xpath-protocol:node-type-p node :document)
1067 (xpath::find-in-pipe-if
1068 (lambda (x)
1069 (xpath-protocol:node-type-p x :element))
1070 (xpath-protocol:child-pipe node)))
1071 ((xpath-protocol:node-type-p node :element)
1072 node)
1074 (xpath-protocol:parent-node node)))))
1076 (xpath-sys:define-xpath-function/lazy
1077 xslt :document
1078 (object &optional node-set)
1079 (let ((instruction-base-uri *instruction-base-uri*))
1080 (lambda (ctx)
1081 (let* ((object (funcall object ctx))
1082 (node-set (and node-set (funcall node-set ctx)))
1083 (base-uri
1084 (if node-set
1085 (document-base-uri (xpath::textually-first-node node-set))
1086 instruction-base-uri)))
1087 (xpath-sys:make-node-set
1088 (if (xpath:node-set-p object)
1089 (xpath:map-node-set->list
1090 (lambda (node)
1091 (%document (xpath:string-value node)
1092 (if node-set
1093 base-uri
1094 (document-base-uri node))))
1095 object)
1096 (list (%document (xpath:string-value object) base-uri))))))))
1098 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1099 (let ((namespaces *namespaces*))
1100 (lambda (ctx)
1101 (let* ((qname (xpath:string-value (funcall name ctx)))
1102 (object (funcall object ctx))
1103 (expanded-name
1104 (multiple-value-bind (local-name uri)
1105 (decode-qname/runtime qname namespaces nil)
1106 (cons local-name uri)))
1107 (key (find-key expanded-name *stylesheet*)))
1108 (labels ((get-by-key (value)
1109 (let ((value (xpath:string-value value)))
1110 (xpath::filter-pipe
1111 #'(lambda (node)
1112 (let ((uses
1113 (xpath:evaluate-compiled (key-use key) node)))
1114 (if (xpath:node-set-p uses)
1115 (xpath::find-in-pipe
1116 value
1117 (xpath-sys:pipe-of uses)
1118 :key #'xpath:string-value
1119 :test #'equal)
1120 (equal value (xpath:string-value uses)))))
1121 (xpath-sys:pipe-of
1122 (xpath:node-set-value
1123 (xpath:evaluate-compiled (key-match key) ctx)))))))
1124 (xpath-sys:make-node-set
1125 (xpath::sort-pipe
1126 (if (xpath:node-set-p object)
1127 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1128 (get-by-key object)))))))))
1130 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1132 (xpath-sys:define-xpath-function/lazy xslt :current ()
1133 #'(lambda (ctx)
1134 (xpath-sys:make-node-set
1135 (xpath-sys:make-pipe
1136 (xpath:context-starting-node ctx)
1137 nil))))
1139 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1140 #'(lambda (ctx)
1141 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1142 (funcall name ctx))
1143 "")))
1145 (defun %get-node-id (node)
1146 (when (xpath:node-set-p node)
1147 (setf node (xpath::textually-first-node node)))
1148 (when node
1149 (let ((id (xpath-sys:get-node-id node))
1150 (highest-base-uri
1151 (loop
1152 for parent = node then next
1153 for next = (xpath-protocol:parent-node parent)
1154 for this-base-uri = (xpath-protocol:base-uri parent)
1155 for highest-base-uri = (if (plusp (length this-base-uri))
1156 this-base-uri
1157 highest-base-uri)
1158 while next
1159 finally (return highest-base-uri))))
1160 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1161 ;; checked only if everything else matches.
1163 ;; This might be pointless premature optimization, but I like the idea :-)
1164 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1166 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1167 (if node-set-thunk
1168 #'(lambda (ctx)
1169 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1170 #'(lambda (ctx)
1171 (%get-node-id (xpath:context-node ctx)))))
1173 (declaim (special *available-instructions*))
1175 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1176 (let ((namespaces *namespaces*))
1177 #'(lambda (ctx)
1178 (let ((qname (funcall qname ctx)))
1179 (multiple-value-bind (local-name uri)
1180 (decode-qname/runtime qname namespaces nil)
1181 (and (equal uri *xsl*)
1182 (gethash local-name *available-instructions*)
1183 t))))))
1185 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1186 (let ((namespaces *namespaces*))
1187 #'(lambda (ctx)
1188 (let ((qname (funcall qname ctx)))
1189 (multiple-value-bind (local-name uri)
1190 (decode-qname/runtime qname namespaces nil)
1191 (and (zerop (length uri))
1192 (or (xpath-sys:find-xpath-function local-name *xsl*)
1193 (xpath-sys:find-xpath-function local-name uri))
1194 t))))))
1196 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1197 (let ((namespaces *namespaces*))
1198 (lambda (ctx)
1199 (let ((qname (funcall qname ctx)))
1200 (multiple-value-bind (local-name uri)
1201 (decode-qname/runtime qname namespaces nil)
1202 (if (equal uri *xsl*)
1203 (cond
1204 ((equal local-name "version")
1205 "1")
1206 ((equal local-name "vendor")
1207 "Xuriella")
1208 ((equal local-name "vendor-uri")
1209 "http://repo.or.cz/w/xuriella.git")
1211 ""))
1212 ""))))))
1214 (defun apply-stylesheet
1215 (stylesheet source-designator
1216 &key output parameters uri-resolver navigator)
1217 (when (typep stylesheet 'xml-designator)
1218 (setf stylesheet
1219 (handler-bind
1220 ((cxml:xml-parse-error
1221 (lambda (c)
1222 (xslt-error "cannot parse stylesheet: ~A" c))))
1223 (parse-stylesheet stylesheet))))
1224 (invoke-with-output-sink
1225 (lambda ()
1226 (handler-case*
1227 (let* ((*documents* (make-hash-table :test 'equal))
1228 (xpath:*navigator* (or navigator :default-navigator))
1229 (puri:*strict-parse* nil)
1230 (*stylesheet* stylesheet)
1231 (*empty-mode* (make-mode))
1232 (*default-mode* (find-mode stylesheet nil))
1233 (global-variable-chains
1234 (stylesheet-global-variables stylesheet))
1235 (*global-variable-values*
1236 (make-variable-value-array (length global-variable-chains)))
1237 (*uri-resolver* uri-resolver)
1238 (source-document
1239 (if (typep source-designator 'xml-designator)
1240 (cxml:parse source-designator (stp:make-builder))
1241 source-designator))
1242 (xpath-root-node
1243 (make-whitespace-stripper
1244 source-document
1245 (stylesheet-strip-tests stylesheet)))
1246 (ctx (xpath:make-context xpath-root-node)))
1247 (when (pathnamep source-designator)
1248 (setf (gethash source-designator *documents*) xpath-root-node))
1249 (map nil
1250 (lambda (chain)
1251 (let ((head (car (variable-chain-definitions chain))))
1252 (when (variable-param-p head)
1253 (let ((value
1254 (find-parameter-value
1255 (variable-chain-local-name chain)
1256 (variable-chain-uri chain)
1257 parameters)))
1258 (when value
1259 (setf (global-variable-value
1260 (variable-chain-index chain))
1261 value))))))
1262 global-variable-chains)
1263 (map nil
1264 (lambda (chain)
1265 (funcall (variable-chain-thunk chain) ctx))
1266 global-variable-chains)
1267 ;; zzz we wouldn't have to mask float traps here if we used the
1268 ;; XPath API properly. Unfortunately I've been using FUNCALL
1269 ;; everywhere instead of EVALUATE, so let's paper over that
1270 ;; at a central place to be sure:
1271 (xpath::with-float-traps-masked ()
1272 (apply-templates ctx :mode *default-mode*)))
1273 (xpath:xpath-error (c)
1274 (xslt-error "~A" c))))
1275 (stylesheet-output-specification stylesheet)
1276 output))
1278 (defun find-attribute-set (local-name uri)
1279 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1280 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1282 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1283 (when sort-predicate
1284 (setf list
1285 (mapcar #'xpath:context-node
1286 (stable-sort (contextify-node-list list)
1287 sort-predicate))))
1288 (let* ((n (length list))
1289 (s/d (lambda () n)))
1290 (loop
1291 for i from 1
1292 for child in list
1294 (apply-templates (xpath:make-context child s/d i)
1295 :param-bindings param-bindings
1296 :mode mode))))
1298 (defvar *stack-limit* 200)
1300 (defun invoke-with-stack-limit (fn)
1301 (let ((*stack-limit* (1- *stack-limit*)))
1302 (unless (plusp *stack-limit*)
1303 (xslt-error "*stack-limit* reached; stack overflow"))
1304 (funcall fn)))
1306 (defun invoke-template (ctx template param-bindings)
1307 (let ((*lexical-variable-values*
1308 (make-variable-value-array (template-n-variables template))))
1309 (with-stack-limit ()
1310 (loop
1311 for (name-cons value) in param-bindings
1312 for (nil index nil) = (find name-cons
1313 (template-params template)
1314 :test #'equal
1315 :key #'car)
1317 (when index
1318 (setf (lexical-variable-value index) value)))
1319 (funcall (template-body template) ctx))))
1321 (defun apply-default-templates (ctx mode)
1322 (let ((node (xpath:context-node ctx)))
1323 (cond
1324 ((or (xpath-protocol:node-type-p node :processing-instruction)
1325 (xpath-protocol:node-type-p node :comment)))
1326 ((or (xpath-protocol:node-type-p node :text)
1327 (xpath-protocol:node-type-p node :attribute))
1328 (write-text (xpath-protocol:node-text node)))
1330 (apply-templates/list
1331 (xpath::force
1332 (xpath-protocol:child-pipe node))
1333 :mode mode)))))
1335 (defvar *apply-imports*)
1337 (defun apply-applicable-templates (ctx templates param-bindings finally)
1338 (labels ((apply-imports (&optional actual-param-bindings)
1339 (if templates
1340 (let* ((this (pop templates))
1341 (low (template-apply-imports-limit this))
1342 (high (template-import-priority this)))
1343 (setf templates
1344 (remove-if-not
1345 (lambda (x)
1346 (<= low (template-import-priority x) high))
1347 templates))
1348 (invoke-template ctx this actual-param-bindings))
1349 (funcall finally))))
1350 (let ((*apply-imports* #'apply-imports))
1351 (apply-imports param-bindings))))
1353 (defun apply-templates (ctx &key param-bindings mode)
1354 (apply-applicable-templates ctx
1355 (find-templates ctx (or mode *default-mode*))
1356 param-bindings
1357 (lambda ()
1358 (apply-default-templates ctx mode))))
1360 (defun call-template (ctx name &optional param-bindings)
1361 (apply-applicable-templates ctx
1362 (find-named-templates name)
1363 param-bindings
1364 (lambda ()
1365 (error "cannot find named template: ~s"
1366 name))))
1368 (defun find-templates (ctx mode)
1369 (let* ((matching-candidates
1370 (remove-if-not (lambda (template)
1371 (template-matches-p template ctx))
1372 (mode-templates mode)))
1373 (npriorities
1374 (if matching-candidates
1375 (1+ (reduce #'max
1376 matching-candidates
1377 :key #'template-import-priority))
1379 (priority-groups (make-array npriorities :initial-element nil)))
1380 (dolist (template matching-candidates)
1381 (push template
1382 (elt priority-groups (template-import-priority template))))
1383 (loop
1384 for i from (1- npriorities) downto 0
1385 for group = (elt priority-groups i)
1386 for template = (maximize #'template< group)
1387 when template
1388 collect template)))
1390 (defun find-named-templates (name)
1391 (gethash name (stylesheet-named-templates *stylesheet*)))
1393 (defun template< (a b) ;assuming same import priority
1394 (let ((p (template-priority a))
1395 (q (template-priority b)))
1396 (cond
1397 ((< p q) t)
1398 ((> p q) nil)
1400 (xslt-cerror "conflicting templates:~_~A,~_~A"
1401 (template-match-expression a)
1402 (template-match-expression b))
1403 (< (template-position a) (template-position b))))))
1405 (defun maximize (< things)
1406 (when things
1407 (let ((max (car things)))
1408 (dolist (other (cdr things))
1409 (when (funcall < max other)
1410 (setf max other)))
1411 max)))
1413 (defun template-matches-p (template ctx)
1414 (find (xpath:context-node ctx)
1415 (xpath:all-nodes (funcall (template-match-thunk template) ctx))
1416 :test #'xpath-protocol:node-equal))
1418 (defun invoke-with-output-sink (fn output-spec output)
1419 (etypecase output
1420 (pathname
1421 (with-open-file (s output
1422 :direction :output
1423 :element-type '(unsigned-byte 8)
1424 :if-exists :rename-and-delete)
1425 (invoke-with-output-sink fn output-spec s)))
1426 ((or stream null)
1427 (invoke-with-output-sink fn
1428 output-spec
1429 (make-output-sink output-spec output)))
1430 ((or hax:abstract-handler sax:abstract-handler)
1431 (with-xml-output output
1432 (when (typep output '(or combi-sink auto-detect-sink))
1433 (sax:start-dtd output
1434 :autodetect-me-please
1435 (output-doctype-public output-spec)
1436 (output-doctype-system output-spec)))
1437 (funcall fn)))))
1439 (defun make-output-sink (output-spec stream)
1440 (let* ((ystream
1441 (if stream
1442 (let ((et (stream-element-type stream)))
1443 (cond
1444 ((or (null et) (subtypep et '(unsigned-byte 8)))
1445 (runes:make-octet-stream-ystream stream))
1446 ((subtypep et 'character)
1447 (runes:make-character-stream-ystream stream))))
1448 (runes:make-rod-ystream)))
1449 (omit-xml-declaration-p
1450 (equal (output-omit-xml-declaration output-spec) "yes"))
1451 (sax-target
1452 (make-instance 'cxml::sink
1453 :ystream ystream
1454 :omit-xml-declaration-p omit-xml-declaration-p)))
1455 (flet ((make-combi-sink ()
1456 (make-instance 'combi-sink
1457 :hax-target (make-instance 'chtml::sink
1458 :ystream ystream)
1459 :sax-target sax-target
1460 :encoding (output-encoding output-spec))))
1461 (let ((method-key
1462 (cond
1463 ((equalp (output-method output-spec) "HTML") :html)
1464 ((equalp (output-method output-spec) "TEXT") :text)
1465 ((equalp (output-method output-spec) "XML") :xml)
1466 (t nil))))
1467 (cond
1468 ((and (eq method-key :html)
1469 (null (output-doctype-system output-spec))
1470 (null (output-doctype-public output-spec)))
1471 (make-combi-sink))
1472 ((eq method-key :text)
1473 (make-text-filter sax-target))
1474 ((and (eq method-key :xml)
1475 (null (output-doctype-system output-spec)))
1476 sax-target)
1478 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1480 (defstruct template
1481 match-expression
1482 match-thunk
1483 name
1484 import-priority
1485 apply-imports-limit
1486 priority
1487 position
1488 mode
1489 mode-qname
1490 params
1491 body
1492 n-variables)
1494 (defun expression-priority (form)
1495 (let ((step (second form)))
1496 (if (and (null (cddr form))
1497 (listp step)
1498 (member (car step) '(:child :attribute))
1499 (null (cddr step)))
1500 (let ((name (second step)))
1501 (cond
1502 ((or (stringp name)
1503 (and (consp name)
1504 (or (eq (car name) :qname)
1505 (eq (car name) :processing-instruction))))
1506 0.0)
1507 ((and (consp name)
1508 (or (eq (car name) :namespace)
1509 (eq (car name) '*)))
1510 -0.25)
1512 -0.5)))
1513 0.5)))
1515 (defun valid-expression-p (expr)
1516 (cond
1517 ((atom expr) t)
1518 ((eq (first expr) :path)
1519 (every (lambda (x)
1520 (let ((filter (third x)))
1521 (or (null filter) (valid-expression-p filter))))
1522 (cdr expr)))
1523 ((eq (first expr) :variable) ;(!)
1524 nil)
1526 (every #'valid-expression-p (cdr expr)))))
1528 (defun parse-xpath (str)
1529 (handler-case
1530 (xpath:parse-xpath str)
1531 (xpath:xpath-error (c)
1532 (xslt-error "~A" c))))
1534 ;; zzz also use naive-pattern-expression here?
1535 (defun parse-key-pattern (str)
1536 (let ((parsed
1537 (mapcar #'(lambda (item)
1538 `(:path (:root :node)
1539 (:descendant-or-self *)
1540 ,@(cdr item)))
1541 (parse-pattern str))))
1542 (if (null (rest parsed))
1543 (first parsed)
1544 `(:union ,@parsed))))
1546 (defun parse-pattern (str)
1547 ;; zzz check here for anything not allowed as an XSLT pattern
1548 ;; zzz can we hack id() and key() here?
1549 (let ((form (parse-xpath str)))
1550 (unless (consp form)
1551 (xslt-error "not a valid pattern: ~A" str))
1552 (labels ((process-form (form)
1553 (cond ((eq (car form) :union)
1554 (alexandria:mappend #'process-form (rest form)))
1555 ((not (or (eq (car form) :path)
1556 (and (eq (car form) :filter)
1557 (let ((filter (second form)))
1558 (and (consp filter)
1559 (member (car filter)
1560 '(:key :id))))
1561 (equal (third form) '(:true)))
1562 (member (car form) '(:key :id))))
1563 (xslt-error "not a valid pattern: ~A ~A" str form))
1564 ((not (valid-expression-p form))
1565 (xslt-error "invalid filter"))
1566 (t (list form)))))
1567 (process-form form))))
1569 (defun naive-pattern-expression (x)
1570 (ecase (car x)
1571 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1572 ((:filter :key :id) x)))
1574 (defun compile-value-thunk (value env)
1575 (if (and (listp value) (eq (car value) 'progn))
1576 (let ((inner-thunk (compile-instruction value env)))
1577 (lambda (ctx)
1578 (apply-to-result-tree-fragment ctx inner-thunk)))
1579 (compile-xpath value env)))
1581 (defun compile-var-binding (name value env)
1582 (multiple-value-bind (local-name uri)
1583 (decode-qname name env nil)
1584 (let ((thunk (xslt-trace-thunk
1585 (compile-value-thunk value env)
1586 "local variable ~s = ~s" name :result)))
1587 (list (cons local-name uri)
1588 (push-variable local-name
1590 *lexical-variable-declarations*)
1591 thunk))))
1593 (defun compile-var-bindings (forms env)
1594 (loop
1595 for (name value) in forms
1596 collect (compile-var-binding name value env)))
1598 (defun compile-template (<template> env position)
1599 (stp:with-attributes (match name priority mode) <template>
1600 (unless (or name match)
1601 (xslt-error "missing match in template"))
1602 (multiple-value-bind (params body-pos)
1603 (loop
1604 for i from 0
1605 for child in (stp:list-children <template>)
1606 while (namep child "param")
1607 collect (parse-param child) into params
1608 finally (return (values params i)))
1609 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1610 (param-bindings (compile-var-bindings params env))
1611 (body (parse-body <template> body-pos (mapcar #'car params)))
1612 (body-thunk (compile-instruction `(progn ,@body) env))
1613 (outer-body-thunk
1614 (xslt-trace-thunk
1615 #'(lambda (ctx)
1616 (unwind-protect
1617 (progn
1618 ;; set params that weren't initialized by apply-templates
1619 (loop for (name index param-thunk) in param-bindings
1620 when (eq (lexical-variable-value index nil) 'unbound)
1621 do (setf (lexical-variable-value index)
1622 (funcall param-thunk ctx)))
1623 (funcall body-thunk ctx))))
1624 "template: match = ~s name = ~s" match name))
1625 (n-variables (length *lexical-variable-declarations*)))
1626 (append
1627 (when name
1628 (multiple-value-bind (local-name uri)
1629 (decode-qname name env nil)
1630 (list
1631 (make-template :name (cons local-name uri)
1632 :import-priority *import-priority*
1633 :apply-imports-limit *apply-imports-limit*
1634 :params param-bindings
1635 :body outer-body-thunk
1636 :n-variables n-variables))))
1637 (when match
1638 (mapcar (lambda (expression)
1639 (let ((match-thunk
1640 (xslt-trace-thunk
1641 (compile-xpath
1642 `(xpath:xpath
1643 ,(naive-pattern-expression expression))
1644 env)
1645 "match-thunk for template (match ~s): ~s --> ~s"
1646 match expression :result))
1647 (p (if priority
1648 (parse-number:parse-number priority)
1649 (expression-priority expression))))
1650 (make-template :match-expression expression
1651 :match-thunk match-thunk
1652 :import-priority *import-priority*
1653 :apply-imports-limit *apply-imports-limit*
1654 :priority p
1655 :position position
1656 :mode-qname mode
1657 :params param-bindings
1658 :body outer-body-thunk
1659 :n-variables n-variables)))
1660 (parse-pattern match))))))))
1661 #+(or)
1662 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")