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