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 (defun compile-xpath (xpath &optional env
)
103 (with-resignalled-errors ()
104 (xpath:compile-xpath xpath env
)))
106 (defmacro with-stack-limit
((&optional
) &body body
)
107 `(invoke-with-stack-limit (lambda () ,@body
)))
109 (defparameter *without-xslt-current-p
* nil
)
111 (defmacro without-xslt-current
((&optional
) &body body
)
112 `(invoke-without-xslt-current (lambda () ,@body
)))
114 (defun invoke-without-xslt-current (fn)
115 (let ((*without-xslt-current-p
* t
))
118 ;;; (defun invoke-without-xslt-current (fn)
119 ;;; (let ((non-extensions (gethash "" xpath::*extensions*))
120 ;;; (xpath::*extensions*
121 ;;; ;; hide XSLT extensions
122 ;;; (make-hash-table :test #'equal)))
123 ;;; (setf (gethash "" xpath::*extensions*) non-extensions)
127 ;;;; Helper functions and macros
129 (defun check-for-invalid-attributes (valid-names node
)
130 (labels ((check-attribute (a)
132 (let ((uri (stp:namespace-uri a
)))
133 (or (and (plusp (length uri
)) (not (equal uri
*xsl
*)))
134 (find (cons (stp:local-name a
) uri
)
137 (xslt-error "attribute ~A not allowed on ~A"
139 (stp:local-name node
)))))
140 (stp:map-attributes nil
#'check-attribute node
)))
142 (defmacro only-with-attributes
((&rest specs
) node
&body body
)
144 (mapcar (lambda (entry)
145 (if (and (listp entry
) (cdr entry
))
146 (destructuring-bind (name &optional
(uri ""))
149 (cons (string-downcase
151 (symbol-name entry
)))
155 `(let ((,%NODE
,node
))
156 (check-for-invalid-attributes ',valid-names
,%NODE
)
157 (stp:with-attributes
,specs
,%NODE
160 (defun map-pipe-eagerly (fn pipe
)
161 (xpath::enumerate pipe
:key fn
:result nil
))
163 (defmacro do-pipe
((var pipe
&optional result
) &body body
)
165 (map-pipe-eagerly #'(lambda (,var
) ,@body
) ,pipe
)
169 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
171 (defparameter *namespaces
*
173 ("xmlns" .
#"http://www.w3.org/2000/xmlns/")
174 ("xml" .
#"http://www.w3.org/XML/1998/namespace")))
176 (defvar *global-variable-declarations
*)
177 (defvar *lexical-variable-declarations
*)
179 (defvar *global-variable-values
*)
180 (defvar *lexical-variable-values
*)
182 (defclass xslt-environment
() ())
184 (defun split-qname (str)
186 (multiple-value-bind (prefix local-name
)
187 (cxml::split-qname str
)
189 ;; FIXME: cxml should really offer a function that does
190 ;; checks for NCName and QName in a sensible way for user code.
191 ;; cxml::split-qname is tailored to the needs of the parser.
193 ;; For now, let's just check the syntax explicitly.
194 (and (or (null prefix
) (xpath::nc-name-p prefix
))
195 (xpath::nc-name-p local-name
))
196 (xslt-error "not a qname: ~A" str
))
197 (values prefix local-name
))
198 (cxml:well-formedness-violation
()
199 (xslt-error "not a qname: ~A" str
))))
201 (defun decode-qname (qname env attributep
)
203 (xslt-error "missing name"))
204 (multiple-value-bind (prefix local-name
)
207 (if (or prefix
(not attributep
))
208 (xpath-sys:environment-find-namespace env
(or prefix
""))
212 (defmethod xpath-sys:environment-find-namespace
((env xslt-environment
) prefix
)
213 (or (cdr (assoc prefix
*namespaces
* :test
'equal
))
215 ;; Change the entire code base to represent "no prefix" as the
216 ;; empty string consistently. unparse.lisp has already been changed.
217 (and (equal prefix
"")
218 (cdr (assoc nil
*namespaces
* :test
'equal
)))
219 (and (eql prefix nil
)
220 (cdr (assoc "" *namespaces
* :test
'equal
)))))
222 (defun find-variable-index (local-name uri table
)
223 (position (cons local-name uri
) table
:test
'equal
))
225 (defun intern-global-variable (local-name uri
)
226 (or (find-variable-index local-name uri
*global-variable-declarations
*)
227 (push-variable local-name uri
*global-variable-declarations
*)))
229 (defun push-variable (local-name uri table
)
232 (vector-push-extend (cons local-name uri
) table
)))
234 (defun lexical-variable-value (index &optional
(errorp t
))
235 (let ((result (svref *lexical-variable-values
* index
)))
237 (assert (not (eq result
'unbound
))))
240 (defun (setf lexical-variable-value
) (newval index
)
241 (assert (not (eq newval
'unbound
)))
242 (setf (svref *lexical-variable-values
* index
) newval
))
244 (defun global-variable-value (index &optional
(errorp t
))
245 (let ((result (svref *global-variable-values
* index
)))
247 (assert (not (eq result
'unbound
))))
250 (defun (setf global-variable-value
) (newval index
)
251 (assert (not (eq newval
'unbound
)))
252 (setf (svref *global-variable-values
* index
) newval
))
254 (defmethod xpath-sys:environment-find-function
255 ((env xslt-environment
) lname uri
)
257 (or (xpath-sys:find-xpath-function lname
*xsl
*)
258 (xpath-sys:find-xpath-function lname uri
))
259 (xpath-sys:find-xpath-function lname uri
)))
261 (defmethod xpath-sys:environment-find-variable
262 ((env xslt-environment
) lname uri
)
264 (find-variable-index lname uri
*lexical-variable-declarations
*)))
267 (declare (ignore ctx
))
268 (svref *lexical-variable-values
* index
)))))
270 (defclass lexical-xslt-environment
(xslt-environment) ())
272 (defmethod xpath-sys:environment-find-variable
273 ((env lexical-xslt-environment
) lname uri
)
274 (or (call-next-method)
276 (find-variable-index lname uri
*global-variable-declarations
*)))
280 (declare (ignore ctx
))
281 (svref *global-variable-values
* index
))
282 "global ~s (uri ~s) = ~s" lname uri
:result
)))))
284 (defclass global-variable-environment
(xslt-environment)
285 ((initial-global-variable-thunks
286 :initarg
:initial-global-variable-thunks
287 :accessor initial-global-variable-thunks
)))
289 (defmethod xpath-sys:environment-find-variable
290 ((env global-variable-environment
) lname uri
)
291 (or (call-next-method)
292 (gethash (cons lname uri
) (initial-global-variable-thunks env
))))
295 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
297 ;;;; A sink that serializes only text not contained in any element.
299 (defmacro with-toplevel-text-output-sink
((var) &body body
)
300 `(invoke-with-toplevel-text-output-sink (lambda (,var
) ,@body
)))
302 (defclass toplevel-text-output-sink
(sax:default-handler
)
303 ((target :initarg
:target
:accessor text-output-sink-target
)
304 (depth :initform
0 :accessor textoutput-sink-depth
)))
306 (defmethod sax:start-element
((sink toplevel-text-output-sink
)
307 namespace-uri local-name qname attributes
)
308 (declare (ignore namespace-uri local-name qname attributes
))
309 (incf (textoutput-sink-depth sink
)))
311 (defmethod sax:characters
((sink toplevel-text-output-sink
) data
)
312 (when (zerop (textoutput-sink-depth sink
))
313 (write-string data
(text-output-sink-target sink
))))
315 (defmethod sax:unescaped
((sink toplevel-text-output-sink
) data
)
316 (sax:characters sink data
))
318 (defmethod sax:end-element
((sink toplevel-text-output-sink
)
319 namespace-uri local-name qname
)
320 (declare (ignore namespace-uri local-name qname
))
321 (decf (textoutput-sink-depth sink
)))
323 (defun invoke-with-toplevel-text-output-sink (fn)
324 (with-output-to-string (s)
325 (funcall fn
(make-instance 'toplevel-text-output-sink
:target s
))))
330 ;;;; A sink that passes through only text (at any level) and turns to
331 ;;;; into unescaped characters.
333 (defclass text-filter
(sax:default-handler
)
334 ((target :initarg
:target
:accessor text-filter-target
)))
336 (defmethod sax:characters
((sink text-filter
) data
)
337 (sax:unescaped
(text-filter-target sink
) data
))
339 (defmethod sax:unescaped
((sink text-filter
) data
)
340 (sax:unescaped
(text-filter-target sink
) data
))
342 (defmethod sax:end-document
((sink text-filter
))
343 (sax:end-document
(text-filter-target sink
)))
345 (defun make-text-filter (target)
346 (make-instance 'text-filter
:target target
))
351 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
354 (defclass escaper
(cxml:broadcast-handler
)
357 (defmethod sax:unescaped
((sink escaper
) data
)
358 (sax:characters sink data
))
360 (defun make-escaper (target)
361 (make-instance 'escaper
:handlers
(list target
)))
366 (defun of-name (local-name)
367 (stp:of-name local-name
*xsl
*))
369 (defun namep (node local-name
)
370 (and (typep node
'(or stp
:element stp
:attribute
))
371 (equal (stp:namespace-uri node
) *xsl
*)
372 (equal (stp:local-name node
) local-name
)))
375 ;;;; PARSE-STYLESHEET
377 (defstruct stylesheet
378 (modes (make-hash-table :test
'equal
))
379 (global-variables (make-empty-declaration-array))
380 (output-specification (make-output-specification))
383 (named-templates (make-hash-table :test
'equal
))
384 (attribute-sets (make-hash-table :test
'equal
))
385 (keys (make-hash-table :test
'equal
))
386 (namespace-aliases (make-hash-table :test
'equal
))
387 (decimal-formats (make-hash-table :test
'equal
))
388 (initial-global-variable-thunks (make-hash-table :test
'equal
)))
392 (match-thunk (lambda (ignore) (declare (ignore ignore
)) nil
)))
394 (defun find-mode (stylesheet local-name
&optional uri
)
395 (gethash (cons local-name uri
) (stylesheet-modes stylesheet
)))
397 (defun ensure-mode (stylesheet &optional local-name uri
)
398 (or (find-mode stylesheet local-name uri
)
399 (setf (gethash (cons local-name uri
) (stylesheet-modes stylesheet
))
402 (defun ensure-mode/qname
(stylesheet qname env
)
404 (multiple-value-bind (local-name uri
)
405 (decode-qname qname env nil
)
406 (ensure-mode stylesheet local-name uri
))
407 (find-mode stylesheet nil
)))
409 (defun acons-namespaces (element &optional
(bindings *namespaces
*))
410 (map-namespace-declarations (lambda (prefix uri
)
411 (push (cons prefix uri
) bindings
))
415 (defun find-key (name stylesheet
)
416 (or (gethash name
(stylesheet-keys stylesheet
))
417 (xslt-error "unknown key: ~a" name
)))
419 (defun make-key (match use
) (cons match use
))
421 (defun key-match (key) (car key
))
423 (defun key-use (key) (cdr key
))
425 (defun add-key (stylesheet name match use
)
426 (if (gethash name
(stylesheet-keys stylesheet
))
427 (xslt-error "duplicate key: ~a" name
)
428 (setf (gethash name
(stylesheet-keys stylesheet
))
429 (make-key match use
))))
431 (defvar *excluded-namespaces
* (list *xsl
*))
432 (defvar *empty-mode
*)
433 (defvar *default-mode
*)
435 (defvar *xsl-include-stack
* nil
)
437 (defun uri-to-pathname (uri)
438 (cxml::uri-to-pathname
(puri:parse-uri uri
)))
440 ;; Why this extra check for literal result element used as stylesheets,
441 ;; instead of a general check for every literal result element? Because
442 ;; Stylesheet__91804 says so.
443 (defun check-Errors_err035 (literal-result-element)
444 (let ((*namespaces
* (acons-namespaces literal-result-element
))
445 (env (make-instance 'lexical-xslt-environment
)))
446 (stp:with-attributes
((extension-element-prefixes
447 "extension-element-prefixes"
449 literal-result-element
450 (dolist (prefix (words (or extension-element-prefixes
"")))
451 (if (equal prefix
"#default")
453 (unless (cxml-stp-impl::nc-name-p prefix
)
454 (xslt-error "invalid prefix: ~A" prefix
)))
456 (or (xpath-sys:environment-find-namespace env prefix
)
457 (xslt-error "namespace not found: ~A" prefix
))))
458 (when (equal uri
(stp:namespace-uri literal-result-element
))
459 (xslt-error "literal result element used as stylesheet, but is ~
460 declared as an extension element")))))))
462 (defun unwrap-2.3
(document)
463 (let ((literal-result-element (stp:document-element document
))
464 (new-template (stp:make-element
"template" *xsl
*))
465 (new-document-element (stp:make-element
"stylesheet" *xsl
*)))
466 (check-Errors_err035 literal-result-element
)
467 (setf (stp:attribute-value new-document-element
"version")
468 (or (stp:attribute-value literal-result-element
"version" *xsl
*)
469 (xslt-error "not a stylesheet: root element lacks xsl:version")))
470 (setf (stp:attribute-value new-template
"match") "/")
471 (setf (stp:document-element document
) new-document-element
)
472 (stp:append-child new-document-element new-template
)
473 (stp:append-child new-template literal-result-element
)
474 new-document-element
))
476 (defun parse-stylesheet-to-stp (input uri-resolver
)
477 (let* ((d (cxml:parse input
(make-text-normalizer (cxml-stp:make-builder
))))
478 (<transform
> (stp:document-element d
)))
479 (unless (equal (stp:namespace-uri
<transform
>) *xsl
*)
480 (setf <transform
> (unwrap-2.3 d
)))
481 (strip-stylesheet <transform
>)
482 (unless (and (equal (stp:namespace-uri
<transform
>) *xsl
*)
483 (or (equal (stp:local-name
<transform
>) "transform")
484 (equal (stp:local-name
<transform
>) "stylesheet")))
485 (xslt-error "not a stylesheet"))
486 (check-for-invalid-attributes '(("version" .
"")
487 ("exclude-result-prefixes" .
"")
488 ("extension-element-prefixes" .
""))
491 (or (stp:find-child-if
(of-name "stylesheet") <transform
>)
492 (stp:find-child-if
(of-name "transform") <transform
>))))
494 (xslt-error "invalid top-level element ~A" (stp:local-name invalid
))))
495 (dolist (include (stp:filter-children
(of-name "include") <transform
>))
496 (let* ((uri (puri:merge-uris
(stp:attribute-value include
"href")
497 (stp:base-uri include
)))
498 (uri (if uri-resolver
499 (funcall uri-resolver
(puri:render-uri uri nil
))
501 (str (puri:render-uri uri nil
))
504 (uri-to-pathname uri
)
505 (cxml:xml-parse-error
(c)
506 (xslt-error "cannot find included stylesheet ~A: ~A"
510 :element-type
'(unsigned-byte 8)
511 :if-does-not-exist nil
)
513 (xslt-error "cannot find included stylesheet ~A at ~A"
515 (when (find str
*xsl-include-stack
* :test
#'equal
)
516 (xslt-error "recursive inclusion of ~A" uri
))
517 (let* ((*xsl-include-stack
* (cons str
*xsl-include-stack
*))
518 (<transform
>2 (parse-stylesheet-to-stp stream uri-resolver
)))
519 (stp:insert-child-after
<transform
>
520 (stp:copy
<transform
>2)
522 (stp:detach include
)))))
525 (defvar *instruction-base-uri
*) ;misnamed, is also used in other attributes
526 (defvar *apply-imports-limit
*)
527 (defvar *import-priority
*)
528 (defvar *extension-namespaces
*)
529 (defvar *forwards-compatible-p
*)
531 (defmacro do-toplevel
((var xpath
<transform
>) &body body
)
532 `(map-toplevel (lambda (,var
) ,@body
) ,xpath
,<transform
>))
534 (defun map-toplevel (fn xpath
<transform
>)
535 (dolist (node (list-toplevel xpath
<transform
>))
536 (let ((*namespaces
* *namespaces
*))
537 (xpath:do-node-set
(ancestor (xpath:evaluate
"ancestor::node()" node
))
538 (when (xpath-protocol:node-type-p ancestor
:element
)
539 (setf *namespaces
* (acons-namespaces ancestor
))))
542 (defun list-toplevel (xpath <transform
>)
543 (labels ((recurse (sub)
546 (xpath:evaluate
"transform|stylesheet" sub
))))
548 (xpath-sys:pipe-of
(xpath:evaluate xpath sub
))
549 (xpath::mappend-pipe
#'recurse subsubs
)))))
550 (xpath::sort-nodes
(recurse <transform
>))))
552 (defmacro with-import-magic
((node env
) &body body
)
553 `(invoke-with-import-magic (lambda () ,@body
) ,node
,env
))
555 (defun invoke-with-import-magic (fn node env
)
556 (unless (or (namep node
"stylesheet") (namep node
"transform"))
557 (setf node
(stp:parent node
)))
558 (let ((*excluded-namespaces
* (list *xsl
*))
559 (*extension-namespaces
* '())
560 (*forwards-compatible-p
*
561 (not (equal (stp:attribute-value node
"version") "1.0"))))
562 (parse-exclude-result-prefixes! node env
)
563 (parse-extension-element-prefixes! node env
)
566 (defun parse-1-stylesheet (env stylesheet designator uri-resolver
)
567 (let* ((<transform
> (parse-stylesheet-to-stp designator uri-resolver
))
568 (instruction-base-uri (stp:base-uri
<transform
>))
569 (namespaces (acons-namespaces <transform
>))
570 (apply-imports-limit (1+ *import-priority
*))
572 (let ((*namespaces
* namespaces
))
573 (invoke-with-import-magic (constantly t
) <transform
> env
))
574 (do-toplevel (elt "node()" <transform
>)
575 (let ((version (stp:attribute-value
(stp:parent elt
) "version")))
578 (xslt-error "stylesheet lacks version"))
579 ((equal version
"1.0")
580 (if (typep elt
'stp
:element
)
581 (when (or (equal (stp:namespace-uri elt
) "")
582 (and (equal (stp:namespace-uri elt
) *xsl
*)
583 (not (find (stp:local-name elt
)
584 '("key" "template" "output"
585 "strip-space" "preserve-space"
586 "attribute-set" "namespace-alias"
587 "decimal-format" "variable" "param"
589 ;; for include handling:
590 "stylesheet" "transform")
592 (xslt-error "unknown top-level element ~A" (stp:local-name elt
)))
593 (xslt-error "text at top-level"))))))
594 (macrolet ((with-specials ((&optional
) &body body
)
595 `(let ((*instruction-base-uri
* instruction-base-uri
)
596 (*namespaces
* namespaces
)
597 (*apply-imports-limit
* apply-imports-limit
))
600 (do-toplevel (import "import" <transform
>)
601 (let ((uri (puri:merge-uris
(stp:attribute-value import
"href")
602 (stp:base-uri import
))))
603 (push (parse-imported-stylesheet env stylesheet uri uri-resolver
)
605 (let ((import-priority
606 (incf *import-priority
*))
607 (var-cont (prepare-global-variables stylesheet
<transform
>)))
608 ;; delay the rest of compilation until we've seen all global
611 (mapc #'funcall
(nreverse continuations
))
613 (let ((*import-priority
* import-priority
))
615 (parse-keys! stylesheet
<transform
> env
)
616 (parse-templates! stylesheet
<transform
> env
)
617 (parse-output! stylesheet
<transform
>)
618 (parse-strip/preserve-space
! stylesheet
<transform
> env
)
619 (parse-attribute-sets! stylesheet
<transform
> env
)
620 (parse-namespace-aliases! stylesheet
<transform
> env
)
621 (parse-decimal-formats! stylesheet
<transform
> env
))))))))
623 (defvar *xsl-import-stack
* nil
)
625 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver
)
626 (let* ((uri (if uri-resolver
627 (funcall uri-resolver
(puri:render-uri uri nil
))
629 (str (puri:render-uri uri nil
))
632 (uri-to-pathname uri
)
633 (cxml:xml-parse-error
(c)
634 (xslt-error "cannot find imported stylesheet ~A: ~A"
638 :element-type
'(unsigned-byte 8)
639 :if-does-not-exist nil
)
641 (xslt-error "cannot find imported stylesheet ~A at ~A"
643 (when (find str
*xsl-import-stack
* :test
#'equal
)
644 (xslt-error "recursive inclusion of ~A" uri
))
645 (let ((*xsl-import-stack
* (cons str
*xsl-import-stack
*)))
646 (parse-1-stylesheet env stylesheet stream uri-resolver
)))))
648 (defvar *included-attribute-sets
*)
650 (defun parse-stylesheet (designator &key uri-resolver
)
651 (with-resignalled-errors ()
652 (xpath:with-namespaces
((nil #.
*xsl
*))
653 (let* ((*import-priority
* 0)
654 (xpath:*allow-variables-in-patterns
* nil
)
655 (puri:*strict-parse
* nil
)
656 (stylesheet (make-stylesheet))
657 (env (make-instance 'lexical-xslt-environment
))
658 (*excluded-namespaces
* *excluded-namespaces
*)
659 (*global-variable-declarations
* (make-empty-declaration-array))
660 (*included-attribute-sets
* nil
))
661 (ensure-mode stylesheet nil
)
662 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver
))
663 ;; reverse attribute sets:
664 (let ((table (stylesheet-attribute-sets stylesheet
)))
665 (maphash (lambda (k v
)
666 (setf (gethash k table
) (nreverse v
)))
669 (dolist (sets *included-attribute-sets
*)
670 (loop for
(local-name uri nil
) in sets do
671 (find-attribute-set local-name uri stylesheet
)))
673 (unless (find-decimal-format "" "" stylesheet nil
)
674 (setf (find-decimal-format "" "" stylesheet
)
675 (make-decimal-format)))
676 ;; compile a template matcher for each mode:
678 for mode being each hash-value in
(stylesheet-modes stylesheet
)
680 (setf (mode-match-thunk mode
)
681 (xpath:make-pattern-matcher
682 (mapcar #'template-compiled-pattern
683 (mode-templates mode
)))))
684 ;; and for the strip tests
685 (setf (stylesheet-strip-thunk stylesheet
)
686 (let ((patterns (stylesheet-strip-tests stylesheet
)))
688 (xpath:make-pattern-matcher
689 (mapcar #'strip-test-compiled-pattern patterns
)))))
692 (defun parse-attribute-sets! (stylesheet <transform
> env
)
693 (do-toplevel (elt "attribute-set" <transform
>)
694 (with-import-magic (elt env
)
696 (mapcar (lambda (qname)
697 (multiple-value-list (decode-qname qname env nil
)))
699 (stp:attribute-value elt
"use-attribute-sets"))))
705 (and (typep child
'stp
:element
)
706 (or (and (equal (stp:namespace-uri child
) *xsl
*)
707 (equal (stp:local-name child
)
709 (find (stp:namespace-uri child
)
710 *extension-namespaces
*
712 (xslt-error "non-attribute found in attribute set"))
713 (parse-instruction child
))
715 (*lexical-variable-declarations
*
716 (make-empty-declaration-array))
718 (compile-instruction `(progn ,@instructions
) env
))
719 (n-variables (length *lexical-variable-declarations
*)))
720 (push sets
*included-attribute-sets
*)
723 (loop for
(local-name uri nil
) in sets do
724 (dolist (thunk (find-attribute-set local-name uri
))
725 (funcall thunk ctx
)))
726 (let ((*lexical-variable-values
*
727 (make-variable-value-array n-variables
)))
728 (funcall thunk ctx
)))))
729 (gethash (multiple-value-bind (local-name uri
)
730 (decode-qname (or (stp:attribute-value elt
"name")
731 (xslt-error "missing name"))
734 (cons local-name uri
))
735 (stylesheet-attribute-sets stylesheet
))))))
737 (defun parse-namespace-aliases! (stylesheet <transform
> env
)
738 (do-toplevel (elt "namespace-alias" <transform
>)
739 (stp:with-attributes
(stylesheet-prefix result-prefix
) elt
741 (if (equal stylesheet-prefix
"#default")
743 (xpath-sys:environment-find-namespace env stylesheet-prefix
))
744 (stylesheet-namespace-aliases stylesheet
))
745 (xpath-sys:environment-find-namespace
747 (if (equal result-prefix
"#default")
751 (defun parse-decimal-formats! (stylesheet <transform
> env
)
752 (do-toplevel (elt "decimal-format" <transform
>)
753 (stp:with-attributes
(name
767 (multiple-value-bind (local-name uri
)
769 (decode-qname name env nil
)
771 (let ((current (find-decimal-format local-name uri stylesheet nil
))
776 (unless (eql (length x
) 1)
777 (xslt-error "not a single character: ~A" x
))
778 (let ((chr (elt x
0)))
779 (when (find chr seen
)
781 "conflicting decimal format characters: ~A"
788 (apply #'make-decimal-format
789 (append (str :infinity infinity
)
791 (chr :decimal-separator decimal-separator
)
792 (chr :grouping-separator grouping-separator
)
793 (chr :zero-digit zero-digit
)
794 (chr :percent percent
)
795 (chr :per-mille per-mille
)
797 (chr :pattern-separator pattern-separator
)
798 (chr :minus-sign minus-sign
)))))))
800 (unless (decimal-format= current new
)
801 (xslt-error "decimal format mismatch for ~S" local-name
))
802 (setf (find-decimal-format local-name uri stylesheet
) new
)))))))
804 (defun parse-exclude-result-prefixes! (node env
)
805 (stp:with-attributes
(exclude-result-prefixes)
807 (dolist (prefix (words (or exclude-result-prefixes
"")))
808 (if (equal prefix
"#default")
810 (unless (cxml-stp-impl::nc-name-p prefix
)
811 (xslt-error "invalid prefix: ~A" prefix
)))
812 (push (or (xpath-sys:environment-find-namespace env prefix
)
813 (xslt-error "namespace not found: ~A" prefix
))
814 *excluded-namespaces
*))))
816 (defun parse-extension-element-prefixes! (node env
)
817 (stp:with-attributes
(extension-element-prefixes)
819 (dolist (prefix (words (or extension-element-prefixes
"")))
820 (if (equal prefix
"#default")
822 (unless (cxml-stp-impl::nc-name-p prefix
)
823 (xslt-error "invalid prefix: ~A" prefix
)))
825 (or (xpath-sys:environment-find-namespace env prefix
)
826 (xslt-error "namespace not found: ~A" prefix
))))
827 (unless (equal uri
*xsl
*)
828 (push uri
*extension-namespaces
*)
829 (push uri
*excluded-namespaces
*))))))
831 (defun parse-nametest-tokens (str)
832 (labels ((check (boolean)
834 (xslt-error "invalid nametest token")))
835 (check-null (boolean)
836 (check (not boolean
))))
839 (mapcar (lambda (name-test)
840 (destructuring-bind (&optional path
&rest junk
)
841 (cdr (xpath:parse-pattern-expression name-test
))
843 (check (eq (car path
) :path
))
844 (destructuring-bind (&optional child
&rest junk
) (cdr path
)
846 (check (eq (car child
) :child
))
847 (destructuring-bind (nodetest &rest junk
) (cdr child
)
849 (check (or (stringp nodetest
)
851 (and (consp nodetest
)
852 (or (eq (car nodetest
) :namespace
)
853 (eq (car nodetest
) :qname
)))))))
857 (defstruct strip-test
863 (defun parse-strip/preserve-space
! (stylesheet <transform
> env
)
865 (do-toplevel (elt "strip-space|preserve-space" <transform
>)
866 (let ((*namespaces
* (acons-namespaces elt
))
868 (if (equal (stp:local-name elt
) "strip-space")
872 (cdr (parse-nametest-tokens
873 (stp:attribute-value elt
"elements"))))
874 (let* ((compiled-pattern
875 (car (without-xslt-current ()
876 (xpath:compute-patterns
877 `(:patterns
,expression
)
882 (make-strip-test :compiled-pattern compiled-pattern
883 :priority
(expression-priority expression
)
886 (setf (xpath:pattern-value compiled-pattern
) strip-test
)
887 (push strip-test
(stylesheet-strip-tests stylesheet
)))))
890 (defstruct (output-specification
891 (:conc-name
"OUTPUT-"))
899 (defun parse-output! (stylesheet <transform
>)
900 (dolist (<output
> (list-toplevel "output" <transform
>))
901 (let ((spec (stylesheet-output-specification stylesheet
)))
902 (stp:with-attributes
( ;; version
911 ;;; cdata-section-elements
915 (setf (output-method spec
) method
))
917 (setf (output-indent spec
) indent
))
919 (setf (output-encoding spec
) encoding
))
921 (setf (output-doctype-system spec
) doctype-system
))
923 (setf (output-doctype-public spec
) doctype-public
))
924 (when omit-xml-declaration
925 (setf (output-omit-xml-declaration spec
) omit-xml-declaration
))
926 ;;; (when cdata-section-elements
927 ;;; (setf (output-cdata-section-elements spec)
928 ;;; (concatenate 'string
929 ;;; (output-cdata-section-elements spec)
931 ;;; cdata-section-elements)))
934 (defun make-empty-declaration-array ()
935 (make-array 1 :fill-pointer
0 :adjustable t
))
937 (defun make-variable-value-array (n-lexical-variables)
938 (make-array n-lexical-variables
:initial-element
'unbound
))
940 (defun compile-global-variable (<variable
> env
) ;; also for <param>
941 (stp:with-attributes
(name select
) <variable
>
942 (when (and select
(stp:list-children
<variable
>))
943 (xslt-error "variable with select and body"))
944 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
947 (compile-xpath select env
))
948 ((stp:list-children
<variable
>)
949 (let* ((inner-sexpr `(progn ,@(parse-body <variable
>)))
950 (inner-thunk (compile-instruction inner-sexpr env
)))
952 (apply-to-result-tree-fragment ctx inner-thunk
))))
955 (declare (ignore ctx
))
957 (n-lexical-variables (length *lexical-variable-declarations
*)))
960 (let* ((*lexical-variable-values
*
961 (make-variable-value-array n-lexical-variables
)))
962 (funcall inner ctx
)))
963 "global ~s (~s) = ~s" name select
:result
))))
965 (defstruct (variable-chain
966 (:constructor make-variable-chain
)
967 (:conc-name
"VARIABLE-CHAIN-"))
974 (defstruct (import-variable
975 (:constructor make-variable
)
976 (:conc-name
"VARIABLE-"))
981 (defun parse-global-variable! (stylesheet <variable
> global-env
)
982 (let* ((*namespaces
* (acons-namespaces <variable
>))
983 (instruction-base-uri (stp:base-uri
<variable
>))
984 (*instruction-base-uri
* instruction-base-uri
)
985 (*excluded-namespaces
* (list *xsl
*))
986 (*extension-namespaces
* '())
987 (qname (stp:attribute-value
<variable
> "name")))
988 (with-import-magic (<variable
> global-env
)
990 (xslt-error "name missing in ~A" (stp:local-name
<variable
>)))
991 (multiple-value-bind (local-name uri
)
992 (decode-qname qname global-env nil
)
993 ;; For the normal compilation environment of templates, install it
994 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
995 (let ((index (intern-global-variable local-name uri
)))
996 ;; For the evaluation of a global variable itself, build a thunk
997 ;; that lazily resolves other variables, stored into
998 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
999 (let* ((value-thunk :unknown
)
1000 (sgv (stylesheet-global-variables stylesheet
))
1002 (if (< index
(length sgv
))
1004 (make-variable-chain
1006 :local-name local-name
1008 (next (car (variable-chain-definitions chain
)))
1009 (global-variable-thunk
1011 (let ((v (global-variable-value index nil
)))
1015 (xslt-error "no next definition for: ~A"
1017 (funcall (variable-value-thunk next
) ctx
))
1019 (setf (global-variable-value index
) 'seen
)
1020 (setf (global-variable-value index
)
1021 (funcall value-thunk ctx
)))
1024 (excluded-namespaces *excluded-namespaces
*)
1025 (extension-namespaces *extension-namespaces
*)
1027 (make-variable :param-p
(namep <variable
> "param")))
1030 (let* ((*instruction-base-uri
* instruction-base-uri
)
1031 (*excluded-namespaces
* excluded-namespaces
)
1032 (*extension-namespaces
* extension-namespaces
)
1034 (compile-global-variable <variable
> global-env
)))
1035 (setf value-thunk fn
)
1036 (setf (variable-value-thunk variable
) fn
)))))
1037 (setf (variable-value-thunk-setter variable
)
1039 (setf (gethash (cons local-name uri
)
1040 (initial-global-variable-thunks global-env
))
1041 global-variable-thunk
)
1042 (setf (variable-chain-thunk chain
) global-variable-thunk
)
1043 (push variable
(variable-chain-definitions chain
))
1046 (defun parse-keys! (stylesheet <transform
> env
)
1047 (xpath:with-namespaces
((nil #.
*xsl
*))
1048 (do-toplevel (<key
> "key" <transform
>)
1049 (let ((*instruction-base-uri
* (stp:base-uri
<key
>)))
1050 (stp:with-attributes
(name match use
) <key
>
1051 (unless name
(xslt-error "key name attribute not specified"))
1052 (unless match
(xslt-error "key match attribute not specified"))
1053 (unless use
(xslt-error "key use attribute not specified"))
1054 (multiple-value-bind (local-name uri
)
1055 (decode-qname name env nil
)
1057 (cons local-name uri
)
1058 (compile-xpath `(xpath:xpath
,(parse-key-pattern match
)) env
)
1059 (compile-xpath use env
))))))))
1061 (defun prepare-global-variables (stylesheet <transform
>)
1062 (xpath:with-namespaces
((nil #.
*xsl
*))
1063 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet
))
1064 (global-env (make-instance 'global-variable-environment
1065 :initial-global-variable-thunks igvt
))
1067 (do-toplevel (<variable
> "variable|param" <transform
>)
1069 (parse-global-variable! stylesheet
<variable
> global-env
)))
1070 (xslt-trace "parsing global variable ~s (uri ~s)"
1071 (variable-chain-local-name chain
)
1072 (variable-chain-uri chain
))
1076 (and (equal (variable-chain-local-name a
)
1077 (variable-chain-local-name b
))
1078 (equal (variable-chain-uri a
)
1079 (variable-chain-uri b
)))))
1080 (xslt-error "duplicate definition for global variable ~A"
1081 (variable-chain-local-name chain
)))
1082 (push chain chains
)))
1083 (setf chains
(nreverse chains
))
1084 (let ((table (stylesheet-global-variables stylesheet
))
1085 (newlen (length *global-variable-declarations
*)))
1086 (adjust-array table newlen
:fill-pointer newlen
)
1087 (dolist (chain chains
)
1088 (setf (elt table
(variable-chain-index chain
)) chain
)))
1090 ;; now that the global environment knows about all variables, run the
1091 ;; thunk setters to perform their compilation
1092 (mapc (lambda (chain)
1093 (dolist (var (variable-chain-definitions chain
))
1094 (funcall (variable-value-thunk-setter var
))))
1097 (defun parse-templates! (stylesheet <transform
> env
)
1099 (do-toplevel (<template
> "template" <transform
>)
1100 (let ((*namespaces
* (acons-namespaces <template
>))
1101 (*instruction-base-uri
* (stp:base-uri
<template
>)))
1102 (with-import-magic (<template
> env
)
1103 (dolist (template (compile-template <template
> env i
))
1104 (let ((name (template-name template
)))
1106 (let* ((table (stylesheet-named-templates stylesheet
))
1107 (head (car (gethash name table
))))
1108 (when (and head
(eql (template-import-priority head
)
1109 (template-import-priority template
)))
1110 ;; fixme: is this supposed to be a run-time error?
1111 (xslt-error "conflicting templates for ~A" name
))
1112 (push template
(gethash name table
)))
1113 (let ((mode (ensure-mode/qname stylesheet
1114 (template-mode-qname template
)
1116 (setf (template-mode template
) mode
)
1117 (push template
(mode-templates mode
))))))))
1121 ;;;; APPLY-STYLESHEET
1123 (defvar *stylesheet
*)
1125 (deftype xml-designator
() '(or runes
:xstream runes
:rod array stream pathname
))
1127 (defun unalias-uri (uri)
1129 (gethash uri
(stylesheet-namespace-aliases *stylesheet
*)
1131 (check-type result string
)
1134 (defstruct (parameter
1135 (:constructor make-parameter
(value local-name
&optional uri
)))
1140 (defun find-parameter-value (local-name uri parameters
)
1141 (dolist (p parameters
)
1142 (when (and (equal (parameter-local-name p
) local-name
)
1143 (equal (parameter-uri p
) uri
))
1144 (return (parameter-value p
)))))
1146 (defvar *uri-resolver
*)
1148 (defun parse-allowing-microsoft-bom (pathname handler
)
1149 (with-open-file (s pathname
:element-type
'(unsigned-byte 8))
1150 (unless (and (eql (read-byte s nil
) #xef
)
1151 (eql (read-byte s nil
) #xbb
)
1152 (eql (read-byte s nil
) #xbf
))
1153 (file-position s
0))
1154 (cxml:parse s handler
)))
1156 (defvar *documents
*)
1158 (defun %document
(uri-string base-uri
)
1159 (let* ((absolute-uri
1160 (puri:merge-uris uri-string
(or base-uri
"")))
1163 (funcall *uri-resolver
* (puri:render-uri absolute-uri nil
))
1167 (uri-to-pathname resolved-uri
)
1168 (cxml:xml-parse-error
(c)
1169 (xslt-error "cannot find referenced document ~A: ~A"
1172 (or (gethash pathname
*documents
*)
1173 (setf (gethash pathname
*documents
*)
1174 (make-whitespace-stripper
1176 (parse-allowing-microsoft-bom pathname
1178 ((or file-error cxml
:xml-parse-error
) (c)
1179 (xslt-error "cannot parse referenced document ~A: ~A"
1181 (stylesheet-strip-thunk *stylesheet
*))))))
1182 (when (puri:uri-fragment absolute-uri
)
1183 (xslt-error "use of fragment identifiers in document() not supported"))
1186 (xpath-sys:define-extension xslt
*xsl
*)
1188 (defun document-base-uri (node)
1189 (xpath-protocol:base-uri
1191 ((xpath-protocol:node-type-p node
:document
)
1192 (xpath::find-in-pipe-if
1194 (xpath-protocol:node-type-p x
:element
))
1195 (xpath-protocol:child-pipe node
)))
1196 ((xpath-protocol:node-type-p node
:element
)
1199 (xpath-protocol:parent-node node
)))))
1201 (xpath-sys:define-xpath-function
/lazy
1203 (object &optional node-set
)
1204 (let ((instruction-base-uri *instruction-base-uri
*))
1206 (let* ((object (funcall object ctx
))
1207 (node-set (and node-set
(funcall node-set ctx
)))
1210 (document-base-uri (xpath::textually-first-node node-set
))
1211 instruction-base-uri
)))
1212 (xpath-sys:make-node-set
1213 (if (xpath:node-set-p object
)
1214 (xpath:map-node-set-
>list
1216 (%document
(xpath:string-value node
)
1219 (document-base-uri node
))))
1221 (list (%document
(xpath:string-value object
) base-uri
))))))))
1223 (xpath-sys:define-xpath-function
/lazy xslt
:key
(name object
)
1224 (let ((namespaces *namespaces
*))
1226 (let* ((qname (xpath:string-value
(funcall name ctx
)))
1227 (object (funcall object ctx
))
1229 (multiple-value-bind (local-name uri
)
1230 (decode-qname/runtime qname namespaces nil
)
1231 (cons local-name uri
)))
1232 (key (find-key expanded-name
*stylesheet
*)))
1233 (labels ((get-by-key (value)
1234 (let ((value (xpath:string-value value
)))
1238 (xpath:evaluate-compiled
(key-use key
) node
)))
1239 (if (xpath:node-set-p uses
)
1240 (xpath::find-in-pipe
1242 (xpath-sys:pipe-of uses
)
1243 :key
#'xpath
:string-value
1245 (equal value
(xpath:string-value uses
)))))
1247 (xpath:node-set-value
1248 (xpath:evaluate-compiled
(key-match key
) ctx
)))))))
1249 (xpath-sys:make-node-set
1251 (if (xpath:node-set-p object
)
1252 (xpath::mappend-pipe
#'get-by-key
(xpath-sys:pipe-of object
))
1253 (get-by-key object
)))))))))
1255 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1257 (xpath-sys:define-xpath-function
/lazy xslt
:current
()
1258 (when *without-xslt-current-p
*
1259 (xslt-error "current() not allowed here"))
1261 (xpath-sys:make-node-set
1262 (xpath-sys:make-pipe
1263 (xpath:context-starting-node ctx
)
1266 (xpath-sys:define-xpath-function
/lazy xslt
:unparsed-entity-uri
(name)
1268 (or (xpath-protocol:unparsed-entity-uri
(xpath:context-node ctx
)
1272 (defun %get-node-id
(node)
1273 (when (xpath:node-set-p node
)
1274 (setf node
(xpath::textually-first-node node
)))
1276 (let ((id (xpath-sys:get-node-id node
))
1279 for parent
= node then next
1280 for next
= (xpath-protocol:parent-node parent
)
1281 for this-base-uri
= (xpath-protocol:base-uri parent
)
1282 for highest-base-uri
= (if (plusp (length this-base-uri
))
1286 finally
(return highest-base-uri
))))
1287 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1288 ;; checked only if everything else matches.
1290 ;; This might be pointless premature optimization, but I like the idea :-)
1291 (nreverse (concatenate 'string highest-base-uri
"//" id
)))))
1293 (xpath-sys:define-xpath-function
/lazy xslt
:generate-id
(&optional node-set-thunk
)
1296 (%get-node-id
(xpath:node-set-value
(funcall node-set-thunk ctx
))))
1298 (%get-node-id
(xpath:context-node ctx
)))))
1300 (declaim (special *available-instructions
*))
1302 (xpath-sys:define-xpath-function
/lazy xslt
:element-available
(qname)
1303 (let ((namespaces *namespaces
*))
1305 (let ((qname (funcall qname ctx
)))
1306 (multiple-value-bind (local-name uri
)
1307 (decode-qname/runtime qname namespaces nil
)
1308 (and (equal uri
*xsl
*)
1309 (gethash local-name
*available-instructions
*)
1312 (xpath-sys:define-xpath-function
/lazy xslt
:function-available
(qname)
1313 (let ((namespaces *namespaces
*))
1315 (let ((qname (funcall qname ctx
)))
1316 (multiple-value-bind (local-name uri
)
1317 (decode-qname/runtime qname namespaces nil
)
1318 (and (zerop (length uri
))
1319 (or (xpath-sys:find-xpath-function local-name
*xsl
*)
1320 (xpath-sys:find-xpath-function local-name uri
))
1323 (xpath-sys:define-xpath-function
/lazy xslt
:system-property
(qname)
1324 (let ((namespaces *namespaces
*))
1326 (let ((qname (funcall qname ctx
)))
1327 (multiple-value-bind (local-name uri
)
1328 (decode-qname/runtime qname namespaces nil
)
1329 (if (equal uri
*xsl
*)
1331 ((equal local-name
"version")
1333 ((equal local-name
"vendor")
1335 ((equal local-name
"vendor-uri")
1336 "http://repo.or.cz/w/xuriella.git")
1341 (defun apply-stylesheet
1342 (stylesheet source-designator
1343 &key output parameters uri-resolver navigator
)
1344 (when (typep stylesheet
'xml-designator
)
1347 ((cxml:xml-parse-error
1349 (xslt-error "cannot parse stylesheet: ~A" c
))))
1350 (parse-stylesheet stylesheet
))))
1351 (with-resignalled-errors ()
1352 (invoke-with-output-sink
1354 (let* ((*documents
* (make-hash-table :test
'equal
))
1355 (xpath:*navigator
* (or navigator
:default-navigator
))
1356 (puri:*strict-parse
* nil
)
1357 (*stylesheet
* stylesheet
)
1358 (*empty-mode
* (make-mode))
1359 (*default-mode
* (find-mode stylesheet nil
))
1360 (global-variable-chains
1361 (stylesheet-global-variables stylesheet
))
1362 (*global-variable-values
*
1363 (make-variable-value-array (length global-variable-chains
)))
1364 (*uri-resolver
* uri-resolver
)
1366 (if (typep source-designator
'xml-designator
)
1367 (cxml:parse source-designator
(stp:make-builder
))
1370 (make-whitespace-stripper
1372 (stylesheet-strip-thunk stylesheet
)))
1373 (ctx (xpath:make-context xpath-root-node
)))
1374 (when (pathnamep source-designator
)
1375 (setf (gethash source-designator
*documents
*) xpath-root-node
))
1378 (let ((head (car (variable-chain-definitions chain
))))
1379 (when (variable-param-p head
)
1381 (find-parameter-value
1382 (variable-chain-local-name chain
)
1383 (variable-chain-uri chain
)
1386 (setf (global-variable-value
1387 (variable-chain-index chain
))
1389 global-variable-chains
)
1392 (funcall (variable-chain-thunk chain
) ctx
))
1393 global-variable-chains
)
1394 ;; zzz we wouldn't have to mask float traps here if we used the
1395 ;; XPath API properly. Unfortunately I've been using FUNCALL
1396 ;; everywhere instead of EVALUATE, so let's paper over that
1397 ;; at a central place to be sure:
1398 (xpath::with-float-traps-masked
()
1399 (apply-templates ctx
:mode
*default-mode
*))))
1400 (stylesheet-output-specification stylesheet
)
1403 (defun find-attribute-set (local-name uri
&optional
(stylesheet *stylesheet
*))
1404 (or (gethash (cons local-name uri
) (stylesheet-attribute-sets stylesheet
))
1405 (xslt-error "no such attribute set: ~A/~A" local-name uri
)))
1407 (defun apply-templates/list
(list &key param-bindings sort-predicate mode
)
1408 (when sort-predicate
1410 (mapcar #'xpath
:context-node
1411 (stable-sort (contextify-node-list list
)
1413 (let* ((n (length list
))
1414 (s/d
(lambda () n
)))
1419 (apply-templates (xpath:make-context child s
/d i
)
1420 :param-bindings param-bindings
1423 (defvar *stack-limit
* 200)
1425 (defun invoke-with-stack-limit (fn)
1426 (let ((*stack-limit
* (1- *stack-limit
*)))
1427 (unless (plusp *stack-limit
*)
1428 (xslt-error "*stack-limit* reached; stack overflow"))
1431 (defun invoke-template (ctx template param-bindings
)
1432 (let ((*lexical-variable-values
*
1433 (make-variable-value-array (template-n-variables template
))))
1434 (with-stack-limit ()
1436 for
(name-cons value
) in param-bindings
1437 for
(nil index nil
) = (find name-cons
1438 (template-params template
)
1443 (setf (lexical-variable-value index
) value
)))
1444 (funcall (template-body template
) ctx
))))
1446 (defun apply-default-templates (ctx mode
)
1447 (let ((node (xpath:context-node ctx
)))
1449 ((or (xpath-protocol:node-type-p node
:processing-instruction
)
1450 (xpath-protocol:node-type-p node
:comment
)))
1451 ((or (xpath-protocol:node-type-p node
:text
)
1452 (xpath-protocol:node-type-p node
:attribute
))
1453 (write-text (xpath-protocol:node-text node
)))
1455 (apply-templates/list
1457 (xpath-protocol:child-pipe node
))
1460 (defvar *apply-imports
*)
1462 (defun apply-applicable-templates (ctx templates param-bindings finally
)
1463 (labels ((apply-imports (&optional actual-param-bindings
)
1465 (let* ((this (pop templates
))
1466 (low (template-apply-imports-limit this
))
1467 (high (template-import-priority this
)))
1471 (<= low
(template-import-priority x
) high
))
1473 (invoke-template ctx this actual-param-bindings
))
1474 (funcall finally
))))
1475 (let ((*apply-imports
* #'apply-imports
))
1476 (apply-imports param-bindings
))))
1478 (defun apply-templates (ctx &key param-bindings mode
)
1479 (apply-applicable-templates ctx
1480 (find-templates ctx
(or mode
*default-mode
*))
1483 (apply-default-templates ctx mode
))))
1485 (defun call-template (ctx name
&optional param-bindings
)
1486 (apply-applicable-templates ctx
1487 (find-named-templates name
)
1490 (error "cannot find named template: ~s"
1493 (defun find-templates (ctx mode
)
1494 (let* ((matching-candidates
1495 (xpath:matching-values
(mode-match-thunk mode
)
1496 (xpath:context-node ctx
)))
1498 (if matching-candidates
1501 :key
#'template-import-priority
))
1503 (priority-groups (make-array npriorities
:initial-element nil
)))
1504 (dolist (template matching-candidates
)
1506 (elt priority-groups
(template-import-priority template
))))
1508 for i from
(1- npriorities
) downto
0
1509 for group
= (elt priority-groups i
)
1510 for template
= (maximize #'template
< group
)
1514 (defun find-named-templates (name)
1515 (gethash name
(stylesheet-named-templates *stylesheet
*)))
1517 (defun template< (a b
) ;assuming same import priority
1518 (let ((p (template-priority a
))
1519 (q (template-priority b
)))
1524 (xslt-cerror "conflicting templates:~_~A,~_~A"
1525 (template-match-expression a
)
1526 (template-match-expression b
))
1527 (< (template-position a
) (template-position b
))))))
1529 (defun maximize (< things
)
1531 (let ((max (car things
)))
1532 (dolist (other (cdr things
))
1533 (when (funcall < max other
)
1537 (defun invoke-with-output-sink (fn output-spec output
)
1540 (with-open-file (s output
1542 :element-type
'(unsigned-byte 8)
1543 :if-exists
:rename-and-delete
)
1544 (invoke-with-output-sink fn output-spec s
)))
1546 (invoke-with-output-sink fn
1548 (make-output-sink output-spec output
)))
1549 ((or hax
:abstract-handler sax
:abstract-handler
)
1550 (with-xml-output output
1551 (when (typep output
'(or combi-sink auto-detect-sink
))
1552 (sax:start-dtd output
1553 :autodetect-me-please
1554 (output-doctype-public output-spec
)
1555 (output-doctype-system output-spec
)))
1558 (defun make-output-sink (output-spec stream
)
1561 (let ((et (stream-element-type stream
)))
1563 ((or (null et
) (subtypep et
'(unsigned-byte 8)))
1564 (runes:make-octet-stream-ystream stream
))
1565 ((subtypep et
'character
)
1566 (runes:make-character-stream-ystream stream
))))
1567 (runes:make-rod-ystream
)))
1568 (omit-xml-declaration-p
1569 (equal (output-omit-xml-declaration output-spec
) "yes"))
1570 (sink-encoding (or (output-encoding output-spec
) "UTF-8"))
1573 (setf (runes:ystream-encoding ystream
)
1574 (cxml::find-output-encoding sink-encoding
))
1575 (make-instance 'cxml
::sink
1577 :omit-xml-declaration-p omit-xml-declaration-p
1578 :encoding sink-encoding
))))
1579 (flet ((make-combi-sink ()
1580 (make-instance 'combi-sink
1581 :hax-target
(make-instance 'chtml
::sink
1583 :sax-target sax-target
1584 :encoding sink-encoding
)))
1587 ((equalp (output-method output-spec
) "HTML") :html
)
1588 ((equalp (output-method output-spec
) "TEXT") :text
)
1589 ((equalp (output-method output-spec
) "XML") :xml
)
1592 ((and (eq method-key
:html
)
1593 (null (output-doctype-system output-spec
))
1594 (null (output-doctype-public output-spec
)))
1596 ((eq method-key
:text
)
1597 (make-text-filter sax-target
))
1598 ((and (eq method-key
:xml
)
1599 (null (output-doctype-system output-spec
)))
1602 (make-auto-detect-sink (make-combi-sink) method-key
)))))))
1618 (defun expression-priority (form)
1619 (let ((step (second form
)))
1620 (if (and (null (cddr form
))
1622 (member (car step
) '(:child
:attribute
))
1624 (let ((name (second step
)))
1628 (or (eq (car name
) :qname
)
1629 (eq (car name
) :processing-instruction
))))
1632 (or (eq (car name
) :namespace
)
1633 (eq (car name
) '*)))
1639 (defun parse-xpath (str)
1640 (with-resignalled-errors ()
1641 (xpath:parse-xpath str
)))
1643 (defun parse-key-pattern (str)
1645 (mapcar #'(lambda (item)
1646 `(:path
(:root
:node
)
1647 (:descendant-or-self
*)
1649 (parse-pattern str
))))
1650 (if (null (rest parsed
))
1652 `(:union
,@parsed
))))
1654 (defun parse-pattern (str)
1655 (with-resignalled-errors ()
1656 (cdr (xpath::parse-pattern-expression str
))))
1658 (defun compile-value-thunk (value env
)
1659 (if (and (listp value
) (eq (car value
) 'progn
))
1660 (let ((inner-thunk (compile-instruction value env
)))
1662 (apply-to-result-tree-fragment ctx inner-thunk
)))
1663 (compile-xpath value env
)))
1665 (defun compile-var-binding (name value env
)
1666 (multiple-value-bind (local-name uri
)
1667 (decode-qname name env nil
)
1668 (let ((thunk (xslt-trace-thunk
1669 (compile-value-thunk value env
)
1670 "local variable ~s = ~s" name
:result
)))
1671 (list (cons local-name uri
)
1672 (push-variable local-name
1674 *lexical-variable-declarations
*)
1677 (defun compile-var-bindings (forms env
)
1679 for
(name value
) in forms
1680 collect
(compile-var-binding name value env
)))
1682 (defun compile-template (<template
> env position
)
1683 (stp:with-attributes
(match name priority mode
) <template
>
1684 (unless (or name match
)
1685 (xslt-error "missing match in template"))
1686 (multiple-value-bind (params body-pos
)
1689 for child in
(stp:list-children
<template
>)
1690 while
(namep child
"param")
1691 collect
(parse-param child
) into params
1692 finally
(return (values params i
)))
1693 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1694 (param-bindings (compile-var-bindings params env
))
1695 (body (parse-body <template
> body-pos
(mapcar #'car params
)))
1696 (body-thunk (compile-instruction `(progn ,@body
) env
))
1702 ;; set params that weren't initialized by apply-templates
1703 (loop for
(name index param-thunk
) in param-bindings
1704 when
(eq (lexical-variable-value index nil
) 'unbound
)
1705 do
(setf (lexical-variable-value index
)
1706 (funcall param-thunk ctx
)))
1707 (funcall body-thunk ctx
))))
1708 "template: match = ~s name = ~s" match name
))
1709 (n-variables (length *lexical-variable-declarations
*)))
1712 (multiple-value-bind (local-name uri
)
1713 (decode-qname name env nil
)
1715 (make-template :name
(cons local-name uri
)
1716 :import-priority
*import-priority
*
1717 :apply-imports-limit
*apply-imports-limit
*
1718 :params param-bindings
1719 :body outer-body-thunk
1720 :n-variables n-variables
))))
1722 (mapcar (lambda (expression)
1723 (let* ((compiled-pattern
1725 (car (without-xslt-current ()
1726 (xpath:compute-patterns
1727 `(:patterns
,expression
)
1731 "match-thunk for template (match ~s): ~s --> ~s"
1732 match expression
:result
))
1734 (xpath::parse-xnum priority
)
1735 (expression-priority expression
)))
1738 (unless (and (numberp p
)
1739 (not (xpath::inf-p p
))
1740 (not (xpath::nan-p p
)))
1741 (xslt-error "failed to parse priority"))
1744 (make-template :match-expression expression
1745 :compiled-pattern compiled-pattern
1746 :import-priority
*import-priority
*
1747 :apply-imports-limit
*apply-imports-limit
*
1751 :params param-bindings
1752 :body outer-body-thunk
1753 :n-variables n-variables
)))
1754 (setf (xpath:pattern-value compiled-pattern
)
1757 (cdr (xpath:parse-pattern-expression match
)))))))))
1759 (xuriella::parse-stylesheet
#p
"/home/david/src/lisp/xuriella/test.xsl")