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