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