Allow id and xml:space on stylesheet
[xuriella.git] / xslt.lisp
blobba08166ef523a6682ae11db537dabecddf1dc741
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-resignalled-errors ((&optional) &body body)
90 `(invoke-with-resignalled-errors (lambda () ,@body)))
92 (defun invoke-with-resignalled-errors (fn)
93 (handler-bind
94 ((xpath:xpath-error
95 (lambda (c)
96 (xslt-error "~A" c)))
97 (babel-encodings:character-encoding-error
98 (lambda (c)
99 (xslt-error "~A" c))))
100 (funcall fn)))
102 (defmacro with-forward-compatible-errors (error-form &body body)
103 `(invoke-with-forward-compatible-errors (lambda () ,@body)
104 (lambda () ,error-form)))
106 (defun invoke-with-forward-compatible-errors (fn error-fn)
107 (let ((result))
108 (tagbody
109 (handler-bind
110 ((xpath:xpath-error
111 (lambda (c)
112 (declare (ignore c))
113 (when *forwards-compatible-p*
114 (go error)))))
115 (setf result (funcall fn)))
116 (go done)
117 error
118 (setf result (funcall error-fn))
119 done)
120 result))
122 (defun compile-xpath (xpath &optional env)
123 (with-resignalled-errors ()
124 (with-forward-compatible-errors
125 (lambda (ctx)
126 (xslt-error "attempt to evaluate an XPath expression with compile-time errors, delayed due to forwards compatible processing: ~A"
127 xpath))
128 (xpath:compile-xpath xpath env))))
130 (defmacro with-stack-limit ((&optional) &body body)
131 `(invoke-with-stack-limit (lambda () ,@body)))
133 (defparameter *without-xslt-current-p* nil)
135 (defmacro without-xslt-current ((&optional) &body body)
136 `(invoke-without-xslt-current (lambda () ,@body)))
138 (defun invoke-without-xslt-current (fn)
139 (let ((*without-xslt-current-p* t))
140 (funcall fn)))
142 ;;; (defun invoke-without-xslt-current (fn)
143 ;;; (let ((non-extensions (gethash "" xpath::*extensions*))
144 ;;; (xpath::*extensions*
145 ;;; ;; hide XSLT extensions
146 ;;; (make-hash-table :test #'equal)))
147 ;;; (setf (gethash "" xpath::*extensions*) non-extensions)
148 ;;; (funcall fn)))
151 ;;;; Helper functions and macros
153 (defun check-for-invalid-attributes (valid-names node)
154 (labels ((check-attribute (a)
155 (unless
156 (let ((uri (stp:namespace-uri a)))
157 (or (and (plusp (length uri)) (not (equal uri *xsl*)))
158 (find (cons (stp:local-name a) uri)
159 valid-names
160 :test #'equal)))
161 (xslt-error "attribute ~A not allowed on ~A"
162 (stp:local-name a)
163 (stp:local-name node)))))
164 (stp:map-attributes nil #'check-attribute node)))
166 (defmacro only-with-attributes ((&rest specs) node &body body)
167 (let ((valid-names
168 (mapcar (lambda (entry)
169 (if (and (listp entry) (cdr entry))
170 (destructuring-bind (name &optional (uri ""))
171 (cdr entry)
172 (cons name uri))
173 (cons (string-downcase
174 (princ-to-string
175 (symbol-name entry)))
176 "")))
177 specs))
178 (%node (gensym)))
179 `(let ((,%NODE ,node))
180 (check-for-invalid-attributes ',valid-names ,%NODE)
181 (stp:with-attributes ,specs ,%NODE
182 ,@body))))
184 (defun map-pipe-eagerly (fn pipe)
185 (xpath::enumerate pipe :key fn :result nil))
187 (defmacro do-pipe ((var pipe &optional result) &body body)
188 `(block nil
189 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
190 ,result))
193 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
195 (defparameter *namespaces*
196 '((nil . "")
197 ("xmlns" . #"http://www.w3.org/2000/xmlns/")
198 ("xml" . #"http://www.w3.org/XML/1998/namespace")))
200 (defvar *global-variable-declarations*)
201 (defvar *lexical-variable-declarations*)
203 (defvar *global-variable-values*)
204 (defvar *lexical-variable-values*)
206 (defclass xslt-environment () ())
208 (defun split-qname (str)
209 (handler-case
210 (multiple-value-bind (prefix local-name)
211 (cxml::split-qname str)
212 (unless
213 ;; FIXME: cxml should really offer a function that does
214 ;; checks for NCName and QName in a sensible way for user code.
215 ;; cxml::split-qname is tailored to the needs of the parser.
217 ;; For now, let's just check the syntax explicitly.
218 (and (or (null prefix) (xpath::nc-name-p prefix))
219 (xpath::nc-name-p local-name))
220 (xslt-error "not a qname: ~A" str))
221 (values prefix local-name))
222 (cxml:well-formedness-violation ()
223 (xslt-error "not a qname: ~A" str))))
225 (defun decode-qname (qname env attributep)
226 (unless qname
227 (xslt-error "missing name"))
228 (multiple-value-bind (prefix local-name)
229 (split-qname qname)
230 (values local-name
231 (if (or prefix (not attributep))
232 (xpath-sys:environment-find-namespace env (or prefix ""))
234 prefix)))
236 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
237 (or (cdr (assoc prefix *namespaces* :test 'equal))
238 ;; zzz gross hack.
239 ;; Change the entire code base to represent "no prefix" as the
240 ;; empty string consistently. unparse.lisp has already been changed.
241 (and (equal prefix "")
242 (cdr (assoc nil *namespaces* :test 'equal)))
243 (and (eql prefix nil)
244 (cdr (assoc "" *namespaces* :test 'equal)))))
246 (defun find-variable-index (local-name uri table)
247 (position (cons local-name uri) table :test 'equal))
249 (defun intern-global-variable (local-name uri)
250 (or (find-variable-index local-name uri *global-variable-declarations*)
251 (push-variable local-name uri *global-variable-declarations*)))
253 (defun push-variable (local-name uri table)
254 (prog1
255 (length table)
256 (vector-push-extend (cons local-name uri) table)))
258 (defun lexical-variable-value (index &optional (errorp t))
259 (let ((result (svref *lexical-variable-values* index)))
260 (when errorp
261 (assert (not (eq result 'unbound))))
262 result))
264 (defun (setf lexical-variable-value) (newval index)
265 (assert (not (eq newval 'unbound)))
266 (setf (svref *lexical-variable-values* index) newval))
268 (defun global-variable-value (index &optional (errorp t))
269 (let ((result (svref *global-variable-values* index)))
270 (when errorp
271 (assert (not (eq result 'unbound))))
272 result))
274 (defun (setf global-variable-value) (newval index)
275 (assert (not (eq newval 'unbound)))
276 (setf (svref *global-variable-values* index) newval))
278 (defmethod xpath-sys:environment-find-function
279 ((env xslt-environment) lname uri)
280 (or (if (string= uri "")
281 (or (xpath-sys:find-xpath-function lname *xsl*)
282 (xpath-sys:find-xpath-function lname uri))
283 (xpath-sys:find-xpath-function lname uri))
284 (when *forwards-compatible-p*
285 (lambda (&rest ignore)
286 (declare (ignore ignore))
287 (xslt-error "attempt to call an unknown XPath function (~A); error delayed until run-time due to forwards compatible processing"
288 lname)))))
290 (defmethod xpath-sys:environment-find-variable
291 ((env xslt-environment) lname uri)
292 (let ((index
293 (find-variable-index lname uri *lexical-variable-declarations*)))
294 (when index
295 (lambda (ctx)
296 (declare (ignore ctx))
297 (svref *lexical-variable-values* index)))))
299 (defclass lexical-xslt-environment (xslt-environment) ())
301 (defmethod xpath-sys:environment-find-variable
302 ((env lexical-xslt-environment) lname uri)
303 (or (call-next-method)
304 (let ((index
305 (find-variable-index lname uri *global-variable-declarations*)))
306 (when index
307 (xslt-trace-thunk
308 (lambda (ctx)
309 (declare (ignore ctx))
310 (svref *global-variable-values* index))
311 "global ~s (uri ~s) = ~s" lname uri :result)))))
313 (defclass key-environment (xslt-environment) ())
315 (defmethod xpath-sys:environment-find-variable
316 ((env key-environment) lname uri)
317 (declare (ignore lname uri))
318 (xslt-error "disallowed variable reference"))
320 (defclass global-variable-environment (xslt-environment)
321 ((initial-global-variable-thunks
322 :initarg :initial-global-variable-thunks
323 :accessor initial-global-variable-thunks)))
325 (defmethod xpath-sys:environment-find-variable
326 ((env global-variable-environment) lname uri)
327 (or (call-next-method)
328 (gethash (cons lname uri) (initial-global-variable-thunks env))))
331 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
332 ;;;;
333 ;;;; A sink that serializes only text not contained in any element.
335 (defmacro with-toplevel-text-output-sink ((var) &body body)
336 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
338 (defclass toplevel-text-output-sink (sax:default-handler)
339 ((target :initarg :target :accessor text-output-sink-target)
340 (depth :initform 0 :accessor textoutput-sink-depth)))
342 (defmethod sax:start-element ((sink toplevel-text-output-sink)
343 namespace-uri local-name qname attributes)
344 (declare (ignore namespace-uri local-name qname attributes))
345 (incf (textoutput-sink-depth sink)))
347 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
348 (when (zerop (textoutput-sink-depth sink))
349 (write-string data (text-output-sink-target sink))))
351 (defmethod sax:unescaped ((sink toplevel-text-output-sink) data)
352 (sax:characters sink data))
354 (defmethod sax:end-element ((sink toplevel-text-output-sink)
355 namespace-uri local-name qname)
356 (declare (ignore namespace-uri local-name qname))
357 (decf (textoutput-sink-depth sink)))
359 (defun invoke-with-toplevel-text-output-sink (fn)
360 (with-output-to-string (s)
361 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
364 ;;;; TEXT-FILTER
365 ;;;;
366 ;;;; A sink that passes through only text (at any level) and turns to
367 ;;;; into unescaped characters.
369 (defclass text-filter (sax:default-handler)
370 ((target :initarg :target :accessor text-filter-target)))
372 (defmethod sax:characters ((sink text-filter) data)
373 (sax:unescaped (text-filter-target sink) data))
375 (defmethod sax:unescaped ((sink text-filter) data)
376 (sax:unescaped (text-filter-target sink) data))
378 (defmethod sax:end-document ((sink text-filter))
379 (sax:end-document (text-filter-target sink)))
381 (defun make-text-filter (target)
382 (make-instance 'text-filter :target target))
385 ;;;; ESCAPER
386 ;;;;
387 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
388 ;;;; XSLT 16.4.
390 (defclass escaper (cxml:broadcast-handler)
393 (defmethod sax:unescaped ((sink escaper) data)
394 (sax:characters sink data))
396 (defun make-escaper (target)
397 (make-instance 'escaper :handlers (list target)))
400 ;;;; Names
402 (defun of-name (local-name)
403 (stp:of-name local-name *xsl*))
405 (defun namep (node local-name)
406 (and (typep node '(or stp:element stp:attribute))
407 (equal (stp:namespace-uri node) *xsl*)
408 (equal (stp:local-name node) local-name)))
411 ;;;; PARSE-STYLESHEET
413 (defstruct stylesheet
414 (modes (make-hash-table :test 'equal))
415 (global-variables (make-empty-declaration-array))
416 (output-specification (make-output-specification))
417 (strip-tests nil)
418 (strip-thunk nil)
419 (named-templates (make-hash-table :test 'equal))
420 (attribute-sets (make-hash-table :test 'equal))
421 (keys (make-hash-table :test 'equal))
422 (namespace-aliases (make-hash-table :test 'equal))
423 (decimal-formats (make-hash-table :test 'equal))
424 (initial-global-variable-thunks (make-hash-table :test 'equal)))
426 (defstruct mode
427 (templates nil)
428 (match-thunk (lambda (ignore) (declare (ignore ignore)) nil)))
430 (defun find-mode (stylesheet local-name &optional uri)
431 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
433 (defun ensure-mode (stylesheet &optional local-name uri)
434 (or (find-mode stylesheet local-name uri)
435 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
436 (make-mode))))
438 (defun ensure-mode/qname (stylesheet qname env)
439 (if qname
440 (multiple-value-bind (local-name uri)
441 (decode-qname qname env nil)
442 (ensure-mode stylesheet local-name uri))
443 (find-mode stylesheet nil)))
445 (defun acons-namespaces (element &optional (bindings *namespaces*))
446 (map-namespace-declarations (lambda (prefix uri)
447 (push (cons prefix uri) bindings))
448 element)
449 bindings)
451 (defun find-key (name stylesheet)
452 (or (gethash name (stylesheet-keys stylesheet))
453 (xslt-error "unknown key: ~a" name)))
455 (defun make-key (match use) (cons match use))
457 (defun key-match (key) (car key))
459 (defun key-use (key) (cdr key))
461 (defun add-key (stylesheet name match use)
462 (if (gethash name (stylesheet-keys stylesheet))
463 (xslt-error "duplicate key: ~a" name)
464 (setf (gethash name (stylesheet-keys stylesheet))
465 (make-key match use))))
467 (defvar *excluded-namespaces* (list *xsl*))
468 (defvar *empty-mode*)
469 (defvar *default-mode*)
471 (defvar *xsl-include-stack* nil)
473 (defun uri-to-pathname (uri)
474 (cxml::uri-to-pathname (puri:parse-uri uri)))
476 ;; Why this extra check for literal result element used as stylesheets,
477 ;; instead of a general check for every literal result element? Because
478 ;; Stylesheet__91804 says so.
479 (defun check-Errors_err035 (literal-result-element)
480 (let ((*namespaces* (acons-namespaces literal-result-element))
481 (env (make-instance 'lexical-xslt-environment)))
482 (stp:with-attributes ((extension-element-prefixes
483 "extension-element-prefixes"
484 *xsl*))
485 literal-result-element
486 (dolist (prefix (words (or extension-element-prefixes "")))
487 (if (equal prefix "#default")
488 (setf prefix nil)
489 (unless (cxml-stp-impl::nc-name-p prefix)
490 (xslt-error "invalid prefix: ~A" prefix)))
491 (let ((uri
492 (or (xpath-sys:environment-find-namespace env prefix)
493 (xslt-error "namespace not found: ~A" prefix))))
494 (when (equal uri (stp:namespace-uri literal-result-element))
495 (xslt-error "literal result element used as stylesheet, but is ~
496 declared as an extension element")))))))
498 (defun unwrap-2.3 (document)
499 (let ((literal-result-element (stp:document-element document))
500 (new-template (stp:make-element "template" *xsl*))
501 (new-document-element (stp:make-element "stylesheet" *xsl*)))
502 (check-Errors_err035 literal-result-element)
503 (setf (stp:attribute-value new-document-element "version")
504 (or (stp:attribute-value literal-result-element "version" *xsl*)
505 (xslt-error "not a stylesheet: root element lacks xsl:version")))
506 (setf (stp:attribute-value new-template "match") "/")
507 (setf (stp:document-element document) new-document-element)
508 (stp:append-child new-document-element new-template)
509 (stp:append-child new-template literal-result-element)
510 new-document-element))
512 (defun parse-stylesheet-to-stp (input uri-resolver)
513 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
514 (<transform> (stp:document-element d)))
515 (unless (equal (stp:namespace-uri <transform>) *xsl*)
516 (setf <transform> (unwrap-2.3 d)))
517 (strip-stylesheet <transform>)
518 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
519 (or (equal (stp:local-name <transform>) "transform")
520 (equal (stp:local-name <transform>) "stylesheet")))
521 (xslt-error "not a stylesheet"))
522 (check-for-invalid-attributes
523 '(("version" . "")
524 ("exclude-result-prefixes" . "")
525 ("extension-element-prefixes" . "")
526 ("space" . "http://www.w3.org/XML/1998/namespace")
527 ("id" . ""))
528 <transform>)
529 (let ((invalid
530 (or (stp:find-child-if (of-name "stylesheet") <transform>)
531 (stp:find-child-if (of-name "transform") <transform>))))
532 (when invalid
533 (xslt-error "invalid top-level element ~A" (stp:local-name invalid))))
534 (dolist (include (stp:filter-children (of-name "include") <transform>))
535 (let* ((uri (puri:merge-uris (or (stp:attribute-value include "href")
536 (xslt-error "include without href"))
537 (stp:base-uri include)))
538 (uri (if uri-resolver
539 (funcall uri-resolver (puri:render-uri uri nil))
540 uri))
541 (str (puri:render-uri uri nil))
542 (pathname
543 (handler-case
544 (uri-to-pathname uri)
545 (cxml:xml-parse-error (c)
546 (xslt-error "cannot find included stylesheet ~A: ~A"
547 uri c)))))
548 (with-open-file
549 (stream pathname
550 :element-type '(unsigned-byte 8)
551 :if-does-not-exist nil)
552 (unless stream
553 (xslt-error "cannot find included stylesheet ~A at ~A"
554 uri pathname))
555 (when (find str *xsl-include-stack* :test #'equal)
556 (xslt-error "recursive inclusion of ~A" uri))
557 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
558 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
559 (stp:insert-child-after <transform>
560 (stp:copy <transform>2)
561 include)
562 (stp:detach include)))))
563 <transform>))
565 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
566 (defvar *apply-imports-limit*)
567 (defvar *import-priority*)
568 (defvar *extension-namespaces*)
569 (defvar *forwards-compatible-p*)
571 (defmacro do-toplevel ((var xpath <transform>) &body body)
572 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
574 (defun map-toplevel (fn xpath <transform>)
575 (dolist (node (list-toplevel xpath <transform>))
576 (let ((*namespaces* *namespaces*))
577 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
578 (when (xpath-protocol:node-type-p ancestor :element)
579 (setf *namespaces* (acons-namespaces ancestor))))
580 (funcall fn node))))
582 (defun list-toplevel (xpath <transform>)
583 (labels ((recurse (sub)
584 (let ((subsubs
585 (xpath-sys:pipe-of
586 (xpath:evaluate "transform|stylesheet" sub))))
587 (xpath::append-pipes
588 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
589 (xpath::mappend-pipe #'recurse subsubs)))))
590 (xpath::sort-nodes (recurse <transform>))))
592 (defmacro with-import-magic ((node env) &body body)
593 `(invoke-with-import-magic (lambda () ,@body) ,node ,env))
595 (defun invoke-with-import-magic (fn node env)
596 (unless (or (namep node "stylesheet") (namep node "transform"))
597 (setf node (stp:parent node)))
598 (let ((*excluded-namespaces* (list *xsl*))
599 (*extension-namespaces* '())
600 (*forwards-compatible-p*
601 (not (equal (stp:attribute-value node "version") "1.0"))))
602 (parse-exclude-result-prefixes! node env)
603 (parse-extension-element-prefixes! node env)
604 (funcall fn)))
606 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
607 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
608 (instruction-base-uri (stp:base-uri <transform>))
609 (namespaces (acons-namespaces <transform>))
610 (apply-imports-limit (1+ *import-priority*))
611 (continuations '()))
612 (let ((*namespaces* namespaces))
613 (invoke-with-import-magic (constantly t) <transform> env))
614 (do-toplevel (elt "node()" <transform>)
615 (let ((version (stp:attribute-value (stp:parent elt) "version")))
616 (cond
617 ((null version)
618 (xslt-error "stylesheet lacks version"))
619 ((equal version "1.0")
620 (if (typep elt 'stp:element)
621 (when (or (equal (stp:namespace-uri elt) "")
622 (and (equal (stp:namespace-uri elt) *xsl*)
623 (not (find (stp:local-name elt)
624 '("key" "template" "output"
625 "strip-space" "preserve-space"
626 "attribute-set" "namespace-alias"
627 "decimal-format" "variable" "param"
628 "import" "include"
629 ;; for include handling:
630 "stylesheet" "transform")
631 :test #'equal))))
632 (xslt-error "unknown top-level element ~A" (stp:local-name elt)))
633 (xslt-error "text at top-level"))))))
634 (macrolet ((with-specials ((&optional) &body body)
635 `(let ((*instruction-base-uri* instruction-base-uri)
636 (*namespaces* namespaces)
637 (*apply-imports-limit* apply-imports-limit))
638 ,@body)))
639 (with-specials ()
640 (do-toplevel (import "import" <transform>)
641 (let ((uri (puri:merge-uris (or (stp:attribute-value import "href")
642 (xslt-error "import without href"))
643 (stp:base-uri import))))
644 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
645 continuations))))
646 (let ((import-priority
647 (incf *import-priority*))
648 (var-cont (prepare-global-variables stylesheet <transform>)))
649 ;; delay the rest of compilation until we've seen all global
650 ;; variables:
651 (lambda ()
652 (mapc #'funcall (nreverse continuations))
653 (with-specials ()
654 (let ((*import-priority* import-priority))
655 (funcall var-cont)
656 (parse-keys! stylesheet <transform> env)
657 (parse-templates! stylesheet <transform> env)
658 (parse-output! stylesheet <transform> env)
659 (parse-strip/preserve-space! stylesheet <transform> env)
660 (parse-attribute-sets! stylesheet <transform> env)
661 (parse-namespace-aliases! stylesheet <transform> env)
662 (parse-decimal-formats! stylesheet <transform> env))))))))
664 (defvar *xsl-import-stack* nil)
666 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
667 (let* ((uri (if uri-resolver
668 (funcall uri-resolver (puri:render-uri uri nil))
669 uri))
670 (str (puri:render-uri uri nil))
671 (pathname
672 (handler-case
673 (uri-to-pathname uri)
674 (cxml:xml-parse-error (c)
675 (xslt-error "cannot find imported stylesheet ~A: ~A"
676 uri c)))))
677 (with-open-file
678 (stream pathname
679 :element-type '(unsigned-byte 8)
680 :if-does-not-exist nil)
681 (unless stream
682 (xslt-error "cannot find imported stylesheet ~A at ~A"
683 uri pathname))
684 (when (find str *xsl-import-stack* :test #'equal)
685 (xslt-error "recursive inclusion of ~A" uri))
686 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
687 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
689 (defvar *included-attribute-sets*)
691 (defun parse-stylesheet (designator &key uri-resolver)
692 (with-resignalled-errors ()
693 (xpath:with-namespaces ((nil #.*xsl*))
694 (let* ((*import-priority* 0)
695 (xpath:*allow-variables-in-patterns* nil)
696 (puri:*strict-parse* nil)
697 (stylesheet (make-stylesheet))
698 (env (make-instance 'lexical-xslt-environment))
699 (*excluded-namespaces* *excluded-namespaces*)
700 (*global-variable-declarations* (make-empty-declaration-array))
701 (*included-attribute-sets* nil))
702 (ensure-mode stylesheet nil)
703 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
704 ;; reverse attribute sets:
705 (let ((table (stylesheet-attribute-sets stylesheet)))
706 (maphash (lambda (k v)
707 (setf (gethash k table) (nreverse v)))
708 table))
709 ;; for Errors_err011
710 (dolist (sets *included-attribute-sets*)
711 (loop for (local-name uri nil) in sets do
712 (find-attribute-set local-name uri stylesheet)))
713 ;; add default df
714 (unless (find-decimal-format "" "" stylesheet nil)
715 (setf (find-decimal-format "" "" stylesheet)
716 (make-decimal-format)))
717 ;; compile a template matcher for each mode:
718 (loop
719 for mode being each hash-value in (stylesheet-modes stylesheet)
721 (setf (mode-match-thunk mode)
722 (xpath:make-pattern-matcher
723 (mapcar #'template-compiled-pattern
724 (mode-templates mode)))))
725 ;; and for the strip tests
726 (setf (stylesheet-strip-thunk stylesheet)
727 (let ((patterns (stylesheet-strip-tests stylesheet)))
728 (and patterns
729 (xpath:make-pattern-matcher
730 (mapcar #'strip-test-compiled-pattern patterns)))))
731 stylesheet))))
733 (defun parse-attribute-sets! (stylesheet <transform> env)
734 (do-toplevel (elt "attribute-set" <transform>)
735 (with-import-magic (elt env)
736 (push (let* ((sets
737 (mapcar (lambda (qname)
738 (multiple-value-list (decode-qname qname env nil)))
739 (words
740 (stp:attribute-value elt "use-attribute-sets"))))
741 (instructions
742 (stp:map-children
743 'list
744 (lambda (child)
745 (unless
746 (and (typep child 'stp:element)
747 (or (and (equal (stp:namespace-uri child) *xsl*)
748 (equal (stp:local-name child)
749 "attribute"))
750 (find (stp:namespace-uri child)
751 *extension-namespaces*
752 :test 'equal)))
753 (xslt-error "non-attribute found in attribute set"))
754 (parse-instruction child))
755 elt))
756 (*lexical-variable-declarations*
757 (make-empty-declaration-array))
758 (thunk
759 (compile-instruction `(progn ,@instructions) env))
760 (n-variables (length *lexical-variable-declarations*)))
761 (push sets *included-attribute-sets*)
762 (lambda (ctx)
763 (with-stack-limit ()
764 (loop for (local-name uri nil) in sets do
765 (dolist (thunk (find-attribute-set local-name uri))
766 (funcall thunk ctx)))
767 (let ((*lexical-variable-values*
768 (make-variable-value-array n-variables)))
769 (funcall thunk ctx)))))
770 (gethash (multiple-value-bind (local-name uri)
771 (decode-qname (or (stp:attribute-value elt "name")
772 (xslt-error "missing name"))
774 nil)
775 (cons local-name uri))
776 (stylesheet-attribute-sets stylesheet))))))
778 (defun parse-namespace-aliases! (stylesheet <transform> env)
779 (do-toplevel (elt "namespace-alias" <transform>)
780 (only-with-attributes (stylesheet-prefix result-prefix) elt
781 (unless stylesheet-prefix
782 (xslt-error "missing stylesheet-prefix in namespace-alias"))
783 (unless result-prefix
784 (xslt-error "missing result-prefix in namespace-alias"))
785 (setf (gethash
786 (if (equal stylesheet-prefix "#default")
788 (xpath-sys:environment-find-namespace env stylesheet-prefix))
789 (stylesheet-namespace-aliases stylesheet))
790 (xpath-sys:environment-find-namespace
792 (if (equal result-prefix "#default")
794 result-prefix))))))
796 (defun parse-decimal-formats! (stylesheet <transform> env)
797 (do-toplevel (elt "decimal-format" <transform>)
798 (stp:with-attributes (name
799 ;; strings
800 infinity
801 (nan "NaN")
802 ;; characters:
803 decimal-separator
804 grouping-separator
805 zero-digit
806 percent
807 per-mille
808 digit
809 pattern-separator
810 minus-sign)
812 (multiple-value-bind (local-name uri)
813 (if name
814 (decode-qname name env nil)
815 (values "" ""))
816 (let ((current (find-decimal-format local-name uri stylesheet nil))
817 (new
818 (let ((seen '()))
819 (flet ((chr (key x)
820 (when x
821 (unless (eql (length x) 1)
822 (xslt-error "not a single character: ~A" x))
823 (let ((chr (elt x 0)))
824 (when (find chr seen)
825 (xslt-error
826 "conflicting decimal format characters: ~A"
827 chr))
828 (push chr seen)
829 (list key chr))))
830 (str (key x)
831 (when x
832 (list key x))))
833 (apply #'make-decimal-format
834 (append (str :infinity infinity)
835 (str :nan nan)
836 (chr :decimal-separator decimal-separator)
837 (chr :grouping-separator grouping-separator)
838 (chr :zero-digit zero-digit)
839 (chr :percent percent)
840 (chr :per-mille per-mille)
841 (chr :digit digit)
842 (chr :pattern-separator pattern-separator)
843 (chr :minus-sign minus-sign)))))))
844 (if current
845 (unless (decimal-format= current new)
846 (xslt-error "decimal format mismatch for ~S" local-name))
847 (setf (find-decimal-format local-name uri stylesheet) new)))))))
849 (defun parse-exclude-result-prefixes! (node env)
850 (stp:with-attributes (exclude-result-prefixes)
851 node
852 (dolist (prefix (words (or exclude-result-prefixes "")))
853 (if (equal prefix "#default")
854 (setf prefix nil)
855 (unless (cxml-stp-impl::nc-name-p prefix)
856 (xslt-error "invalid prefix: ~A" prefix)))
857 (push (or (xpath-sys:environment-find-namespace env prefix)
858 (xslt-error "namespace not found: ~A" prefix))
859 *excluded-namespaces*))))
861 (defun parse-extension-element-prefixes! (node env)
862 (stp:with-attributes (extension-element-prefixes)
863 node
864 (dolist (prefix (words (or extension-element-prefixes "")))
865 (if (equal prefix "#default")
866 (setf prefix nil)
867 (unless (cxml-stp-impl::nc-name-p prefix)
868 (xslt-error "invalid prefix: ~A" prefix)))
869 (let ((uri
870 (or (xpath-sys:environment-find-namespace env prefix)
871 (xslt-error "namespace not found: ~A" prefix))))
872 (unless (equal uri *xsl*)
873 (push uri *extension-namespaces*)
874 (push uri *excluded-namespaces*))))))
876 (defun parse-nametest-tokens (str)
877 (labels ((check (boolean)
878 (unless boolean
879 (xslt-error "invalid nametest token")))
880 (check-null (boolean)
881 (check (not boolean))))
882 (cons
883 :patterns
884 (mapcar (lambda (name-test)
885 (destructuring-bind (&optional path &rest junk)
886 (cdr (xpath:parse-pattern-expression name-test))
887 (check-null junk)
888 (check (eq (car path) :path))
889 (destructuring-bind (&optional child &rest junk) (cdr path)
890 (check-null junk)
891 (check (eq (car child) :child))
892 (destructuring-bind (nodetest &rest junk) (cdr child)
893 (check-null junk)
894 (check (or (stringp nodetest)
895 (eq nodetest '*)
896 (and (consp nodetest)
897 (or (eq (car nodetest) :namespace)
898 (eq (car nodetest) :qname)))))))
899 path))
900 (words str)))))
902 (defstruct strip-test
903 compiled-pattern
904 priority
905 position
906 value)
908 (defun parse-strip/preserve-space! (stylesheet <transform> env)
909 (let ((i 0))
910 (do-toplevel (elt "strip-space|preserve-space" <transform>)
911 (let ((*namespaces* (acons-namespaces elt))
912 (value
913 (if (equal (stp:local-name elt) "strip-space")
914 :strip
915 :preserve)))
916 (dolist (expression
917 (cdr (parse-nametest-tokens
918 (stp:attribute-value elt "elements"))))
919 (let* ((compiled-pattern
920 (car (without-xslt-current ()
921 (xpath:compute-patterns
922 `(:patterns ,expression)
923 *import-priority*
924 "will set below"
925 env))))
926 (strip-test
927 (make-strip-test :compiled-pattern compiled-pattern
928 :priority (expression-priority expression)
929 :position i
930 :value value)))
931 (setf (xpath:pattern-value compiled-pattern) strip-test)
932 (push strip-test (stylesheet-strip-tests stylesheet)))))
933 (incf i))))
935 (defstruct (output-specification
936 (:conc-name "OUTPUT-"))
937 method
938 indent
939 omit-xml-declaration
940 encoding
941 doctype-system
942 doctype-public
943 cdata-section-matchers)
945 (defun parse-output! (stylesheet <transform> env)
946 (dolist (<output> (list-toplevel "output" <transform>))
947 (let ((spec (stylesheet-output-specification stylesheet)))
948 (only-with-attributes (version
949 method
950 indent
951 encoding
952 media-type
953 doctype-system
954 doctype-public
955 omit-xml-declaration
956 standalone
957 cdata-section-elements)
958 <output>
959 (declare (ignore version
960 ;; FIXME:
961 media-type
962 standalone))
963 (when method
964 (setf (output-method spec) method))
965 (when indent
966 (setf (output-indent spec) indent))
967 (when encoding
968 (setf (output-encoding spec) encoding))
969 (when doctype-system
970 (setf (output-doctype-system spec) doctype-system))
971 (when doctype-public
972 (setf (output-doctype-public spec) doctype-public))
973 (when omit-xml-declaration
974 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
975 (when cdata-section-elements
976 (dolist (qname (words cdata-section-elements))
977 (decode-qname qname env nil) ;check the syntax
978 (push (xpath:make-pattern-matcher* qname env)
979 (output-cdata-section-matchers spec))))))))
981 (defun make-empty-declaration-array ()
982 (make-array 1 :fill-pointer 0 :adjustable t))
984 (defun make-variable-value-array (n-lexical-variables)
985 (make-array n-lexical-variables :initial-element 'unbound))
987 (defun compile-global-variable (<variable> env) ;; also for <param>
988 (stp:with-attributes (name select) <variable>
989 (when (and select (stp:list-children <variable>))
990 (xslt-error "variable with select and body"))
991 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
992 (inner (cond
993 (select
994 (compile-xpath select env))
995 ((stp:list-children <variable>)
996 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
997 (inner-thunk (compile-instruction inner-sexpr env)))
998 (lambda (ctx)
999 (apply-to-result-tree-fragment ctx inner-thunk))))
1001 (lambda (ctx)
1002 (declare (ignore ctx))
1003 ""))))
1004 (n-lexical-variables (length *lexical-variable-declarations*)))
1005 (xslt-trace-thunk
1006 (lambda (ctx)
1007 (let* ((*lexical-variable-values*
1008 (make-variable-value-array n-lexical-variables)))
1009 (funcall inner ctx)))
1010 "global ~s (~s) = ~s" name select :result))))
1012 (defstruct (variable-chain
1013 (:constructor make-variable-chain)
1014 (:conc-name "VARIABLE-CHAIN-"))
1015 definitions
1016 index
1017 local-name
1018 thunk
1019 uri)
1021 (defstruct (import-variable
1022 (:constructor make-variable)
1023 (:conc-name "VARIABLE-"))
1024 value-thunk
1025 value-thunk-setter
1026 param-p)
1028 (defun parse-global-variable! (stylesheet <variable> global-env)
1029 (let* ((*namespaces* (acons-namespaces <variable>))
1030 (instruction-base-uri (stp:base-uri <variable>))
1031 (*instruction-base-uri* instruction-base-uri)
1032 (*excluded-namespaces* (list *xsl*))
1033 (*extension-namespaces* '())
1034 (qname (stp:attribute-value <variable> "name")))
1035 (with-import-magic (<variable> global-env)
1036 (unless qname
1037 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
1038 (multiple-value-bind (local-name uri)
1039 (decode-qname qname global-env nil)
1040 ;; For the normal compilation environment of templates, install it
1041 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
1042 (let ((index (intern-global-variable local-name uri)))
1043 ;; For the evaluation of a global variable itself, build a thunk
1044 ;; that lazily resolves other variables, stored into
1045 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
1046 (let* ((value-thunk :unknown)
1047 (sgv (stylesheet-global-variables stylesheet))
1048 (chain
1049 (if (< index (length sgv))
1050 (elt sgv index)
1051 (make-variable-chain
1052 :index index
1053 :local-name local-name
1054 :uri uri)))
1055 (next (car (variable-chain-definitions chain)))
1056 (global-variable-thunk
1057 (lambda (ctx)
1058 (let ((v (global-variable-value index nil)))
1059 (cond
1060 ((eq v 'seen)
1061 (unless next
1062 (xslt-error "no next definition for: ~A"
1063 local-name))
1064 (funcall (variable-value-thunk next) ctx))
1065 ((eq v 'unbound)
1066 (setf (global-variable-value index) 'seen)
1067 (setf (global-variable-value index)
1068 (funcall value-thunk ctx)))
1070 v)))))
1071 (excluded-namespaces *excluded-namespaces*)
1072 (extension-namespaces *extension-namespaces*)
1073 (variable
1074 (make-variable :param-p (namep <variable> "param")))
1075 (forwards-compatible-p *forwards-compatible-p*)
1076 (value-thunk-setter
1077 (lambda ()
1078 (let* ((*instruction-base-uri* instruction-base-uri)
1079 (*excluded-namespaces* excluded-namespaces)
1080 (*extension-namespaces* extension-namespaces)
1081 (*forwards-compatible-p* forwards-compatible-p)
1083 (compile-global-variable <variable> global-env)))
1084 (setf value-thunk fn)
1085 (setf (variable-value-thunk variable) fn)))))
1086 (setf (variable-value-thunk-setter variable)
1087 value-thunk-setter)
1088 (setf (gethash (cons local-name uri)
1089 (initial-global-variable-thunks global-env))
1090 global-variable-thunk)
1091 (setf (variable-chain-thunk chain) global-variable-thunk)
1092 (push variable (variable-chain-definitions chain))
1093 chain))))))
1095 (defun parse-keys! (stylesheet <transform> env)
1096 (xpath:with-namespaces ((nil #.*xsl*))
1097 (do-toplevel (<key> "key" <transform>)
1098 (with-import-magic (<key> env)
1099 (let ((*instruction-base-uri* (stp:base-uri <key>)))
1100 (stp:with-attributes (name match use) <key>
1101 (unless name (xslt-error "key name attribute not specified"))
1102 (unless match (xslt-error "key match attribute not specified"))
1103 (unless use (xslt-error "key use attribute not specified"))
1104 (multiple-value-bind (local-name uri)
1105 (decode-qname name env nil)
1106 (add-key stylesheet
1107 (cons local-name uri)
1108 (compile-xpath `(xpath:xpath ,(parse-key-pattern match))
1109 env)
1110 (compile-xpath use
1111 (make-instance 'key-environment))))))))))
1113 (defun prepare-global-variables (stylesheet <transform>)
1114 (xpath:with-namespaces ((nil #.*xsl*))
1115 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet))
1116 (global-env (make-instance 'global-variable-environment
1117 :initial-global-variable-thunks igvt))
1118 (chains '()))
1119 (do-toplevel (<variable> "variable|param" <transform>)
1120 (let ((chain
1121 (parse-global-variable! stylesheet <variable> global-env)))
1122 (xslt-trace "parsing global variable ~s (uri ~s)"
1123 (variable-chain-local-name chain)
1124 (variable-chain-uri chain))
1125 (when (find chain
1126 chains
1127 :test (lambda (a b)
1128 (and (equal (variable-chain-local-name a)
1129 (variable-chain-local-name b))
1130 (equal (variable-chain-uri a)
1131 (variable-chain-uri b)))))
1132 (xslt-error "duplicate definition for global variable ~A"
1133 (variable-chain-local-name chain)))
1134 (push chain chains)))
1135 (setf chains (nreverse chains))
1136 (let ((table (stylesheet-global-variables stylesheet))
1137 (newlen (length *global-variable-declarations*)))
1138 (adjust-array table newlen :fill-pointer newlen)
1139 (dolist (chain chains)
1140 (setf (elt table (variable-chain-index chain)) chain)))
1141 (lambda ()
1142 ;; now that the global environment knows about all variables, run the
1143 ;; thunk setters to perform their compilation
1144 (mapc (lambda (chain)
1145 (dolist (var (variable-chain-definitions chain))
1146 (funcall (variable-value-thunk-setter var))))
1147 chains)))))
1149 (defun parse-templates! (stylesheet <transform> env)
1150 (let ((i 0))
1151 (do-toplevel (<template> "template" <transform>)
1152 (let ((*namespaces* (acons-namespaces <template>))
1153 (*instruction-base-uri* (stp:base-uri <template>)))
1154 (with-import-magic (<template> env)
1155 (dolist (template (compile-template <template> env i))
1156 (let ((name (template-name template)))
1157 (if name
1158 (let* ((table (stylesheet-named-templates stylesheet))
1159 (head (car (gethash name table))))
1160 (when (and head (eql (template-import-priority head)
1161 (template-import-priority template)))
1162 ;; fixme: is this supposed to be a run-time error?
1163 (xslt-error "conflicting templates for ~A" name))
1164 (push template (gethash name table)))
1165 (let ((mode (ensure-mode/qname stylesheet
1166 (template-mode-qname template)
1167 env)))
1168 (setf (template-mode template) mode)
1169 (push template (mode-templates mode))))))))
1170 (incf i))))
1173 ;;;; APPLY-STYLESHEET
1175 (defvar *stylesheet*)
1177 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
1179 (defun unalias-uri (uri)
1180 (let ((result
1181 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
1182 uri)))
1183 (check-type result string)
1184 result))
1186 (defstruct (parameter
1187 (:constructor make-parameter (value local-name &optional uri)))
1188 (uri "")
1189 local-name
1190 value)
1192 (defun find-parameter-value (local-name uri parameters)
1193 (dolist (p parameters)
1194 (when (and (equal (parameter-local-name p) local-name)
1195 (equal (parameter-uri p) uri))
1196 (return (parameter-value p)))))
1198 (defvar *uri-resolver*)
1200 (defun parse-allowing-microsoft-bom (pathname handler)
1201 (with-open-file (s pathname :element-type '(unsigned-byte 8))
1202 (unless (and (eql (read-byte s nil) #xef)
1203 (eql (read-byte s nil) #xbb)
1204 (eql (read-byte s nil) #xbf))
1205 (file-position s 0))
1206 (cxml:parse s handler)))
1208 (defvar *documents*)
1210 (defun %document (uri-string base-uri)
1211 (let* ((absolute-uri
1212 (puri:merge-uris uri-string (or base-uri "")))
1213 (resolved-uri
1214 (if *uri-resolver*
1215 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
1216 absolute-uri))
1217 (pathname
1218 (handler-case
1219 (uri-to-pathname resolved-uri)
1220 (cxml:xml-parse-error (c)
1221 (xslt-error "cannot find referenced document ~A: ~A"
1222 resolved-uri c))))
1223 (xpath-root-node
1224 (or (gethash pathname *documents*)
1225 (setf (gethash pathname *documents*)
1226 (make-whitespace-stripper
1227 (handler-case
1228 (parse-allowing-microsoft-bom pathname
1229 (stp:make-builder))
1230 ((or file-error cxml:xml-parse-error) (c)
1231 (xslt-error "cannot parse referenced document ~A: ~A"
1232 pathname c)))
1233 (stylesheet-strip-thunk *stylesheet*))))))
1234 (when (puri:uri-fragment absolute-uri)
1235 (xslt-error "use of fragment identifiers in document() not supported"))
1236 xpath-root-node))
1238 (xpath-sys:define-extension xslt *xsl*)
1240 (defun document-base-uri (node)
1241 (xpath-protocol:base-uri
1242 (cond
1243 ((xpath-protocol:node-type-p node :document)
1244 (xpath::find-in-pipe-if
1245 (lambda (x)
1246 (xpath-protocol:node-type-p x :element))
1247 (xpath-protocol:child-pipe node)))
1248 ((xpath-protocol:node-type-p node :element)
1249 node)
1251 (xpath-protocol:parent-node node)))))
1253 (xpath-sys:define-xpath-function/lazy
1254 xslt :document
1255 (object &optional node-set)
1256 (let ((instruction-base-uri *instruction-base-uri*))
1257 (lambda (ctx)
1258 (let* ((object (funcall object ctx))
1259 (node-set (and node-set (funcall node-set ctx)))
1260 (base-uri
1261 (if node-set
1262 (document-base-uri (xpath::textually-first-node node-set))
1263 instruction-base-uri)))
1264 (xpath-sys:make-node-set
1265 (if (xpath:node-set-p object)
1266 (xpath:map-node-set->list
1267 (lambda (node)
1268 (%document (xpath:string-value node)
1269 (if node-set
1270 base-uri
1271 (document-base-uri node))))
1272 object)
1273 (list (%document (xpath:string-value object) base-uri))))))))
1275 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1276 (let ((namespaces *namespaces*))
1277 (lambda (ctx)
1278 (let* ((qname (xpath:string-value (funcall name ctx)))
1279 (object (funcall object ctx))
1280 (expanded-name
1281 (multiple-value-bind (local-name uri)
1282 (decode-qname/runtime qname namespaces nil)
1283 (cons local-name uri)))
1284 (key (find-key expanded-name *stylesheet*)))
1285 (labels ((get-by-key (value)
1286 (let ((value (xpath:string-value value)))
1287 (xpath::filter-pipe
1288 #'(lambda (node)
1289 (let ((uses
1290 (xpath:evaluate-compiled (key-use key) node)))
1291 (if (xpath:node-set-p uses)
1292 (xpath::find-in-pipe
1293 value
1294 (xpath-sys:pipe-of uses)
1295 :key #'xpath:string-value
1296 :test #'equal)
1297 (equal value (xpath:string-value uses)))))
1298 (xpath-sys:pipe-of
1299 (xpath:node-set-value
1300 (xpath:evaluate-compiled (key-match key) ctx)))))))
1301 (xpath-sys:make-node-set
1302 (xpath::sort-pipe
1303 (if (xpath:node-set-p object)
1304 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1305 (get-by-key object)))))))))
1307 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1309 (xpath-sys:define-xpath-function/lazy xslt :current ()
1310 (when *without-xslt-current-p*
1311 (xslt-error "current() not allowed here"))
1312 #'(lambda (ctx)
1313 (xpath-sys:make-node-set
1314 (xpath-sys:make-pipe
1315 (xpath:context-starting-node ctx)
1316 nil))))
1318 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1319 #'(lambda (ctx)
1320 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1321 (funcall name ctx))
1322 "")))
1324 (defun %get-node-id (node)
1325 (when (xpath:node-set-p node)
1326 (setf node (xpath::textually-first-node node)))
1327 (when node
1328 (let ((id (xpath-sys:get-node-id node))
1329 (highest-base-uri
1330 (loop
1331 for parent = node then next
1332 for next = (xpath-protocol:parent-node parent)
1333 for this-base-uri = (xpath-protocol:base-uri parent)
1334 for highest-base-uri = (if (plusp (length this-base-uri))
1335 this-base-uri
1336 highest-base-uri)
1337 while next
1338 finally (return highest-base-uri))))
1339 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1340 ;; checked only if everything else matches.
1342 ;; This might be pointless premature optimization, but I like the idea :-)
1343 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1345 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1346 (if node-set-thunk
1347 #'(lambda (ctx)
1348 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1349 #'(lambda (ctx)
1350 (%get-node-id (xpath:context-node ctx)))))
1352 (declaim (special *available-instructions*))
1354 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1355 (let ((namespaces *namespaces*))
1356 #'(lambda (ctx)
1357 (let ((qname (funcall qname ctx)))
1358 (multiple-value-bind (local-name uri)
1359 (decode-qname/runtime qname namespaces nil)
1360 (and (equal uri *xsl*)
1361 (gethash local-name *available-instructions*)
1362 t))))))
1364 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1365 (let ((namespaces *namespaces*))
1366 #'(lambda (ctx)
1367 (let ((qname (funcall qname ctx)))
1368 (multiple-value-bind (local-name uri)
1369 (decode-qname/runtime qname namespaces nil)
1370 (and (zerop (length uri))
1371 (or (xpath-sys:find-xpath-function local-name *xsl*)
1372 (xpath-sys:find-xpath-function local-name uri))
1373 t))))))
1375 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1376 (let ((namespaces *namespaces*))
1377 (lambda (ctx)
1378 (let ((qname (xpath:string-value (funcall qname ctx))))
1379 (multiple-value-bind (local-name uri)
1380 (decode-qname/runtime qname namespaces nil)
1381 (if (equal uri *xsl*)
1382 (cond
1383 ((equal local-name "version")
1384 "1")
1385 ((equal local-name "vendor")
1386 "Xuriella")
1387 ((equal local-name "vendor-uri")
1388 "http://repo.or.cz/w/xuriella.git")
1390 ""))
1391 ""))))))
1393 (defun apply-stylesheet
1394 (stylesheet source-designator
1395 &key output parameters uri-resolver navigator)
1396 (when (typep stylesheet 'xml-designator)
1397 (setf stylesheet
1398 (handler-bind
1399 ((cxml:xml-parse-error
1400 (lambda (c)
1401 (xslt-error "cannot parse stylesheet: ~A" c))))
1402 (parse-stylesheet stylesheet))))
1403 (with-resignalled-errors ()
1404 (invoke-with-output-sink
1405 (lambda ()
1406 (let* ((*documents* (make-hash-table :test 'equal))
1407 (xpath:*navigator* (or navigator :default-navigator))
1408 (puri:*strict-parse* nil)
1409 (*stylesheet* stylesheet)
1410 (*empty-mode* (make-mode))
1411 (*default-mode* (find-mode stylesheet nil))
1412 (global-variable-chains
1413 (stylesheet-global-variables stylesheet))
1414 (*global-variable-values*
1415 (make-variable-value-array (length global-variable-chains)))
1416 (*uri-resolver* uri-resolver)
1417 (source-document
1418 (if (typep source-designator 'xml-designator)
1419 (cxml:parse source-designator (stp:make-builder))
1420 source-designator))
1421 (xpath-root-node
1422 (make-whitespace-stripper
1423 source-document
1424 (stylesheet-strip-thunk stylesheet)))
1425 (ctx (xpath:make-context xpath-root-node)))
1426 (when (pathnamep source-designator)
1427 (setf (gethash source-designator *documents*) xpath-root-node))
1428 (map nil
1429 (lambda (chain)
1430 (let ((head (car (variable-chain-definitions chain))))
1431 (when (variable-param-p head)
1432 (let ((value
1433 (find-parameter-value
1434 (variable-chain-local-name chain)
1435 (variable-chain-uri chain)
1436 parameters)))
1437 (when value
1438 (setf (global-variable-value
1439 (variable-chain-index chain))
1440 value))))))
1441 global-variable-chains)
1442 (map nil
1443 (lambda (chain)
1444 (funcall (variable-chain-thunk chain) ctx))
1445 global-variable-chains)
1446 ;; zzz we wouldn't have to mask float traps here if we used the
1447 ;; XPath API properly. Unfortunately I've been using FUNCALL
1448 ;; everywhere instead of EVALUATE, so let's paper over that
1449 ;; at a central place to be sure:
1450 (xpath::with-float-traps-masked ()
1451 (apply-templates ctx :mode *default-mode*))))
1452 (stylesheet-output-specification stylesheet)
1453 output)))
1455 (defun find-attribute-set (local-name uri &optional (stylesheet *stylesheet*))
1456 (or (gethash (cons local-name uri) (stylesheet-attribute-sets stylesheet))
1457 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1459 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1460 (when sort-predicate
1461 (setf list
1462 (mapcar #'xpath:context-node
1463 (stable-sort (contextify-node-list list)
1464 sort-predicate))))
1465 (let* ((n (length list))
1466 (s/d (lambda () n)))
1467 (loop
1468 for i from 1
1469 for child in list
1471 (apply-templates (xpath:make-context child s/d i)
1472 :param-bindings param-bindings
1473 :mode mode))))
1475 (defvar *stack-limit* 200)
1477 (defun invoke-with-stack-limit (fn)
1478 (let ((*stack-limit* (1- *stack-limit*)))
1479 (unless (plusp *stack-limit*)
1480 (xslt-error "*stack-limit* reached; stack overflow"))
1481 (funcall fn)))
1483 (defun invoke-template (ctx template param-bindings)
1484 (let ((*lexical-variable-values*
1485 (make-variable-value-array (template-n-variables template))))
1486 (with-stack-limit ()
1487 (loop
1488 for (name-cons value) in param-bindings
1489 for (nil index nil) = (find name-cons
1490 (template-params template)
1491 :test #'equal
1492 :key #'car)
1494 (when index
1495 (setf (lexical-variable-value index) value)))
1496 (funcall (template-body template) ctx))))
1498 (defun apply-default-templates (ctx mode)
1499 (let ((node (xpath:context-node ctx)))
1500 (cond
1501 ((or (xpath-protocol:node-type-p node :processing-instruction)
1502 (xpath-protocol:node-type-p node :comment)))
1503 ((or (xpath-protocol:node-type-p node :text)
1504 (xpath-protocol:node-type-p node :attribute))
1505 (write-text (xpath-protocol:node-text node)))
1507 (apply-templates/list
1508 (xpath::force
1509 (xpath-protocol:child-pipe node))
1510 :mode mode)))))
1512 (defvar *apply-imports*)
1514 (defun apply-applicable-templates (ctx templates param-bindings finally)
1515 (labels ((apply-imports (&optional actual-param-bindings)
1516 (if templates
1517 (let* ((this (pop templates))
1518 (low (template-apply-imports-limit this))
1519 (high (template-import-priority this)))
1520 (setf templates
1521 (remove-if-not
1522 (lambda (x)
1523 (<= low (template-import-priority x) high))
1524 templates))
1525 (invoke-template ctx this actual-param-bindings))
1526 (funcall finally))))
1527 (let ((*apply-imports* #'apply-imports))
1528 (apply-imports param-bindings))))
1530 (defun apply-templates (ctx &key param-bindings mode)
1531 (apply-applicable-templates ctx
1532 (find-templates ctx (or mode *default-mode*))
1533 param-bindings
1534 (lambda ()
1535 (apply-default-templates ctx mode))))
1537 (defun call-template (ctx name &optional param-bindings)
1538 (apply-applicable-templates ctx
1539 (find-named-templates name)
1540 param-bindings
1541 (lambda ()
1542 (xslt-error "cannot find named template: ~s"
1543 name))))
1545 (defun find-templates (ctx mode)
1546 (let* ((matching-candidates
1547 (xpath:matching-values (mode-match-thunk mode)
1548 (xpath:context-node ctx)))
1549 (npriorities
1550 (if matching-candidates
1551 (1+ (reduce #'max
1552 matching-candidates
1553 :key #'template-import-priority))
1555 (priority-groups (make-array npriorities :initial-element nil)))
1556 (dolist (template matching-candidates)
1557 (push template
1558 (elt priority-groups (template-import-priority template))))
1559 (loop
1560 for i from (1- npriorities) downto 0
1561 for group = (elt priority-groups i)
1562 for template = (maximize #'template< group)
1563 when template
1564 collect template)))
1566 (defun find-named-templates (name)
1567 (gethash name (stylesheet-named-templates *stylesheet*)))
1569 (defun template< (a b) ;assuming same import priority
1570 (let ((p (template-priority a))
1571 (q (template-priority b)))
1572 (cond
1573 ((< p q) t)
1574 ((> p q) nil)
1576 (xslt-cerror "conflicting templates:~_~A,~_~A"
1577 (template-match-expression a)
1578 (template-match-expression b))
1579 (< (template-position a) (template-position b))))))
1581 (defun maximize (< things)
1582 (when things
1583 (let ((max (car things)))
1584 (dolist (other (cdr things))
1585 (when (funcall < max other)
1586 (setf max other)))
1587 max)))
1589 (defun invoke-with-output-sink (fn output-spec output)
1590 (etypecase output
1591 (pathname
1592 (with-open-file (s output
1593 :direction :output
1594 :element-type '(unsigned-byte 8)
1595 :if-exists :rename-and-delete)
1596 (invoke-with-output-sink fn output-spec s)))
1597 ((or stream null)
1598 (invoke-with-output-sink fn
1599 output-spec
1600 (make-output-sink output-spec output)))
1601 ((or hax:abstract-handler sax:abstract-handler)
1602 (with-xml-output output
1603 (when (typep output '(or combi-sink auto-detect-sink))
1604 (sax:start-dtd output
1605 :autodetect-me-please
1606 (output-doctype-public output-spec)
1607 (output-doctype-system output-spec)))
1608 (funcall fn)))))
1610 (defun make-output-sink (output-spec stream)
1611 (let* ((ystream
1612 (if stream
1613 (let ((et (stream-element-type stream)))
1614 (cond
1615 ((or (null et) (subtypep et '(unsigned-byte 8)))
1616 (runes:make-octet-stream-ystream stream))
1617 ((subtypep et 'character)
1618 (runes:make-character-stream-ystream stream))))
1619 (runes:make-rod-ystream)))
1620 (omit-xml-declaration-p
1621 (boolean-or-error (output-omit-xml-declaration output-spec)))
1622 (sink-encoding (or (output-encoding output-spec) "UTF-8"))
1623 (sax-target
1624 (progn
1625 (setf (runes:ystream-encoding ystream)
1626 (cxml::find-output-encoding sink-encoding))
1627 (make-instance 'cxml::sink
1628 :ystream ystream
1629 :omit-xml-declaration-p omit-xml-declaration-p
1630 :encoding sink-encoding))))
1631 (flet ((make-combi-sink ()
1632 (make-instance 'combi-sink
1633 :hax-target (make-instance 'chtml::sink
1634 :ystream ystream)
1635 :sax-target sax-target
1636 :encoding sink-encoding)))
1637 (let ((method-key
1638 (cond
1639 ((equalp (output-method output-spec) "HTML") :html)
1640 ((equalp (output-method output-spec) "TEXT") :text)
1641 ((equalp (output-method output-spec) "XML") :xml)
1642 (t nil))))
1643 (cond
1644 ((and (eq method-key :html)
1645 (null (output-doctype-system output-spec))
1646 (null (output-doctype-public output-spec)))
1647 (make-combi-sink))
1648 ((eq method-key :text)
1649 (make-text-filter sax-target))
1650 ((and (eq method-key :xml)
1651 (null (output-doctype-system output-spec)))
1652 sax-target)
1654 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1656 (defstruct template
1657 match-expression
1658 compiled-pattern
1659 name
1660 import-priority
1661 apply-imports-limit
1662 priority
1663 position
1664 mode
1665 mode-qname
1666 params
1667 body
1668 n-variables)
1670 (defun expression-priority (form)
1671 (let ((step (second form)))
1672 (if (and (null (cddr form))
1673 (listp step)
1674 (member (car step) '(:child :attribute))
1675 (null (cddr step)))
1676 (let ((name (second step)))
1677 (cond
1678 ((or (stringp name)
1679 (and (consp name)
1680 (or (eq (car name) :qname)
1681 (eq (car name) :processing-instruction))))
1682 0.0)
1683 ((and (consp name)
1684 (or (eq (car name) :namespace)
1685 (eq (car name) '*)))
1686 -0.25)
1688 -0.5)))
1689 0.5)))
1691 (defun parse-key-pattern (str)
1692 (with-resignalled-errors ()
1693 (with-forward-compatible-errors
1694 (xpath:parse-xpath "compile-time-error()") ;hack
1695 (let ((parsed
1696 (mapcar #'(lambda (item)
1697 `(:path (:root :node)
1698 (:descendant-or-self *)
1699 ,@(cdr item)))
1700 (cdr (xpath::parse-pattern-expression str)))))
1701 (if (null (rest parsed))
1702 (first parsed)
1703 `(:union ,@parsed))))))
1705 (defun compile-value-thunk (value env)
1706 (if (and (listp value) (eq (car value) 'progn))
1707 (let ((inner-thunk (compile-instruction value env)))
1708 (lambda (ctx)
1709 (apply-to-result-tree-fragment ctx inner-thunk)))
1710 (compile-xpath value env)))
1712 (defun compile-var-binding (name value env)
1713 (multiple-value-bind (local-name uri)
1714 (decode-qname name env nil)
1715 (let ((thunk (xslt-trace-thunk
1716 (compile-value-thunk value env)
1717 "local variable ~s = ~s" name :result)))
1718 (list (cons local-name uri)
1719 (push-variable local-name
1721 *lexical-variable-declarations*)
1722 thunk))))
1724 (defun compile-var-bindings (forms env)
1725 (loop
1726 for (name value) in forms
1727 collect (compile-var-binding name value env)))
1729 (defun compile-template (<template> env position)
1730 (stp:with-attributes (match name priority mode) <template>
1731 (unless (or name match)
1732 (xslt-error "missing match in template"))
1733 (multiple-value-bind (params body-pos)
1734 (loop
1735 for i from 0
1736 for child in (stp:list-children <template>)
1737 while (namep child "param")
1738 collect (parse-param child) into params
1739 finally (return (values params i)))
1740 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1741 (param-bindings (compile-var-bindings params env))
1742 (body (parse-body <template> body-pos (mapcar #'car params)))
1743 (body-thunk (compile-instruction `(progn ,@body) env))
1744 (outer-body-thunk
1745 (xslt-trace-thunk
1746 #'(lambda (ctx)
1747 (unwind-protect
1748 (progn
1749 ;; set params that weren't initialized by apply-templates
1750 (loop for (name index param-thunk) in param-bindings
1751 when (eq (lexical-variable-value index nil) 'unbound)
1752 do (setf (lexical-variable-value index)
1753 (funcall param-thunk ctx)))
1754 (funcall body-thunk ctx))))
1755 "template: match = ~s name = ~s" match name))
1756 (n-variables (length *lexical-variable-declarations*)))
1757 (append
1758 (when name
1759 (multiple-value-bind (local-name uri)
1760 (decode-qname name env nil)
1761 (list
1762 (make-template :name (cons local-name uri)
1763 :import-priority *import-priority*
1764 :apply-imports-limit *apply-imports-limit*
1765 :params param-bindings
1766 :body outer-body-thunk
1767 :n-variables n-variables))))
1768 (when match
1769 (mapcar (lambda (expression)
1770 (let* ((compiled-pattern
1771 (xslt-trace-thunk
1772 (car (without-xslt-current ()
1773 (xpath:compute-patterns
1774 `(:patterns ,expression)
1776 :dummy
1777 env)))
1778 "match-thunk for template (match ~s): ~s --> ~s"
1779 match expression :result))
1780 (p (if priority
1781 (xpath::parse-xnum priority)
1782 (expression-priority expression)))
1784 (progn
1785 (unless (and (numberp p)
1786 (not (xpath::inf-p p))
1787 (not (xpath::nan-p p)))
1788 (xslt-error "failed to parse priority"))
1789 (float p 1.0d0)))
1790 (template
1791 (make-template :match-expression expression
1792 :compiled-pattern compiled-pattern
1793 :import-priority *import-priority*
1794 :apply-imports-limit *apply-imports-limit*
1795 :priority p
1796 :position position
1797 :mode-qname mode
1798 :params param-bindings
1799 :body outer-body-thunk
1800 :n-variables n-variables)))
1801 (setf (xpath:pattern-value compiled-pattern)
1802 template)
1803 template))
1804 (cdr (xpath:parse-pattern-expression match)))))))))
1805 #+(or)
1806 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")