In forwards compatibleprocessing, delay XPath errors until run-time
[xuriella.git] / xslt.lisp
blobd34cdca9a059eb495d10d25de016fd7a8195a50b
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 '(("version" . "")
523 ("exclude-result-prefixes" . "")
524 ("extension-element-prefixes" . ""))
525 <transform>)
526 (let ((invalid
527 (or (stp:find-child-if (of-name "stylesheet") <transform>)
528 (stp:find-child-if (of-name "transform") <transform>))))
529 (when invalid
530 (xslt-error "invalid top-level element ~A" (stp:local-name invalid))))
531 (dolist (include (stp:filter-children (of-name "include") <transform>))
532 (let* ((uri (puri:merge-uris (or (stp:attribute-value include "href")
533 (xslt-error "include without href"))
534 (stp:base-uri include)))
535 (uri (if uri-resolver
536 (funcall uri-resolver (puri:render-uri uri nil))
537 uri))
538 (str (puri:render-uri uri nil))
539 (pathname
540 (handler-case
541 (uri-to-pathname uri)
542 (cxml:xml-parse-error (c)
543 (xslt-error "cannot find included stylesheet ~A: ~A"
544 uri c)))))
545 (with-open-file
546 (stream pathname
547 :element-type '(unsigned-byte 8)
548 :if-does-not-exist nil)
549 (unless stream
550 (xslt-error "cannot find included stylesheet ~A at ~A"
551 uri pathname))
552 (when (find str *xsl-include-stack* :test #'equal)
553 (xslt-error "recursive inclusion of ~A" uri))
554 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
555 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
556 (stp:insert-child-after <transform>
557 (stp:copy <transform>2)
558 include)
559 (stp:detach include)))))
560 <transform>))
562 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
563 (defvar *apply-imports-limit*)
564 (defvar *import-priority*)
565 (defvar *extension-namespaces*)
566 (defvar *forwards-compatible-p*)
568 (defmacro do-toplevel ((var xpath <transform>) &body body)
569 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
571 (defun map-toplevel (fn xpath <transform>)
572 (dolist (node (list-toplevel xpath <transform>))
573 (let ((*namespaces* *namespaces*))
574 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
575 (when (xpath-protocol:node-type-p ancestor :element)
576 (setf *namespaces* (acons-namespaces ancestor))))
577 (funcall fn node))))
579 (defun list-toplevel (xpath <transform>)
580 (labels ((recurse (sub)
581 (let ((subsubs
582 (xpath-sys:pipe-of
583 (xpath:evaluate "transform|stylesheet" sub))))
584 (xpath::append-pipes
585 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
586 (xpath::mappend-pipe #'recurse subsubs)))))
587 (xpath::sort-nodes (recurse <transform>))))
589 (defmacro with-import-magic ((node env) &body body)
590 `(invoke-with-import-magic (lambda () ,@body) ,node ,env))
592 (defun invoke-with-import-magic (fn node env)
593 (unless (or (namep node "stylesheet") (namep node "transform"))
594 (setf node (stp:parent node)))
595 (let ((*excluded-namespaces* (list *xsl*))
596 (*extension-namespaces* '())
597 (*forwards-compatible-p*
598 (not (equal (stp:attribute-value node "version") "1.0"))))
599 (parse-exclude-result-prefixes! node env)
600 (parse-extension-element-prefixes! node env)
601 (funcall fn)))
603 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
604 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
605 (instruction-base-uri (stp:base-uri <transform>))
606 (namespaces (acons-namespaces <transform>))
607 (apply-imports-limit (1+ *import-priority*))
608 (continuations '()))
609 (let ((*namespaces* namespaces))
610 (invoke-with-import-magic (constantly t) <transform> env))
611 (do-toplevel (elt "node()" <transform>)
612 (let ((version (stp:attribute-value (stp:parent elt) "version")))
613 (cond
614 ((null version)
615 (xslt-error "stylesheet lacks version"))
616 ((equal version "1.0")
617 (if (typep elt 'stp:element)
618 (when (or (equal (stp:namespace-uri elt) "")
619 (and (equal (stp:namespace-uri elt) *xsl*)
620 (not (find (stp:local-name elt)
621 '("key" "template" "output"
622 "strip-space" "preserve-space"
623 "attribute-set" "namespace-alias"
624 "decimal-format" "variable" "param"
625 "import" "include"
626 ;; for include handling:
627 "stylesheet" "transform")
628 :test #'equal))))
629 (xslt-error "unknown top-level element ~A" (stp:local-name elt)))
630 (xslt-error "text at top-level"))))))
631 (macrolet ((with-specials ((&optional) &body body)
632 `(let ((*instruction-base-uri* instruction-base-uri)
633 (*namespaces* namespaces)
634 (*apply-imports-limit* apply-imports-limit))
635 ,@body)))
636 (with-specials ()
637 (do-toplevel (import "import" <transform>)
638 (let ((uri (puri:merge-uris (or (stp:attribute-value import "href")
639 (xslt-error "import without href"))
640 (stp:base-uri import))))
641 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
642 continuations))))
643 (let ((import-priority
644 (incf *import-priority*))
645 (var-cont (prepare-global-variables stylesheet <transform>)))
646 ;; delay the rest of compilation until we've seen all global
647 ;; variables:
648 (lambda ()
649 (mapc #'funcall (nreverse continuations))
650 (with-specials ()
651 (let ((*import-priority* import-priority))
652 (funcall var-cont)
653 (parse-keys! stylesheet <transform> env)
654 (parse-templates! stylesheet <transform> env)
655 (parse-output! stylesheet <transform> env)
656 (parse-strip/preserve-space! stylesheet <transform> env)
657 (parse-attribute-sets! stylesheet <transform> env)
658 (parse-namespace-aliases! stylesheet <transform> env)
659 (parse-decimal-formats! stylesheet <transform> env))))))))
661 (defvar *xsl-import-stack* nil)
663 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
664 (let* ((uri (if uri-resolver
665 (funcall uri-resolver (puri:render-uri uri nil))
666 uri))
667 (str (puri:render-uri uri nil))
668 (pathname
669 (handler-case
670 (uri-to-pathname uri)
671 (cxml:xml-parse-error (c)
672 (xslt-error "cannot find imported stylesheet ~A: ~A"
673 uri c)))))
674 (with-open-file
675 (stream pathname
676 :element-type '(unsigned-byte 8)
677 :if-does-not-exist nil)
678 (unless stream
679 (xslt-error "cannot find imported stylesheet ~A at ~A"
680 uri pathname))
681 (when (find str *xsl-import-stack* :test #'equal)
682 (xslt-error "recursive inclusion of ~A" uri))
683 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
684 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
686 (defvar *included-attribute-sets*)
688 (defun parse-stylesheet (designator &key uri-resolver)
689 (with-resignalled-errors ()
690 (xpath:with-namespaces ((nil #.*xsl*))
691 (let* ((*import-priority* 0)
692 (xpath:*allow-variables-in-patterns* nil)
693 (puri:*strict-parse* nil)
694 (stylesheet (make-stylesheet))
695 (env (make-instance 'lexical-xslt-environment))
696 (*excluded-namespaces* *excluded-namespaces*)
697 (*global-variable-declarations* (make-empty-declaration-array))
698 (*included-attribute-sets* nil))
699 (ensure-mode stylesheet nil)
700 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
701 ;; reverse attribute sets:
702 (let ((table (stylesheet-attribute-sets stylesheet)))
703 (maphash (lambda (k v)
704 (setf (gethash k table) (nreverse v)))
705 table))
706 ;; for Errors_err011
707 (dolist (sets *included-attribute-sets*)
708 (loop for (local-name uri nil) in sets do
709 (find-attribute-set local-name uri stylesheet)))
710 ;; add default df
711 (unless (find-decimal-format "" "" stylesheet nil)
712 (setf (find-decimal-format "" "" stylesheet)
713 (make-decimal-format)))
714 ;; compile a template matcher for each mode:
715 (loop
716 for mode being each hash-value in (stylesheet-modes stylesheet)
718 (setf (mode-match-thunk mode)
719 (xpath:make-pattern-matcher
720 (mapcar #'template-compiled-pattern
721 (mode-templates mode)))))
722 ;; and for the strip tests
723 (setf (stylesheet-strip-thunk stylesheet)
724 (let ((patterns (stylesheet-strip-tests stylesheet)))
725 (and patterns
726 (xpath:make-pattern-matcher
727 (mapcar #'strip-test-compiled-pattern patterns)))))
728 stylesheet))))
730 (defun parse-attribute-sets! (stylesheet <transform> env)
731 (do-toplevel (elt "attribute-set" <transform>)
732 (with-import-magic (elt env)
733 (push (let* ((sets
734 (mapcar (lambda (qname)
735 (multiple-value-list (decode-qname qname env nil)))
736 (words
737 (stp:attribute-value elt "use-attribute-sets"))))
738 (instructions
739 (stp:map-children
740 'list
741 (lambda (child)
742 (unless
743 (and (typep child 'stp:element)
744 (or (and (equal (stp:namespace-uri child) *xsl*)
745 (equal (stp:local-name child)
746 "attribute"))
747 (find (stp:namespace-uri child)
748 *extension-namespaces*
749 :test 'equal)))
750 (xslt-error "non-attribute found in attribute set"))
751 (parse-instruction child))
752 elt))
753 (*lexical-variable-declarations*
754 (make-empty-declaration-array))
755 (thunk
756 (compile-instruction `(progn ,@instructions) env))
757 (n-variables (length *lexical-variable-declarations*)))
758 (push sets *included-attribute-sets*)
759 (lambda (ctx)
760 (with-stack-limit ()
761 (loop for (local-name uri nil) in sets do
762 (dolist (thunk (find-attribute-set local-name uri))
763 (funcall thunk ctx)))
764 (let ((*lexical-variable-values*
765 (make-variable-value-array n-variables)))
766 (funcall thunk ctx)))))
767 (gethash (multiple-value-bind (local-name uri)
768 (decode-qname (or (stp:attribute-value elt "name")
769 (xslt-error "missing name"))
771 nil)
772 (cons local-name uri))
773 (stylesheet-attribute-sets stylesheet))))))
775 (defun parse-namespace-aliases! (stylesheet <transform> env)
776 (do-toplevel (elt "namespace-alias" <transform>)
777 (only-with-attributes (stylesheet-prefix result-prefix) elt
778 (unless stylesheet-prefix
779 (xslt-error "missing stylesheet-prefix in namespace-alias"))
780 (unless result-prefix
781 (xslt-error "missing result-prefix in namespace-alias"))
782 (setf (gethash
783 (if (equal stylesheet-prefix "#default")
785 (xpath-sys:environment-find-namespace env stylesheet-prefix))
786 (stylesheet-namespace-aliases stylesheet))
787 (xpath-sys:environment-find-namespace
789 (if (equal result-prefix "#default")
791 result-prefix))))))
793 (defun parse-decimal-formats! (stylesheet <transform> env)
794 (do-toplevel (elt "decimal-format" <transform>)
795 (stp:with-attributes (name
796 ;; strings
797 infinity
798 (nan "NaN")
799 ;; characters:
800 decimal-separator
801 grouping-separator
802 zero-digit
803 percent
804 per-mille
805 digit
806 pattern-separator
807 minus-sign)
809 (multiple-value-bind (local-name uri)
810 (if name
811 (decode-qname name env nil)
812 (values "" ""))
813 (let ((current (find-decimal-format local-name uri stylesheet nil))
814 (new
815 (let ((seen '()))
816 (flet ((chr (key x)
817 (when x
818 (unless (eql (length x) 1)
819 (xslt-error "not a single character: ~A" x))
820 (let ((chr (elt x 0)))
821 (when (find chr seen)
822 (xslt-error
823 "conflicting decimal format characters: ~A"
824 chr))
825 (push chr seen)
826 (list key chr))))
827 (str (key x)
828 (when x
829 (list key x))))
830 (apply #'make-decimal-format
831 (append (str :infinity infinity)
832 (str :nan nan)
833 (chr :decimal-separator decimal-separator)
834 (chr :grouping-separator grouping-separator)
835 (chr :zero-digit zero-digit)
836 (chr :percent percent)
837 (chr :per-mille per-mille)
838 (chr :digit digit)
839 (chr :pattern-separator pattern-separator)
840 (chr :minus-sign minus-sign)))))))
841 (if current
842 (unless (decimal-format= current new)
843 (xslt-error "decimal format mismatch for ~S" local-name))
844 (setf (find-decimal-format local-name uri stylesheet) new)))))))
846 (defun parse-exclude-result-prefixes! (node env)
847 (stp:with-attributes (exclude-result-prefixes)
848 node
849 (dolist (prefix (words (or exclude-result-prefixes "")))
850 (if (equal prefix "#default")
851 (setf prefix nil)
852 (unless (cxml-stp-impl::nc-name-p prefix)
853 (xslt-error "invalid prefix: ~A" prefix)))
854 (push (or (xpath-sys:environment-find-namespace env prefix)
855 (xslt-error "namespace not found: ~A" prefix))
856 *excluded-namespaces*))))
858 (defun parse-extension-element-prefixes! (node env)
859 (stp:with-attributes (extension-element-prefixes)
860 node
861 (dolist (prefix (words (or extension-element-prefixes "")))
862 (if (equal prefix "#default")
863 (setf prefix nil)
864 (unless (cxml-stp-impl::nc-name-p prefix)
865 (xslt-error "invalid prefix: ~A" prefix)))
866 (let ((uri
867 (or (xpath-sys:environment-find-namespace env prefix)
868 (xslt-error "namespace not found: ~A" prefix))))
869 (unless (equal uri *xsl*)
870 (push uri *extension-namespaces*)
871 (push uri *excluded-namespaces*))))))
873 (defun parse-nametest-tokens (str)
874 (labels ((check (boolean)
875 (unless boolean
876 (xslt-error "invalid nametest token")))
877 (check-null (boolean)
878 (check (not boolean))))
879 (cons
880 :patterns
881 (mapcar (lambda (name-test)
882 (destructuring-bind (&optional path &rest junk)
883 (cdr (xpath:parse-pattern-expression name-test))
884 (check-null junk)
885 (check (eq (car path) :path))
886 (destructuring-bind (&optional child &rest junk) (cdr path)
887 (check-null junk)
888 (check (eq (car child) :child))
889 (destructuring-bind (nodetest &rest junk) (cdr child)
890 (check-null junk)
891 (check (or (stringp nodetest)
892 (eq nodetest '*)
893 (and (consp nodetest)
894 (or (eq (car nodetest) :namespace)
895 (eq (car nodetest) :qname)))))))
896 path))
897 (words str)))))
899 (defstruct strip-test
900 compiled-pattern
901 priority
902 position
903 value)
905 (defun parse-strip/preserve-space! (stylesheet <transform> env)
906 (let ((i 0))
907 (do-toplevel (elt "strip-space|preserve-space" <transform>)
908 (let ((*namespaces* (acons-namespaces elt))
909 (value
910 (if (equal (stp:local-name elt) "strip-space")
911 :strip
912 :preserve)))
913 (dolist (expression
914 (cdr (parse-nametest-tokens
915 (stp:attribute-value elt "elements"))))
916 (let* ((compiled-pattern
917 (car (without-xslt-current ()
918 (xpath:compute-patterns
919 `(:patterns ,expression)
920 *import-priority*
921 "will set below"
922 env))))
923 (strip-test
924 (make-strip-test :compiled-pattern compiled-pattern
925 :priority (expression-priority expression)
926 :position i
927 :value value)))
928 (setf (xpath:pattern-value compiled-pattern) strip-test)
929 (push strip-test (stylesheet-strip-tests stylesheet)))))
930 (incf i))))
932 (defstruct (output-specification
933 (:conc-name "OUTPUT-"))
934 method
935 indent
936 omit-xml-declaration
937 encoding
938 doctype-system
939 doctype-public
940 cdata-section-matchers)
942 (defun parse-output! (stylesheet <transform> env)
943 (dolist (<output> (list-toplevel "output" <transform>))
944 (let ((spec (stylesheet-output-specification stylesheet)))
945 (only-with-attributes (version
946 method
947 indent
948 encoding
949 media-type
950 doctype-system
951 doctype-public
952 omit-xml-declaration
953 standalone
954 cdata-section-elements)
955 <output>
956 (declare (ignore version
957 ;; FIXME:
958 media-type
959 standalone))
960 (when method
961 (setf (output-method spec) method))
962 (when indent
963 (setf (output-indent spec) indent))
964 (when encoding
965 (setf (output-encoding spec) encoding))
966 (when doctype-system
967 (setf (output-doctype-system spec) doctype-system))
968 (when doctype-public
969 (setf (output-doctype-public spec) doctype-public))
970 (when omit-xml-declaration
971 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
972 (when cdata-section-elements
973 (dolist (qname (words cdata-section-elements))
974 (decode-qname qname env nil) ;check the syntax
975 (push (xpath:make-pattern-matcher* qname env)
976 (output-cdata-section-matchers spec))))))))
978 (defun make-empty-declaration-array ()
979 (make-array 1 :fill-pointer 0 :adjustable t))
981 (defun make-variable-value-array (n-lexical-variables)
982 (make-array n-lexical-variables :initial-element 'unbound))
984 (defun compile-global-variable (<variable> env) ;; also for <param>
985 (stp:with-attributes (name select) <variable>
986 (when (and select (stp:list-children <variable>))
987 (xslt-error "variable with select and body"))
988 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
989 (inner (cond
990 (select
991 (compile-xpath select env))
992 ((stp:list-children <variable>)
993 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
994 (inner-thunk (compile-instruction inner-sexpr env)))
995 (lambda (ctx)
996 (apply-to-result-tree-fragment ctx inner-thunk))))
998 (lambda (ctx)
999 (declare (ignore ctx))
1000 ""))))
1001 (n-lexical-variables (length *lexical-variable-declarations*)))
1002 (xslt-trace-thunk
1003 (lambda (ctx)
1004 (let* ((*lexical-variable-values*
1005 (make-variable-value-array n-lexical-variables)))
1006 (funcall inner ctx)))
1007 "global ~s (~s) = ~s" name select :result))))
1009 (defstruct (variable-chain
1010 (:constructor make-variable-chain)
1011 (:conc-name "VARIABLE-CHAIN-"))
1012 definitions
1013 index
1014 local-name
1015 thunk
1016 uri)
1018 (defstruct (import-variable
1019 (:constructor make-variable)
1020 (:conc-name "VARIABLE-"))
1021 value-thunk
1022 value-thunk-setter
1023 param-p)
1025 (defun parse-global-variable! (stylesheet <variable> global-env)
1026 (let* ((*namespaces* (acons-namespaces <variable>))
1027 (instruction-base-uri (stp:base-uri <variable>))
1028 (*instruction-base-uri* instruction-base-uri)
1029 (*excluded-namespaces* (list *xsl*))
1030 (*extension-namespaces* '())
1031 (qname (stp:attribute-value <variable> "name")))
1032 (with-import-magic (<variable> global-env)
1033 (unless qname
1034 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
1035 (multiple-value-bind (local-name uri)
1036 (decode-qname qname global-env nil)
1037 ;; For the normal compilation environment of templates, install it
1038 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
1039 (let ((index (intern-global-variable local-name uri)))
1040 ;; For the evaluation of a global variable itself, build a thunk
1041 ;; that lazily resolves other variables, stored into
1042 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
1043 (let* ((value-thunk :unknown)
1044 (sgv (stylesheet-global-variables stylesheet))
1045 (chain
1046 (if (< index (length sgv))
1047 (elt sgv index)
1048 (make-variable-chain
1049 :index index
1050 :local-name local-name
1051 :uri uri)))
1052 (next (car (variable-chain-definitions chain)))
1053 (global-variable-thunk
1054 (lambda (ctx)
1055 (let ((v (global-variable-value index nil)))
1056 (cond
1057 ((eq v 'seen)
1058 (unless next
1059 (xslt-error "no next definition for: ~A"
1060 local-name))
1061 (funcall (variable-value-thunk next) ctx))
1062 ((eq v 'unbound)
1063 (setf (global-variable-value index) 'seen)
1064 (setf (global-variable-value index)
1065 (funcall value-thunk ctx)))
1067 v)))))
1068 (excluded-namespaces *excluded-namespaces*)
1069 (extension-namespaces *extension-namespaces*)
1070 (variable
1071 (make-variable :param-p (namep <variable> "param")))
1072 (forwards-compatible-p *forwards-compatible-p*)
1073 (value-thunk-setter
1074 (lambda ()
1075 (let* ((*instruction-base-uri* instruction-base-uri)
1076 (*excluded-namespaces* excluded-namespaces)
1077 (*extension-namespaces* extension-namespaces)
1078 (*forwards-compatible-p* forwards-compatible-p)
1080 (compile-global-variable <variable> global-env)))
1081 (setf value-thunk fn)
1082 (setf (variable-value-thunk variable) fn)))))
1083 (setf (variable-value-thunk-setter variable)
1084 value-thunk-setter)
1085 (setf (gethash (cons local-name uri)
1086 (initial-global-variable-thunks global-env))
1087 global-variable-thunk)
1088 (setf (variable-chain-thunk chain) global-variable-thunk)
1089 (push variable (variable-chain-definitions chain))
1090 chain))))))
1092 (defun parse-keys! (stylesheet <transform> env)
1093 (xpath:with-namespaces ((nil #.*xsl*))
1094 (do-toplevel (<key> "key" <transform>)
1095 (with-import-magic (<key> env)
1096 (let ((*instruction-base-uri* (stp:base-uri <key>)))
1097 (stp:with-attributes (name match use) <key>
1098 (unless name (xslt-error "key name attribute not specified"))
1099 (unless match (xslt-error "key match attribute not specified"))
1100 (unless use (xslt-error "key use attribute not specified"))
1101 (multiple-value-bind (local-name uri)
1102 (decode-qname name env nil)
1103 (add-key stylesheet
1104 (cons local-name uri)
1105 (compile-xpath `(xpath:xpath ,(parse-key-pattern match))
1106 env)
1107 (compile-xpath use
1108 (make-instance 'key-environment))))))))))
1110 (defun prepare-global-variables (stylesheet <transform>)
1111 (xpath:with-namespaces ((nil #.*xsl*))
1112 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet))
1113 (global-env (make-instance 'global-variable-environment
1114 :initial-global-variable-thunks igvt))
1115 (chains '()))
1116 (do-toplevel (<variable> "variable|param" <transform>)
1117 (let ((chain
1118 (parse-global-variable! stylesheet <variable> global-env)))
1119 (xslt-trace "parsing global variable ~s (uri ~s)"
1120 (variable-chain-local-name chain)
1121 (variable-chain-uri chain))
1122 (when (find chain
1123 chains
1124 :test (lambda (a b)
1125 (and (equal (variable-chain-local-name a)
1126 (variable-chain-local-name b))
1127 (equal (variable-chain-uri a)
1128 (variable-chain-uri b)))))
1129 (xslt-error "duplicate definition for global variable ~A"
1130 (variable-chain-local-name chain)))
1131 (push chain chains)))
1132 (setf chains (nreverse chains))
1133 (let ((table (stylesheet-global-variables stylesheet))
1134 (newlen (length *global-variable-declarations*)))
1135 (adjust-array table newlen :fill-pointer newlen)
1136 (dolist (chain chains)
1137 (setf (elt table (variable-chain-index chain)) chain)))
1138 (lambda ()
1139 ;; now that the global environment knows about all variables, run the
1140 ;; thunk setters to perform their compilation
1141 (mapc (lambda (chain)
1142 (dolist (var (variable-chain-definitions chain))
1143 (funcall (variable-value-thunk-setter var))))
1144 chains)))))
1146 (defun parse-templates! (stylesheet <transform> env)
1147 (let ((i 0))
1148 (do-toplevel (<template> "template" <transform>)
1149 (let ((*namespaces* (acons-namespaces <template>))
1150 (*instruction-base-uri* (stp:base-uri <template>)))
1151 (with-import-magic (<template> env)
1152 (dolist (template (compile-template <template> env i))
1153 (let ((name (template-name template)))
1154 (if name
1155 (let* ((table (stylesheet-named-templates stylesheet))
1156 (head (car (gethash name table))))
1157 (when (and head (eql (template-import-priority head)
1158 (template-import-priority template)))
1159 ;; fixme: is this supposed to be a run-time error?
1160 (xslt-error "conflicting templates for ~A" name))
1161 (push template (gethash name table)))
1162 (let ((mode (ensure-mode/qname stylesheet
1163 (template-mode-qname template)
1164 env)))
1165 (setf (template-mode template) mode)
1166 (push template (mode-templates mode))))))))
1167 (incf i))))
1170 ;;;; APPLY-STYLESHEET
1172 (defvar *stylesheet*)
1174 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
1176 (defun unalias-uri (uri)
1177 (let ((result
1178 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
1179 uri)))
1180 (check-type result string)
1181 result))
1183 (defstruct (parameter
1184 (:constructor make-parameter (value local-name &optional uri)))
1185 (uri "")
1186 local-name
1187 value)
1189 (defun find-parameter-value (local-name uri parameters)
1190 (dolist (p parameters)
1191 (when (and (equal (parameter-local-name p) local-name)
1192 (equal (parameter-uri p) uri))
1193 (return (parameter-value p)))))
1195 (defvar *uri-resolver*)
1197 (defun parse-allowing-microsoft-bom (pathname handler)
1198 (with-open-file (s pathname :element-type '(unsigned-byte 8))
1199 (unless (and (eql (read-byte s nil) #xef)
1200 (eql (read-byte s nil) #xbb)
1201 (eql (read-byte s nil) #xbf))
1202 (file-position s 0))
1203 (cxml:parse s handler)))
1205 (defvar *documents*)
1207 (defun %document (uri-string base-uri)
1208 (let* ((absolute-uri
1209 (puri:merge-uris uri-string (or base-uri "")))
1210 (resolved-uri
1211 (if *uri-resolver*
1212 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
1213 absolute-uri))
1214 (pathname
1215 (handler-case
1216 (uri-to-pathname resolved-uri)
1217 (cxml:xml-parse-error (c)
1218 (xslt-error "cannot find referenced document ~A: ~A"
1219 resolved-uri c))))
1220 (xpath-root-node
1221 (or (gethash pathname *documents*)
1222 (setf (gethash pathname *documents*)
1223 (make-whitespace-stripper
1224 (handler-case
1225 (parse-allowing-microsoft-bom pathname
1226 (stp:make-builder))
1227 ((or file-error cxml:xml-parse-error) (c)
1228 (xslt-error "cannot parse referenced document ~A: ~A"
1229 pathname c)))
1230 (stylesheet-strip-thunk *stylesheet*))))))
1231 (when (puri:uri-fragment absolute-uri)
1232 (xslt-error "use of fragment identifiers in document() not supported"))
1233 xpath-root-node))
1235 (xpath-sys:define-extension xslt *xsl*)
1237 (defun document-base-uri (node)
1238 (xpath-protocol:base-uri
1239 (cond
1240 ((xpath-protocol:node-type-p node :document)
1241 (xpath::find-in-pipe-if
1242 (lambda (x)
1243 (xpath-protocol:node-type-p x :element))
1244 (xpath-protocol:child-pipe node)))
1245 ((xpath-protocol:node-type-p node :element)
1246 node)
1248 (xpath-protocol:parent-node node)))))
1250 (xpath-sys:define-xpath-function/lazy
1251 xslt :document
1252 (object &optional node-set)
1253 (let ((instruction-base-uri *instruction-base-uri*))
1254 (lambda (ctx)
1255 (let* ((object (funcall object ctx))
1256 (node-set (and node-set (funcall node-set ctx)))
1257 (base-uri
1258 (if node-set
1259 (document-base-uri (xpath::textually-first-node node-set))
1260 instruction-base-uri)))
1261 (xpath-sys:make-node-set
1262 (if (xpath:node-set-p object)
1263 (xpath:map-node-set->list
1264 (lambda (node)
1265 (%document (xpath:string-value node)
1266 (if node-set
1267 base-uri
1268 (document-base-uri node))))
1269 object)
1270 (list (%document (xpath:string-value object) base-uri))))))))
1272 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1273 (let ((namespaces *namespaces*))
1274 (lambda (ctx)
1275 (let* ((qname (xpath:string-value (funcall name ctx)))
1276 (object (funcall object ctx))
1277 (expanded-name
1278 (multiple-value-bind (local-name uri)
1279 (decode-qname/runtime qname namespaces nil)
1280 (cons local-name uri)))
1281 (key (find-key expanded-name *stylesheet*)))
1282 (labels ((get-by-key (value)
1283 (let ((value (xpath:string-value value)))
1284 (xpath::filter-pipe
1285 #'(lambda (node)
1286 (let ((uses
1287 (xpath:evaluate-compiled (key-use key) node)))
1288 (if (xpath:node-set-p uses)
1289 (xpath::find-in-pipe
1290 value
1291 (xpath-sys:pipe-of uses)
1292 :key #'xpath:string-value
1293 :test #'equal)
1294 (equal value (xpath:string-value uses)))))
1295 (xpath-sys:pipe-of
1296 (xpath:node-set-value
1297 (xpath:evaluate-compiled (key-match key) ctx)))))))
1298 (xpath-sys:make-node-set
1299 (xpath::sort-pipe
1300 (if (xpath:node-set-p object)
1301 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1302 (get-by-key object)))))))))
1304 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1306 (xpath-sys:define-xpath-function/lazy xslt :current ()
1307 (when *without-xslt-current-p*
1308 (xslt-error "current() not allowed here"))
1309 #'(lambda (ctx)
1310 (xpath-sys:make-node-set
1311 (xpath-sys:make-pipe
1312 (xpath:context-starting-node ctx)
1313 nil))))
1315 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1316 #'(lambda (ctx)
1317 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1318 (funcall name ctx))
1319 "")))
1321 (defun %get-node-id (node)
1322 (when (xpath:node-set-p node)
1323 (setf node (xpath::textually-first-node node)))
1324 (when node
1325 (let ((id (xpath-sys:get-node-id node))
1326 (highest-base-uri
1327 (loop
1328 for parent = node then next
1329 for next = (xpath-protocol:parent-node parent)
1330 for this-base-uri = (xpath-protocol:base-uri parent)
1331 for highest-base-uri = (if (plusp (length this-base-uri))
1332 this-base-uri
1333 highest-base-uri)
1334 while next
1335 finally (return highest-base-uri))))
1336 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1337 ;; checked only if everything else matches.
1339 ;; This might be pointless premature optimization, but I like the idea :-)
1340 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1342 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1343 (if node-set-thunk
1344 #'(lambda (ctx)
1345 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1346 #'(lambda (ctx)
1347 (%get-node-id (xpath:context-node ctx)))))
1349 (declaim (special *available-instructions*))
1351 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1352 (let ((namespaces *namespaces*))
1353 #'(lambda (ctx)
1354 (let ((qname (funcall qname ctx)))
1355 (multiple-value-bind (local-name uri)
1356 (decode-qname/runtime qname namespaces nil)
1357 (and (equal uri *xsl*)
1358 (gethash local-name *available-instructions*)
1359 t))))))
1361 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1362 (let ((namespaces *namespaces*))
1363 #'(lambda (ctx)
1364 (let ((qname (funcall qname ctx)))
1365 (multiple-value-bind (local-name uri)
1366 (decode-qname/runtime qname namespaces nil)
1367 (and (zerop (length uri))
1368 (or (xpath-sys:find-xpath-function local-name *xsl*)
1369 (xpath-sys:find-xpath-function local-name uri))
1370 t))))))
1372 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1373 (let ((namespaces *namespaces*))
1374 (lambda (ctx)
1375 (let ((qname (funcall qname ctx)))
1376 (multiple-value-bind (local-name uri)
1377 (decode-qname/runtime qname namespaces nil)
1378 (if (equal uri *xsl*)
1379 (cond
1380 ((equal local-name "version")
1381 "1")
1382 ((equal local-name "vendor")
1383 "Xuriella")
1384 ((equal local-name "vendor-uri")
1385 "http://repo.or.cz/w/xuriella.git")
1387 ""))
1388 ""))))))
1390 (defun apply-stylesheet
1391 (stylesheet source-designator
1392 &key output parameters uri-resolver navigator)
1393 (when (typep stylesheet 'xml-designator)
1394 (setf stylesheet
1395 (handler-bind
1396 ((cxml:xml-parse-error
1397 (lambda (c)
1398 (xslt-error "cannot parse stylesheet: ~A" c))))
1399 (parse-stylesheet stylesheet))))
1400 (with-resignalled-errors ()
1401 (invoke-with-output-sink
1402 (lambda ()
1403 (let* ((*documents* (make-hash-table :test 'equal))
1404 (xpath:*navigator* (or navigator :default-navigator))
1405 (puri:*strict-parse* nil)
1406 (*stylesheet* stylesheet)
1407 (*empty-mode* (make-mode))
1408 (*default-mode* (find-mode stylesheet nil))
1409 (global-variable-chains
1410 (stylesheet-global-variables stylesheet))
1411 (*global-variable-values*
1412 (make-variable-value-array (length global-variable-chains)))
1413 (*uri-resolver* uri-resolver)
1414 (source-document
1415 (if (typep source-designator 'xml-designator)
1416 (cxml:parse source-designator (stp:make-builder))
1417 source-designator))
1418 (xpath-root-node
1419 (make-whitespace-stripper
1420 source-document
1421 (stylesheet-strip-thunk stylesheet)))
1422 (ctx (xpath:make-context xpath-root-node)))
1423 (when (pathnamep source-designator)
1424 (setf (gethash source-designator *documents*) xpath-root-node))
1425 (map nil
1426 (lambda (chain)
1427 (let ((head (car (variable-chain-definitions chain))))
1428 (when (variable-param-p head)
1429 (let ((value
1430 (find-parameter-value
1431 (variable-chain-local-name chain)
1432 (variable-chain-uri chain)
1433 parameters)))
1434 (when value
1435 (setf (global-variable-value
1436 (variable-chain-index chain))
1437 value))))))
1438 global-variable-chains)
1439 (map nil
1440 (lambda (chain)
1441 (funcall (variable-chain-thunk chain) ctx))
1442 global-variable-chains)
1443 ;; zzz we wouldn't have to mask float traps here if we used the
1444 ;; XPath API properly. Unfortunately I've been using FUNCALL
1445 ;; everywhere instead of EVALUATE, so let's paper over that
1446 ;; at a central place to be sure:
1447 (xpath::with-float-traps-masked ()
1448 (apply-templates ctx :mode *default-mode*))))
1449 (stylesheet-output-specification stylesheet)
1450 output)))
1452 (defun find-attribute-set (local-name uri &optional (stylesheet *stylesheet*))
1453 (or (gethash (cons local-name uri) (stylesheet-attribute-sets stylesheet))
1454 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1456 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1457 (when sort-predicate
1458 (setf list
1459 (mapcar #'xpath:context-node
1460 (stable-sort (contextify-node-list list)
1461 sort-predicate))))
1462 (let* ((n (length list))
1463 (s/d (lambda () n)))
1464 (loop
1465 for i from 1
1466 for child in list
1468 (apply-templates (xpath:make-context child s/d i)
1469 :param-bindings param-bindings
1470 :mode mode))))
1472 (defvar *stack-limit* 200)
1474 (defun invoke-with-stack-limit (fn)
1475 (let ((*stack-limit* (1- *stack-limit*)))
1476 (unless (plusp *stack-limit*)
1477 (xslt-error "*stack-limit* reached; stack overflow"))
1478 (funcall fn)))
1480 (defun invoke-template (ctx template param-bindings)
1481 (let ((*lexical-variable-values*
1482 (make-variable-value-array (template-n-variables template))))
1483 (with-stack-limit ()
1484 (loop
1485 for (name-cons value) in param-bindings
1486 for (nil index nil) = (find name-cons
1487 (template-params template)
1488 :test #'equal
1489 :key #'car)
1491 (when index
1492 (setf (lexical-variable-value index) value)))
1493 (funcall (template-body template) ctx))))
1495 (defun apply-default-templates (ctx mode)
1496 (let ((node (xpath:context-node ctx)))
1497 (cond
1498 ((or (xpath-protocol:node-type-p node :processing-instruction)
1499 (xpath-protocol:node-type-p node :comment)))
1500 ((or (xpath-protocol:node-type-p node :text)
1501 (xpath-protocol:node-type-p node :attribute))
1502 (write-text (xpath-protocol:node-text node)))
1504 (apply-templates/list
1505 (xpath::force
1506 (xpath-protocol:child-pipe node))
1507 :mode mode)))))
1509 (defvar *apply-imports*)
1511 (defun apply-applicable-templates (ctx templates param-bindings finally)
1512 (labels ((apply-imports (&optional actual-param-bindings)
1513 (if templates
1514 (let* ((this (pop templates))
1515 (low (template-apply-imports-limit this))
1516 (high (template-import-priority this)))
1517 (setf templates
1518 (remove-if-not
1519 (lambda (x)
1520 (<= low (template-import-priority x) high))
1521 templates))
1522 (invoke-template ctx this actual-param-bindings))
1523 (funcall finally))))
1524 (let ((*apply-imports* #'apply-imports))
1525 (apply-imports param-bindings))))
1527 (defun apply-templates (ctx &key param-bindings mode)
1528 (apply-applicable-templates ctx
1529 (find-templates ctx (or mode *default-mode*))
1530 param-bindings
1531 (lambda ()
1532 (apply-default-templates ctx mode))))
1534 (defun call-template (ctx name &optional param-bindings)
1535 (apply-applicable-templates ctx
1536 (find-named-templates name)
1537 param-bindings
1538 (lambda ()
1539 (xslt-error "cannot find named template: ~s"
1540 name))))
1542 (defun find-templates (ctx mode)
1543 (let* ((matching-candidates
1544 (xpath:matching-values (mode-match-thunk mode)
1545 (xpath:context-node ctx)))
1546 (npriorities
1547 (if matching-candidates
1548 (1+ (reduce #'max
1549 matching-candidates
1550 :key #'template-import-priority))
1552 (priority-groups (make-array npriorities :initial-element nil)))
1553 (dolist (template matching-candidates)
1554 (push template
1555 (elt priority-groups (template-import-priority template))))
1556 (loop
1557 for i from (1- npriorities) downto 0
1558 for group = (elt priority-groups i)
1559 for template = (maximize #'template< group)
1560 when template
1561 collect template)))
1563 (defun find-named-templates (name)
1564 (gethash name (stylesheet-named-templates *stylesheet*)))
1566 (defun template< (a b) ;assuming same import priority
1567 (let ((p (template-priority a))
1568 (q (template-priority b)))
1569 (cond
1570 ((< p q) t)
1571 ((> p q) nil)
1573 (xslt-cerror "conflicting templates:~_~A,~_~A"
1574 (template-match-expression a)
1575 (template-match-expression b))
1576 (< (template-position a) (template-position b))))))
1578 (defun maximize (< things)
1579 (when things
1580 (let ((max (car things)))
1581 (dolist (other (cdr things))
1582 (when (funcall < max other)
1583 (setf max other)))
1584 max)))
1586 (defun invoke-with-output-sink (fn output-spec output)
1587 (etypecase output
1588 (pathname
1589 (with-open-file (s output
1590 :direction :output
1591 :element-type '(unsigned-byte 8)
1592 :if-exists :rename-and-delete)
1593 (invoke-with-output-sink fn output-spec s)))
1594 ((or stream null)
1595 (invoke-with-output-sink fn
1596 output-spec
1597 (make-output-sink output-spec output)))
1598 ((or hax:abstract-handler sax:abstract-handler)
1599 (with-xml-output output
1600 (when (typep output '(or combi-sink auto-detect-sink))
1601 (sax:start-dtd output
1602 :autodetect-me-please
1603 (output-doctype-public output-spec)
1604 (output-doctype-system output-spec)))
1605 (funcall fn)))))
1607 (defun make-output-sink (output-spec stream)
1608 (let* ((ystream
1609 (if stream
1610 (let ((et (stream-element-type stream)))
1611 (cond
1612 ((or (null et) (subtypep et '(unsigned-byte 8)))
1613 (runes:make-octet-stream-ystream stream))
1614 ((subtypep et 'character)
1615 (runes:make-character-stream-ystream stream))))
1616 (runes:make-rod-ystream)))
1617 (omit-xml-declaration-p
1618 (boolean-or-error (output-omit-xml-declaration output-spec)))
1619 (sink-encoding (or (output-encoding output-spec) "UTF-8"))
1620 (sax-target
1621 (progn
1622 (setf (runes:ystream-encoding ystream)
1623 (cxml::find-output-encoding sink-encoding))
1624 (make-instance 'cxml::sink
1625 :ystream ystream
1626 :omit-xml-declaration-p omit-xml-declaration-p
1627 :encoding sink-encoding))))
1628 (flet ((make-combi-sink ()
1629 (make-instance 'combi-sink
1630 :hax-target (make-instance 'chtml::sink
1631 :ystream ystream)
1632 :sax-target sax-target
1633 :encoding sink-encoding)))
1634 (let ((method-key
1635 (cond
1636 ((equalp (output-method output-spec) "HTML") :html)
1637 ((equalp (output-method output-spec) "TEXT") :text)
1638 ((equalp (output-method output-spec) "XML") :xml)
1639 (t nil))))
1640 (cond
1641 ((and (eq method-key :html)
1642 (null (output-doctype-system output-spec))
1643 (null (output-doctype-public output-spec)))
1644 (make-combi-sink))
1645 ((eq method-key :text)
1646 (make-text-filter sax-target))
1647 ((and (eq method-key :xml)
1648 (null (output-doctype-system output-spec)))
1649 sax-target)
1651 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1653 (defstruct template
1654 match-expression
1655 compiled-pattern
1656 name
1657 import-priority
1658 apply-imports-limit
1659 priority
1660 position
1661 mode
1662 mode-qname
1663 params
1664 body
1665 n-variables)
1667 (defun expression-priority (form)
1668 (let ((step (second form)))
1669 (if (and (null (cddr form))
1670 (listp step)
1671 (member (car step) '(:child :attribute))
1672 (null (cddr step)))
1673 (let ((name (second step)))
1674 (cond
1675 ((or (stringp name)
1676 (and (consp name)
1677 (or (eq (car name) :qname)
1678 (eq (car name) :processing-instruction))))
1679 0.0)
1680 ((and (consp name)
1681 (or (eq (car name) :namespace)
1682 (eq (car name) '*)))
1683 -0.25)
1685 -0.5)))
1686 0.5)))
1688 (defun parse-key-pattern (str)
1689 (with-resignalled-errors ()
1690 (with-forward-compatible-errors
1691 (xpath:parse-xpath "compile-time-error()") ;hack
1692 (let ((parsed
1693 (mapcar #'(lambda (item)
1694 `(:path (:root :node)
1695 (:descendant-or-self *)
1696 ,@(cdr item)))
1697 (cdr (xpath::parse-pattern-expression str)))))
1698 (if (null (rest parsed))
1699 (first parsed)
1700 `(:union ,@parsed))))))
1702 (defun compile-value-thunk (value env)
1703 (if (and (listp value) (eq (car value) 'progn))
1704 (let ((inner-thunk (compile-instruction value env)))
1705 (lambda (ctx)
1706 (apply-to-result-tree-fragment ctx inner-thunk)))
1707 (compile-xpath value env)))
1709 (defun compile-var-binding (name value env)
1710 (multiple-value-bind (local-name uri)
1711 (decode-qname name env nil)
1712 (let ((thunk (xslt-trace-thunk
1713 (compile-value-thunk value env)
1714 "local variable ~s = ~s" name :result)))
1715 (list (cons local-name uri)
1716 (push-variable local-name
1718 *lexical-variable-declarations*)
1719 thunk))))
1721 (defun compile-var-bindings (forms env)
1722 (loop
1723 for (name value) in forms
1724 collect (compile-var-binding name value env)))
1726 (defun compile-template (<template> env position)
1727 (stp:with-attributes (match name priority mode) <template>
1728 (unless (or name match)
1729 (xslt-error "missing match in template"))
1730 (multiple-value-bind (params body-pos)
1731 (loop
1732 for i from 0
1733 for child in (stp:list-children <template>)
1734 while (namep child "param")
1735 collect (parse-param child) into params
1736 finally (return (values params i)))
1737 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1738 (param-bindings (compile-var-bindings params env))
1739 (body (parse-body <template> body-pos (mapcar #'car params)))
1740 (body-thunk (compile-instruction `(progn ,@body) env))
1741 (outer-body-thunk
1742 (xslt-trace-thunk
1743 #'(lambda (ctx)
1744 (unwind-protect
1745 (progn
1746 ;; set params that weren't initialized by apply-templates
1747 (loop for (name index param-thunk) in param-bindings
1748 when (eq (lexical-variable-value index nil) 'unbound)
1749 do (setf (lexical-variable-value index)
1750 (funcall param-thunk ctx)))
1751 (funcall body-thunk ctx))))
1752 "template: match = ~s name = ~s" match name))
1753 (n-variables (length *lexical-variable-declarations*)))
1754 (append
1755 (when name
1756 (multiple-value-bind (local-name uri)
1757 (decode-qname name env nil)
1758 (list
1759 (make-template :name (cons local-name uri)
1760 :import-priority *import-priority*
1761 :apply-imports-limit *apply-imports-limit*
1762 :params param-bindings
1763 :body outer-body-thunk
1764 :n-variables n-variables))))
1765 (when match
1766 (mapcar (lambda (expression)
1767 (let* ((compiled-pattern
1768 (xslt-trace-thunk
1769 (car (without-xslt-current ()
1770 (xpath:compute-patterns
1771 `(:patterns ,expression)
1773 :dummy
1774 env)))
1775 "match-thunk for template (match ~s): ~s --> ~s"
1776 match expression :result))
1777 (p (if priority
1778 (xpath::parse-xnum priority)
1779 (expression-priority expression)))
1781 (progn
1782 (unless (and (numberp p)
1783 (not (xpath::inf-p p))
1784 (not (xpath::nan-p p)))
1785 (xslt-error "failed to parse priority"))
1786 (float p 1.0d0)))
1787 (template
1788 (make-template :match-expression expression
1789 :compiled-pattern compiled-pattern
1790 :import-priority *import-priority*
1791 :apply-imports-limit *apply-imports-limit*
1792 :priority p
1793 :position position
1794 :mode-qname mode
1795 :params param-bindings
1796 :body outer-body-thunk
1797 :n-variables n-variables)))
1798 (setf (xpath:pattern-value compiled-pattern)
1799 template)
1800 template))
1801 (cdr (xpath:parse-pattern-expression match)))))))))
1802 #+(or)
1803 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")