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 (xpath-sys:environment-find-namespace env stylesheet-prefix
)
677 (stylesheet-namespace-aliases stylesheet
))
678 (xpath-sys:environment-find-namespace
680 (if (equal result-prefix
"#default")
684 (defun parse-decimal-formats! (stylesheet <transform
> env
)
685 (do-toplevel (elt "decimal-format" <transform
>)
686 (stp:with-attributes
(name
700 (multiple-value-bind (local-name uri
)
702 (decode-qname name env nil
)
704 (let ((current (find-decimal-format local-name uri stylesheet nil
))
709 (unless (eql (length x
) 1)
710 (xslt-error "not a single character: ~A" x
))
711 (let ((chr (elt x
0)))
712 (when (find chr seen
)
714 "conflicting decimal format characters: ~A"
721 (apply #'make-decimal-format
722 (append (str :infinity infinity
)
724 (chr :decimal-separator decimal-separator
)
725 (chr :grouping-separator grouping-separator
)
726 (chr :zero-digit zero-digit
)
727 (chr :percent percent
)
728 (chr :per-mille per-mille
)
730 (chr :pattern-separator pattern-separator
)
731 (chr :minus-sign minus-sign
)))))))
733 (unless (decimal-format= current new
)
734 (xslt-error "decimal format mismatch for ~S" local-name
))
735 (setf (find-decimal-format local-name uri stylesheet
) new
)))))))
737 (defun parse-exclude-result-prefixes! (node env
)
738 (stp:with-attributes
(exclude-result-prefixes)
740 (dolist (prefix (words (or exclude-result-prefixes
"")))
741 (if (equal prefix
"#default")
743 (unless (cxml-stp-impl::nc-name-p prefix
)
744 (xslt-error "invalid prefix: ~A" prefix
)))
745 (push (or (xpath-sys:environment-find-namespace env prefix
)
746 (xslt-error "namespace not found: ~A" prefix
))
747 *excluded-namespaces
*))))
749 (defun parse-extension-element-prefixes! (node env
)
750 (stp:with-attributes
(extension-element-prefixes)
752 (dolist (prefix (words (or extension-element-prefixes
"")))
753 (if (equal prefix
"#default")
755 (unless (cxml-stp-impl::nc-name-p prefix
)
756 (xslt-error "invalid prefix: ~A" prefix
)))
758 (or (xpath-sys:environment-find-namespace env prefix
)
759 (xslt-error "namespace not found: ~A" prefix
))))
760 (unless (equal uri
*xsl
*)
761 (push uri
*extension-namespaces
*)
762 (push uri
*excluded-namespaces
*))))))
764 (defun parse-strip/preserve-space
! (stylesheet <transform
> env
)
765 (xpath:with-namespaces
((nil #.
*xsl
*))
766 (do-toplevel (elt "strip-space|preserve-space" <transform
>)
767 (let ((*namespaces
* (acons-namespaces elt
))
769 (if (equal (stp:local-name elt
) "strip-space")
772 (dolist (name-test (words (stp:attribute-value elt
"elements")))
773 (let* ((pos (search ":*" name-test
))
776 ((eql pos
(- (length name-test
) 2))
777 (let* ((prefix (subseq name-test
0 pos
))
779 (xpath-sys:environment-find-namespace env prefix
)))
780 (unless (xpath::nc-name-p prefix
)
781 (xslt-error "not an NCName: ~A" prefix
))
782 (lambda (local-name uri
)
783 (declare (ignore local-name
))
784 (if (equal uri name-test-uri
)
787 ((equal name-test
"*")
788 (lambda (local-name uri
)
789 (declare (ignore local-name uri
))
792 (multiple-value-bind (name-test-local-name name-test-uri
)
793 (decode-qname name-test env nil
)
794 (lambda (local-name uri
)
795 (if (and (equal local-name name-test-local-name
)
796 (equal uri name-test-uri
))
799 (push test-function
(stylesheet-strip-tests stylesheet
))))))))
801 (defstruct (output-specification
802 (:conc-name
"OUTPUT-"))
810 (defun parse-output! (stylesheet <transform
>)
811 (dolist (<output
> (list-toplevel "output" <transform
>))
812 (let ((spec (stylesheet-output-specification stylesheet
)))
813 (stp:with-attributes
( ;; version
822 ;;; cdata-section-elements
826 (setf (output-method spec
) method
))
828 (setf (output-indent spec
) indent
))
830 (setf (output-encoding spec
) encoding
))
832 (setf (output-doctype-system spec
) doctype-system
))
834 (setf (output-doctype-public spec
) doctype-public
))
835 (when omit-xml-declaration
836 (setf (output-omit-xml-declaration spec
) omit-xml-declaration
))
837 ;;; (when cdata-section-elements
838 ;;; (setf (output-cdata-section-elements spec)
839 ;;; (concatenate 'string
840 ;;; (output-cdata-section-elements spec)
842 ;;; cdata-section-elements)))
845 (defun make-empty-declaration-array ()
846 (make-array 1 :fill-pointer
0 :adjustable t
))
848 (defun make-variable-value-array (n-lexical-variables)
849 (make-array n-lexical-variables
:initial-element
'unbound
))
851 (defun compile-global-variable (<variable
> env
) ;; also for <param>
852 (stp:with-attributes
(name select
) <variable
>
853 (when (and select
(stp:list-children
<variable
>))
854 (xslt-error "variable with select and body"))
855 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
858 (compile-xpath select env
))
859 ((stp:list-children
<variable
>)
860 (let* ((inner-sexpr `(progn ,@(parse-body <variable
>)))
861 (inner-thunk (compile-instruction inner-sexpr env
)))
863 (apply-to-result-tree-fragment ctx inner-thunk
))))
866 (declare (ignore ctx
))
868 (n-lexical-variables (length *lexical-variable-declarations
*)))
871 (let* ((*lexical-variable-values
*
872 (make-variable-value-array n-lexical-variables
)))
873 (funcall inner ctx
)))
874 "global ~s (~s) = ~s" name select
:result
))))
876 (defstruct (variable-chain
877 (:constructor make-variable-chain
)
878 (:conc-name
"VARIABLE-CHAIN-"))
885 (defstruct (import-variable
886 (:constructor make-variable
)
887 (:conc-name
"VARIABLE-"))
892 (defun parse-global-variable! (stylesheet <variable
> global-env
)
893 (let* ((*namespaces
* (acons-namespaces <variable
>))
894 (instruction-base-uri (stp:base-uri
<variable
>))
895 (*instruction-base-uri
* instruction-base-uri
)
896 (*excluded-namespaces
* (list *xsl
*))
897 (*extension-namespaces
* '())
898 (qname (stp:attribute-value
<variable
> "name")))
899 (with-import-magic (<variable
> global-env
)
901 (xslt-error "name missing in ~A" (stp:local-name
<variable
>)))
902 (multiple-value-bind (local-name uri
)
903 (decode-qname qname global-env nil
)
904 ;; For the normal compilation environment of templates, install it
905 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
906 (let ((index (intern-global-variable local-name uri
)))
907 ;; For the evaluation of a global variable itself, build a thunk
908 ;; that lazily resolves other variables, stored into
909 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
910 (let* ((value-thunk :unknown
)
911 (sgv (stylesheet-global-variables stylesheet
))
913 (if (< index
(length sgv
))
917 :local-name local-name
919 (next (car (variable-chain-definitions chain
)))
920 (global-variable-thunk
922 (let ((v (global-variable-value index nil
)))
926 (xslt-error "no next definition for: ~A"
928 (funcall (variable-value-thunk next
) ctx
))
930 (setf (global-variable-value index
) 'seen
)
931 (setf (global-variable-value index
)
932 (funcall value-thunk ctx
)))
935 (excluded-namespaces *excluded-namespaces
*)
936 (extension-namespaces *extension-namespaces
*)
938 (make-variable :param-p
(namep <variable
> "param")))
941 (let* ((*instruction-base-uri
* instruction-base-uri
)
942 (*excluded-namespaces
* excluded-namespaces
)
943 (*extension-namespaces
* extension-namespaces
)
945 (compile-global-variable <variable
> global-env
)))
946 (setf value-thunk fn
)
947 (setf (variable-value-thunk variable
) fn
)))))
948 (setf (variable-value-thunk-setter variable
)
950 (setf (gethash (cons local-name uri
)
951 (initial-global-variable-thunks global-env
))
952 global-variable-thunk
)
953 (setf (variable-chain-thunk chain
) global-variable-thunk
)
954 (push variable
(variable-chain-definitions chain
))
957 (defun parse-keys! (stylesheet <transform
> env
)
958 (xpath:with-namespaces
((nil #.
*xsl
*))
959 (do-toplevel (<key
> "key" <transform
>)
960 (let ((*instruction-base-uri
* (stp:base-uri
<key
>)))
961 (stp:with-attributes
(name match use
) <key
>
962 (unless name
(xslt-error "key name attribute not specified"))
963 (unless match
(xslt-error "key match attribute not specified"))
964 (unless use
(xslt-error "key use attribute not specified"))
965 (multiple-value-bind (local-name uri
)
966 (decode-qname name env nil
)
968 (cons local-name uri
)
969 (compile-xpath `(xpath:xpath
,(parse-key-pattern match
)) env
)
970 (compile-xpath use env
))))))))
972 (defun prepare-global-variables (stylesheet <transform
>)
973 (xpath:with-namespaces
((nil #.
*xsl
*))
974 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet
))
975 (global-env (make-instance 'global-variable-environment
976 :initial-global-variable-thunks igvt
))
978 (do-toplevel (<variable
> "variable|param" <transform
>)
980 (parse-global-variable! stylesheet
<variable
> global-env
)))
981 (xslt-trace "parsing global variable ~s (uri ~s)"
982 (variable-chain-local-name chain
)
983 (variable-chain-uri chain
))
987 (and (equal (variable-chain-local-name a
)
988 (variable-chain-local-name b
))
989 (equal (variable-chain-uri a
)
990 (variable-chain-uri b
)))))
991 (xslt-error "duplicate definition for global variable ~A"
992 (variable-chain-local-name chain
)))
993 (push chain chains
)))
994 (setf chains
(nreverse chains
))
995 (let ((table (stylesheet-global-variables stylesheet
))
996 (newlen (length *global-variable-declarations
*)))
997 (adjust-array table newlen
:fill-pointer newlen
)
998 (dolist (chain chains
)
999 (setf (elt table
(variable-chain-index chain
)) chain
)))
1001 ;; now that the global environment knows about all variables, run the
1002 ;; thunk setters to perform their compilation
1003 (mapc (lambda (chain)
1004 (dolist (var (variable-chain-definitions chain
))
1005 (funcall (variable-value-thunk-setter var
))))
1008 (defun parse-templates! (stylesheet <transform
> env
)
1010 (do-toplevel (<template
> "template" <transform
>)
1011 (let ((*namespaces
* (acons-namespaces <template
>))
1012 (*instruction-base-uri
* (stp:base-uri
<template
>)))
1013 (with-import-magic (<template
> env
)
1014 (dolist (template (compile-template <template
> env i
))
1015 (let ((name (template-name template
)))
1017 (let* ((table (stylesheet-named-templates stylesheet
))
1018 (head (car (gethash name table
))))
1019 (when (and head
(eql (template-import-priority head
)
1020 (template-import-priority template
)))
1021 ;; fixme: is this supposed to be a run-time error?
1022 (xslt-error "conflicting templates for ~A" name
))
1023 (push template
(gethash name table
)))
1024 (let ((mode (ensure-mode/qname stylesheet
1025 (template-mode-qname template
)
1027 (setf (template-mode template
) mode
)
1028 (push template
(mode-templates mode
))))))))
1032 ;;;; APPLY-STYLESHEET
1034 (defvar *stylesheet
*)
1036 (deftype xml-designator
() '(or runes
:xstream runes
:rod array stream pathname
))
1038 (defun unalias-uri (uri)
1040 (gethash uri
(stylesheet-namespace-aliases *stylesheet
*)
1042 (check-type result string
)
1045 (defstruct (parameter
1046 (:constructor make-parameter
(value local-name
&optional uri
)))
1051 (defun find-parameter-value (local-name uri parameters
)
1052 (dolist (p parameters
)
1053 (when (and (equal (parameter-local-name p
) local-name
)
1054 (equal (parameter-uri p
) uri
))
1055 (return (parameter-value p
)))))
1057 (defvar *uri-resolver
*)
1059 (defun parse-allowing-microsoft-bom (pathname handler
)
1060 (with-open-file (s pathname
:element-type
'(unsigned-byte 8))
1061 (unless (and (eql (read-byte s nil
) #xef
)
1062 (eql (read-byte s nil
) #xbb
)
1063 (eql (read-byte s nil
) #xbf
))
1064 (file-position s
0))
1065 (cxml:parse s handler
)))
1067 (defvar *documents
*)
1069 (defun %document
(uri-string base-uri
)
1070 (let* ((absolute-uri
1071 (puri:merge-uris uri-string
(or base-uri
"")))
1074 (funcall *uri-resolver
* (puri:render-uri absolute-uri nil
))
1078 (uri-to-pathname resolved-uri
)
1079 (cxml:xml-parse-error
(c)
1080 (xslt-error "cannot find referenced document ~A: ~A"
1083 (or (gethash pathname
*documents
*)
1084 (setf (gethash pathname
*documents
*)
1085 (make-whitespace-stripper
1087 (parse-allowing-microsoft-bom pathname
1089 ((or file-error cxml
:xml-parse-error
) (c)
1090 (xslt-error "cannot parse referenced document ~A: ~A"
1092 (stylesheet-strip-tests *stylesheet
*))))))
1093 (when (puri:uri-fragment absolute-uri
)
1094 (xslt-error "use of fragment identifiers in document() not supported"))
1097 (xpath-sys:define-extension xslt
*xsl
*)
1099 (defun document-base-uri (node)
1100 (xpath-protocol:base-uri
1102 ((xpath-protocol:node-type-p node
:document
)
1103 (xpath::find-in-pipe-if
1105 (xpath-protocol:node-type-p x
:element
))
1106 (xpath-protocol:child-pipe node
)))
1107 ((xpath-protocol:node-type-p node
:element
)
1110 (xpath-protocol:parent-node node
)))))
1112 (xpath-sys:define-xpath-function
/lazy
1114 (object &optional node-set
)
1115 (let ((instruction-base-uri *instruction-base-uri
*))
1117 (let* ((object (funcall object ctx
))
1118 (node-set (and node-set
(funcall node-set ctx
)))
1121 (document-base-uri (xpath::textually-first-node node-set
))
1122 instruction-base-uri
)))
1123 (xpath-sys:make-node-set
1124 (if (xpath:node-set-p object
)
1125 (xpath:map-node-set-
>list
1127 (%document
(xpath:string-value node
)
1130 (document-base-uri node
))))
1132 (list (%document
(xpath:string-value object
) base-uri
))))))))
1134 (xpath-sys:define-xpath-function
/lazy xslt
:key
(name object
)
1135 (let ((namespaces *namespaces
*))
1137 (let* ((qname (xpath:string-value
(funcall name ctx
)))
1138 (object (funcall object ctx
))
1140 (multiple-value-bind (local-name uri
)
1141 (decode-qname/runtime qname namespaces nil
)
1142 (cons local-name uri
)))
1143 (key (find-key expanded-name
*stylesheet
*)))
1144 (labels ((get-by-key (value)
1145 (let ((value (xpath:string-value value
)))
1149 (xpath:evaluate-compiled
(key-use key
) node
)))
1150 (if (xpath:node-set-p uses
)
1151 (xpath::find-in-pipe
1153 (xpath-sys:pipe-of uses
)
1154 :key
#'xpath
:string-value
1156 (equal value
(xpath:string-value uses
)))))
1158 (xpath:node-set-value
1159 (xpath:evaluate-compiled
(key-match key
) ctx
)))))))
1160 (xpath-sys:make-node-set
1162 (if (xpath:node-set-p object
)
1163 (xpath::mappend-pipe
#'get-by-key
(xpath-sys:pipe-of object
))
1164 (get-by-key object
)))))))))
1166 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1168 (xpath-sys:define-xpath-function
/lazy xslt
:current
()
1170 (xpath-sys:make-node-set
1171 (xpath-sys:make-pipe
1172 (xpath:context-starting-node ctx
)
1175 (xpath-sys:define-xpath-function
/lazy xslt
:unparsed-entity-uri
(name)
1177 (or (xpath-protocol:unparsed-entity-uri
(xpath:context-node ctx
)
1181 (defun %get-node-id
(node)
1182 (when (xpath:node-set-p node
)
1183 (setf node
(xpath::textually-first-node node
)))
1185 (let ((id (xpath-sys:get-node-id node
))
1188 for parent
= node then next
1189 for next
= (xpath-protocol:parent-node parent
)
1190 for this-base-uri
= (xpath-protocol:base-uri parent
)
1191 for highest-base-uri
= (if (plusp (length this-base-uri
))
1195 finally
(return highest-base-uri
))))
1196 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1197 ;; checked only if everything else matches.
1199 ;; This might be pointless premature optimization, but I like the idea :-)
1200 (nreverse (concatenate 'string highest-base-uri
"//" id
)))))
1202 (xpath-sys:define-xpath-function
/lazy xslt
:generate-id
(&optional node-set-thunk
)
1205 (%get-node-id
(xpath:node-set-value
(funcall node-set-thunk ctx
))))
1207 (%get-node-id
(xpath:context-node ctx
)))))
1209 (declaim (special *available-instructions
*))
1211 (xpath-sys:define-xpath-function
/lazy xslt
:element-available
(qname)
1212 (let ((namespaces *namespaces
*))
1214 (let ((qname (funcall qname ctx
)))
1215 (multiple-value-bind (local-name uri
)
1216 (decode-qname/runtime qname namespaces nil
)
1217 (and (equal uri
*xsl
*)
1218 (gethash local-name
*available-instructions
*)
1221 (xpath-sys:define-xpath-function
/lazy xslt
:function-available
(qname)
1222 (let ((namespaces *namespaces
*))
1224 (let ((qname (funcall qname ctx
)))
1225 (multiple-value-bind (local-name uri
)
1226 (decode-qname/runtime qname namespaces nil
)
1227 (and (zerop (length uri
))
1228 (or (xpath-sys:find-xpath-function local-name
*xsl
*)
1229 (xpath-sys:find-xpath-function local-name uri
))
1232 (xpath-sys:define-xpath-function
/lazy xslt
:system-property
(qname)
1233 (let ((namespaces *namespaces
*))
1235 (let ((qname (funcall qname ctx
)))
1236 (multiple-value-bind (local-name uri
)
1237 (decode-qname/runtime qname namespaces nil
)
1238 (if (equal uri
*xsl
*)
1240 ((equal local-name
"version")
1242 ((equal local-name
"vendor")
1244 ((equal local-name
"vendor-uri")
1245 "http://repo.or.cz/w/xuriella.git")
1250 (defun apply-stylesheet
1251 (stylesheet source-designator
1252 &key output parameters uri-resolver navigator
)
1253 (when (typep stylesheet
'xml-designator
)
1256 ((cxml:xml-parse-error
1258 (xslt-error "cannot parse stylesheet: ~A" c
))))
1259 (parse-stylesheet stylesheet
))))
1260 (with-resignalled-errors ()
1261 (invoke-with-output-sink
1263 (let* ((*documents
* (make-hash-table :test
'equal
))
1264 (xpath:*navigator
* (or navigator
:default-navigator
))
1265 (puri:*strict-parse
* nil
)
1266 (*stylesheet
* stylesheet
)
1267 (*empty-mode
* (make-mode))
1268 (*default-mode
* (find-mode stylesheet nil
))
1269 (global-variable-chains
1270 (stylesheet-global-variables stylesheet
))
1271 (*global-variable-values
*
1272 (make-variable-value-array (length global-variable-chains
)))
1273 (*uri-resolver
* uri-resolver
)
1275 (if (typep source-designator
'xml-designator
)
1276 (cxml:parse source-designator
(stp:make-builder
))
1279 (make-whitespace-stripper
1281 (stylesheet-strip-tests stylesheet
)))
1282 (ctx (xpath:make-context xpath-root-node
)))
1283 (when (pathnamep source-designator
)
1284 (setf (gethash source-designator
*documents
*) xpath-root-node
))
1287 (let ((head (car (variable-chain-definitions chain
))))
1288 (when (variable-param-p head
)
1290 (find-parameter-value
1291 (variable-chain-local-name chain
)
1292 (variable-chain-uri chain
)
1295 (setf (global-variable-value
1296 (variable-chain-index chain
))
1298 global-variable-chains
)
1301 (funcall (variable-chain-thunk chain
) ctx
))
1302 global-variable-chains
)
1303 ;; zzz we wouldn't have to mask float traps here if we used the
1304 ;; XPath API properly. Unfortunately I've been using FUNCALL
1305 ;; everywhere instead of EVALUATE, so let's paper over that
1306 ;; at a central place to be sure:
1307 (xpath::with-float-traps-masked
()
1308 (apply-templates ctx
:mode
*default-mode
*))))
1309 (stylesheet-output-specification stylesheet
)
1312 (defun find-attribute-set (local-name uri
)
1313 (or (gethash (cons local-name uri
) (stylesheet-attribute-sets *stylesheet
*))
1314 (xslt-error "no such attribute set: ~A/~A" local-name uri
)))
1316 (defun apply-templates/list
(list &key param-bindings sort-predicate mode
)
1317 (when sort-predicate
1319 (mapcar #'xpath
:context-node
1320 (stable-sort (contextify-node-list list
)
1322 (let* ((n (length list
))
1323 (s/d
(lambda () n
)))
1328 (apply-templates (xpath:make-context child s
/d i
)
1329 :param-bindings param-bindings
1332 (defvar *stack-limit
* 200)
1334 (defun invoke-with-stack-limit (fn)
1335 (let ((*stack-limit
* (1- *stack-limit
*)))
1336 (unless (plusp *stack-limit
*)
1337 (xslt-error "*stack-limit* reached; stack overflow"))
1340 (defun invoke-template (ctx template param-bindings
)
1341 (let ((*lexical-variable-values
*
1342 (make-variable-value-array (template-n-variables template
))))
1343 (with-stack-limit ()
1345 for
(name-cons value
) in param-bindings
1346 for
(nil index nil
) = (find name-cons
1347 (template-params template
)
1352 (setf (lexical-variable-value index
) value
)))
1353 (funcall (template-body template
) ctx
))))
1355 (defun apply-default-templates (ctx mode
)
1356 (let ((node (xpath:context-node ctx
)))
1358 ((or (xpath-protocol:node-type-p node
:processing-instruction
)
1359 (xpath-protocol:node-type-p node
:comment
)))
1360 ((or (xpath-protocol:node-type-p node
:text
)
1361 (xpath-protocol:node-type-p node
:attribute
))
1362 (write-text (xpath-protocol:node-text node
)))
1364 (apply-templates/list
1366 (xpath-protocol:child-pipe node
))
1369 (defvar *apply-imports
*)
1371 (defun apply-applicable-templates (ctx templates param-bindings finally
)
1372 (labels ((apply-imports (&optional actual-param-bindings
)
1374 (let* ((this (pop templates
))
1375 (low (template-apply-imports-limit this
))
1376 (high (template-import-priority this
)))
1380 (<= low
(template-import-priority x
) high
))
1382 (invoke-template ctx this actual-param-bindings
))
1383 (funcall finally
))))
1384 (let ((*apply-imports
* #'apply-imports
))
1385 (apply-imports param-bindings
))))
1387 (defun apply-templates (ctx &key param-bindings mode
)
1388 (apply-applicable-templates ctx
1389 (find-templates ctx
(or mode
*default-mode
*))
1392 (apply-default-templates ctx mode
))))
1394 (defun call-template (ctx name
&optional param-bindings
)
1395 (apply-applicable-templates ctx
1396 (find-named-templates name
)
1399 (error "cannot find named template: ~s"
1402 (defun find-templates (ctx mode
)
1403 (let* ((matching-candidates
1404 (xpath:matching-values
(mode-match-thunk mode
)
1405 (xpath:context-node ctx
)))
1407 (if matching-candidates
1410 :key
#'template-import-priority
))
1412 (priority-groups (make-array npriorities
:initial-element nil
)))
1413 (dolist (template matching-candidates
)
1415 (elt priority-groups
(template-import-priority template
))))
1417 for i from
(1- npriorities
) downto
0
1418 for group
= (elt priority-groups i
)
1419 for template
= (maximize #'template
< group
)
1423 (defun find-named-templates (name)
1424 (gethash name
(stylesheet-named-templates *stylesheet
*)))
1426 (defun template< (a b
) ;assuming same import priority
1427 (let ((p (template-priority a
))
1428 (q (template-priority b
)))
1433 (xslt-cerror "conflicting templates:~_~A,~_~A"
1434 (template-match-expression a
)
1435 (template-match-expression b
))
1436 (< (template-position a
) (template-position b
))))))
1438 (defun maximize (< things
)
1440 (let ((max (car things
)))
1441 (dolist (other (cdr things
))
1442 (when (funcall < max other
)
1446 (defun invoke-with-output-sink (fn output-spec output
)
1449 (with-open-file (s output
1451 :element-type
'(unsigned-byte 8)
1452 :if-exists
:rename-and-delete
)
1453 (invoke-with-output-sink fn output-spec s
)))
1455 (invoke-with-output-sink fn
1457 (make-output-sink output-spec output
)))
1458 ((or hax
:abstract-handler sax
:abstract-handler
)
1459 (with-xml-output output
1460 (when (typep output
'(or combi-sink auto-detect-sink
))
1461 (sax:start-dtd output
1462 :autodetect-me-please
1463 (output-doctype-public output-spec
)
1464 (output-doctype-system output-spec
)))
1467 (defun make-output-sink (output-spec stream
)
1470 (let ((et (stream-element-type stream
)))
1472 ((or (null et
) (subtypep et
'(unsigned-byte 8)))
1473 (runes:make-octet-stream-ystream stream
))
1474 ((subtypep et
'character
)
1475 (runes:make-character-stream-ystream stream
))))
1476 (runes:make-rod-ystream
)))
1477 (omit-xml-declaration-p
1478 (equal (output-omit-xml-declaration output-spec
) "yes"))
1479 (sink-encoding (or (output-encoding output-spec
) "UTF-8"))
1482 (setf (runes:ystream-encoding ystream
)
1483 (cxml::find-output-encoding sink-encoding
))
1484 (make-instance 'cxml
::sink
1486 :omit-xml-declaration-p omit-xml-declaration-p
1487 :encoding sink-encoding
))))
1488 (flet ((make-combi-sink ()
1489 (make-instance 'combi-sink
1490 :hax-target
(make-instance 'chtml
::sink
1492 :sax-target sax-target
1493 :encoding sink-encoding
)))
1496 ((equalp (output-method output-spec
) "HTML") :html
)
1497 ((equalp (output-method output-spec
) "TEXT") :text
)
1498 ((equalp (output-method output-spec
) "XML") :xml
)
1501 ((and (eq method-key
:html
)
1502 (null (output-doctype-system output-spec
))
1503 (null (output-doctype-public output-spec
)))
1505 ((eq method-key
:text
)
1506 (make-text-filter sax-target
))
1507 ((and (eq method-key
:xml
)
1508 (null (output-doctype-system output-spec
)))
1511 (make-auto-detect-sink (make-combi-sink) method-key
)))))))
1527 (defun expression-priority (form)
1528 (let ((step (second form
)))
1529 (if (and (null (cddr form
))
1531 (member (car step
) '(:child
:attribute
))
1533 (let ((name (second step
)))
1537 (or (eq (car name
) :qname
)
1538 (eq (car name
) :processing-instruction
))))
1541 (or (eq (car name
) :namespace
)
1542 (eq (car name
) '*)))
1548 (defun parse-xpath (str)
1549 (with-resignalled-errors ()
1550 (xpath:parse-xpath str
)))
1552 (defun parse-key-pattern (str)
1554 (mapcar #'(lambda (item)
1555 `(:path
(:root
:node
)
1556 (:descendant-or-self
*)
1558 (parse-pattern str
))))
1559 (if (null (rest parsed
))
1561 `(:union
,@parsed
))))
1563 (defun parse-pattern (str)
1564 (with-resignalled-errors ()
1565 (cdr (xpath::parse-pattern-expression str
))))
1567 (defun compile-value-thunk (value env
)
1568 (if (and (listp value
) (eq (car value
) 'progn
))
1569 (let ((inner-thunk (compile-instruction value env
)))
1571 (apply-to-result-tree-fragment ctx inner-thunk
)))
1572 (compile-xpath value env
)))
1574 (defun compile-var-binding (name value env
)
1575 (multiple-value-bind (local-name uri
)
1576 (decode-qname name env nil
)
1577 (let ((thunk (xslt-trace-thunk
1578 (compile-value-thunk value env
)
1579 "local variable ~s = ~s" name
:result
)))
1580 (list (cons local-name uri
)
1581 (push-variable local-name
1583 *lexical-variable-declarations
*)
1586 (defun compile-var-bindings (forms env
)
1588 for
(name value
) in forms
1589 collect
(compile-var-binding name value env
)))
1591 (defun compile-template (<template
> env position
)
1592 (stp:with-attributes
(match name priority mode
) <template
>
1593 (unless (or name match
)
1594 (xslt-error "missing match in template"))
1595 (multiple-value-bind (params body-pos
)
1598 for child in
(stp:list-children
<template
>)
1599 while
(namep child
"param")
1600 collect
(parse-param child
) into params
1601 finally
(return (values params i
)))
1602 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1603 (param-bindings (compile-var-bindings params env
))
1604 (body (parse-body <template
> body-pos
(mapcar #'car params
)))
1605 (body-thunk (compile-instruction `(progn ,@body
) env
))
1611 ;; set params that weren't initialized by apply-templates
1612 (loop for
(name index param-thunk
) in param-bindings
1613 when
(eq (lexical-variable-value index nil
) 'unbound
)
1614 do
(setf (lexical-variable-value index
)
1615 (funcall param-thunk ctx
)))
1616 (funcall body-thunk ctx
))))
1617 "template: match = ~s name = ~s" match name
))
1618 (n-variables (length *lexical-variable-declarations
*)))
1621 (multiple-value-bind (local-name uri
)
1622 (decode-qname name env nil
)
1624 (make-template :name
(cons local-name uri
)
1625 :import-priority
*import-priority
*
1626 :apply-imports-limit
*apply-imports-limit
*
1627 :params param-bindings
1628 :body outer-body-thunk
1629 :n-variables n-variables
))))
1631 (mapcar (lambda (expression)
1632 (let* ((compiled-pattern
1634 (car (xpath:compute-patterns
1635 `(:patterns
,expression
)
1639 "match-thunk for template (match ~s): ~s --> ~s"
1640 match expression
:result
))
1642 (parse-number:parse-number priority
)
1643 (expression-priority expression
)))
1645 (make-template :match-expression expression
1646 :compiled-pattern compiled-pattern
1647 :import-priority
*import-priority
*
1648 :apply-imports-limit
*apply-imports-limit
*
1652 :params param-bindings
1653 :body outer-body-thunk
1654 :n-variables n-variables
)))
1655 (setf (xpath:pattern-value compiled-pattern
)
1658 (cdr (xpath:parse-pattern-expression match
)))))))))
1660 (xuriella::parse-stylesheet
#p
"/home/david/src/lisp/xuriella/test.xsl")