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
)))
110 ;;;; Helper functions and macros
112 (defun check-for-invalid-attributes (valid-names node
)
113 (labels ((check-attribute (a)
115 (let ((uri (stp:namespace-uri a
)))
116 (or (and (plusp (length uri
)) (not (equal uri
*xsl
*)))
117 (find (cons (stp:local-name a
) uri
)
120 (xslt-error "attribute ~A not allowed on ~A"
122 (stp:local-name node
)))))
123 (stp:map-attributes nil
#'check-attribute node
)))
125 (defmacro only-with-attributes
((&rest specs
) node
&body body
)
127 (mapcar (lambda (entry)
128 (if (and (listp entry
) (cdr entry
))
129 (destructuring-bind (name &optional
(uri ""))
132 (cons (string-downcase
134 (symbol-name entry
)))
138 `(let ((,%NODE
,node
))
139 (check-for-invalid-attributes ',valid-names
,%NODE
)
140 (stp:with-attributes
,specs
,%NODE
143 (defun map-pipe-eagerly (fn pipe
)
144 (xpath::enumerate pipe
:key fn
:result nil
))
146 (defmacro do-pipe
((var pipe
&optional result
) &body body
)
148 (map-pipe-eagerly #'(lambda (,var
) ,@body
) ,pipe
)
152 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
154 (defparameter *namespaces
*
156 ("xmlns" .
#"http://www.w3.org/2000/xmlns/")
157 ("xml" .
#"http://www.w3.org/XML/1998/namespace")))
159 (defvar *global-variable-declarations
*)
160 (defvar *lexical-variable-declarations
*)
162 (defvar *global-variable-values
*)
163 (defvar *lexical-variable-values
*)
165 (defclass xslt-environment
() ())
167 (defun split-qname (str)
169 (multiple-value-bind (prefix local-name
)
170 (cxml::split-qname str
)
172 ;; FIXME: cxml should really offer a function that does
173 ;; checks for NCName and QName in a sensible way for user code.
174 ;; cxml::split-qname is tailored to the needs of the parser.
176 ;; For now, let's just check the syntax explicitly.
177 (and (or (null prefix
) (xpath::nc-name-p prefix
))
178 (xpath::nc-name-p local-name
))
179 (xslt-error "not a qname: ~A" str
))
180 (values prefix local-name
))
181 (cxml:well-formedness-violation
()
182 (xslt-error "not a qname: ~A" str
))))
184 (defun decode-qname (qname env attributep
)
185 (multiple-value-bind (prefix local-name
)
188 (if (or prefix
(not attributep
))
189 (xpath-sys:environment-find-namespace env
(or prefix
""))
193 (defmethod xpath-sys:environment-find-namespace
((env xslt-environment
) prefix
)
194 (or (cdr (assoc prefix
*namespaces
* :test
'equal
))
196 ;; Change the entire code base to represent "no prefix" as the
197 ;; empty string consistently. unparse.lisp has already been changed.
198 (and (equal prefix
"")
199 (cdr (assoc nil
*namespaces
* :test
'equal
)))
200 (and (eql prefix nil
)
201 (cdr (assoc "" *namespaces
* :test
'equal
)))))
203 (defun find-variable-index (local-name uri table
)
204 (position (cons local-name uri
) table
:test
'equal
))
206 (defun intern-global-variable (local-name uri
)
207 (or (find-variable-index local-name uri
*global-variable-declarations
*)
208 (push-variable local-name uri
*global-variable-declarations
*)))
210 (defun push-variable (local-name uri table
)
213 (vector-push-extend (cons local-name uri
) table
)))
215 (defun lexical-variable-value (index &optional
(errorp t
))
216 (let ((result (svref *lexical-variable-values
* index
)))
218 (assert (not (eq result
'unbound
))))
221 (defun (setf lexical-variable-value
) (newval index
)
222 (assert (not (eq newval
'unbound
)))
223 (setf (svref *lexical-variable-values
* index
) newval
))
225 (defun global-variable-value (index &optional
(errorp t
))
226 (let ((result (svref *global-variable-values
* index
)))
228 (assert (not (eq result
'unbound
))))
231 (defun (setf global-variable-value
) (newval index
)
232 (assert (not (eq newval
'unbound
)))
233 (setf (svref *global-variable-values
* index
) newval
))
235 (defmethod xpath-sys:environment-find-function
236 ((env xslt-environment
) lname uri
)
238 (or (xpath-sys:find-xpath-function lname
*xsl
*)
239 (xpath-sys:find-xpath-function lname uri
))
240 (xpath-sys:find-xpath-function lname uri
)))
242 (defmethod xpath-sys:environment-find-variable
243 ((env xslt-environment
) lname uri
)
245 (find-variable-index lname uri
*lexical-variable-declarations
*)))
248 (declare (ignore ctx
))
249 (svref *lexical-variable-values
* index
)))))
251 (defclass lexical-xslt-environment
(xslt-environment) ())
253 (defmethod xpath-sys:environment-find-variable
254 ((env lexical-xslt-environment
) lname uri
)
255 (or (call-next-method)
257 (find-variable-index lname uri
*global-variable-declarations
*)))
261 (declare (ignore ctx
))
262 (svref *global-variable-values
* index
))
263 "global ~s (uri ~s) = ~s" lname uri
:result
)))))
265 (defclass global-variable-environment
(xslt-environment)
266 ((initial-global-variable-thunks
267 :initarg
:initial-global-variable-thunks
268 :accessor initial-global-variable-thunks
)))
270 (defmethod xpath-sys:environment-find-variable
271 ((env global-variable-environment
) lname uri
)
272 (or (call-next-method)
273 (gethash (cons lname uri
) (initial-global-variable-thunks env
))))
276 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
278 ;;;; A sink that serializes only text not contained in any element.
280 (defmacro with-toplevel-text-output-sink
((var) &body body
)
281 `(invoke-with-toplevel-text-output-sink (lambda (,var
) ,@body
)))
283 (defclass toplevel-text-output-sink
(sax:default-handler
)
284 ((target :initarg
:target
:accessor text-output-sink-target
)
285 (depth :initform
0 :accessor textoutput-sink-depth
)))
287 (defmethod sax:start-element
((sink toplevel-text-output-sink
)
288 namespace-uri local-name qname attributes
)
289 (declare (ignore namespace-uri local-name qname attributes
))
290 (incf (textoutput-sink-depth sink
)))
292 (defmethod sax:characters
((sink toplevel-text-output-sink
) data
)
293 (when (zerop (textoutput-sink-depth sink
))
294 (write-string data
(text-output-sink-target sink
))))
296 (defmethod sax:unescaped
((sink toplevel-text-output-sink
) data
)
297 (sax:characters sink data
))
299 (defmethod sax:end-element
((sink toplevel-text-output-sink
)
300 namespace-uri local-name qname
)
301 (declare (ignore namespace-uri local-name qname
))
302 (decf (textoutput-sink-depth sink
)))
304 (defun invoke-with-toplevel-text-output-sink (fn)
305 (with-output-to-string (s)
306 (funcall fn
(make-instance 'toplevel-text-output-sink
:target s
))))
311 ;;;; A sink that passes through only text (at any level) and turns to
312 ;;;; into unescaped characters.
314 (defclass text-filter
(sax:default-handler
)
315 ((target :initarg
:target
:accessor text-filter-target
)))
317 (defmethod sax:characters
((sink text-filter
) data
)
318 (sax:unescaped
(text-filter-target sink
) data
))
320 (defmethod sax:unescaped
((sink text-filter
) data
)
321 (sax:unescaped
(text-filter-target sink
) data
))
323 (defmethod sax:end-document
((sink text-filter
))
324 (sax:end-document
(text-filter-target sink
)))
326 (defun make-text-filter (target)
327 (make-instance 'text-filter
:target target
))
332 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
335 (defclass escaper
(cxml:broadcast-handler
)
338 (defmethod sax:unescaped
((sink escaper
) data
)
339 (sax:characters sink data
))
341 (defun make-escaper (target)
342 (make-instance 'escaper
:handlers
(list target
)))
347 (defun of-name (local-name)
348 (stp:of-name local-name
*xsl
*))
350 (defun namep (node local-name
)
351 (and (typep node
'(or stp
:element stp
:attribute
))
352 (equal (stp:namespace-uri node
) *xsl
*)
353 (equal (stp:local-name node
) local-name
)))
356 ;;;; PARSE-STYLESHEET
358 (defstruct stylesheet
359 (modes (make-hash-table :test
'equal
))
360 (global-variables (make-empty-declaration-array))
361 (output-specification (make-output-specification))
363 (named-templates (make-hash-table :test
'equal
))
364 (attribute-sets (make-hash-table :test
'equal
))
365 (keys (make-hash-table :test
'equal
))
366 (namespace-aliases (make-hash-table :test
'equal
))
367 (decimal-formats (make-hash-table :test
'equal
))
368 (initial-global-variable-thunks (make-hash-table :test
'equal
)))
372 (match-thunk (lambda (ignore) (declare (ignore ignore
)) nil
)))
374 (defun find-mode (stylesheet local-name
&optional uri
)
375 (gethash (cons local-name uri
) (stylesheet-modes stylesheet
)))
377 (defun ensure-mode (stylesheet &optional local-name uri
)
378 (or (find-mode stylesheet local-name uri
)
379 (setf (gethash (cons local-name uri
) (stylesheet-modes stylesheet
))
382 (defun ensure-mode/qname
(stylesheet qname env
)
384 (multiple-value-bind (local-name uri
)
385 (decode-qname qname env nil
)
386 (ensure-mode stylesheet local-name uri
))
387 (find-mode stylesheet nil
)))
389 (defun acons-namespaces (element &optional
(bindings *namespaces
*))
390 (map-namespace-declarations (lambda (prefix uri
)
391 (push (cons prefix uri
) bindings
))
395 (defun find-key (name stylesheet
)
396 (or (gethash name
(stylesheet-keys stylesheet
))
397 (xslt-error "unknown key: ~a" name
)))
399 (defun make-key (match use
) (cons match use
))
401 (defun key-match (key) (car key
))
403 (defun key-use (key) (cdr key
))
405 (defun add-key (stylesheet name match use
)
406 (if (gethash name
(stylesheet-keys stylesheet
))
407 (xslt-error "duplicate key: ~a" name
)
408 (setf (gethash name
(stylesheet-keys stylesheet
))
409 (make-key match use
))))
411 (defvar *excluded-namespaces
* (list *xsl
*))
412 (defvar *empty-mode
*)
413 (defvar *default-mode
*)
415 (defvar *xsl-include-stack
* nil
)
417 (defun uri-to-pathname (uri)
418 (cxml::uri-to-pathname
(puri:parse-uri uri
)))
420 (defun unwrap-2.3
(document)
421 (let ((literal-result-element (stp:document-element document
))
422 (new-template (stp:make-element
"template" *xsl
*))
423 (new-document-element (stp:make-element
"stylesheet" *xsl
*)))
424 (setf (stp:attribute-value new-document-element
"version")
425 (or (stp:attribute-value literal-result-element
"version" *xsl
*)
426 (xslt-error "not a stylesheet: root element lacks xsl:version")))
427 (setf (stp:attribute-value new-template
"match") "/")
428 (setf (stp:document-element document
) new-document-element
)
429 (stp:append-child new-document-element new-template
)
430 (stp:append-child new-template literal-result-element
)
431 new-document-element
))
433 (defun parse-stylesheet-to-stp (input uri-resolver
)
434 (let* ((d (cxml:parse input
(make-text-normalizer (cxml-stp:make-builder
))))
435 (<transform
> (stp:document-element d
)))
436 (unless (equal (stp:namespace-uri
<transform
>) *xsl
*)
437 (setf <transform
> (unwrap-2.3 d
)))
438 (strip-stylesheet <transform
>)
439 (unless (and (equal (stp:namespace-uri
<transform
>) *xsl
*)
440 (or (equal (stp:local-name
<transform
>) "transform")
441 (equal (stp:local-name
<transform
>) "stylesheet")))
442 (xslt-error "not a stylesheet"))
443 (check-for-invalid-attributes '(("version" .
"")
444 ("exclude-result-prefixes" .
"")
445 ("extension-element-prefixes" .
""))
448 (or (stp:find-child-if
(of-name "stylesheet") <transform
>)
449 (stp:find-child-if
(of-name "transform") <transform
>))))
451 (xslt-error "invalid top-level element ~A" (stp:local-name invalid
))))
452 (dolist (include (stp:filter-children
(of-name "include") <transform
>))
453 (let* ((uri (puri:merge-uris
(stp:attribute-value include
"href")
454 (stp:base-uri include
)))
455 (uri (if uri-resolver
456 (funcall uri-resolver
(puri:render-uri uri nil
))
458 (str (puri:render-uri uri nil
))
461 (uri-to-pathname uri
)
462 (cxml:xml-parse-error
(c)
463 (xslt-error "cannot find included stylesheet ~A: ~A"
467 :element-type
'(unsigned-byte 8)
468 :if-does-not-exist nil
)
470 (xslt-error "cannot find included stylesheet ~A at ~A"
472 (when (find str
*xsl-include-stack
* :test
#'equal
)
473 (xslt-error "recursive inclusion of ~A" uri
))
474 (let* ((*xsl-include-stack
* (cons str
*xsl-include-stack
*))
475 (<transform
>2 (parse-stylesheet-to-stp stream uri-resolver
)))
476 (stp:insert-child-after
<transform
>
477 (stp:copy
<transform
>2)
479 (stp:detach include
)))))
482 (defvar *instruction-base-uri
*) ;misnamed, is also used in other attributes
483 (defvar *apply-imports-limit
*)
484 (defvar *import-priority
*)
485 (defvar *extension-namespaces
*)
486 (defvar *forwards-compatible-p
*)
488 (defmacro do-toplevel
((var xpath
<transform
>) &body body
)
489 `(map-toplevel (lambda (,var
) ,@body
) ,xpath
,<transform
>))
491 (defun map-toplevel (fn xpath
<transform
>)
492 (dolist (node (list-toplevel xpath
<transform
>))
493 (let ((*namespaces
* *namespaces
*))
494 (xpath:do-node-set
(ancestor (xpath:evaluate
"ancestor::node()" node
))
495 (when (xpath-protocol:node-type-p ancestor
:element
)
496 (setf *namespaces
* (acons-namespaces ancestor
))))
499 (defun list-toplevel (xpath <transform
>)
500 (labels ((recurse (sub)
503 (xpath:evaluate
"transform|stylesheet" sub
))))
505 (xpath-sys:pipe-of
(xpath:evaluate xpath sub
))
506 (xpath::mappend-pipe
#'recurse subsubs
)))))
507 (xpath::sort-nodes
(recurse <transform
>))))
509 (defmacro with-import-magic
((node env
) &body body
)
510 `(invoke-with-import-magic (lambda () ,@body
) ,node
,env
))
512 (defun invoke-with-import-magic (fn node env
)
513 (unless (or (namep node
"stylesheet") (namep node
"transform"))
514 (setf node
(stp:parent node
)))
515 (let ((*excluded-namespaces
* (list *xsl
*))
516 (*extension-namespaces
* '())
517 (*forwards-compatible-p
*
518 (not (equal (stp:attribute-value node
"version") "1.0"))))
519 (parse-exclude-result-prefixes! node env
)
520 (parse-extension-element-prefixes! node env
)
523 (defun parse-1-stylesheet (env stylesheet designator uri-resolver
)
524 (let* ((<transform
> (parse-stylesheet-to-stp designator uri-resolver
))
525 (instruction-base-uri (stp:base-uri
<transform
>))
526 (namespaces (acons-namespaces <transform
>))
527 (apply-imports-limit (1+ *import-priority
*))
529 (let ((*namespaces
* namespaces
))
530 (invoke-with-import-magic (constantly t
) <transform
> env
))
531 (do-toplevel (elt "node()" <transform
>)
532 (when (equal (stp:attribute-value
(stp:parent elt
) "version") "1.0")
533 (if (typep elt
'stp
:element
)
534 (when (or (equal (stp:namespace-uri elt
) "")
535 (and (equal (stp:namespace-uri elt
) *xsl
*)
536 (not (find (stp:local-name elt
)
537 '("key" "template" "output" "strip-space"
538 "preserve-space" "attribute-set"
539 "namespace-alias" "decimal-format"
540 "variable" "param" "import" "include"
541 ;; for include handling:
542 "stylesheet" "transform")
544 (xslt-error "unknown top-level element ~A" (stp:local-name elt
)))
545 (xslt-error "text at top-level"))))
546 (macrolet ((with-specials ((&optional
) &body body
)
547 `(let ((*instruction-base-uri
* instruction-base-uri
)
548 (*namespaces
* namespaces
)
549 (*apply-imports-limit
* apply-imports-limit
))
552 (do-toplevel (import "import" <transform
>)
553 (let ((uri (puri:merge-uris
(stp:attribute-value import
"href")
554 (stp:base-uri import
))))
555 (push (parse-imported-stylesheet env stylesheet uri uri-resolver
)
557 (let ((import-priority
558 (incf *import-priority
*))
559 (var-cont (prepare-global-variables stylesheet
<transform
>)))
560 ;; delay the rest of compilation until we've seen all global
563 (mapc #'funcall
(nreverse continuations
))
565 (let ((*import-priority
* import-priority
))
567 (parse-keys! stylesheet
<transform
> env
)
568 (parse-templates! stylesheet
<transform
> env
)
569 (parse-output! stylesheet
<transform
>)
570 (parse-strip/preserve-space
! stylesheet
<transform
> env
)
571 (parse-attribute-sets! stylesheet
<transform
> env
)
572 (parse-namespace-aliases! stylesheet
<transform
> env
)
573 (parse-decimal-formats! stylesheet
<transform
> env
))))))))
575 (defvar *xsl-import-stack
* nil
)
577 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver
)
578 (let* ((uri (if uri-resolver
579 (funcall uri-resolver
(puri:render-uri uri nil
))
581 (str (puri:render-uri uri nil
))
584 (uri-to-pathname uri
)
585 (cxml:xml-parse-error
(c)
586 (xslt-error "cannot find imported stylesheet ~A: ~A"
590 :element-type
'(unsigned-byte 8)
591 :if-does-not-exist nil
)
593 (xslt-error "cannot find imported stylesheet ~A at ~A"
595 (when (find str
*xsl-import-stack
* :test
#'equal
)
596 (xslt-error "recursive inclusion of ~A" uri
))
597 (let ((*xsl-import-stack
* (cons str
*xsl-import-stack
*)))
598 (parse-1-stylesheet env stylesheet stream uri-resolver
)))))
600 (defun parse-stylesheet (designator &key uri-resolver
)
601 (with-resignalled-errors ()
602 (xpath:with-namespaces
((nil #.
*xsl
*))
603 (let* ((*import-priority
* 0)
604 (xpath:*allow-variables-in-patterns
* nil
)
605 (puri:*strict-parse
* nil
)
606 (stylesheet (make-stylesheet))
607 (env (make-instance 'lexical-xslt-environment
))
608 (*excluded-namespaces
* *excluded-namespaces
*)
609 (*global-variable-declarations
* (make-empty-declaration-array)))
610 (ensure-mode stylesheet nil
)
611 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver
))
612 ;; reverse attribute sets:
613 (let ((table (stylesheet-attribute-sets stylesheet
)))
614 (maphash (lambda (k v
)
615 (setf (gethash k table
) (nreverse v
)))
618 (unless (find-decimal-format "" "" stylesheet nil
)
619 (setf (find-decimal-format "" "" stylesheet
)
620 (make-decimal-format)))
621 ;; compile a template matcher for each mode:
623 for mode being each hash-value in
(stylesheet-modes stylesheet
)
625 (setf (mode-match-thunk mode
)
626 (xpath:make-pattern-matcher
627 (mapcar #'template-compiled-pattern
628 (mode-templates mode
)))))
631 (defun parse-attribute-sets! (stylesheet <transform
> env
)
632 (do-toplevel (elt "attribute-set" <transform
>)
633 (with-import-magic (elt env
)
635 (mapcar (lambda (qname)
636 (multiple-value-list (decode-qname qname env nil
)))
638 (stp:attribute-value elt
"use-attribute-sets"))))
644 (and (typep child
'stp
:element
)
645 (or (and (equal (stp:namespace-uri child
) *xsl
*)
646 (equal (stp:local-name child
)
648 (find (stp:namespace-uri child
)
649 *extension-namespaces
*
651 (xslt-error "non-attribute found in attribute set"))
652 (parse-instruction child
))
654 (*lexical-variable-declarations
*
655 (make-empty-declaration-array))
657 (compile-instruction `(progn ,@instructions
) env
))
658 (n-variables (length *lexical-variable-declarations
*)))
661 (loop for
(local-name uri nil
) in sets do
662 (dolist (thunk (find-attribute-set local-name uri
))
663 (funcall thunk ctx
)))
664 (let ((*lexical-variable-values
*
665 (make-variable-value-array n-variables
)))
666 (funcall thunk ctx
)))))
667 (gethash (multiple-value-bind (local-name uri
)
668 (decode-qname (stp:attribute-value elt
"name") env nil
)
669 (cons local-name uri
))
670 (stylesheet-attribute-sets stylesheet
))))))
672 (defun parse-namespace-aliases! (stylesheet <transform
> env
)
673 (do-toplevel (elt "namespace-alias" <transform
>)
674 (stp:with-attributes
(stylesheet-prefix result-prefix
) elt
676 (if (equal stylesheet-prefix
"#default")
678 (xpath-sys:environment-find-namespace env stylesheet-prefix
))
679 (stylesheet-namespace-aliases stylesheet
))
680 (xpath-sys:environment-find-namespace
682 (if (equal result-prefix
"#default")
686 (defun parse-decimal-formats! (stylesheet <transform
> env
)
687 (do-toplevel (elt "decimal-format" <transform
>)
688 (stp:with-attributes
(name
702 (multiple-value-bind (local-name uri
)
704 (decode-qname name env nil
)
706 (let ((current (find-decimal-format local-name uri stylesheet nil
))
711 (unless (eql (length x
) 1)
712 (xslt-error "not a single character: ~A" x
))
713 (let ((chr (elt x
0)))
714 (when (find chr seen
)
716 "conflicting decimal format characters: ~A"
723 (apply #'make-decimal-format
724 (append (str :infinity infinity
)
726 (chr :decimal-separator decimal-separator
)
727 (chr :grouping-separator grouping-separator
)
728 (chr :zero-digit zero-digit
)
729 (chr :percent percent
)
730 (chr :per-mille per-mille
)
732 (chr :pattern-separator pattern-separator
)
733 (chr :minus-sign minus-sign
)))))))
735 (unless (decimal-format= current new
)
736 (xslt-error "decimal format mismatch for ~S" local-name
))
737 (setf (find-decimal-format local-name uri stylesheet
) new
)))))))
739 (defun parse-exclude-result-prefixes! (node env
)
740 (stp:with-attributes
(exclude-result-prefixes)
742 (dolist (prefix (words (or exclude-result-prefixes
"")))
743 (if (equal prefix
"#default")
745 (unless (cxml-stp-impl::nc-name-p prefix
)
746 (xslt-error "invalid prefix: ~A" prefix
)))
747 (push (or (xpath-sys:environment-find-namespace env prefix
)
748 (xslt-error "namespace not found: ~A" prefix
))
749 *excluded-namespaces
*))))
751 (defun parse-extension-element-prefixes! (node env
)
752 (stp:with-attributes
(extension-element-prefixes)
754 (dolist (prefix (words (or extension-element-prefixes
"")))
755 (if (equal prefix
"#default")
757 (unless (cxml-stp-impl::nc-name-p prefix
)
758 (xslt-error "invalid prefix: ~A" prefix
)))
760 (or (xpath-sys:environment-find-namespace env prefix
)
761 (xslt-error "namespace not found: ~A" prefix
))))
762 (unless (equal uri
*xsl
*)
763 (push uri
*extension-namespaces
*)
764 (push uri
*excluded-namespaces
*))))))
766 (defun parse-strip/preserve-space
! (stylesheet <transform
> env
)
767 (xpath:with-namespaces
((nil #.
*xsl
*))
768 (do-toplevel (elt "strip-space|preserve-space" <transform
>)
769 (let ((*namespaces
* (acons-namespaces elt
))
771 (if (equal (stp:local-name elt
) "strip-space")
774 (dolist (name-test (words (stp:attribute-value elt
"elements")))
775 (let* ((pos (search ":*" name-test
))
778 ((eql pos
(- (length name-test
) 2))
779 (let* ((prefix (subseq name-test
0 pos
))
781 (xpath-sys:environment-find-namespace env prefix
)))
782 (unless (xpath::nc-name-p prefix
)
783 (xslt-error "not an NCName: ~A" prefix
))
784 (lambda (local-name uri
)
785 (declare (ignore local-name
))
786 (if (equal uri name-test-uri
)
789 ((equal name-test
"*")
790 (lambda (local-name uri
)
791 (declare (ignore local-name uri
))
794 (multiple-value-bind (name-test-local-name name-test-uri
)
795 (decode-qname name-test env nil
)
796 (lambda (local-name uri
)
797 (if (and (equal local-name name-test-local-name
)
798 (equal uri name-test-uri
))
801 (push test-function
(stylesheet-strip-tests stylesheet
))))))))
803 (defstruct (output-specification
804 (:conc-name
"OUTPUT-"))
812 (defun parse-output! (stylesheet <transform
>)
813 (dolist (<output
> (list-toplevel "output" <transform
>))
814 (let ((spec (stylesheet-output-specification stylesheet
)))
815 (stp:with-attributes
( ;; version
824 ;;; cdata-section-elements
828 (setf (output-method spec
) method
))
830 (setf (output-indent spec
) indent
))
832 (setf (output-encoding spec
) encoding
))
834 (setf (output-doctype-system spec
) doctype-system
))
836 (setf (output-doctype-public spec
) doctype-public
))
837 (when omit-xml-declaration
838 (setf (output-omit-xml-declaration spec
) omit-xml-declaration
))
839 ;;; (when cdata-section-elements
840 ;;; (setf (output-cdata-section-elements spec)
841 ;;; (concatenate 'string
842 ;;; (output-cdata-section-elements spec)
844 ;;; cdata-section-elements)))
847 (defun make-empty-declaration-array ()
848 (make-array 1 :fill-pointer
0 :adjustable t
))
850 (defun make-variable-value-array (n-lexical-variables)
851 (make-array n-lexical-variables
:initial-element
'unbound
))
853 (defun compile-global-variable (<variable
> env
) ;; also for <param>
854 (stp:with-attributes
(name select
) <variable
>
855 (when (and select
(stp:list-children
<variable
>))
856 (xslt-error "variable with select and body"))
857 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
860 (compile-xpath select env
))
861 ((stp:list-children
<variable
>)
862 (let* ((inner-sexpr `(progn ,@(parse-body <variable
>)))
863 (inner-thunk (compile-instruction inner-sexpr env
)))
865 (apply-to-result-tree-fragment ctx inner-thunk
))))
868 (declare (ignore ctx
))
870 (n-lexical-variables (length *lexical-variable-declarations
*)))
873 (let* ((*lexical-variable-values
*
874 (make-variable-value-array n-lexical-variables
)))
875 (funcall inner ctx
)))
876 "global ~s (~s) = ~s" name select
:result
))))
878 (defstruct (variable-chain
879 (:constructor make-variable-chain
)
880 (:conc-name
"VARIABLE-CHAIN-"))
887 (defstruct (import-variable
888 (:constructor make-variable
)
889 (:conc-name
"VARIABLE-"))
894 (defun parse-global-variable! (stylesheet <variable
> global-env
)
895 (let* ((*namespaces
* (acons-namespaces <variable
>))
896 (instruction-base-uri (stp:base-uri
<variable
>))
897 (*instruction-base-uri
* instruction-base-uri
)
898 (*excluded-namespaces
* (list *xsl
*))
899 (*extension-namespaces
* '())
900 (qname (stp:attribute-value
<variable
> "name")))
901 (with-import-magic (<variable
> global-env
)
903 (xslt-error "name missing in ~A" (stp:local-name
<variable
>)))
904 (multiple-value-bind (local-name uri
)
905 (decode-qname qname global-env nil
)
906 ;; For the normal compilation environment of templates, install it
907 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
908 (let ((index (intern-global-variable local-name uri
)))
909 ;; For the evaluation of a global variable itself, build a thunk
910 ;; that lazily resolves other variables, stored into
911 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
912 (let* ((value-thunk :unknown
)
913 (sgv (stylesheet-global-variables stylesheet
))
915 (if (< index
(length sgv
))
919 :local-name local-name
921 (next (car (variable-chain-definitions chain
)))
922 (global-variable-thunk
924 (let ((v (global-variable-value index nil
)))
928 (xslt-error "no next definition for: ~A"
930 (funcall (variable-value-thunk next
) ctx
))
932 (setf (global-variable-value index
) 'seen
)
933 (setf (global-variable-value index
)
934 (funcall value-thunk ctx
)))
937 (excluded-namespaces *excluded-namespaces
*)
938 (extension-namespaces *extension-namespaces
*)
940 (make-variable :param-p
(namep <variable
> "param")))
943 (let* ((*instruction-base-uri
* instruction-base-uri
)
944 (*excluded-namespaces
* excluded-namespaces
)
945 (*extension-namespaces
* extension-namespaces
)
947 (compile-global-variable <variable
> global-env
)))
948 (setf value-thunk fn
)
949 (setf (variable-value-thunk variable
) fn
)))))
950 (setf (variable-value-thunk-setter variable
)
952 (setf (gethash (cons local-name uri
)
953 (initial-global-variable-thunks global-env
))
954 global-variable-thunk
)
955 (setf (variable-chain-thunk chain
) global-variable-thunk
)
956 (push variable
(variable-chain-definitions chain
))
959 (defun parse-keys! (stylesheet <transform
> env
)
960 (xpath:with-namespaces
((nil #.
*xsl
*))
961 (do-toplevel (<key
> "key" <transform
>)
962 (let ((*instruction-base-uri
* (stp:base-uri
<key
>)))
963 (stp:with-attributes
(name match use
) <key
>
964 (unless name
(xslt-error "key name attribute not specified"))
965 (unless match
(xslt-error "key match attribute not specified"))
966 (unless use
(xslt-error "key use attribute not specified"))
967 (multiple-value-bind (local-name uri
)
968 (decode-qname name env nil
)
970 (cons local-name uri
)
971 (compile-xpath `(xpath:xpath
,(parse-key-pattern match
)) env
)
972 (compile-xpath use env
))))))))
974 (defun prepare-global-variables (stylesheet <transform
>)
975 (xpath:with-namespaces
((nil #.
*xsl
*))
976 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet
))
977 (global-env (make-instance 'global-variable-environment
978 :initial-global-variable-thunks igvt
))
980 (do-toplevel (<variable
> "variable|param" <transform
>)
982 (parse-global-variable! stylesheet
<variable
> global-env
)))
983 (xslt-trace "parsing global variable ~s (uri ~s)"
984 (variable-chain-local-name chain
)
985 (variable-chain-uri chain
))
989 (and (equal (variable-chain-local-name a
)
990 (variable-chain-local-name b
))
991 (equal (variable-chain-uri a
)
992 (variable-chain-uri b
)))))
993 (xslt-error "duplicate definition for global variable ~A"
994 (variable-chain-local-name chain
)))
995 (push chain chains
)))
996 (setf chains
(nreverse chains
))
997 (let ((table (stylesheet-global-variables stylesheet
))
998 (newlen (length *global-variable-declarations
*)))
999 (adjust-array table newlen
:fill-pointer newlen
)
1000 (dolist (chain chains
)
1001 (setf (elt table
(variable-chain-index chain
)) chain
)))
1003 ;; now that the global environment knows about all variables, run the
1004 ;; thunk setters to perform their compilation
1005 (mapc (lambda (chain)
1006 (dolist (var (variable-chain-definitions chain
))
1007 (funcall (variable-value-thunk-setter var
))))
1010 (defun parse-templates! (stylesheet <transform
> env
)
1012 (do-toplevel (<template
> "template" <transform
>)
1013 (let ((*namespaces
* (acons-namespaces <template
>))
1014 (*instruction-base-uri
* (stp:base-uri
<template
>)))
1015 (with-import-magic (<template
> env
)
1016 (dolist (template (compile-template <template
> env i
))
1017 (let ((name (template-name template
)))
1019 (let* ((table (stylesheet-named-templates stylesheet
))
1020 (head (car (gethash name table
))))
1021 (when (and head
(eql (template-import-priority head
)
1022 (template-import-priority template
)))
1023 ;; fixme: is this supposed to be a run-time error?
1024 (xslt-error "conflicting templates for ~A" name
))
1025 (push template
(gethash name table
)))
1026 (let ((mode (ensure-mode/qname stylesheet
1027 (template-mode-qname template
)
1029 (setf (template-mode template
) mode
)
1030 (push template
(mode-templates mode
))))))))
1034 ;;;; APPLY-STYLESHEET
1036 (defvar *stylesheet
*)
1038 (deftype xml-designator
() '(or runes
:xstream runes
:rod array stream pathname
))
1040 (defun unalias-uri (uri)
1042 (gethash uri
(stylesheet-namespace-aliases *stylesheet
*)
1044 (check-type result string
)
1047 (defstruct (parameter
1048 (:constructor make-parameter
(value local-name
&optional uri
)))
1053 (defun find-parameter-value (local-name uri parameters
)
1054 (dolist (p parameters
)
1055 (when (and (equal (parameter-local-name p
) local-name
)
1056 (equal (parameter-uri p
) uri
))
1057 (return (parameter-value p
)))))
1059 (defvar *uri-resolver
*)
1061 (defun parse-allowing-microsoft-bom (pathname handler
)
1062 (with-open-file (s pathname
:element-type
'(unsigned-byte 8))
1063 (unless (and (eql (read-byte s nil
) #xef
)
1064 (eql (read-byte s nil
) #xbb
)
1065 (eql (read-byte s nil
) #xbf
))
1066 (file-position s
0))
1067 (cxml:parse s handler
)))
1069 (defvar *documents
*)
1071 (defun %document
(uri-string base-uri
)
1072 (let* ((absolute-uri
1073 (puri:merge-uris uri-string
(or base-uri
"")))
1076 (funcall *uri-resolver
* (puri:render-uri absolute-uri nil
))
1080 (uri-to-pathname resolved-uri
)
1081 (cxml:xml-parse-error
(c)
1082 (xslt-error "cannot find referenced document ~A: ~A"
1085 (or (gethash pathname
*documents
*)
1086 (setf (gethash pathname
*documents
*)
1087 (make-whitespace-stripper
1089 (parse-allowing-microsoft-bom pathname
1091 ((or file-error cxml
:xml-parse-error
) (c)
1092 (xslt-error "cannot parse referenced document ~A: ~A"
1094 (stylesheet-strip-tests *stylesheet
*))))))
1095 (when (puri:uri-fragment absolute-uri
)
1096 (xslt-error "use of fragment identifiers in document() not supported"))
1099 (xpath-sys:define-extension xslt
*xsl
*)
1101 (defun document-base-uri (node)
1102 (xpath-protocol:base-uri
1104 ((xpath-protocol:node-type-p node
:document
)
1105 (xpath::find-in-pipe-if
1107 (xpath-protocol:node-type-p x
:element
))
1108 (xpath-protocol:child-pipe node
)))
1109 ((xpath-protocol:node-type-p node
:element
)
1112 (xpath-protocol:parent-node node
)))))
1114 (xpath-sys:define-xpath-function
/lazy
1116 (object &optional node-set
)
1117 (let ((instruction-base-uri *instruction-base-uri
*))
1119 (let* ((object (funcall object ctx
))
1120 (node-set (and node-set
(funcall node-set ctx
)))
1123 (document-base-uri (xpath::textually-first-node node-set
))
1124 instruction-base-uri
)))
1125 (xpath-sys:make-node-set
1126 (if (xpath:node-set-p object
)
1127 (xpath:map-node-set-
>list
1129 (%document
(xpath:string-value node
)
1132 (document-base-uri node
))))
1134 (list (%document
(xpath:string-value object
) base-uri
))))))))
1136 (xpath-sys:define-xpath-function
/lazy xslt
:key
(name object
)
1137 (let ((namespaces *namespaces
*))
1139 (let* ((qname (xpath:string-value
(funcall name ctx
)))
1140 (object (funcall object ctx
))
1142 (multiple-value-bind (local-name uri
)
1143 (decode-qname/runtime qname namespaces nil
)
1144 (cons local-name uri
)))
1145 (key (find-key expanded-name
*stylesheet
*)))
1146 (labels ((get-by-key (value)
1147 (let ((value (xpath:string-value value
)))
1151 (xpath:evaluate-compiled
(key-use key
) node
)))
1152 (if (xpath:node-set-p uses
)
1153 (xpath::find-in-pipe
1155 (xpath-sys:pipe-of uses
)
1156 :key
#'xpath
:string-value
1158 (equal value
(xpath:string-value uses
)))))
1160 (xpath:node-set-value
1161 (xpath:evaluate-compiled
(key-match key
) ctx
)))))))
1162 (xpath-sys:make-node-set
1164 (if (xpath:node-set-p object
)
1165 (xpath::mappend-pipe
#'get-by-key
(xpath-sys:pipe-of object
))
1166 (get-by-key object
)))))))))
1168 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1170 (xpath-sys:define-xpath-function
/lazy xslt
:current
()
1172 (xpath-sys:make-node-set
1173 (xpath-sys:make-pipe
1174 (xpath:context-starting-node ctx
)
1177 (xpath-sys:define-xpath-function
/lazy xslt
:unparsed-entity-uri
(name)
1179 (or (xpath-protocol:unparsed-entity-uri
(xpath:context-node ctx
)
1183 (defun %get-node-id
(node)
1184 (when (xpath:node-set-p node
)
1185 (setf node
(xpath::textually-first-node node
)))
1187 (let ((id (xpath-sys:get-node-id node
))
1190 for parent
= node then next
1191 for next
= (xpath-protocol:parent-node parent
)
1192 for this-base-uri
= (xpath-protocol:base-uri parent
)
1193 for highest-base-uri
= (if (plusp (length this-base-uri
))
1197 finally
(return highest-base-uri
))))
1198 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1199 ;; checked only if everything else matches.
1201 ;; This might be pointless premature optimization, but I like the idea :-)
1202 (nreverse (concatenate 'string highest-base-uri
"//" id
)))))
1204 (xpath-sys:define-xpath-function
/lazy xslt
:generate-id
(&optional node-set-thunk
)
1207 (%get-node-id
(xpath:node-set-value
(funcall node-set-thunk ctx
))))
1209 (%get-node-id
(xpath:context-node ctx
)))))
1211 (declaim (special *available-instructions
*))
1213 (xpath-sys:define-xpath-function
/lazy xslt
:element-available
(qname)
1214 (let ((namespaces *namespaces
*))
1216 (let ((qname (funcall qname ctx
)))
1217 (multiple-value-bind (local-name uri
)
1218 (decode-qname/runtime qname namespaces nil
)
1219 (and (equal uri
*xsl
*)
1220 (gethash local-name
*available-instructions
*)
1223 (xpath-sys:define-xpath-function
/lazy xslt
:function-available
(qname)
1224 (let ((namespaces *namespaces
*))
1226 (let ((qname (funcall qname ctx
)))
1227 (multiple-value-bind (local-name uri
)
1228 (decode-qname/runtime qname namespaces nil
)
1229 (and (zerop (length uri
))
1230 (or (xpath-sys:find-xpath-function local-name
*xsl
*)
1231 (xpath-sys:find-xpath-function local-name uri
))
1234 (xpath-sys:define-xpath-function
/lazy xslt
:system-property
(qname)
1235 (let ((namespaces *namespaces
*))
1237 (let ((qname (funcall qname ctx
)))
1238 (multiple-value-bind (local-name uri
)
1239 (decode-qname/runtime qname namespaces nil
)
1240 (if (equal uri
*xsl
*)
1242 ((equal local-name
"version")
1244 ((equal local-name
"vendor")
1246 ((equal local-name
"vendor-uri")
1247 "http://repo.or.cz/w/xuriella.git")
1252 (defun apply-stylesheet
1253 (stylesheet source-designator
1254 &key output parameters uri-resolver navigator
)
1255 (when (typep stylesheet
'xml-designator
)
1258 ((cxml:xml-parse-error
1260 (xslt-error "cannot parse stylesheet: ~A" c
))))
1261 (parse-stylesheet stylesheet
))))
1262 (with-resignalled-errors ()
1263 (invoke-with-output-sink
1265 (let* ((*documents
* (make-hash-table :test
'equal
))
1266 (xpath:*navigator
* (or navigator
:default-navigator
))
1267 (puri:*strict-parse
* nil
)
1268 (*stylesheet
* stylesheet
)
1269 (*empty-mode
* (make-mode))
1270 (*default-mode
* (find-mode stylesheet nil
))
1271 (global-variable-chains
1272 (stylesheet-global-variables stylesheet
))
1273 (*global-variable-values
*
1274 (make-variable-value-array (length global-variable-chains
)))
1275 (*uri-resolver
* uri-resolver
)
1277 (if (typep source-designator
'xml-designator
)
1278 (cxml:parse source-designator
(stp:make-builder
))
1281 (make-whitespace-stripper
1283 (stylesheet-strip-tests stylesheet
)))
1284 (ctx (xpath:make-context xpath-root-node
)))
1285 (when (pathnamep source-designator
)
1286 (setf (gethash source-designator
*documents
*) xpath-root-node
))
1289 (let ((head (car (variable-chain-definitions chain
))))
1290 (when (variable-param-p head
)
1292 (find-parameter-value
1293 (variable-chain-local-name chain
)
1294 (variable-chain-uri chain
)
1297 (setf (global-variable-value
1298 (variable-chain-index chain
))
1300 global-variable-chains
)
1303 (funcall (variable-chain-thunk chain
) ctx
))
1304 global-variable-chains
)
1305 ;; zzz we wouldn't have to mask float traps here if we used the
1306 ;; XPath API properly. Unfortunately I've been using FUNCALL
1307 ;; everywhere instead of EVALUATE, so let's paper over that
1308 ;; at a central place to be sure:
1309 (xpath::with-float-traps-masked
()
1310 (apply-templates ctx
:mode
*default-mode
*))))
1311 (stylesheet-output-specification stylesheet
)
1314 (defun find-attribute-set (local-name uri
)
1315 (or (gethash (cons local-name uri
) (stylesheet-attribute-sets *stylesheet
*))
1316 (xslt-error "no such attribute set: ~A/~A" local-name uri
)))
1318 (defun apply-templates/list
(list &key param-bindings sort-predicate mode
)
1319 (when sort-predicate
1321 (mapcar #'xpath
:context-node
1322 (stable-sort (contextify-node-list list
)
1324 (let* ((n (length list
))
1325 (s/d
(lambda () n
)))
1330 (apply-templates (xpath:make-context child s
/d i
)
1331 :param-bindings param-bindings
1334 (defvar *stack-limit
* 200)
1336 (defun invoke-with-stack-limit (fn)
1337 (let ((*stack-limit
* (1- *stack-limit
*)))
1338 (unless (plusp *stack-limit
*)
1339 (xslt-error "*stack-limit* reached; stack overflow"))
1342 (defun invoke-template (ctx template param-bindings
)
1343 (let ((*lexical-variable-values
*
1344 (make-variable-value-array (template-n-variables template
))))
1345 (with-stack-limit ()
1347 for
(name-cons value
) in param-bindings
1348 for
(nil index nil
) = (find name-cons
1349 (template-params template
)
1354 (setf (lexical-variable-value index
) value
)))
1355 (funcall (template-body template
) ctx
))))
1357 (defun apply-default-templates (ctx mode
)
1358 (let ((node (xpath:context-node ctx
)))
1360 ((or (xpath-protocol:node-type-p node
:processing-instruction
)
1361 (xpath-protocol:node-type-p node
:comment
)))
1362 ((or (xpath-protocol:node-type-p node
:text
)
1363 (xpath-protocol:node-type-p node
:attribute
))
1364 (write-text (xpath-protocol:node-text node
)))
1366 (apply-templates/list
1368 (xpath-protocol:child-pipe node
))
1371 (defvar *apply-imports
*)
1373 (defun apply-applicable-templates (ctx templates param-bindings finally
)
1374 (labels ((apply-imports (&optional actual-param-bindings
)
1376 (let* ((this (pop templates
))
1377 (low (template-apply-imports-limit this
))
1378 (high (template-import-priority this
)))
1382 (<= low
(template-import-priority x
) high
))
1384 (invoke-template ctx this actual-param-bindings
))
1385 (funcall finally
))))
1386 (let ((*apply-imports
* #'apply-imports
))
1387 (apply-imports param-bindings
))))
1389 (defun apply-templates (ctx &key param-bindings mode
)
1390 (apply-applicable-templates ctx
1391 (find-templates ctx
(or mode
*default-mode
*))
1394 (apply-default-templates ctx mode
))))
1396 (defun call-template (ctx name
&optional param-bindings
)
1397 (apply-applicable-templates ctx
1398 (find-named-templates name
)
1401 (error "cannot find named template: ~s"
1404 (defun find-templates (ctx mode
)
1405 (let* ((matching-candidates
1406 (xpath:matching-values
(mode-match-thunk mode
)
1407 (xpath:context-node ctx
)))
1409 (if matching-candidates
1412 :key
#'template-import-priority
))
1414 (priority-groups (make-array npriorities
:initial-element nil
)))
1415 (dolist (template matching-candidates
)
1417 (elt priority-groups
(template-import-priority template
))))
1419 for i from
(1- npriorities
) downto
0
1420 for group
= (elt priority-groups i
)
1421 for template
= (maximize #'template
< group
)
1425 (defun find-named-templates (name)
1426 (gethash name
(stylesheet-named-templates *stylesheet
*)))
1428 (defun template< (a b
) ;assuming same import priority
1429 (let ((p (template-priority a
))
1430 (q (template-priority b
)))
1435 (xslt-cerror "conflicting templates:~_~A,~_~A"
1436 (template-match-expression a
)
1437 (template-match-expression b
))
1438 (< (template-position a
) (template-position b
))))))
1440 (defun maximize (< things
)
1442 (let ((max (car things
)))
1443 (dolist (other (cdr things
))
1444 (when (funcall < max other
)
1448 (defun invoke-with-output-sink (fn output-spec output
)
1451 (with-open-file (s output
1453 :element-type
'(unsigned-byte 8)
1454 :if-exists
:rename-and-delete
)
1455 (invoke-with-output-sink fn output-spec s
)))
1457 (invoke-with-output-sink fn
1459 (make-output-sink output-spec output
)))
1460 ((or hax
:abstract-handler sax
:abstract-handler
)
1461 (with-xml-output output
1462 (when (typep output
'(or combi-sink auto-detect-sink
))
1463 (sax:start-dtd output
1464 :autodetect-me-please
1465 (output-doctype-public output-spec
)
1466 (output-doctype-system output-spec
)))
1469 (defun make-output-sink (output-spec stream
)
1472 (let ((et (stream-element-type stream
)))
1474 ((or (null et
) (subtypep et
'(unsigned-byte 8)))
1475 (runes:make-octet-stream-ystream stream
))
1476 ((subtypep et
'character
)
1477 (runes:make-character-stream-ystream stream
))))
1478 (runes:make-rod-ystream
)))
1479 (omit-xml-declaration-p
1480 (equal (output-omit-xml-declaration output-spec
) "yes"))
1481 (sink-encoding (or (output-encoding output-spec
) "UTF-8"))
1484 (setf (runes:ystream-encoding ystream
)
1485 (cxml::find-output-encoding sink-encoding
))
1486 (make-instance 'cxml
::sink
1488 :omit-xml-declaration-p omit-xml-declaration-p
1489 :encoding sink-encoding
))))
1490 (flet ((make-combi-sink ()
1491 (make-instance 'combi-sink
1492 :hax-target
(make-instance 'chtml
::sink
1494 :sax-target sax-target
1495 :encoding sink-encoding
)))
1498 ((equalp (output-method output-spec
) "HTML") :html
)
1499 ((equalp (output-method output-spec
) "TEXT") :text
)
1500 ((equalp (output-method output-spec
) "XML") :xml
)
1503 ((and (eq method-key
:html
)
1504 (null (output-doctype-system output-spec
))
1505 (null (output-doctype-public output-spec
)))
1507 ((eq method-key
:text
)
1508 (make-text-filter sax-target
))
1509 ((and (eq method-key
:xml
)
1510 (null (output-doctype-system output-spec
)))
1513 (make-auto-detect-sink (make-combi-sink) method-key
)))))))
1529 (defun expression-priority (form)
1530 (let ((step (second form
)))
1531 (if (and (null (cddr form
))
1533 (member (car step
) '(:child
:attribute
))
1535 (let ((name (second step
)))
1539 (or (eq (car name
) :qname
)
1540 (eq (car name
) :processing-instruction
))))
1543 (or (eq (car name
) :namespace
)
1544 (eq (car name
) '*)))
1550 (defun parse-xpath (str)
1551 (with-resignalled-errors ()
1552 (xpath:parse-xpath str
)))
1554 (defun parse-key-pattern (str)
1556 (mapcar #'(lambda (item)
1557 `(:path
(:root
:node
)
1558 (:descendant-or-self
*)
1560 (parse-pattern str
))))
1561 (if (null (rest parsed
))
1563 `(:union
,@parsed
))))
1565 (defun parse-pattern (str)
1566 (with-resignalled-errors ()
1567 (cdr (xpath::parse-pattern-expression str
))))
1569 (defun compile-value-thunk (value env
)
1570 (if (and (listp value
) (eq (car value
) 'progn
))
1571 (let ((inner-thunk (compile-instruction value env
)))
1573 (apply-to-result-tree-fragment ctx inner-thunk
)))
1574 (compile-xpath value env
)))
1576 (defun compile-var-binding (name value env
)
1577 (multiple-value-bind (local-name uri
)
1578 (decode-qname name env nil
)
1579 (let ((thunk (xslt-trace-thunk
1580 (compile-value-thunk value env
)
1581 "local variable ~s = ~s" name
:result
)))
1582 (list (cons local-name uri
)
1583 (push-variable local-name
1585 *lexical-variable-declarations
*)
1588 (defun compile-var-bindings (forms env
)
1590 for
(name value
) in forms
1591 collect
(compile-var-binding name value env
)))
1593 (defun compile-template (<template
> env position
)
1594 (stp:with-attributes
(match name priority mode
) <template
>
1595 (unless (or name match
)
1596 (xslt-error "missing match in template"))
1597 (multiple-value-bind (params body-pos
)
1600 for child in
(stp:list-children
<template
>)
1601 while
(namep child
"param")
1602 collect
(parse-param child
) into params
1603 finally
(return (values params i
)))
1604 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1605 (param-bindings (compile-var-bindings params env
))
1606 (body (parse-body <template
> body-pos
(mapcar #'car params
)))
1607 (body-thunk (compile-instruction `(progn ,@body
) env
))
1613 ;; set params that weren't initialized by apply-templates
1614 (loop for
(name index param-thunk
) in param-bindings
1615 when
(eq (lexical-variable-value index nil
) 'unbound
)
1616 do
(setf (lexical-variable-value index
)
1617 (funcall param-thunk ctx
)))
1618 (funcall body-thunk ctx
))))
1619 "template: match = ~s name = ~s" match name
))
1620 (n-variables (length *lexical-variable-declarations
*)))
1623 (multiple-value-bind (local-name uri
)
1624 (decode-qname name env nil
)
1626 (make-template :name
(cons local-name uri
)
1627 :import-priority
*import-priority
*
1628 :apply-imports-limit
*apply-imports-limit
*
1629 :params param-bindings
1630 :body outer-body-thunk
1631 :n-variables n-variables
))))
1633 (mapcar (lambda (expression)
1634 (let* ((compiled-pattern
1636 (car (xpath:compute-patterns
1637 `(:patterns
,expression
)
1641 "match-thunk for template (match ~s): ~s --> ~s"
1642 match expression
:result
))
1644 (parse-number:parse-number priority
)
1645 (expression-priority expression
)))
1647 (make-template :match-expression expression
1648 :compiled-pattern compiled-pattern
1649 :import-priority
*import-priority
*
1650 :apply-imports-limit
*apply-imports-limit
*
1654 :params param-bindings
1655 :body outer-body-thunk
1656 :n-variables n-variables
)))
1657 (setf (xpath:pattern-value compiled-pattern
)
1660 (cdr (xpath:parse-pattern-expression match
)))))))))
1662 (xuriella::parse-stylesheet
#p
"/home/david/src/lisp/xuriella/test.xsl")