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 (defvar *forwards-compatible-p
*)
108 (defun invoke-with-forward-compatible-errors (fn error-fn
)
115 (when *forwards-compatible-p
*
117 (setf result
(funcall fn
)))
120 (setf result
(funcall error-fn
))
124 (defun compile-xpath (xpath &optional env
)
125 (with-resignalled-errors ()
126 (with-forward-compatible-errors
128 (xslt-error "attempt to evaluate an XPath expression with compile-time errors, delayed due to forwards compatible processing: ~A"
130 (xpath:compile-xpath xpath env
))))
132 (defmacro with-stack-limit
((&optional
) &body body
)
133 `(invoke-with-stack-limit (lambda () ,@body
)))
135 (defparameter *without-xslt-current-p
* nil
)
137 (defmacro without-xslt-current
((&optional
) &body body
)
138 `(invoke-without-xslt-current (lambda () ,@body
)))
140 (defun invoke-without-xslt-current (fn)
141 (let ((*without-xslt-current-p
* t
))
144 ;;; (defun invoke-without-xslt-current (fn)
145 ;;; (let ((non-extensions (gethash "" xpath::*extensions*))
146 ;;; (xpath::*extensions*
147 ;;; ;; hide XSLT extensions
148 ;;; (make-hash-table :test #'equal)))
149 ;;; (setf (gethash "" xpath::*extensions*) non-extensions)
153 ;;;; Helper functions and macros
155 (defun check-for-invalid-attributes (valid-names node
)
156 (labels ((check-attribute (a)
158 (let ((uri (stp:namespace-uri a
)))
159 (or (and (plusp (length uri
)) (not (equal uri
*xsl
*)))
160 (find (cons (stp:local-name a
) uri
)
163 (xslt-error "attribute ~A not allowed on ~A"
165 (stp:local-name node
)))))
166 (stp:map-attributes nil
#'check-attribute node
)))
168 (defmacro only-with-attributes
((&rest specs
) node
&body body
)
170 (mapcar (lambda (entry)
171 (if (and (listp entry
) (cdr entry
))
172 (destructuring-bind (name &optional
(uri ""))
175 (cons (string-downcase
177 (symbol-name entry
)))
181 `(let ((,%NODE
,node
))
182 (check-for-invalid-attributes ',valid-names
,%NODE
)
183 (stp:with-attributes
,specs
,%NODE
186 (defun map-pipe-eagerly (fn pipe
)
187 (xpath::enumerate pipe
:key fn
:result nil
))
189 (defmacro do-pipe
((var pipe
&optional result
) &body body
)
191 (map-pipe-eagerly #'(lambda (,var
) ,@body
) ,pipe
)
195 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
197 (defparameter *initial-namespaces
*
199 ("xmlns" .
#"http://www.w3.org/2000/xmlns/")
200 ("xml" .
#"http://www.w3.org/XML/1998/namespace")))
202 (defparameter *namespaces
*
203 *initial-namespaces
*)
205 (defvar *global-variable-declarations
*)
206 (defvar *lexical-variable-declarations
*)
208 (defvar *global-variable-values
*)
209 (defvar *lexical-variable-values
*)
211 (defclass xslt-environment
() ())
213 (defun split-qname (str)
215 (multiple-value-bind (prefix local-name
)
216 (cxml::split-qname str
)
218 ;; FIXME: cxml should really offer a function that does
219 ;; checks for NCName and QName in a sensible way for user code.
220 ;; cxml::split-qname is tailored to the needs of the parser.
222 ;; For now, let's just check the syntax explicitly.
223 (and (or (null prefix
) (xpath::nc-name-p prefix
))
224 (xpath::nc-name-p local-name
))
225 (xslt-error "not a qname: ~A" str
))
226 (values prefix local-name
))
227 (cxml:well-formedness-violation
()
228 (xslt-error "not a qname: ~A" str
))))
230 (defun decode-qname (qname env attributep
&key allow-unknown-namespace
)
232 (xslt-error "missing name"))
233 (multiple-value-bind (prefix local-name
)
236 (if (or prefix
(not attributep
))
237 (or (xpath-sys:environment-find-namespace env
(or prefix
""))
238 (if allow-unknown-namespace
240 (xslt-error "namespace not found: ~A" prefix
)))
244 (defmethod xpath-sys:environment-find-namespace
((env xslt-environment
) prefix
)
245 (or (cdr (assoc prefix
*namespaces
* :test
'equal
))
247 ;; Change the entire code base to represent "no prefix" as the
248 ;; empty string consistently. unparse.lisp has already been changed.
249 (and (equal prefix
"")
250 (cdr (assoc nil
*namespaces
* :test
'equal
)))
251 (and (eql prefix nil
)
252 (cdr (assoc "" *namespaces
* :test
'equal
)))))
254 (defun find-variable-index (local-name uri table
)
255 (position (cons local-name uri
) table
:test
'equal
))
257 (defun intern-global-variable (local-name uri
)
258 (or (find-variable-index local-name uri
*global-variable-declarations
*)
259 (push-variable local-name uri
*global-variable-declarations
*)))
261 (defun push-variable (local-name uri table
)
264 (vector-push-extend (cons local-name uri
) table
)))
266 (defun lexical-variable-value (index &optional
(errorp t
))
267 (let ((result (svref *lexical-variable-values
* index
)))
269 (assert (not (eq result
'unbound
))))
272 (defun (setf lexical-variable-value
) (newval index
)
273 (assert (not (eq newval
'unbound
)))
274 (setf (svref *lexical-variable-values
* index
) newval
))
276 (defun global-variable-value (index &optional
(errorp t
))
277 (let ((result (svref *global-variable-values
* index
)))
279 (assert (not (eq result
'unbound
))))
282 (defun (setf global-variable-value
) (newval index
)
283 (assert (not (eq newval
'unbound
)))
284 (setf (svref *global-variable-values
* index
) newval
))
286 (defmethod xpath-sys:environment-find-function
287 ((env xslt-environment
) lname uri
)
288 (or (if (string= uri
"")
289 (or (xpath-sys:find-xpath-function lname
*xsl
*)
290 (xpath-sys:find-xpath-function lname uri
))
291 (xpath-sys:find-xpath-function lname uri
))
292 (when *forwards-compatible-p
*
293 (lambda (&rest ignore
)
294 (declare (ignore ignore
))
295 (xslt-error "attempt to call an unknown XPath function (~A); error delayed until run-time due to forwards compatible processing"
298 (defmethod xpath-sys:environment-find-variable
299 ((env xslt-environment
) lname uri
)
301 (find-variable-index lname uri
*lexical-variable-declarations
*)))
304 (declare (ignore ctx
))
305 (svref *lexical-variable-values
* index
)))))
307 (defclass lexical-xslt-environment
(xslt-environment) ())
309 (defmethod xpath-sys:environment-find-variable
310 ((env lexical-xslt-environment
) lname uri
)
311 (or (call-next-method)
313 (find-variable-index lname uri
*global-variable-declarations
*)))
317 (declare (ignore ctx
))
318 (svref *global-variable-values
* index
))
319 "global ~s (uri ~s) = ~s" lname uri
:result
)))))
321 (defclass key-environment
(xslt-environment) ())
323 (defmethod xpath-sys:environment-find-variable
324 ((env key-environment
) lname uri
)
325 (declare (ignore lname uri
))
326 (xslt-error "disallowed variable reference"))
328 (defclass global-variable-environment
(xslt-environment)
329 ((initial-global-variable-thunks
330 :initarg
:initial-global-variable-thunks
331 :accessor initial-global-variable-thunks
)))
333 (defmethod xpath-sys:environment-find-variable
334 ((env global-variable-environment
) lname uri
)
335 (or (call-next-method)
336 (gethash (cons lname uri
) (initial-global-variable-thunks env
))))
339 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
341 ;;;; A sink that serializes only text not contained in any element.
343 (defmacro with-toplevel-text-output-sink
((var) &body body
)
344 `(invoke-with-toplevel-text-output-sink (lambda (,var
) ,@body
)))
346 (defclass toplevel-text-output-sink
(sax:default-handler
)
347 ((target :initarg
:target
:accessor text-output-sink-target
)
348 (depth :initform
0 :accessor textoutput-sink-depth
)))
350 (defmethod sax:start-element
((sink toplevel-text-output-sink
)
351 namespace-uri local-name qname attributes
)
352 (declare (ignore namespace-uri local-name qname attributes
))
353 (incf (textoutput-sink-depth sink
)))
355 (defmethod sax:characters
((sink toplevel-text-output-sink
) data
)
356 (when (zerop (textoutput-sink-depth sink
))
357 (write-string data
(text-output-sink-target sink
))))
359 (defmethod sax:unescaped
((sink toplevel-text-output-sink
) data
)
360 (sax:characters sink data
))
362 (defmethod sax:end-element
((sink toplevel-text-output-sink
)
363 namespace-uri local-name qname
)
364 (declare (ignore namespace-uri local-name qname
))
365 (decf (textoutput-sink-depth sink
)))
367 (defun invoke-with-toplevel-text-output-sink (fn)
368 (with-output-to-string (s)
369 (funcall fn
(make-instance 'toplevel-text-output-sink
:target s
))))
374 ;;;; A sink that passes through only text (at any level) and turns to
375 ;;;; into unescaped characters.
377 (defclass text-filter
(sax:default-handler
)
378 ((target :initarg
:target
:accessor text-filter-target
)))
380 (defmethod sax:characters
((sink text-filter
) data
)
381 (sax:unescaped
(text-filter-target sink
) data
))
383 (defmethod sax:unescaped
((sink text-filter
) data
)
384 (sax:unescaped
(text-filter-target sink
) data
))
386 (defmethod sax:end-document
((sink text-filter
))
387 (sax:end-document
(text-filter-target sink
)))
389 (defun make-text-filter (target)
390 (make-instance 'text-filter
:target target
))
395 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
398 (defclass escaper
(cxml:broadcast-handler
)
401 (defmethod sax:unescaped
((sink escaper
) data
)
402 (sax:characters sink data
))
404 (defun make-escaper (target)
405 (make-instance 'escaper
:handlers
(list target
)))
410 (defun of-name (local-name)
411 (stp:of-name local-name
*xsl
*))
413 (defun namep (node local-name
)
414 (and (typep node
'(or stp
:element stp
:attribute
))
415 (equal (stp:namespace-uri node
) *xsl
*)
416 (equal (stp:local-name node
) local-name
)))
419 ;;;; PARSE-STYLESHEET
421 (defstruct stylesheet
422 (modes (make-hash-table :test
'equal
))
423 (global-variables (make-empty-declaration-array))
424 (output-specification (make-output-specification))
427 (named-templates (make-hash-table :test
'equal
))
428 (attribute-sets (make-hash-table :test
'equal
))
429 (keys (make-hash-table :test
'equal
))
430 (namespace-aliases (make-hash-table :test
'equal
))
431 (decimal-formats (make-hash-table :test
'equal
))
432 (initial-global-variable-thunks (make-hash-table :test
'equal
)))
436 (match-thunk (lambda (ignore) (declare (ignore ignore
)) nil
)))
438 (defun find-mode (stylesheet local-name
&optional uri
)
439 (gethash (cons local-name uri
) (stylesheet-modes stylesheet
)))
441 (defun ensure-mode (stylesheet &optional local-name uri
)
442 (or (find-mode stylesheet local-name uri
)
443 (setf (gethash (cons local-name uri
) (stylesheet-modes stylesheet
))
446 (defun ensure-mode/qname
(stylesheet qname env
)
448 (multiple-value-bind (local-name uri
)
449 (decode-qname qname env nil
)
450 (ensure-mode stylesheet local-name uri
))
451 (find-mode stylesheet nil
)))
453 (defun acons-namespaces
454 (element &optional
(bindings *namespaces
*) include-redeclared
)
455 (map-namespace-declarations (lambda (prefix uri
)
456 (push (cons prefix uri
) bindings
))
461 (defun find-key (name stylesheet
)
462 (or (gethash name
(stylesheet-keys stylesheet
))
463 (xslt-error "unknown key: ~a" name
)))
465 (defun make-key (match use
) (cons match use
))
467 (defun key-match (key) (car key
))
469 (defun key-use (key) (cdr key
))
471 (defun add-key (stylesheet name match use
)
472 (push (make-key match use
)
473 (gethash name
(stylesheet-keys stylesheet
))))
475 (defvar *excluded-namespaces
* (list *xsl
*))
476 (defvar *empty-mode
*)
477 (defvar *default-mode
*)
479 (defvar *xsl-include-stack
* nil
)
481 (defun uri-to-pathname (uri)
482 (cxml::uri-to-pathname
(puri:parse-uri uri
)))
484 ;; Why this extra check for literal result element used as stylesheets,
485 ;; instead of a general check for every literal result element? Because
486 ;; Stylesheet__91804 says so.
487 (defun check-Errors_err035 (literal-result-element)
488 (let ((*namespaces
* (acons-namespaces literal-result-element
))
489 (env (make-instance 'lexical-xslt-environment
)))
490 (stp:with-attributes
((extension-element-prefixes
491 "extension-element-prefixes"
493 literal-result-element
494 (dolist (prefix (words (or extension-element-prefixes
"")))
495 (if (equal prefix
"#default")
497 (unless (cxml-stp-impl::nc-name-p prefix
)
498 (xslt-error "invalid prefix: ~A" prefix
)))
500 (or (xpath-sys:environment-find-namespace env prefix
)
501 (xslt-error "namespace not found: ~A" prefix
))))
502 (when (equal uri
(stp:namespace-uri literal-result-element
))
503 (xslt-error "literal result element used as stylesheet, but is ~
504 declared as an extension element")))))))
506 (defun unwrap-2.3
(document)
507 (let ((literal-result-element (stp:document-element document
))
508 (new-template (stp:make-element
"template" *xsl
*))
509 (new-document-element (stp:make-element
"stylesheet" *xsl
*)))
510 (check-Errors_err035 literal-result-element
)
511 (setf (stp:attribute-value new-document-element
"version")
512 (or (stp:attribute-value literal-result-element
"version" *xsl
*)
513 (xslt-error "not a stylesheet: root element lacks xsl:version")))
514 (setf (stp:attribute-value new-template
"match") "/")
515 (setf (stp:document-element document
) new-document-element
)
516 (stp:append-child new-document-element new-template
)
517 (stp:append-child new-template literal-result-element
)
518 new-document-element
))
520 (defun parse-stylesheet-to-stp (input uri-resolver
)
521 (let* ((d (cxml:parse input
(make-text-normalizer (cxml-stp:make-builder
))))
522 (<transform
> (stp:document-element d
)))
523 (unless (equal (stp:namespace-uri
<transform
>) *xsl
*)
524 (setf <transform
> (unwrap-2.3 d
)))
525 (strip-stylesheet <transform
>)
526 (unless (and (equal (stp:namespace-uri
<transform
>) *xsl
*)
527 (or (equal (stp:local-name
<transform
>) "transform")
528 (equal (stp:local-name
<transform
>) "stylesheet")))
529 (xslt-error "not a stylesheet"))
530 (check-for-invalid-attributes
532 ("exclude-result-prefixes" .
"")
533 ("extension-element-prefixes" .
"")
534 ("space" .
"http://www.w3.org/XML/1998/namespace")
538 (or (stp:find-child-if
(of-name "stylesheet") <transform
>)
539 (stp:find-child-if
(of-name "transform") <transform
>))))
541 (xslt-error "invalid top-level element ~A" (stp:local-name invalid
))))
542 (dolist (include (stp:filter-children
(of-name "include") <transform
>))
543 (let* ((uri (puri:merge-uris
(or (stp:attribute-value include
"href")
544 (xslt-error "include without href"))
545 (stp:base-uri include
)))
546 (uri (if uri-resolver
547 (funcall uri-resolver uri
)
549 (str (puri:render-uri uri nil
))
552 (uri-to-pathname uri
)
553 (cxml:xml-parse-error
(c)
554 (xslt-error "cannot find included stylesheet ~A: ~A"
558 :element-type
'(unsigned-byte 8)
559 :if-does-not-exist nil
)
561 (xslt-error "cannot find included stylesheet ~A at ~A"
563 (when (find str
*xsl-include-stack
* :test
#'equal
)
564 (xslt-error "recursive inclusion of ~A" uri
))
565 (let* ((*xsl-include-stack
* (cons str
*xsl-include-stack
*))
566 (<transform
>2 (parse-stylesheet-to-stp stream uri-resolver
)))
567 (stp:insert-child-after
<transform
>
568 (stp:copy
<transform
>2)
570 (stp:detach include
)))))
573 (defvar *instruction-base-uri
*) ;misnamed, is also used in other attributes
574 (defvar *apply-imports-limit
*)
575 (defvar *import-priority
*)
576 (defvar *extension-namespaces
*)
578 (defmacro do-toplevel
((var xpath
<transform
>) &body body
)
579 `(map-toplevel (lambda (,var
) ,@body
) ,xpath
,<transform
>))
581 (defun map-toplevel (fn xpath
<transform
>)
582 (dolist (node (list-toplevel xpath
<transform
>))
583 (let ((*namespaces
* *initial-namespaces
*))
584 (xpath:do-node-set
(ancestor (xpath:evaluate
"ancestor::node()" node
))
585 (xpath:with-namespaces
(("" #.
*xsl
*))
586 (when (xpath:node-matches-p ancestor
"stylesheet|transform")
587 ;; discard namespaces from including stylesheets
588 (setf *namespaces
* *initial-namespaces
*)))
589 (when (xpath-protocol:node-type-p ancestor
:element
)
590 (setf *namespaces
* (acons-namespaces ancestor
*namespaces
* t
))))
593 (defun list-toplevel (xpath <transform
>)
594 (labels ((recurse (sub)
597 (xpath:evaluate
"transform|stylesheet" sub
))))
599 (xpath-sys:pipe-of
(xpath:evaluate xpath sub
))
600 (xpath::mappend-pipe
#'recurse subsubs
)))))
601 (xpath::sort-nodes
(recurse <transform
>))))
603 (defmacro with-import-magic
((node env
) &body body
)
604 `(invoke-with-import-magic (lambda () ,@body
) ,node
,env
))
606 (defun invoke-with-import-magic (fn node env
)
607 (unless (or (namep node
"stylesheet") (namep node
"transform"))
608 (setf node
(stp:parent node
)))
609 (let ((*excluded-namespaces
* (list *xsl
*))
610 (*extension-namespaces
* '())
611 (*forwards-compatible-p
*
612 (not (equal (stp:attribute-value node
"version") "1.0"))))
613 (parse-exclude-result-prefixes! node env
)
614 (parse-extension-element-prefixes! node env
)
617 (defun parse-1-stylesheet (env stylesheet designator uri-resolver
)
618 (let* ((<transform
> (parse-stylesheet-to-stp designator uri-resolver
))
619 (instruction-base-uri (stp:base-uri
<transform
>))
620 (namespaces (acons-namespaces <transform
>))
621 (apply-imports-limit (1+ *import-priority
*))
623 (let ((*namespaces
* namespaces
))
624 (invoke-with-import-magic (constantly t
) <transform
> env
))
625 (do-toplevel (elt "node()" <transform
>)
626 (let ((version (stp:attribute-value
(stp:parent elt
) "version")))
629 (xslt-error "stylesheet lacks version"))
630 ((equal version
"1.0")
631 (if (typep elt
'stp
:element
)
632 (when (or (equal (stp:namespace-uri elt
) "")
633 (and (equal (stp:namespace-uri elt
) *xsl
*)
634 (not (find (stp:local-name elt
)
635 '("key" "template" "output"
636 "strip-space" "preserve-space"
637 "attribute-set" "namespace-alias"
638 "decimal-format" "variable" "param"
640 ;; for include handling:
641 "stylesheet" "transform")
643 (xslt-error "unknown top-level element ~A" (stp:local-name elt
)))
644 (xslt-error "text at top-level"))))))
645 (macrolet ((with-specials ((&optional
) &body body
)
646 `(let ((*instruction-base-uri
* instruction-base-uri
)
647 (*namespaces
* namespaces
)
648 (*apply-imports-limit
* apply-imports-limit
))
651 (do-toplevel (import "import" <transform
>)
652 (when (let ((prev (xpath:first-node
653 (xpath:evaluate
"preceding-sibling::*"
656 (and prev
(not (namep prev
"import"))))
657 (xslt-error "import not at beginning of stylesheet"))
658 (let ((uri (puri:merge-uris
(or (stp:attribute-value import
"href")
659 (xslt-error "import without href"))
660 (stp:base-uri import
))))
661 (push (parse-imported-stylesheet env stylesheet uri uri-resolver
)
663 (let ((import-priority
664 (incf *import-priority
*))
665 (var-cont (prepare-global-variables stylesheet
<transform
>)))
666 (parse-namespace-aliases! stylesheet
<transform
> env
)
667 ;; delay the rest of compilation until we've seen all global
670 (mapc #'funcall
(nreverse continuations
))
672 (let ((*import-priority
* import-priority
))
674 (parse-keys! stylesheet
<transform
> env
)
675 (parse-templates! stylesheet
<transform
> env
)
676 (parse-output! stylesheet
<transform
> env
)
677 (parse-strip/preserve-space
! stylesheet
<transform
> env
)
678 (parse-attribute-sets! stylesheet
<transform
> env
)
679 (parse-decimal-formats! stylesheet
<transform
> env
))))))))
681 (defvar *xsl-import-stack
* nil
)
683 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver
)
684 (let* ((uri (if uri-resolver
685 (funcall uri-resolver uri
)
687 (str (puri:render-uri uri nil
))
690 (uri-to-pathname uri
)
691 (cxml:xml-parse-error
(c)
692 (xslt-error "cannot find imported stylesheet ~A: ~A"
696 :element-type
'(unsigned-byte 8)
697 :if-does-not-exist nil
)
699 (xslt-error "cannot find imported stylesheet ~A at ~A"
701 (when (find str
*xsl-import-stack
* :test
#'equal
)
702 (xslt-error "recursive inclusion of ~A" uri
))
703 (let ((*xsl-import-stack
* (cons str
*xsl-import-stack
*)))
704 (parse-1-stylesheet env stylesheet stream uri-resolver
)))))
706 (defvar *included-attribute-sets
*)
708 (defvar *stylesheet
*)
710 (defun parse-stylesheet (designator &key uri-resolver
)
711 (with-resignalled-errors ()
712 (xpath:with-namespaces
((nil #.
*xsl
*))
713 (let* ((*import-priority
* 0)
714 (xpath:*allow-variables-in-patterns
* nil
)
715 (puri:*strict-parse
* nil
)
716 (stylesheet (make-stylesheet))
718 ;; zzz this is for remove-excluded-namespaces only
720 (env (make-instance 'lexical-xslt-environment
))
721 (*excluded-namespaces
* *excluded-namespaces
*)
722 (*global-variable-declarations
* (make-empty-declaration-array))
723 (*included-attribute-sets
* nil
))
724 (ensure-mode stylesheet nil
)
725 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver
))
726 ;; reverse attribute sets:
727 (let ((table (stylesheet-attribute-sets stylesheet
)))
728 (maphash (lambda (k v
)
729 (setf (gethash k table
) (nreverse v
)))
732 (dolist (sets *included-attribute-sets
*)
733 (loop for
(local-name uri nil
) in sets do
734 (find-attribute-set local-name uri stylesheet
)))
736 (unless (find-decimal-format "" "" stylesheet nil
)
737 (setf (find-decimal-format "" "" stylesheet
)
738 (make-decimal-format)))
739 ;; compile a template matcher for each mode:
741 for mode being each hash-value in
(stylesheet-modes stylesheet
)
743 (setf (mode-match-thunk mode
)
744 (xpath:make-pattern-matcher
745 (mapcar #'template-compiled-pattern
746 (mode-templates mode
)))))
747 ;; and for the strip tests
748 (setf (stylesheet-strip-thunk stylesheet
)
749 (let ((patterns (stylesheet-strip-tests stylesheet
)))
751 (xpath:make-pattern-matcher
752 (mapcar #'strip-test-compiled-pattern patterns
)))))
755 (defun parse-attribute-sets! (stylesheet <transform
> env
)
756 (do-toplevel (elt "attribute-set" <transform
>)
757 (with-import-magic (elt env
)
759 (mapcar (lambda (qname)
760 (multiple-value-list (decode-qname qname env nil
)))
762 (stp:attribute-value elt
"use-attribute-sets"))))
768 (and (typep child
'stp
:element
)
769 (or (and (equal (stp:namespace-uri child
) *xsl
*)
770 (equal (stp:local-name child
)
772 (find (stp:namespace-uri child
)
773 *extension-namespaces
*
775 (xslt-error "non-attribute found in attribute set"))
776 (parse-instruction child
))
778 (*lexical-variable-declarations
*
779 (make-empty-declaration-array))
781 (compile-instruction `(progn ,@instructions
) env
))
782 (n-variables (length *lexical-variable-declarations
*)))
783 (push sets
*included-attribute-sets
*)
786 (loop for
(local-name uri nil
) in sets do
787 (dolist (thunk (find-attribute-set local-name uri
))
788 (funcall thunk ctx
)))
789 (let ((*lexical-variable-values
*
790 (make-variable-value-array n-variables
)))
791 (funcall thunk ctx
)))))
792 (gethash (multiple-value-bind (local-name uri
)
793 (decode-qname (or (stp:attribute-value elt
"name")
794 (xslt-error "missing name"))
797 (cons local-name uri
))
798 (stylesheet-attribute-sets stylesheet
))))))
800 (defun parse-namespace-aliases! (stylesheet <transform
> env
)
801 (do-toplevel (elt "namespace-alias" <transform
>)
802 (let ((*namespaces
* (acons-namespaces elt
)))
803 (only-with-attributes (stylesheet-prefix result-prefix
) elt
804 (unless stylesheet-prefix
805 (xslt-error "missing stylesheet-prefix in namespace-alias"))
806 (unless result-prefix
807 (xslt-error "missing result-prefix in namespace-alias"))
809 (if (equal stylesheet-prefix
"#default")
811 (or (xpath-sys:environment-find-namespace
814 (xslt-error "stylesheet namespace not found in alias: ~A"
816 (stylesheet-namespace-aliases stylesheet
))
817 (or (xpath-sys:environment-find-namespace
819 (if (equal result-prefix
"#default")
822 (xslt-error "result namespace not found in alias: ~A"
825 (defun parse-decimal-formats! (stylesheet <transform
> env
)
826 (do-toplevel (elt "decimal-format" <transform
>)
827 (stp:with-attributes
(name
841 (multiple-value-bind (local-name uri
)
843 (decode-qname name env nil
)
845 (let ((current (find-decimal-format local-name uri stylesheet nil
))
850 (unless (eql (length x
) 1)
851 (xslt-error "not a single character: ~A" x
))
852 (let ((chr (elt x
0)))
853 (when (find chr seen
)
855 "conflicting decimal format characters: ~A"
862 (apply #'make-decimal-format
863 (append (str :infinity infinity
)
865 (chr :decimal-separator decimal-separator
)
866 (chr :grouping-separator grouping-separator
)
867 (chr :zero-digit zero-digit
)
868 (chr :percent percent
)
869 (chr :per-mille per-mille
)
871 (chr :pattern-separator pattern-separator
)
872 (chr :minus-sign minus-sign
)))))))
874 (unless (decimal-format= current new
)
875 (xslt-error "decimal format mismatch for ~S" local-name
))
876 (setf (find-decimal-format local-name uri stylesheet
) new
)))))))
878 (defun parse-exclude-result-prefixes! (node env
)
879 (stp:with-attributes
(exclude-result-prefixes)
881 (dolist (prefix (words (or exclude-result-prefixes
"")))
882 (if (equal prefix
"#default")
884 (unless (cxml-stp-impl::nc-name-p prefix
)
885 (xslt-error "invalid prefix: ~A" prefix
)))
886 (push (or (xpath-sys:environment-find-namespace env prefix
)
887 (xslt-error "namespace not found: ~A" prefix
))
888 *excluded-namespaces
*))))
890 (defun parse-extension-element-prefixes! (node env
)
891 (stp:with-attributes
(extension-element-prefixes)
893 (dolist (prefix (words (or extension-element-prefixes
"")))
894 (if (equal prefix
"#default")
896 (unless (cxml-stp-impl::nc-name-p prefix
)
897 (xslt-error "invalid prefix: ~A" prefix
)))
899 (or (xpath-sys:environment-find-namespace env prefix
)
900 (xslt-error "namespace not found: ~A" prefix
))))
901 (unless (equal uri
*xsl
*)
902 (push uri
*extension-namespaces
*)
903 (push uri
*excluded-namespaces
*))))))
905 (defun parse-nametest-tokens (str)
906 (labels ((check (boolean)
908 (xslt-error "invalid nametest token")))
909 (check-null (boolean)
910 (check (not boolean
))))
913 (mapcar (lambda (name-test)
914 (destructuring-bind (&optional path
&rest junk
)
915 (cdr (xpath:parse-pattern-expression name-test
))
917 (check (eq (car path
) :path
))
918 (destructuring-bind (&optional child
&rest junk
) (cdr path
)
920 (check (eq (car child
) :child
))
921 (destructuring-bind (nodetest &rest junk
) (cdr child
)
923 (check (or (stringp nodetest
)
925 (and (consp nodetest
)
926 (or (eq (car nodetest
) :namespace
)
927 (eq (car nodetest
) :qname
)))))))
931 (defstruct strip-test
937 (defun parse-strip/preserve-space
! (stylesheet <transform
> env
)
939 (do-toplevel (elt "strip-space|preserve-space" <transform
>)
940 (let ((*namespaces
* (acons-namespaces elt
))
942 (if (equal (stp:local-name elt
) "strip-space")
946 (cdr (parse-nametest-tokens
947 (stp:attribute-value elt
"elements"))))
948 (let* ((compiled-pattern
949 (car (without-xslt-current ()
950 (xpath:compute-patterns
951 `(:patterns
,expression
)
956 (make-strip-test :compiled-pattern compiled-pattern
957 :priority
(expression-priority expression
)
960 (setf (xpath:pattern-value compiled-pattern
) strip-test
)
961 (push strip-test
(stylesheet-strip-tests stylesheet
)))))
964 (defstruct (output-specification
965 (:conc-name
"OUTPUT-"))
972 cdata-section-matchers
976 (defun parse-output! (stylesheet <transform
> env
)
977 (dolist (<output
> (list-toplevel "output" <transform
>))
978 (let ((spec (stylesheet-output-specification stylesheet
)))
979 (only-with-attributes (version
988 cdata-section-elements
)
990 (declare (ignore version
))
992 (multiple-value-bind (local-name uri
)
993 (decode-qname method env t
)
994 (setf (output-method spec
)
995 (if (plusp (length uri
))
998 ((equalp local-name
"HTML") :html
)
999 ((equalp local-name
"TEXT") :text
)
1000 ((equalp local-name
"XML") :xml
)
1002 (xslt-error "invalid output method: ~A" method
)))))))
1004 (setf (output-indent spec
) indent
))
1006 (setf (output-encoding spec
) encoding
))
1007 (when doctype-system
1008 (setf (output-doctype-system spec
) doctype-system
))
1009 (when doctype-public
1010 (setf (output-doctype-public spec
) doctype-public
))
1011 (when omit-xml-declaration
1012 (setf (output-omit-xml-declaration spec
) omit-xml-declaration
))
1013 (when cdata-section-elements
1014 (dolist (qname (words cdata-section-elements
))
1015 (decode-qname qname env nil
) ;check the syntax
1016 (push (xpath:make-pattern-matcher
* qname env
)
1017 (output-cdata-section-matchers spec
))))
1019 (setf (output-standalone-p spec
)
1020 (boolean-or-error standalone
)))
1022 (setf (output-media-type spec
) media-type
))))))
1024 (defun make-empty-declaration-array ()
1025 (make-array 1 :fill-pointer
0 :adjustable t
))
1027 (defun make-variable-value-array (n-lexical-variables)
1028 (make-array n-lexical-variables
:initial-element
'unbound
))
1030 (defun compile-global-variable (<variable
> env
) ;; also for <param>
1031 (stp:with-attributes
(name select
) <variable
>
1032 (when (and select
(stp:list-children
<variable
>))
1033 (xslt-error "variable with select and body"))
1034 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1037 (compile-xpath select env
))
1038 ((stp:list-children
<variable
>)
1039 (let* ((inner-sexpr `(progn ,@(parse-body <variable
>)))
1040 (inner-thunk (compile-instruction inner-sexpr env
)))
1042 (apply-to-result-tree-fragment ctx inner-thunk
))))
1045 (declare (ignore ctx
))
1047 (n-lexical-variables (length *lexical-variable-declarations
*)))
1050 (let* ((*lexical-variable-values
*
1051 (make-variable-value-array n-lexical-variables
)))
1052 (funcall inner ctx
)))
1053 "global ~s (~s) = ~s" name select
:result
))))
1055 (defstruct (variable-chain
1056 (:constructor make-variable-chain
)
1057 (:conc-name
"VARIABLE-CHAIN-"))
1064 (defstruct (import-variable
1065 (:constructor make-variable
)
1066 (:conc-name
"VARIABLE-"))
1071 (defun parse-global-variable! (stylesheet <variable
> global-env
)
1072 (let* ((*namespaces
* (acons-namespaces <variable
>))
1073 (instruction-base-uri (stp:base-uri
<variable
>))
1074 (*instruction-base-uri
* instruction-base-uri
)
1075 (*excluded-namespaces
* (list *xsl
*))
1076 (*extension-namespaces
* '())
1077 (qname (stp:attribute-value
<variable
> "name")))
1078 (with-import-magic (<variable
> global-env
)
1080 (xslt-error "name missing in ~A" (stp:local-name
<variable
>)))
1081 (multiple-value-bind (local-name uri
)
1082 (decode-qname qname global-env nil
)
1083 ;; For the normal compilation environment of templates, install it
1084 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
1085 (let ((index (intern-global-variable local-name uri
)))
1086 ;; For the evaluation of a global variable itself, build a thunk
1087 ;; that lazily resolves other variables, stored into
1088 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
1089 (let* ((value-thunk :unknown
)
1090 (sgv (stylesheet-global-variables stylesheet
))
1092 (if (< index
(length sgv
))
1094 (make-variable-chain
1096 :local-name local-name
1098 (next (car (variable-chain-definitions chain
)))
1099 (global-variable-thunk
1101 (let ((v (global-variable-value index nil
)))
1105 (xslt-error "no next definition for: ~A"
1107 (funcall (variable-value-thunk next
) ctx
))
1109 (setf (global-variable-value index
) 'seen
)
1110 (setf (global-variable-value index
)
1111 (funcall value-thunk ctx
)))
1114 (excluded-namespaces *excluded-namespaces
*)
1115 (extension-namespaces *extension-namespaces
*)
1117 (make-variable :param-p
(namep <variable
> "param")))
1118 (forwards-compatible-p *forwards-compatible-p
*)
1121 (let* ((*instruction-base-uri
* instruction-base-uri
)
1122 (*excluded-namespaces
* excluded-namespaces
)
1123 (*extension-namespaces
* extension-namespaces
)
1124 (*forwards-compatible-p
* forwards-compatible-p
)
1126 (compile-global-variable <variable
> global-env
)))
1127 (setf value-thunk fn
)
1128 (setf (variable-value-thunk variable
) fn
)))))
1129 (setf (variable-value-thunk-setter variable
)
1131 (setf (gethash (cons local-name uri
)
1132 (initial-global-variable-thunks global-env
))
1133 global-variable-thunk
)
1134 (setf (variable-chain-thunk chain
) global-variable-thunk
)
1135 (push variable
(variable-chain-definitions chain
))
1138 (defun parse-keys! (stylesheet <transform
> env
)
1139 (xpath:with-namespaces
((nil #.
*xsl
*))
1140 (do-toplevel (<key
> "key" <transform
>)
1141 (with-import-magic (<key
> env
)
1142 (let ((*instruction-base-uri
* (stp:base-uri
<key
>)))
1143 (only-with-attributes (name match use
) <key
>
1144 (unless name
(xslt-error "key name attribute not specified"))
1145 (unless match
(xslt-error "key match attribute not specified"))
1146 (unless use
(xslt-error "key use attribute not specified"))
1147 (multiple-value-bind (local-name uri
)
1148 (decode-qname name env nil
)
1150 (cons local-name uri
)
1151 (compile-xpath `(xpath:xpath
,(parse-key-pattern match
))
1154 (make-instance 'key-environment
))))))))))
1156 (defun prepare-global-variables (stylesheet <transform
>)
1157 (xpath:with-namespaces
((nil #.
*xsl
*))
1158 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet
))
1159 (global-env (make-instance 'global-variable-environment
1160 :initial-global-variable-thunks igvt
))
1162 (do-toplevel (<variable
> "variable|param" <transform
>)
1164 (parse-global-variable! stylesheet
<variable
> global-env
)))
1165 (xslt-trace "parsing global variable ~s (uri ~s)"
1166 (variable-chain-local-name chain
)
1167 (variable-chain-uri chain
))
1171 (and (equal (variable-chain-local-name a
)
1172 (variable-chain-local-name b
))
1173 (equal (variable-chain-uri a
)
1174 (variable-chain-uri b
)))))
1175 (xslt-error "duplicate definition for global variable ~A"
1176 (variable-chain-local-name chain
)))
1177 (push chain chains
)))
1178 (setf chains
(nreverse chains
))
1179 (let ((table (stylesheet-global-variables stylesheet
))
1180 (newlen (length *global-variable-declarations
*)))
1181 (adjust-array table newlen
:fill-pointer newlen
)
1182 (dolist (chain chains
)
1183 (setf (elt table
(variable-chain-index chain
)) chain
)))
1185 ;; now that the global environment knows about all variables, run the
1186 ;; thunk setters to perform their compilation
1187 (mapc (lambda (chain)
1188 (dolist (var (variable-chain-definitions chain
))
1189 (funcall (variable-value-thunk-setter var
))))
1192 (defun parse-templates! (stylesheet <transform
> env
)
1194 (do-toplevel (<template
> "template" <transform
>)
1195 (let ((*namespaces
* (acons-namespaces <template
>))
1196 (*instruction-base-uri
* (stp:base-uri
<template
>)))
1197 (with-import-magic (<template
> env
)
1198 (dolist (template (compile-template <template
> env i
))
1199 (let ((name (template-name template
)))
1201 (let* ((table (stylesheet-named-templates stylesheet
))
1202 (head (car (gethash name table
))))
1203 (when (and head
(eql (template-import-priority head
)
1204 (template-import-priority template
)))
1205 ;; fixme: is this supposed to be a run-time error?
1206 (xslt-error "conflicting templates for ~A" name
))
1207 (push template
(gethash name table
)))
1208 (let ((mode (ensure-mode/qname stylesheet
1209 (template-mode-qname template
)
1211 (setf (template-mode template
) mode
)
1212 (push template
(mode-templates mode
))))))))
1216 ;;;; APPLY-STYLESHEET
1218 (deftype xml-designator
() '(or runes
:xstream runes
:rod array stream pathname
))
1220 (defun unalias-uri (uri)
1222 (gethash uri
(stylesheet-namespace-aliases *stylesheet
*)
1224 (check-type result string
)
1227 (defstruct (parameter
1228 (:constructor make-parameter
(value local-name
&optional uri
)))
1233 (defun find-parameter-value (local-name uri parameters
)
1234 (dolist (p parameters
)
1235 (when (and (equal (parameter-local-name p
) local-name
)
1236 (equal (parameter-uri p
) uri
))
1237 (return (parameter-value p
)))))
1239 (defvar *uri-resolver
*)
1241 (defun parse-allowing-microsoft-bom (pathname handler
)
1242 (with-open-file (s pathname
:element-type
'(unsigned-byte 8))
1243 (unless (and (eql (read-byte s nil
) #xef
)
1244 (eql (read-byte s nil
) #xbb
)
1245 (eql (read-byte s nil
) #xbf
))
1246 (file-position s
0))
1247 (cxml:parse s handler
)))
1249 (defstruct source-document
1252 (indices (make-hash-table)))
1254 (defvar *uri-to-document
*)
1255 (defvar *root-to-document
*)
1257 (defun %document
(uri-string base-uri
)
1258 (let* ((absolute-uri
1259 (puri:merge-uris uri-string
(or base-uri
"")))
1262 (funcall *uri-resolver
* absolute-uri
)
1266 (uri-to-pathname resolved-uri
)
1267 (cxml:xml-parse-error
(c)
1268 (xslt-error "cannot find referenced document ~A: ~A"
1270 (document (gethash pathname
*uri-to-document
*)))
1273 (make-whitespace-stripper
1275 (parse-allowing-microsoft-bom pathname
1277 ((or file-error cxml
:xml-parse-error
) (c)
1278 (xslt-error "cannot parse referenced document ~A: ~A"
1280 (stylesheet-strip-thunk *stylesheet
*)))
1281 (id (hash-table-count *root-to-document
*)))
1282 (setf document
(make-source-document :id id
:root-node root-node
))
1283 (setf (gethash pathname
*uri-to-document
*) document
)
1284 (setf (gethash root-node
*root-to-document
*) document
)))
1285 (when (puri:uri-fragment absolute-uri
)
1286 (xslt-error "use of fragment identifiers in document() not supported"))
1287 (source-document-root-node document
)))
1289 (xpath-sys:define-extension xslt
*xsl
*)
1291 (defun document-base-uri (node)
1292 (xpath-protocol:base-uri
1294 ((xpath-protocol:node-type-p node
:document
)
1295 (xpath::find-in-pipe-if
1297 (xpath-protocol:node-type-p x
:element
))
1298 (xpath-protocol:child-pipe node
)))
1299 ((xpath-protocol:node-type-p node
:element
)
1302 (xpath-protocol:parent-node node
)))))
1304 (xpath-sys:define-xpath-function
/lazy
1306 (object &optional node-set
)
1307 (let ((instruction-base-uri *instruction-base-uri
*))
1309 (let* ((object (funcall object ctx
))
1310 (node-set (and node-set
(funcall node-set ctx
)))
1313 (document-base-uri (xpath::textually-first-node node-set
))
1314 instruction-base-uri
)))
1315 (xpath-sys:make-node-set
1316 (if (xpath:node-set-p object
)
1317 (xpath:map-node-set-
>list
1319 (%document
(xpath:string-value node
)
1322 (document-base-uri node
))))
1324 (list (%document
(xpath:string-value object
) base-uri
))))))))
1327 (defun build-key-index (document key-conses
)
1328 (let ((index (make-hash-table :test
'equal
)))
1329 (dolist (key key-conses
)
1332 (xpath:evaluate-compiled
(key-match key
)
1334 (source-document-root-node document
))))
1335 (let* ((use-result (xpath:evaluate-compiled
(key-use key
) node
))
1336 (uses (if (xpath:node-set-p use-result
)
1337 (xpath:all-nodes use-result
)
1338 (list use-result
))))
1340 (push node
(gethash (xpath:string-value use
) index
))))))
1343 (defun %key
(document key-conses value
)
1344 (let* ((indices (source-document-indices document
))
1345 (index (or (gethash key-conses indices
)
1346 (setf (gethash key-conses indices
)
1347 (build-key-index document key-conses
)))))
1348 (gethash value index
)))
1350 (xpath-sys:define-xpath-function
/lazy xslt
:key
(name object
)
1351 (let ((namespaces *namespaces
*))
1353 (let* ((qname (xpath:string-value
(funcall name ctx
)))
1354 (object (funcall object ctx
))
1356 (multiple-value-bind (local-name uri
)
1357 (decode-qname/runtime qname namespaces nil
)
1358 (cons local-name uri
)))
1359 (key-conses (find-key expanded-name
*stylesheet
*)))
1360 (xpath-sys:make-node-set
1361 (labels ((get-by-key (value)
1362 (%key
(node-to-source-document (xpath:context-node ctx
))
1364 (xpath:string-value value
))))
1366 (if (xpath:node-set-p object
)
1367 (xpath::mappend-pipe
#'get-by-key
(xpath-sys:pipe-of object
))
1368 (get-by-key object
)))))))))
1370 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1372 (xpath-sys:define-xpath-function
/lazy xslt
:current
()
1373 (when *without-xslt-current-p
*
1374 (xslt-error "current() not allowed here"))
1376 (xpath-sys:make-node-set
1377 (xpath-sys:make-pipe
1378 (xpath:context-starting-node ctx
)
1381 (xpath-sys:define-xpath-function
/lazy xslt
:unparsed-entity-uri
(name)
1383 (or (xpath-protocol:unparsed-entity-uri
(xpath:context-node ctx
)
1387 (defun node-to-source-document (node)
1388 (gethash (xpath:first-node
1389 (xpath:evaluate
(xpath:xpath
(:path
(:root
:node
))) node
))
1390 *root-to-document
*))
1392 (defun %get-node-id
(node)
1393 (when (xpath:node-set-p node
)
1394 (setf node
(xpath::textually-first-node node
)))
1397 (source-document-id (node-to-source-document node
))
1398 (xpath-sys:get-node-id node
))))
1400 (xpath-sys:define-xpath-function
/lazy xslt
:generate-id
(&optional node-set-thunk
)
1403 (%get-node-id
(xpath:node-set-value
(funcall node-set-thunk ctx
))))
1405 (%get-node-id
(xpath:context-node ctx
)))))
1407 (declaim (special *builtin-instructions
*))
1409 (xpath-sys:define-xpath-function
/lazy xslt
:element-available
(qname)
1410 (let ((namespaces *namespaces
*)
1411 (extensions *extension-namespaces
*))
1413 (let ((qname (funcall qname ctx
)))
1414 (multiple-value-bind (local-name uri
)
1415 (decode-qname/runtime qname namespaces nil
)
1418 (and (gethash local-name
*builtin-instructions
*) t
))
1419 ((find uri extensions
:test
#'equal
)
1420 (and (find-extension-element local-name uri
) t
))
1424 (xpath-sys:define-xpath-function
/lazy xslt
:function-available
(qname)
1425 (let ((namespaces *namespaces
*))
1427 (let ((qname (funcall qname ctx
)))
1428 (multiple-value-bind (local-name uri
)
1429 (decode-qname/runtime qname namespaces nil
)
1430 (and (zerop (length uri
))
1431 (or (xpath-sys:find-xpath-function local-name
*xsl
*)
1432 (xpath-sys:find-xpath-function local-name uri
))
1435 (xpath-sys:define-xpath-function
/lazy xslt
:system-property
(qname)
1436 (let ((namespaces *namespaces
*))
1438 (let ((qname (xpath:string-value
(funcall qname ctx
))))
1439 (multiple-value-bind (local-name uri
)
1440 (decode-qname/runtime qname namespaces nil
)
1441 (if (equal uri
*xsl
*)
1443 ((equal local-name
"version")
1445 ((equal local-name
"vendor")
1447 ((equal local-name
"vendor-url")
1448 "http://repo.or.cz/w/xuriella.git")
1453 ;; FIXME: should there be separate uri-resolver arguments for stylesheet
1455 (defun apply-stylesheet
1456 (stylesheet source-designator
1457 &key output parameters uri-resolver navigator
)
1458 (when (typep stylesheet
'xml-designator
)
1461 ((cxml:xml-parse-error
1463 (xslt-error "cannot parse stylesheet: ~A" c
))))
1464 (parse-stylesheet stylesheet
:uri-resolver uri-resolver
))))
1465 (with-resignalled-errors ()
1466 (invoke-with-output-sink
1468 (let* ((*uri-to-document
* (make-hash-table :test
'equal
))
1470 ;; fixme? should be xpath-protocol:node-equal
1471 (make-hash-table :test
'equal
))
1472 (xpath:*navigator
* (or navigator
:default-navigator
))
1473 (puri:*strict-parse
* nil
)
1474 (*stylesheet
* stylesheet
)
1475 (*empty-mode
* (make-mode))
1476 (*default-mode
* (find-mode stylesheet nil
))
1477 (global-variable-chains
1478 (stylesheet-global-variables stylesheet
))
1479 (*global-variable-values
*
1480 (make-variable-value-array (length global-variable-chains
)))
1481 (*uri-resolver
* uri-resolver
)
1483 (if (typep source-designator
'xml-designator
)
1484 (cxml:parse source-designator
(stp:make-builder
))
1487 (make-whitespace-stripper
1489 (stylesheet-strip-thunk stylesheet
)))
1490 (ctx (xpath:make-context xpath-root-node
))
1491 (document (make-source-document
1493 :root-node xpath-root-node
)))
1494 (when (pathnamep source-designator
) ;fixme: else use base uri?
1495 (setf (gethash source-designator
*uri-to-document
*) document
))
1496 (setf (gethash xpath-root-node
*root-to-document
*) document
)
1499 (let ((head (car (variable-chain-definitions chain
))))
1500 (when (variable-param-p head
)
1502 (find-parameter-value
1503 (variable-chain-local-name chain
)
1504 (variable-chain-uri chain
)
1507 (setf (global-variable-value
1508 (variable-chain-index chain
))
1510 global-variable-chains
)
1513 (funcall (variable-chain-thunk chain
) ctx
))
1514 global-variable-chains
)
1515 ;; zzz we wouldn't have to mask float traps here if we used the
1516 ;; XPath API properly. Unfortunately I've been using FUNCALL
1517 ;; everywhere instead of EVALUATE, so let's paper over that
1518 ;; at a central place to be sure:
1519 (xpath::with-float-traps-masked
()
1520 (apply-templates ctx
:mode
*default-mode
*))))
1521 (stylesheet-output-specification stylesheet
)
1524 (defun find-attribute-set (local-name uri
&optional
(stylesheet *stylesheet
*))
1525 (or (gethash (cons local-name uri
) (stylesheet-attribute-sets stylesheet
))
1526 (xslt-error "no such attribute set: ~A/~A" local-name uri
)))
1528 (defun apply-templates/list
(list &key param-bindings sort-predicate mode
)
1529 (when sort-predicate
1531 (mapcar #'xpath
:context-node
1532 (stable-sort (contextify-node-list list
)
1534 (let* ((n (length list
))
1535 (s/d
(lambda () n
)))
1540 (apply-templates (xpath:make-context child s
/d i
)
1541 :param-bindings param-bindings
1544 (defvar *stack-limit
* 200)
1546 (defun invoke-with-stack-limit (fn)
1547 (let ((*stack-limit
* (1- *stack-limit
*)))
1548 (unless (plusp *stack-limit
*)
1549 (xslt-error "*stack-limit* reached; stack overflow"))
1552 (defun invoke-template (ctx template param-bindings
)
1553 (let ((*lexical-variable-values
*
1554 (make-variable-value-array (template-n-variables template
))))
1555 (with-stack-limit ()
1557 for
(name-cons value
) in param-bindings
1558 for
(nil index nil
) = (find name-cons
1559 (template-params template
)
1564 (setf (lexical-variable-value index
) value
)))
1565 (funcall (template-body template
) ctx
))))
1567 (defun apply-default-templates (ctx mode
)
1568 (let ((node (xpath:context-node ctx
)))
1570 ((or (xpath-protocol:node-type-p node
:processing-instruction
)
1571 (xpath-protocol:node-type-p node
:comment
)))
1572 ((or (xpath-protocol:node-type-p node
:text
)
1573 (xpath-protocol:node-type-p node
:attribute
))
1574 (write-text (xpath-protocol:node-text node
)))
1576 (apply-templates/list
1578 (xpath-protocol:child-pipe node
))
1581 (defvar *apply-imports
*)
1583 (defun apply-applicable-templates (ctx templates param-bindings finally
)
1584 (labels ((apply-imports (&optional actual-param-bindings
)
1586 (let* ((this (pop templates
))
1587 (low (template-apply-imports-limit this
))
1588 (high (template-import-priority this
)))
1592 (<= low
(template-import-priority x
) high
))
1594 (invoke-template ctx this actual-param-bindings
))
1595 (funcall finally
))))
1596 (let ((*apply-imports
* #'apply-imports
))
1597 (apply-imports param-bindings
))))
1599 (defun apply-templates (ctx &key param-bindings mode
)
1600 (apply-applicable-templates ctx
1601 (find-templates ctx
(or mode
*default-mode
*))
1604 (apply-default-templates ctx mode
))))
1606 (defun call-template (ctx name
&optional param-bindings
)
1607 (apply-applicable-templates ctx
1608 (find-named-templates name
)
1611 (xslt-error "cannot find named template: ~s"
1614 (defun find-templates (ctx mode
)
1615 (let* ((matching-candidates
1616 (xpath:matching-values
(mode-match-thunk mode
)
1617 (xpath:context-node ctx
)))
1619 (if matching-candidates
1622 :key
#'template-import-priority
))
1624 (priority-groups (make-array npriorities
:initial-element nil
)))
1625 (dolist (template matching-candidates
)
1627 (elt priority-groups
(template-import-priority template
))))
1629 for i from
(1- npriorities
) downto
0
1630 for group
= (elt priority-groups i
)
1631 for template
= (maximize #'template
< group
)
1635 (defun find-named-templates (name)
1636 (gethash name
(stylesheet-named-templates *stylesheet
*)))
1638 (defun template< (a b
) ;assuming same import priority
1639 (let ((p (template-priority a
))
1640 (q (template-priority b
)))
1645 (xslt-cerror "conflicting templates:~_~A,~_~A"
1646 (template-match-expression a
)
1647 (template-match-expression b
))
1648 (< (template-position a
) (template-position b
))))))
1650 (defun maximize (< things
)
1652 (let ((max (car things
)))
1653 (dolist (other (cdr things
))
1654 (when (funcall < max other
)
1658 (defun invoke-with-output-sink (fn output-spec output
)
1661 (with-open-file (s output
1663 :element-type
'(unsigned-byte 8)
1664 :if-exists
:rename-and-delete
)
1665 (invoke-with-output-sink fn output-spec s
)))
1667 (invoke-with-output-sink fn
1669 (make-output-sink output-spec output
)))
1670 ((or hax
:abstract-handler sax
:abstract-handler
)
1671 (with-xml-output output
1672 (when (typep output
'(or combi-sink auto-detect-sink
))
1673 (sax:start-dtd output
1674 :autodetect-me-please
1675 (output-doctype-public output-spec
)
1676 (output-doctype-system output-spec
)))
1679 (defun make-output-sink (output-spec stream
)
1682 (let ((et (stream-element-type stream
)))
1684 ((or (null et
) (subtypep et
'(unsigned-byte 8)))
1685 (runes:make-octet-stream-ystream stream
))
1686 ((subtypep et
'character
)
1687 (runes:make-character-stream-ystream stream
))))
1688 (runes:make-rod-ystream
)))
1689 (omit-xml-declaration-p
1690 (boolean-or-error (output-omit-xml-declaration output-spec
)))
1691 (sink-encoding (or (output-encoding output-spec
) "UTF-8"))
1694 (setf (runes:ystream-encoding ystream
)
1695 (cxml::find-output-encoding sink-encoding
))
1696 (make-instance 'cxml
::sink
1698 :omit-xml-declaration-p omit-xml-declaration-p
1699 :encoding sink-encoding
))))
1700 (flet ((make-combi-sink ()
1701 (make-instance 'combi-sink
1702 :hax-target
(make-instance 'chtml
::sink
1704 :sax-target sax-target
1705 :media-type
(output-media-type output-spec
)
1706 :encoding sink-encoding
)))
1707 (let ((method-key (output-method output-spec
)))
1709 ((and (eq method-key
:html
)
1710 (null (output-doctype-system output-spec
))
1711 (null (output-doctype-public output-spec
)))
1713 ((eq method-key
:text
)
1714 (make-text-filter sax-target
))
1715 ((and (eq method-key
:xml
)
1716 (null (output-doctype-system output-spec
)))
1719 (make-auto-detect-sink (make-combi-sink) method-key
)))))))
1735 (defun expression-priority (form)
1736 (let ((step (second form
)))
1737 (if (and (null (cddr form
))
1739 (member (car step
) '(:child
:attribute
))
1741 (let ((name (second step
)))
1745 (or (eq (car name
) :qname
)
1746 (eq (car name
) :processing-instruction
))))
1749 (or (eq (car name
) :namespace
)
1750 (eq (car name
) '*)))
1756 (defun parse-key-pattern (str)
1757 (with-resignalled-errors ()
1758 (with-forward-compatible-errors
1759 (xpath:parse-xpath
"compile-time-error()") ;hack
1761 (mapcar #'(lambda (item)
1762 `(:path
(:root
:node
)
1763 (:descendant-or-self
:node
)
1765 (cdr (xpath::parse-pattern-expression str
)))))
1766 (if (null (rest parsed
))
1768 `(:union
,@parsed
))))))
1770 (defun compile-value-thunk (value env
)
1771 (if (and (listp value
) (eq (car value
) 'progn
))
1772 (let ((inner-thunk (compile-instruction value env
)))
1774 (apply-to-result-tree-fragment ctx inner-thunk
)))
1775 (compile-xpath value env
)))
1777 (defun compile-var-binding (name value env
)
1778 (multiple-value-bind (local-name uri
)
1779 (decode-qname name env nil
)
1780 (let ((thunk (xslt-trace-thunk
1781 (compile-value-thunk value env
)
1782 "local variable ~s = ~s" name
:result
)))
1783 (list (cons local-name uri
)
1784 (push-variable local-name
1786 *lexical-variable-declarations
*)
1789 (defun compile-var-bindings (forms env
)
1791 for
(name value
) in forms
1792 collect
(compile-var-binding name value env
)))
1794 (defmacro sometimes-with-attributes
((&rest attrs
) node
&body body
)
1797 (if *forwards-compatible-p
*
1798 (stp:with-attributes
(,@attrs
) ,x
,@body
)
1799 (only-with-attributes (,@attrs
) ,x
,@body
)))))
1801 (defun compile-template (<template
> env position
)
1802 (sometimes-with-attributes (match name priority mode
) <template
>
1803 (unless (or name match
)
1804 (xslt-error "missing match in template"))
1805 (multiple-value-bind (params body-pos
)
1808 for child in
(stp:list-children
<template
>)
1809 while
(namep child
"param")
1810 collect
(parse-param child
) into params
1811 finally
(return (values params i
)))
1812 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1813 (param-bindings (compile-var-bindings params env
))
1814 (body (parse-body <template
> body-pos
(mapcar #'car params
)))
1815 (body-thunk (compile-instruction `(progn ,@body
) env
))
1821 ;; set params that weren't initialized by apply-templates
1822 (loop for
(name index param-thunk
) in param-bindings
1823 when
(eq (lexical-variable-value index nil
) 'unbound
)
1824 do
(setf (lexical-variable-value index
)
1825 (funcall param-thunk ctx
)))
1826 (funcall body-thunk ctx
))))
1827 "template: match = ~s name = ~s" match name
))
1828 (n-variables (length *lexical-variable-declarations
*)))
1831 (multiple-value-bind (local-name uri
)
1832 (decode-qname name env nil
)
1834 (make-template :name
(cons local-name uri
)
1835 :import-priority
*import-priority
*
1836 :apply-imports-limit
*apply-imports-limit
*
1837 :params param-bindings
1838 :body outer-body-thunk
1839 :n-variables n-variables
))))
1841 (mapcar (lambda (expression)
1842 (let* ((compiled-pattern
1844 (car (without-xslt-current ()
1845 (xpath:compute-patterns
1846 `(:patterns
,expression
)
1850 "match-thunk for template (match ~s): ~s --> ~s"
1851 match expression
:result
))
1853 (xpath::parse-xnum priority
)
1854 (expression-priority expression
)))
1857 (unless (and (numberp p
)
1858 (not (xpath::inf-p p
))
1859 (not (xpath::nan-p p
)))
1860 (xslt-error "failed to parse priority"))
1863 (make-template :match-expression expression
1864 :compiled-pattern compiled-pattern
1865 :import-priority
*import-priority
*
1866 :apply-imports-limit
*apply-imports-limit
*
1870 :params param-bindings
1871 :body outer-body-thunk
1872 :n-variables n-variables
)))
1873 (setf (xpath:pattern-value compiled-pattern
)
1876 (cdr (xpath:parse-pattern-expression match
)))))))))
1878 (xuriella::parse-stylesheet
#p
"/home/david/src/lisp/xuriella/test.xsl")