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
10 ;;; * Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
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.
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
)
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"))
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
66 (defun xslt-cerror (fmt &rest args
)
67 (declare (ignore fmt args
))
69 (with-simple-restart (recover "recover")
70 (error 'recoverable-xslt-error
72 :format-arguments args
)))
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
81 (let ((doit (gensym)))
82 `(flet ((,doit
() ,form
))
89 (defmacro with-resignalled-errors
((&optional
) &body body
)
90 `(invoke-with-resignalled-errors (lambda () ,@body
)))
92 (defun invoke-with-resignalled-errors (fn)
97 (babel-encodings:character-encoding-error
99 (xslt-error "~A" c
))))
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
)
113 (when *forwards-compatible-p
*
115 (setf result
(funcall fn
)))
118 (setf result
(funcall error-fn
))
122 (defun compile-xpath (xpath &optional env
)
123 (with-resignalled-errors ()
124 (with-forward-compatible-errors
126 (xslt-error "attempt to evaluate an XPath expression with compile-time errors, delayed due to forwards compatible processing: ~A"
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
))
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)
151 ;;;; Helper functions and macros
153 (defun check-for-invalid-attributes (valid-names node
)
154 (labels ((check-attribute (a)
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
)
161 (xslt-error "attribute ~A not allowed on ~A"
163 (stp:local-name node
)))))
164 (stp:map-attributes nil
#'check-attribute node
)))
166 (defmacro only-with-attributes
((&rest specs
) node
&body body
)
168 (mapcar (lambda (entry)
169 (if (and (listp entry
) (cdr entry
))
170 (destructuring-bind (name &optional
(uri ""))
173 (cons (string-downcase
175 (symbol-name entry
)))
179 `(let ((,%NODE
,node
))
180 (check-for-invalid-attributes ',valid-names
,%NODE
)
181 (stp:with-attributes
,specs
,%NODE
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
)
189 (map-pipe-eagerly #'(lambda (,var
) ,@body
) ,pipe
)
193 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
195 (defparameter *namespaces
*
197 ("xmlns" .
#"http://www.w3.org/2000/xmlns/")
198 ("xml" .
#"http://www.w3.org/XML/1998/namespace")))
200 (defvar *global-variable-declarations
*)
201 (defvar *lexical-variable-declarations
*)
203 (defvar *global-variable-values
*)
204 (defvar *lexical-variable-values
*)
206 (defclass xslt-environment
() ())
208 (defun split-qname (str)
210 (multiple-value-bind (prefix local-name
)
211 (cxml::split-qname str
)
213 ;; FIXME: cxml should really offer a function that does
214 ;; checks for NCName and QName in a sensible way for user code.
215 ;; cxml::split-qname is tailored to the needs of the parser.
217 ;; For now, let's just check the syntax explicitly.
218 (and (or (null prefix
) (xpath::nc-name-p prefix
))
219 (xpath::nc-name-p local-name
))
220 (xslt-error "not a qname: ~A" str
))
221 (values prefix local-name
))
222 (cxml:well-formedness-violation
()
223 (xslt-error "not a qname: ~A" str
))))
225 (defun decode-qname (qname env attributep
)
227 (xslt-error "missing name"))
228 (multiple-value-bind (prefix local-name
)
231 (if (or prefix
(not attributep
))
232 (xpath-sys:environment-find-namespace env
(or prefix
""))
236 (defmethod xpath-sys:environment-find-namespace
((env xslt-environment
) prefix
)
237 (or (cdr (assoc prefix
*namespaces
* :test
'equal
))
239 ;; Change the entire code base to represent "no prefix" as the
240 ;; empty string consistently. unparse.lisp has already been changed.
241 (and (equal prefix
"")
242 (cdr (assoc nil
*namespaces
* :test
'equal
)))
243 (and (eql prefix nil
)
244 (cdr (assoc "" *namespaces
* :test
'equal
)))))
246 (defun find-variable-index (local-name uri table
)
247 (position (cons local-name uri
) table
:test
'equal
))
249 (defun intern-global-variable (local-name uri
)
250 (or (find-variable-index local-name uri
*global-variable-declarations
*)
251 (push-variable local-name uri
*global-variable-declarations
*)))
253 (defun push-variable (local-name uri table
)
256 (vector-push-extend (cons local-name uri
) table
)))
258 (defun lexical-variable-value (index &optional
(errorp t
))
259 (let ((result (svref *lexical-variable-values
* index
)))
261 (assert (not (eq result
'unbound
))))
264 (defun (setf lexical-variable-value
) (newval index
)
265 (assert (not (eq newval
'unbound
)))
266 (setf (svref *lexical-variable-values
* index
) newval
))
268 (defun global-variable-value (index &optional
(errorp t
))
269 (let ((result (svref *global-variable-values
* index
)))
271 (assert (not (eq result
'unbound
))))
274 (defun (setf global-variable-value
) (newval index
)
275 (assert (not (eq newval
'unbound
)))
276 (setf (svref *global-variable-values
* index
) newval
))
278 (defmethod xpath-sys:environment-find-function
279 ((env xslt-environment
) lname uri
)
280 (or (if (string= uri
"")
281 (or (xpath-sys:find-xpath-function lname
*xsl
*)
282 (xpath-sys:find-xpath-function lname uri
))
283 (xpath-sys:find-xpath-function lname uri
))
284 (when *forwards-compatible-p
*
285 (lambda (&rest ignore
)
286 (declare (ignore ignore
))
287 (xslt-error "attempt to call an unknown XPath function (~A); error delayed until run-time due to forwards compatible processing"
290 (defmethod xpath-sys:environment-find-variable
291 ((env xslt-environment
) lname uri
)
293 (find-variable-index lname uri
*lexical-variable-declarations
*)))
296 (declare (ignore ctx
))
297 (svref *lexical-variable-values
* index
)))))
299 (defclass lexical-xslt-environment
(xslt-environment) ())
301 (defmethod xpath-sys:environment-find-variable
302 ((env lexical-xslt-environment
) lname uri
)
303 (or (call-next-method)
305 (find-variable-index lname uri
*global-variable-declarations
*)))
309 (declare (ignore ctx
))
310 (svref *global-variable-values
* index
))
311 "global ~s (uri ~s) = ~s" lname uri
:result
)))))
313 (defclass key-environment
(xslt-environment) ())
315 (defmethod xpath-sys:environment-find-variable
316 ((env key-environment
) lname uri
)
317 (declare (ignore lname uri
))
318 (xslt-error "disallowed variable reference"))
320 (defclass global-variable-environment
(xslt-environment)
321 ((initial-global-variable-thunks
322 :initarg
:initial-global-variable-thunks
323 :accessor initial-global-variable-thunks
)))
325 (defmethod xpath-sys:environment-find-variable
326 ((env global-variable-environment
) lname uri
)
327 (or (call-next-method)
328 (gethash (cons lname uri
) (initial-global-variable-thunks env
))))
331 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
333 ;;;; A sink that serializes only text not contained in any element.
335 (defmacro with-toplevel-text-output-sink
((var) &body body
)
336 `(invoke-with-toplevel-text-output-sink (lambda (,var
) ,@body
)))
338 (defclass toplevel-text-output-sink
(sax:default-handler
)
339 ((target :initarg
:target
:accessor text-output-sink-target
)
340 (depth :initform
0 :accessor textoutput-sink-depth
)))
342 (defmethod sax:start-element
((sink toplevel-text-output-sink
)
343 namespace-uri local-name qname attributes
)
344 (declare (ignore namespace-uri local-name qname attributes
))
345 (incf (textoutput-sink-depth sink
)))
347 (defmethod sax:characters
((sink toplevel-text-output-sink
) data
)
348 (when (zerop (textoutput-sink-depth sink
))
349 (write-string data
(text-output-sink-target sink
))))
351 (defmethod sax:unescaped
((sink toplevel-text-output-sink
) data
)
352 (sax:characters sink data
))
354 (defmethod sax:end-element
((sink toplevel-text-output-sink
)
355 namespace-uri local-name qname
)
356 (declare (ignore namespace-uri local-name qname
))
357 (decf (textoutput-sink-depth sink
)))
359 (defun invoke-with-toplevel-text-output-sink (fn)
360 (with-output-to-string (s)
361 (funcall fn
(make-instance 'toplevel-text-output-sink
:target s
))))
366 ;;;; A sink that passes through only text (at any level) and turns to
367 ;;;; into unescaped characters.
369 (defclass text-filter
(sax:default-handler
)
370 ((target :initarg
:target
:accessor text-filter-target
)))
372 (defmethod sax:characters
((sink text-filter
) data
)
373 (sax:unescaped
(text-filter-target sink
) data
))
375 (defmethod sax:unescaped
((sink text-filter
) data
)
376 (sax:unescaped
(text-filter-target sink
) data
))
378 (defmethod sax:end-document
((sink text-filter
))
379 (sax:end-document
(text-filter-target sink
)))
381 (defun make-text-filter (target)
382 (make-instance 'text-filter
:target target
))
387 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
390 (defclass escaper
(cxml:broadcast-handler
)
393 (defmethod sax:unescaped
((sink escaper
) data
)
394 (sax:characters sink data
))
396 (defun make-escaper (target)
397 (make-instance 'escaper
:handlers
(list target
)))
402 (defun of-name (local-name)
403 (stp:of-name local-name
*xsl
*))
405 (defun namep (node local-name
)
406 (and (typep node
'(or stp
:element stp
:attribute
))
407 (equal (stp:namespace-uri node
) *xsl
*)
408 (equal (stp:local-name node
) local-name
)))
411 ;;;; PARSE-STYLESHEET
413 (defstruct stylesheet
414 (modes (make-hash-table :test
'equal
))
415 (global-variables (make-empty-declaration-array))
416 (output-specification (make-output-specification))
419 (named-templates (make-hash-table :test
'equal
))
420 (attribute-sets (make-hash-table :test
'equal
))
421 (keys (make-hash-table :test
'equal
))
422 (namespace-aliases (make-hash-table :test
'equal
))
423 (decimal-formats (make-hash-table :test
'equal
))
424 (initial-global-variable-thunks (make-hash-table :test
'equal
)))
428 (match-thunk (lambda (ignore) (declare (ignore ignore
)) nil
)))
430 (defun find-mode (stylesheet local-name
&optional uri
)
431 (gethash (cons local-name uri
) (stylesheet-modes stylesheet
)))
433 (defun ensure-mode (stylesheet &optional local-name uri
)
434 (or (find-mode stylesheet local-name uri
)
435 (setf (gethash (cons local-name uri
) (stylesheet-modes stylesheet
))
438 (defun ensure-mode/qname
(stylesheet qname env
)
440 (multiple-value-bind (local-name uri
)
441 (decode-qname qname env nil
)
442 (ensure-mode stylesheet local-name uri
))
443 (find-mode stylesheet nil
)))
445 (defun acons-namespaces (element &optional
(bindings *namespaces
*))
446 (map-namespace-declarations (lambda (prefix uri
)
447 (push (cons prefix uri
) bindings
))
451 (defun find-key (name stylesheet
)
452 (or (gethash name
(stylesheet-keys stylesheet
))
453 (xslt-error "unknown key: ~a" name
)))
455 (defun make-key (match use
) (cons match use
))
457 (defun key-match (key) (car key
))
459 (defun key-use (key) (cdr key
))
461 (defun add-key (stylesheet name match use
)
462 (if (gethash name
(stylesheet-keys stylesheet
))
463 (xslt-error "duplicate key: ~a" name
)
464 (setf (gethash name
(stylesheet-keys stylesheet
))
465 (make-key match use
))))
467 (defvar *excluded-namespaces
* (list *xsl
*))
468 (defvar *empty-mode
*)
469 (defvar *default-mode
*)
471 (defvar *xsl-include-stack
* nil
)
473 (defun uri-to-pathname (uri)
474 (cxml::uri-to-pathname
(puri:parse-uri uri
)))
476 ;; Why this extra check for literal result element used as stylesheets,
477 ;; instead of a general check for every literal result element? Because
478 ;; Stylesheet__91804 says so.
479 (defun check-Errors_err035 (literal-result-element)
480 (let ((*namespaces
* (acons-namespaces literal-result-element
))
481 (env (make-instance 'lexical-xslt-environment
)))
482 (stp:with-attributes
((extension-element-prefixes
483 "extension-element-prefixes"
485 literal-result-element
486 (dolist (prefix (words (or extension-element-prefixes
"")))
487 (if (equal prefix
"#default")
489 (unless (cxml-stp-impl::nc-name-p prefix
)
490 (xslt-error "invalid prefix: ~A" prefix
)))
492 (or (xpath-sys:environment-find-namespace env prefix
)
493 (xslt-error "namespace not found: ~A" prefix
))))
494 (when (equal uri
(stp:namespace-uri literal-result-element
))
495 (xslt-error "literal result element used as stylesheet, but is ~
496 declared as an extension element")))))))
498 (defun unwrap-2.3
(document)
499 (let ((literal-result-element (stp:document-element document
))
500 (new-template (stp:make-element
"template" *xsl
*))
501 (new-document-element (stp:make-element
"stylesheet" *xsl
*)))
502 (check-Errors_err035 literal-result-element
)
503 (setf (stp:attribute-value new-document-element
"version")
504 (or (stp:attribute-value literal-result-element
"version" *xsl
*)
505 (xslt-error "not a stylesheet: root element lacks xsl:version")))
506 (setf (stp:attribute-value new-template
"match") "/")
507 (setf (stp:document-element document
) new-document-element
)
508 (stp:append-child new-document-element new-template
)
509 (stp:append-child new-template literal-result-element
)
510 new-document-element
))
512 (defun parse-stylesheet-to-stp (input uri-resolver
)
513 (let* ((d (cxml:parse input
(make-text-normalizer (cxml-stp:make-builder
))))
514 (<transform
> (stp:document-element d
)))
515 (unless (equal (stp:namespace-uri
<transform
>) *xsl
*)
516 (setf <transform
> (unwrap-2.3 d
)))
517 (strip-stylesheet <transform
>)
518 (unless (and (equal (stp:namespace-uri
<transform
>) *xsl
*)
519 (or (equal (stp:local-name
<transform
>) "transform")
520 (equal (stp:local-name
<transform
>) "stylesheet")))
521 (xslt-error "not a stylesheet"))
522 (check-for-invalid-attributes
524 ("exclude-result-prefixes" .
"")
525 ("extension-element-prefixes" .
"")
526 ("space" .
"http://www.w3.org/XML/1998/namespace")
530 (or (stp:find-child-if
(of-name "stylesheet") <transform
>)
531 (stp:find-child-if
(of-name "transform") <transform
>))))
533 (xslt-error "invalid top-level element ~A" (stp:local-name invalid
))))
534 (dolist (include (stp:filter-children
(of-name "include") <transform
>))
535 (let* ((uri (puri:merge-uris
(or (stp:attribute-value include
"href")
536 (xslt-error "include without href"))
537 (stp:base-uri include
)))
538 (uri (if uri-resolver
539 (funcall uri-resolver
(puri:render-uri uri nil
))
541 (str (puri:render-uri uri nil
))
544 (uri-to-pathname uri
)
545 (cxml:xml-parse-error
(c)
546 (xslt-error "cannot find included stylesheet ~A: ~A"
550 :element-type
'(unsigned-byte 8)
551 :if-does-not-exist nil
)
553 (xslt-error "cannot find included stylesheet ~A at ~A"
555 (when (find str
*xsl-include-stack
* :test
#'equal
)
556 (xslt-error "recursive inclusion of ~A" uri
))
557 (let* ((*xsl-include-stack
* (cons str
*xsl-include-stack
*))
558 (<transform
>2 (parse-stylesheet-to-stp stream uri-resolver
)))
559 (stp:insert-child-after
<transform
>
560 (stp:copy
<transform
>2)
562 (stp:detach include
)))))
565 (defvar *instruction-base-uri
*) ;misnamed, is also used in other attributes
566 (defvar *apply-imports-limit
*)
567 (defvar *import-priority
*)
568 (defvar *extension-namespaces
*)
569 (defvar *forwards-compatible-p
*)
571 (defmacro do-toplevel
((var xpath
<transform
>) &body body
)
572 `(map-toplevel (lambda (,var
) ,@body
) ,xpath
,<transform
>))
574 (defun map-toplevel (fn xpath
<transform
>)
575 (dolist (node (list-toplevel xpath
<transform
>))
576 (let ((*namespaces
* *namespaces
*))
577 (xpath:do-node-set
(ancestor (xpath:evaluate
"ancestor::node()" node
))
578 (when (xpath-protocol:node-type-p ancestor
:element
)
579 (setf *namespaces
* (acons-namespaces ancestor
))))
582 (defun list-toplevel (xpath <transform
>)
583 (labels ((recurse (sub)
586 (xpath:evaluate
"transform|stylesheet" sub
))))
588 (xpath-sys:pipe-of
(xpath:evaluate xpath sub
))
589 (xpath::mappend-pipe
#'recurse subsubs
)))))
590 (xpath::sort-nodes
(recurse <transform
>))))
592 (defmacro with-import-magic
((node env
) &body body
)
593 `(invoke-with-import-magic (lambda () ,@body
) ,node
,env
))
595 (defun invoke-with-import-magic (fn node env
)
596 (unless (or (namep node
"stylesheet") (namep node
"transform"))
597 (setf node
(stp:parent node
)))
598 (let ((*excluded-namespaces
* (list *xsl
*))
599 (*extension-namespaces
* '())
600 (*forwards-compatible-p
*
601 (not (equal (stp:attribute-value node
"version") "1.0"))))
602 (parse-exclude-result-prefixes! node env
)
603 (parse-extension-element-prefixes! node env
)
606 (defun parse-1-stylesheet (env stylesheet designator uri-resolver
)
607 (let* ((<transform
> (parse-stylesheet-to-stp designator uri-resolver
))
608 (instruction-base-uri (stp:base-uri
<transform
>))
609 (namespaces (acons-namespaces <transform
>))
610 (apply-imports-limit (1+ *import-priority
*))
612 (let ((*namespaces
* namespaces
))
613 (invoke-with-import-magic (constantly t
) <transform
> env
))
614 (do-toplevel (elt "node()" <transform
>)
615 (let ((version (stp:attribute-value
(stp:parent elt
) "version")))
618 (xslt-error "stylesheet lacks version"))
619 ((equal version
"1.0")
620 (if (typep elt
'stp
:element
)
621 (when (or (equal (stp:namespace-uri elt
) "")
622 (and (equal (stp:namespace-uri elt
) *xsl
*)
623 (not (find (stp:local-name elt
)
624 '("key" "template" "output"
625 "strip-space" "preserve-space"
626 "attribute-set" "namespace-alias"
627 "decimal-format" "variable" "param"
629 ;; for include handling:
630 "stylesheet" "transform")
632 (xslt-error "unknown top-level element ~A" (stp:local-name elt
)))
633 (xslt-error "text at top-level"))))))
634 (macrolet ((with-specials ((&optional
) &body body
)
635 `(let ((*instruction-base-uri
* instruction-base-uri
)
636 (*namespaces
* namespaces
)
637 (*apply-imports-limit
* apply-imports-limit
))
640 (do-toplevel (import "import" <transform
>)
641 (let ((uri (puri:merge-uris
(or (stp:attribute-value import
"href")
642 (xslt-error "import without href"))
643 (stp:base-uri import
))))
644 (push (parse-imported-stylesheet env stylesheet uri uri-resolver
)
646 (let ((import-priority
647 (incf *import-priority
*))
648 (var-cont (prepare-global-variables stylesheet
<transform
>)))
649 ;; delay the rest of compilation until we've seen all global
652 (mapc #'funcall
(nreverse continuations
))
654 (let ((*import-priority
* import-priority
))
656 (parse-keys! stylesheet
<transform
> env
)
657 (parse-templates! stylesheet
<transform
> env
)
658 (parse-output! stylesheet
<transform
> env
)
659 (parse-strip/preserve-space
! stylesheet
<transform
> env
)
660 (parse-attribute-sets! stylesheet
<transform
> env
)
661 (parse-namespace-aliases! stylesheet
<transform
> env
)
662 (parse-decimal-formats! stylesheet
<transform
> env
))))))))
664 (defvar *xsl-import-stack
* nil
)
666 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver
)
667 (let* ((uri (if uri-resolver
668 (funcall uri-resolver
(puri:render-uri uri nil
))
670 (str (puri:render-uri uri nil
))
673 (uri-to-pathname uri
)
674 (cxml:xml-parse-error
(c)
675 (xslt-error "cannot find imported stylesheet ~A: ~A"
679 :element-type
'(unsigned-byte 8)
680 :if-does-not-exist nil
)
682 (xslt-error "cannot find imported stylesheet ~A at ~A"
684 (when (find str
*xsl-import-stack
* :test
#'equal
)
685 (xslt-error "recursive inclusion of ~A" uri
))
686 (let ((*xsl-import-stack
* (cons str
*xsl-import-stack
*)))
687 (parse-1-stylesheet env stylesheet stream uri-resolver
)))))
689 (defvar *included-attribute-sets
*)
691 (defun parse-stylesheet (designator &key uri-resolver
)
692 (with-resignalled-errors ()
693 (xpath:with-namespaces
((nil #.
*xsl
*))
694 (let* ((*import-priority
* 0)
695 (xpath:*allow-variables-in-patterns
* nil
)
696 (puri:*strict-parse
* nil
)
697 (stylesheet (make-stylesheet))
698 (env (make-instance 'lexical-xslt-environment
))
699 (*excluded-namespaces
* *excluded-namespaces
*)
700 (*global-variable-declarations
* (make-empty-declaration-array))
701 (*included-attribute-sets
* nil
))
702 (ensure-mode stylesheet nil
)
703 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver
))
704 ;; reverse attribute sets:
705 (let ((table (stylesheet-attribute-sets stylesheet
)))
706 (maphash (lambda (k v
)
707 (setf (gethash k table
) (nreverse v
)))
710 (dolist (sets *included-attribute-sets
*)
711 (loop for
(local-name uri nil
) in sets do
712 (find-attribute-set local-name uri stylesheet
)))
714 (unless (find-decimal-format "" "" stylesheet nil
)
715 (setf (find-decimal-format "" "" stylesheet
)
716 (make-decimal-format)))
717 ;; compile a template matcher for each mode:
719 for mode being each hash-value in
(stylesheet-modes stylesheet
)
721 (setf (mode-match-thunk mode
)
722 (xpath:make-pattern-matcher
723 (mapcar #'template-compiled-pattern
724 (mode-templates mode
)))))
725 ;; and for the strip tests
726 (setf (stylesheet-strip-thunk stylesheet
)
727 (let ((patterns (stylesheet-strip-tests stylesheet
)))
729 (xpath:make-pattern-matcher
730 (mapcar #'strip-test-compiled-pattern patterns
)))))
733 (defun parse-attribute-sets! (stylesheet <transform
> env
)
734 (do-toplevel (elt "attribute-set" <transform
>)
735 (with-import-magic (elt env
)
737 (mapcar (lambda (qname)
738 (multiple-value-list (decode-qname qname env nil
)))
740 (stp:attribute-value elt
"use-attribute-sets"))))
746 (and (typep child
'stp
:element
)
747 (or (and (equal (stp:namespace-uri child
) *xsl
*)
748 (equal (stp:local-name child
)
750 (find (stp:namespace-uri child
)
751 *extension-namespaces
*
753 (xslt-error "non-attribute found in attribute set"))
754 (parse-instruction child
))
756 (*lexical-variable-declarations
*
757 (make-empty-declaration-array))
759 (compile-instruction `(progn ,@instructions
) env
))
760 (n-variables (length *lexical-variable-declarations
*)))
761 (push sets
*included-attribute-sets
*)
764 (loop for
(local-name uri nil
) in sets do
765 (dolist (thunk (find-attribute-set local-name uri
))
766 (funcall thunk ctx
)))
767 (let ((*lexical-variable-values
*
768 (make-variable-value-array n-variables
)))
769 (funcall thunk ctx
)))))
770 (gethash (multiple-value-bind (local-name uri
)
771 (decode-qname (or (stp:attribute-value elt
"name")
772 (xslt-error "missing name"))
775 (cons local-name uri
))
776 (stylesheet-attribute-sets stylesheet
))))))
778 (defun parse-namespace-aliases! (stylesheet <transform
> env
)
779 (do-toplevel (elt "namespace-alias" <transform
>)
780 (only-with-attributes (stylesheet-prefix result-prefix
) elt
781 (unless stylesheet-prefix
782 (xslt-error "missing stylesheet-prefix in namespace-alias"))
783 (unless result-prefix
784 (xslt-error "missing result-prefix in namespace-alias"))
786 (if (equal stylesheet-prefix
"#default")
788 (xpath-sys:environment-find-namespace env stylesheet-prefix
))
789 (stylesheet-namespace-aliases stylesheet
))
790 (xpath-sys:environment-find-namespace
792 (if (equal result-prefix
"#default")
796 (defun parse-decimal-formats! (stylesheet <transform
> env
)
797 (do-toplevel (elt "decimal-format" <transform
>)
798 (stp:with-attributes
(name
812 (multiple-value-bind (local-name uri
)
814 (decode-qname name env nil
)
816 (let ((current (find-decimal-format local-name uri stylesheet nil
))
821 (unless (eql (length x
) 1)
822 (xslt-error "not a single character: ~A" x
))
823 (let ((chr (elt x
0)))
824 (when (find chr seen
)
826 "conflicting decimal format characters: ~A"
833 (apply #'make-decimal-format
834 (append (str :infinity infinity
)
836 (chr :decimal-separator decimal-separator
)
837 (chr :grouping-separator grouping-separator
)
838 (chr :zero-digit zero-digit
)
839 (chr :percent percent
)
840 (chr :per-mille per-mille
)
842 (chr :pattern-separator pattern-separator
)
843 (chr :minus-sign minus-sign
)))))))
845 (unless (decimal-format= current new
)
846 (xslt-error "decimal format mismatch for ~S" local-name
))
847 (setf (find-decimal-format local-name uri stylesheet
) new
)))))))
849 (defun parse-exclude-result-prefixes! (node env
)
850 (stp:with-attributes
(exclude-result-prefixes)
852 (dolist (prefix (words (or exclude-result-prefixes
"")))
853 (if (equal prefix
"#default")
855 (unless (cxml-stp-impl::nc-name-p prefix
)
856 (xslt-error "invalid prefix: ~A" prefix
)))
857 (push (or (xpath-sys:environment-find-namespace env prefix
)
858 (xslt-error "namespace not found: ~A" prefix
))
859 *excluded-namespaces
*))))
861 (defun parse-extension-element-prefixes! (node env
)
862 (stp:with-attributes
(extension-element-prefixes)
864 (dolist (prefix (words (or extension-element-prefixes
"")))
865 (if (equal prefix
"#default")
867 (unless (cxml-stp-impl::nc-name-p prefix
)
868 (xslt-error "invalid prefix: ~A" prefix
)))
870 (or (xpath-sys:environment-find-namespace env prefix
)
871 (xslt-error "namespace not found: ~A" prefix
))))
872 (unless (equal uri
*xsl
*)
873 (push uri
*extension-namespaces
*)
874 (push uri
*excluded-namespaces
*))))))
876 (defun parse-nametest-tokens (str)
877 (labels ((check (boolean)
879 (xslt-error "invalid nametest token")))
880 (check-null (boolean)
881 (check (not boolean
))))
884 (mapcar (lambda (name-test)
885 (destructuring-bind (&optional path
&rest junk
)
886 (cdr (xpath:parse-pattern-expression name-test
))
888 (check (eq (car path
) :path
))
889 (destructuring-bind (&optional child
&rest junk
) (cdr path
)
891 (check (eq (car child
) :child
))
892 (destructuring-bind (nodetest &rest junk
) (cdr child
)
894 (check (or (stringp nodetest
)
896 (and (consp nodetest
)
897 (or (eq (car nodetest
) :namespace
)
898 (eq (car nodetest
) :qname
)))))))
902 (defstruct strip-test
908 (defun parse-strip/preserve-space
! (stylesheet <transform
> env
)
910 (do-toplevel (elt "strip-space|preserve-space" <transform
>)
911 (let ((*namespaces
* (acons-namespaces elt
))
913 (if (equal (stp:local-name elt
) "strip-space")
917 (cdr (parse-nametest-tokens
918 (stp:attribute-value elt
"elements"))))
919 (let* ((compiled-pattern
920 (car (without-xslt-current ()
921 (xpath:compute-patterns
922 `(:patterns
,expression
)
927 (make-strip-test :compiled-pattern compiled-pattern
928 :priority
(expression-priority expression
)
931 (setf (xpath:pattern-value compiled-pattern
) strip-test
)
932 (push strip-test
(stylesheet-strip-tests stylesheet
)))))
935 (defstruct (output-specification
936 (:conc-name
"OUTPUT-"))
943 cdata-section-matchers
)
945 (defun parse-output! (stylesheet <transform
> env
)
946 (dolist (<output
> (list-toplevel "output" <transform
>))
947 (let ((spec (stylesheet-output-specification stylesheet
)))
948 (only-with-attributes (version
957 cdata-section-elements
)
959 (declare (ignore version
964 (setf (output-method spec
) method
))
966 (setf (output-indent spec
) indent
))
968 (setf (output-encoding spec
) encoding
))
970 (setf (output-doctype-system spec
) doctype-system
))
972 (setf (output-doctype-public spec
) doctype-public
))
973 (when omit-xml-declaration
974 (setf (output-omit-xml-declaration spec
) omit-xml-declaration
))
975 (when cdata-section-elements
976 (dolist (qname (words cdata-section-elements
))
977 (decode-qname qname env nil
) ;check the syntax
978 (push (xpath:make-pattern-matcher
* qname env
)
979 (output-cdata-section-matchers spec
))))))))
981 (defun make-empty-declaration-array ()
982 (make-array 1 :fill-pointer
0 :adjustable t
))
984 (defun make-variable-value-array (n-lexical-variables)
985 (make-array n-lexical-variables
:initial-element
'unbound
))
987 (defun compile-global-variable (<variable
> env
) ;; also for <param>
988 (stp:with-attributes
(name select
) <variable
>
989 (when (and select
(stp:list-children
<variable
>))
990 (xslt-error "variable with select and body"))
991 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
994 (compile-xpath select env
))
995 ((stp:list-children
<variable
>)
996 (let* ((inner-sexpr `(progn ,@(parse-body <variable
>)))
997 (inner-thunk (compile-instruction inner-sexpr env
)))
999 (apply-to-result-tree-fragment ctx inner-thunk
))))
1002 (declare (ignore ctx
))
1004 (n-lexical-variables (length *lexical-variable-declarations
*)))
1007 (let* ((*lexical-variable-values
*
1008 (make-variable-value-array n-lexical-variables
)))
1009 (funcall inner ctx
)))
1010 "global ~s (~s) = ~s" name select
:result
))))
1012 (defstruct (variable-chain
1013 (:constructor make-variable-chain
)
1014 (:conc-name
"VARIABLE-CHAIN-"))
1021 (defstruct (import-variable
1022 (:constructor make-variable
)
1023 (:conc-name
"VARIABLE-"))
1028 (defun parse-global-variable! (stylesheet <variable
> global-env
)
1029 (let* ((*namespaces
* (acons-namespaces <variable
>))
1030 (instruction-base-uri (stp:base-uri
<variable
>))
1031 (*instruction-base-uri
* instruction-base-uri
)
1032 (*excluded-namespaces
* (list *xsl
*))
1033 (*extension-namespaces
* '())
1034 (qname (stp:attribute-value
<variable
> "name")))
1035 (with-import-magic (<variable
> global-env
)
1037 (xslt-error "name missing in ~A" (stp:local-name
<variable
>)))
1038 (multiple-value-bind (local-name uri
)
1039 (decode-qname qname global-env nil
)
1040 ;; For the normal compilation environment of templates, install it
1041 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
1042 (let ((index (intern-global-variable local-name uri
)))
1043 ;; For the evaluation of a global variable itself, build a thunk
1044 ;; that lazily resolves other variables, stored into
1045 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
1046 (let* ((value-thunk :unknown
)
1047 (sgv (stylesheet-global-variables stylesheet
))
1049 (if (< index
(length sgv
))
1051 (make-variable-chain
1053 :local-name local-name
1055 (next (car (variable-chain-definitions chain
)))
1056 (global-variable-thunk
1058 (let ((v (global-variable-value index nil
)))
1062 (xslt-error "no next definition for: ~A"
1064 (funcall (variable-value-thunk next
) ctx
))
1066 (setf (global-variable-value index
) 'seen
)
1067 (setf (global-variable-value index
)
1068 (funcall value-thunk ctx
)))
1071 (excluded-namespaces *excluded-namespaces
*)
1072 (extension-namespaces *extension-namespaces
*)
1074 (make-variable :param-p
(namep <variable
> "param")))
1075 (forwards-compatible-p *forwards-compatible-p
*)
1078 (let* ((*instruction-base-uri
* instruction-base-uri
)
1079 (*excluded-namespaces
* excluded-namespaces
)
1080 (*extension-namespaces
* extension-namespaces
)
1081 (*forwards-compatible-p
* forwards-compatible-p
)
1083 (compile-global-variable <variable
> global-env
)))
1084 (setf value-thunk fn
)
1085 (setf (variable-value-thunk variable
) fn
)))))
1086 (setf (variable-value-thunk-setter variable
)
1088 (setf (gethash (cons local-name uri
)
1089 (initial-global-variable-thunks global-env
))
1090 global-variable-thunk
)
1091 (setf (variable-chain-thunk chain
) global-variable-thunk
)
1092 (push variable
(variable-chain-definitions chain
))
1095 (defun parse-keys! (stylesheet <transform
> env
)
1096 (xpath:with-namespaces
((nil #.
*xsl
*))
1097 (do-toplevel (<key
> "key" <transform
>)
1098 (with-import-magic (<key
> env
)
1099 (let ((*instruction-base-uri
* (stp:base-uri
<key
>)))
1100 (stp:with-attributes
(name match use
) <key
>
1101 (unless name
(xslt-error "key name attribute not specified"))
1102 (unless match
(xslt-error "key match attribute not specified"))
1103 (unless use
(xslt-error "key use attribute not specified"))
1104 (multiple-value-bind (local-name uri
)
1105 (decode-qname name env nil
)
1107 (cons local-name uri
)
1108 (compile-xpath `(xpath:xpath
,(parse-key-pattern match
))
1111 (make-instance 'key-environment
))))))))))
1113 (defun prepare-global-variables (stylesheet <transform
>)
1114 (xpath:with-namespaces
((nil #.
*xsl
*))
1115 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet
))
1116 (global-env (make-instance 'global-variable-environment
1117 :initial-global-variable-thunks igvt
))
1119 (do-toplevel (<variable
> "variable|param" <transform
>)
1121 (parse-global-variable! stylesheet
<variable
> global-env
)))
1122 (xslt-trace "parsing global variable ~s (uri ~s)"
1123 (variable-chain-local-name chain
)
1124 (variable-chain-uri chain
))
1128 (and (equal (variable-chain-local-name a
)
1129 (variable-chain-local-name b
))
1130 (equal (variable-chain-uri a
)
1131 (variable-chain-uri b
)))))
1132 (xslt-error "duplicate definition for global variable ~A"
1133 (variable-chain-local-name chain
)))
1134 (push chain chains
)))
1135 (setf chains
(nreverse chains
))
1136 (let ((table (stylesheet-global-variables stylesheet
))
1137 (newlen (length *global-variable-declarations
*)))
1138 (adjust-array table newlen
:fill-pointer newlen
)
1139 (dolist (chain chains
)
1140 (setf (elt table
(variable-chain-index chain
)) chain
)))
1142 ;; now that the global environment knows about all variables, run the
1143 ;; thunk setters to perform their compilation
1144 (mapc (lambda (chain)
1145 (dolist (var (variable-chain-definitions chain
))
1146 (funcall (variable-value-thunk-setter var
))))
1149 (defun parse-templates! (stylesheet <transform
> env
)
1151 (do-toplevel (<template
> "template" <transform
>)
1152 (let ((*namespaces
* (acons-namespaces <template
>))
1153 (*instruction-base-uri
* (stp:base-uri
<template
>)))
1154 (with-import-magic (<template
> env
)
1155 (dolist (template (compile-template <template
> env i
))
1156 (let ((name (template-name template
)))
1158 (let* ((table (stylesheet-named-templates stylesheet
))
1159 (head (car (gethash name table
))))
1160 (when (and head
(eql (template-import-priority head
)
1161 (template-import-priority template
)))
1162 ;; fixme: is this supposed to be a run-time error?
1163 (xslt-error "conflicting templates for ~A" name
))
1164 (push template
(gethash name table
)))
1165 (let ((mode (ensure-mode/qname stylesheet
1166 (template-mode-qname template
)
1168 (setf (template-mode template
) mode
)
1169 (push template
(mode-templates mode
))))))))
1173 ;;;; APPLY-STYLESHEET
1175 (defvar *stylesheet
*)
1177 (deftype xml-designator
() '(or runes
:xstream runes
:rod array stream pathname
))
1179 (defun unalias-uri (uri)
1181 (gethash uri
(stylesheet-namespace-aliases *stylesheet
*)
1183 (check-type result string
)
1186 (defstruct (parameter
1187 (:constructor make-parameter
(value local-name
&optional uri
)))
1192 (defun find-parameter-value (local-name uri parameters
)
1193 (dolist (p parameters
)
1194 (when (and (equal (parameter-local-name p
) local-name
)
1195 (equal (parameter-uri p
) uri
))
1196 (return (parameter-value p
)))))
1198 (defvar *uri-resolver
*)
1200 (defun parse-allowing-microsoft-bom (pathname handler
)
1201 (with-open-file (s pathname
:element-type
'(unsigned-byte 8))
1202 (unless (and (eql (read-byte s nil
) #xef
)
1203 (eql (read-byte s nil
) #xbb
)
1204 (eql (read-byte s nil
) #xbf
))
1205 (file-position s
0))
1206 (cxml:parse s handler
)))
1208 (defvar *documents
*)
1210 (defun %document
(uri-string base-uri
)
1211 (let* ((absolute-uri
1212 (puri:merge-uris uri-string
(or base-uri
"")))
1215 (funcall *uri-resolver
* (puri:render-uri absolute-uri nil
))
1219 (uri-to-pathname resolved-uri
)
1220 (cxml:xml-parse-error
(c)
1221 (xslt-error "cannot find referenced document ~A: ~A"
1224 (or (gethash pathname
*documents
*)
1225 (setf (gethash pathname
*documents
*)
1226 (make-whitespace-stripper
1228 (parse-allowing-microsoft-bom pathname
1230 ((or file-error cxml
:xml-parse-error
) (c)
1231 (xslt-error "cannot parse referenced document ~A: ~A"
1233 (stylesheet-strip-thunk *stylesheet
*))))))
1234 (when (puri:uri-fragment absolute-uri
)
1235 (xslt-error "use of fragment identifiers in document() not supported"))
1238 (xpath-sys:define-extension xslt
*xsl
*)
1240 (defun document-base-uri (node)
1241 (xpath-protocol:base-uri
1243 ((xpath-protocol:node-type-p node
:document
)
1244 (xpath::find-in-pipe-if
1246 (xpath-protocol:node-type-p x
:element
))
1247 (xpath-protocol:child-pipe node
)))
1248 ((xpath-protocol:node-type-p node
:element
)
1251 (xpath-protocol:parent-node node
)))))
1253 (xpath-sys:define-xpath-function
/lazy
1255 (object &optional node-set
)
1256 (let ((instruction-base-uri *instruction-base-uri
*))
1258 (let* ((object (funcall object ctx
))
1259 (node-set (and node-set
(funcall node-set ctx
)))
1262 (document-base-uri (xpath::textually-first-node node-set
))
1263 instruction-base-uri
)))
1264 (xpath-sys:make-node-set
1265 (if (xpath:node-set-p object
)
1266 (xpath:map-node-set-
>list
1268 (%document
(xpath:string-value node
)
1271 (document-base-uri node
))))
1273 (list (%document
(xpath:string-value object
) base-uri
))))))))
1275 (xpath-sys:define-xpath-function
/lazy xslt
:key
(name object
)
1276 (let ((namespaces *namespaces
*))
1278 (let* ((qname (xpath:string-value
(funcall name ctx
)))
1279 (object (funcall object ctx
))
1281 (multiple-value-bind (local-name uri
)
1282 (decode-qname/runtime qname namespaces nil
)
1283 (cons local-name uri
)))
1284 (key (find-key expanded-name
*stylesheet
*)))
1285 (labels ((get-by-key (value)
1286 (let ((value (xpath:string-value value
)))
1290 (xpath:evaluate-compiled
(key-use key
) node
)))
1291 (if (xpath:node-set-p uses
)
1292 (xpath::find-in-pipe
1294 (xpath-sys:pipe-of uses
)
1295 :key
#'xpath
:string-value
1297 (equal value
(xpath:string-value uses
)))))
1299 (xpath:node-set-value
1300 (xpath:evaluate-compiled
(key-match key
) ctx
)))))))
1301 (xpath-sys:make-node-set
1303 (if (xpath:node-set-p object
)
1304 (xpath::mappend-pipe
#'get-by-key
(xpath-sys:pipe-of object
))
1305 (get-by-key object
)))))))))
1307 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1309 (xpath-sys:define-xpath-function
/lazy xslt
:current
()
1310 (when *without-xslt-current-p
*
1311 (xslt-error "current() not allowed here"))
1313 (xpath-sys:make-node-set
1314 (xpath-sys:make-pipe
1315 (xpath:context-starting-node ctx
)
1318 (xpath-sys:define-xpath-function
/lazy xslt
:unparsed-entity-uri
(name)
1320 (or (xpath-protocol:unparsed-entity-uri
(xpath:context-node ctx
)
1324 (defun %get-node-id
(node)
1325 (when (xpath:node-set-p node
)
1326 (setf node
(xpath::textually-first-node node
)))
1328 (let ((id (xpath-sys:get-node-id node
))
1331 for parent
= node then next
1332 for next
= (xpath-protocol:parent-node parent
)
1333 for this-base-uri
= (xpath-protocol:base-uri parent
)
1334 for highest-base-uri
= (if (plusp (length this-base-uri
))
1338 finally
(return highest-base-uri
))))
1339 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1340 ;; checked only if everything else matches.
1342 ;; This might be pointless premature optimization, but I like the idea :-)
1343 (nreverse (concatenate 'string highest-base-uri
"//" id
)))))
1345 (xpath-sys:define-xpath-function
/lazy xslt
:generate-id
(&optional node-set-thunk
)
1348 (%get-node-id
(xpath:node-set-value
(funcall node-set-thunk ctx
))))
1350 (%get-node-id
(xpath:context-node ctx
)))))
1352 (declaim (special *available-instructions
*))
1354 (xpath-sys:define-xpath-function
/lazy xslt
:element-available
(qname)
1355 (let ((namespaces *namespaces
*))
1357 (let ((qname (funcall qname ctx
)))
1358 (multiple-value-bind (local-name uri
)
1359 (decode-qname/runtime qname namespaces nil
)
1360 (and (equal uri
*xsl
*)
1361 (gethash local-name
*available-instructions
*)
1364 (xpath-sys:define-xpath-function
/lazy xslt
:function-available
(qname)
1365 (let ((namespaces *namespaces
*))
1367 (let ((qname (funcall qname ctx
)))
1368 (multiple-value-bind (local-name uri
)
1369 (decode-qname/runtime qname namespaces nil
)
1370 (and (zerop (length uri
))
1371 (or (xpath-sys:find-xpath-function local-name
*xsl
*)
1372 (xpath-sys:find-xpath-function local-name uri
))
1375 (xpath-sys:define-xpath-function
/lazy xslt
:system-property
(qname)
1376 (let ((namespaces *namespaces
*))
1378 (let ((qname (xpath:string-value
(funcall qname ctx
))))
1379 (multiple-value-bind (local-name uri
)
1380 (decode-qname/runtime qname namespaces nil
)
1381 (if (equal uri
*xsl
*)
1383 ((equal local-name
"version")
1385 ((equal local-name
"vendor")
1387 ((equal local-name
"vendor-uri")
1388 "http://repo.or.cz/w/xuriella.git")
1393 (defun apply-stylesheet
1394 (stylesheet source-designator
1395 &key output parameters uri-resolver navigator
)
1396 (when (typep stylesheet
'xml-designator
)
1399 ((cxml:xml-parse-error
1401 (xslt-error "cannot parse stylesheet: ~A" c
))))
1402 (parse-stylesheet stylesheet
))))
1403 (with-resignalled-errors ()
1404 (invoke-with-output-sink
1406 (let* ((*documents
* (make-hash-table :test
'equal
))
1407 (xpath:*navigator
* (or navigator
:default-navigator
))
1408 (puri:*strict-parse
* nil
)
1409 (*stylesheet
* stylesheet
)
1410 (*empty-mode
* (make-mode))
1411 (*default-mode
* (find-mode stylesheet nil
))
1412 (global-variable-chains
1413 (stylesheet-global-variables stylesheet
))
1414 (*global-variable-values
*
1415 (make-variable-value-array (length global-variable-chains
)))
1416 (*uri-resolver
* uri-resolver
)
1418 (if (typep source-designator
'xml-designator
)
1419 (cxml:parse source-designator
(stp:make-builder
))
1422 (make-whitespace-stripper
1424 (stylesheet-strip-thunk stylesheet
)))
1425 (ctx (xpath:make-context xpath-root-node
)))
1426 (when (pathnamep source-designator
)
1427 (setf (gethash source-designator
*documents
*) xpath-root-node
))
1430 (let ((head (car (variable-chain-definitions chain
))))
1431 (when (variable-param-p head
)
1433 (find-parameter-value
1434 (variable-chain-local-name chain
)
1435 (variable-chain-uri chain
)
1438 (setf (global-variable-value
1439 (variable-chain-index chain
))
1441 global-variable-chains
)
1444 (funcall (variable-chain-thunk chain
) ctx
))
1445 global-variable-chains
)
1446 ;; zzz we wouldn't have to mask float traps here if we used the
1447 ;; XPath API properly. Unfortunately I've been using FUNCALL
1448 ;; everywhere instead of EVALUATE, so let's paper over that
1449 ;; at a central place to be sure:
1450 (xpath::with-float-traps-masked
()
1451 (apply-templates ctx
:mode
*default-mode
*))))
1452 (stylesheet-output-specification stylesheet
)
1455 (defun find-attribute-set (local-name uri
&optional
(stylesheet *stylesheet
*))
1456 (or (gethash (cons local-name uri
) (stylesheet-attribute-sets stylesheet
))
1457 (xslt-error "no such attribute set: ~A/~A" local-name uri
)))
1459 (defun apply-templates/list
(list &key param-bindings sort-predicate mode
)
1460 (when sort-predicate
1462 (mapcar #'xpath
:context-node
1463 (stable-sort (contextify-node-list list
)
1465 (let* ((n (length list
))
1466 (s/d
(lambda () n
)))
1471 (apply-templates (xpath:make-context child s
/d i
)
1472 :param-bindings param-bindings
1475 (defvar *stack-limit
* 200)
1477 (defun invoke-with-stack-limit (fn)
1478 (let ((*stack-limit
* (1- *stack-limit
*)))
1479 (unless (plusp *stack-limit
*)
1480 (xslt-error "*stack-limit* reached; stack overflow"))
1483 (defun invoke-template (ctx template param-bindings
)
1484 (let ((*lexical-variable-values
*
1485 (make-variable-value-array (template-n-variables template
))))
1486 (with-stack-limit ()
1488 for
(name-cons value
) in param-bindings
1489 for
(nil index nil
) = (find name-cons
1490 (template-params template
)
1495 (setf (lexical-variable-value index
) value
)))
1496 (funcall (template-body template
) ctx
))))
1498 (defun apply-default-templates (ctx mode
)
1499 (let ((node (xpath:context-node ctx
)))
1501 ((or (xpath-protocol:node-type-p node
:processing-instruction
)
1502 (xpath-protocol:node-type-p node
:comment
)))
1503 ((or (xpath-protocol:node-type-p node
:text
)
1504 (xpath-protocol:node-type-p node
:attribute
))
1505 (write-text (xpath-protocol:node-text node
)))
1507 (apply-templates/list
1509 (xpath-protocol:child-pipe node
))
1512 (defvar *apply-imports
*)
1514 (defun apply-applicable-templates (ctx templates param-bindings finally
)
1515 (labels ((apply-imports (&optional actual-param-bindings
)
1517 (let* ((this (pop templates
))
1518 (low (template-apply-imports-limit this
))
1519 (high (template-import-priority this
)))
1523 (<= low
(template-import-priority x
) high
))
1525 (invoke-template ctx this actual-param-bindings
))
1526 (funcall finally
))))
1527 (let ((*apply-imports
* #'apply-imports
))
1528 (apply-imports param-bindings
))))
1530 (defun apply-templates (ctx &key param-bindings mode
)
1531 (apply-applicable-templates ctx
1532 (find-templates ctx
(or mode
*default-mode
*))
1535 (apply-default-templates ctx mode
))))
1537 (defun call-template (ctx name
&optional param-bindings
)
1538 (apply-applicable-templates ctx
1539 (find-named-templates name
)
1542 (xslt-error "cannot find named template: ~s"
1545 (defun find-templates (ctx mode
)
1546 (let* ((matching-candidates
1547 (xpath:matching-values
(mode-match-thunk mode
)
1548 (xpath:context-node ctx
)))
1550 (if matching-candidates
1553 :key
#'template-import-priority
))
1555 (priority-groups (make-array npriorities
:initial-element nil
)))
1556 (dolist (template matching-candidates
)
1558 (elt priority-groups
(template-import-priority template
))))
1560 for i from
(1- npriorities
) downto
0
1561 for group
= (elt priority-groups i
)
1562 for template
= (maximize #'template
< group
)
1566 (defun find-named-templates (name)
1567 (gethash name
(stylesheet-named-templates *stylesheet
*)))
1569 (defun template< (a b
) ;assuming same import priority
1570 (let ((p (template-priority a
))
1571 (q (template-priority b
)))
1576 (xslt-cerror "conflicting templates:~_~A,~_~A"
1577 (template-match-expression a
)
1578 (template-match-expression b
))
1579 (< (template-position a
) (template-position b
))))))
1581 (defun maximize (< things
)
1583 (let ((max (car things
)))
1584 (dolist (other (cdr things
))
1585 (when (funcall < max other
)
1589 (defun invoke-with-output-sink (fn output-spec output
)
1592 (with-open-file (s output
1594 :element-type
'(unsigned-byte 8)
1595 :if-exists
:rename-and-delete
)
1596 (invoke-with-output-sink fn output-spec s
)))
1598 (invoke-with-output-sink fn
1600 (make-output-sink output-spec output
)))
1601 ((or hax
:abstract-handler sax
:abstract-handler
)
1602 (with-xml-output output
1603 (when (typep output
'(or combi-sink auto-detect-sink
))
1604 (sax:start-dtd output
1605 :autodetect-me-please
1606 (output-doctype-public output-spec
)
1607 (output-doctype-system output-spec
)))
1610 (defun make-output-sink (output-spec stream
)
1613 (let ((et (stream-element-type stream
)))
1615 ((or (null et
) (subtypep et
'(unsigned-byte 8)))
1616 (runes:make-octet-stream-ystream stream
))
1617 ((subtypep et
'character
)
1618 (runes:make-character-stream-ystream stream
))))
1619 (runes:make-rod-ystream
)))
1620 (omit-xml-declaration-p
1621 (boolean-or-error (output-omit-xml-declaration output-spec
)))
1622 (sink-encoding (or (output-encoding output-spec
) "UTF-8"))
1625 (setf (runes:ystream-encoding ystream
)
1626 (cxml::find-output-encoding sink-encoding
))
1627 (make-instance 'cxml
::sink
1629 :omit-xml-declaration-p omit-xml-declaration-p
1630 :encoding sink-encoding
))))
1631 (flet ((make-combi-sink ()
1632 (make-instance 'combi-sink
1633 :hax-target
(make-instance 'chtml
::sink
1635 :sax-target sax-target
1636 :encoding sink-encoding
)))
1639 ((equalp (output-method output-spec
) "HTML") :html
)
1640 ((equalp (output-method output-spec
) "TEXT") :text
)
1641 ((equalp (output-method output-spec
) "XML") :xml
)
1644 ((and (eq method-key
:html
)
1645 (null (output-doctype-system output-spec
))
1646 (null (output-doctype-public output-spec
)))
1648 ((eq method-key
:text
)
1649 (make-text-filter sax-target
))
1650 ((and (eq method-key
:xml
)
1651 (null (output-doctype-system output-spec
)))
1654 (make-auto-detect-sink (make-combi-sink) method-key
)))))))
1670 (defun expression-priority (form)
1671 (let ((step (second form
)))
1672 (if (and (null (cddr form
))
1674 (member (car step
) '(:child
:attribute
))
1676 (let ((name (second step
)))
1680 (or (eq (car name
) :qname
)
1681 (eq (car name
) :processing-instruction
))))
1684 (or (eq (car name
) :namespace
)
1685 (eq (car name
) '*)))
1691 (defun parse-key-pattern (str)
1692 (with-resignalled-errors ()
1693 (with-forward-compatible-errors
1694 (xpath:parse-xpath
"compile-time-error()") ;hack
1696 (mapcar #'(lambda (item)
1697 `(:path
(:root
:node
)
1698 (:descendant-or-self
*)
1700 (cdr (xpath::parse-pattern-expression str
)))))
1701 (if (null (rest parsed
))
1703 `(:union
,@parsed
))))))
1705 (defun compile-value-thunk (value env
)
1706 (if (and (listp value
) (eq (car value
) 'progn
))
1707 (let ((inner-thunk (compile-instruction value env
)))
1709 (apply-to-result-tree-fragment ctx inner-thunk
)))
1710 (compile-xpath value env
)))
1712 (defun compile-var-binding (name value env
)
1713 (multiple-value-bind (local-name uri
)
1714 (decode-qname name env nil
)
1715 (let ((thunk (xslt-trace-thunk
1716 (compile-value-thunk value env
)
1717 "local variable ~s = ~s" name
:result
)))
1718 (list (cons local-name uri
)
1719 (push-variable local-name
1721 *lexical-variable-declarations
*)
1724 (defun compile-var-bindings (forms env
)
1726 for
(name value
) in forms
1727 collect
(compile-var-binding name value env
)))
1729 (defun compile-template (<template
> env position
)
1730 (stp:with-attributes
(match name priority mode
) <template
>
1731 (unless (or name match
)
1732 (xslt-error "missing match in template"))
1733 (multiple-value-bind (params body-pos
)
1736 for child in
(stp:list-children
<template
>)
1737 while
(namep child
"param")
1738 collect
(parse-param child
) into params
1739 finally
(return (values params i
)))
1740 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1741 (param-bindings (compile-var-bindings params env
))
1742 (body (parse-body <template
> body-pos
(mapcar #'car params
)))
1743 (body-thunk (compile-instruction `(progn ,@body
) env
))
1749 ;; set params that weren't initialized by apply-templates
1750 (loop for
(name index param-thunk
) in param-bindings
1751 when
(eq (lexical-variable-value index nil
) 'unbound
)
1752 do
(setf (lexical-variable-value index
)
1753 (funcall param-thunk ctx
)))
1754 (funcall body-thunk ctx
))))
1755 "template: match = ~s name = ~s" match name
))
1756 (n-variables (length *lexical-variable-declarations
*)))
1759 (multiple-value-bind (local-name uri
)
1760 (decode-qname name env nil
)
1762 (make-template :name
(cons local-name uri
)
1763 :import-priority
*import-priority
*
1764 :apply-imports-limit
*apply-imports-limit
*
1765 :params param-bindings
1766 :body outer-body-thunk
1767 :n-variables n-variables
))))
1769 (mapcar (lambda (expression)
1770 (let* ((compiled-pattern
1772 (car (without-xslt-current ()
1773 (xpath:compute-patterns
1774 `(:patterns
,expression
)
1778 "match-thunk for template (match ~s): ~s --> ~s"
1779 match expression
:result
))
1781 (xpath::parse-xnum priority
)
1782 (expression-priority expression
)))
1785 (unless (and (numberp p
)
1786 (not (xpath::inf-p p
))
1787 (not (xpath::nan-p p
)))
1788 (xslt-error "failed to parse priority"))
1791 (make-template :match-expression expression
1792 :compiled-pattern compiled-pattern
1793 :import-priority
*import-priority
*
1794 :apply-imports-limit
*apply-imports-limit
*
1798 :params param-bindings
1799 :body outer-body-thunk
1800 :n-variables n-variables
)))
1801 (setf (xpath:pattern-value compiled-pattern
)
1804 (cdr (xpath:parse-pattern-expression match
)))))))))
1806 (xuriella::parse-stylesheet
#p
"/home/david/src/lisp/xuriella/test.xsl")