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-xpath-errors
((&optional
) &body body
)
93 (xslt-error "~A" c
))))
96 (defun compile-xpath (xpath &optional env
)
98 (xpath:compile-xpath xpath env
)))
100 (defmacro with-stack-limit
((&optional
) &body body
)
101 `(invoke-with-stack-limit (lambda () ,@body
)))
104 ;;;; Helper functions and macros
106 (defun check-for-invalid-attributes (valid-names node
)
107 (labels ((check-attribute (a)
109 (let ((uri (stp:namespace-uri a
)))
110 (or (and (plusp (length uri
)) (not (equal uri
*xsl
*)))
111 (find (cons (stp:local-name a
) uri
)
114 (xslt-error "attribute ~A not allowed on ~A"
116 (stp:local-name node
)))))
117 (stp:map-attributes nil
#'check-attribute node
)))
119 (defmacro only-with-attributes
((&rest specs
) node
&body body
)
121 (mapcar (lambda (entry)
122 (if (and (listp entry
) (cdr entry
))
123 (destructuring-bind (name &optional
(uri ""))
126 (cons (string-downcase
128 (symbol-name entry
)))
132 `(let ((,%NODE
,node
))
133 (check-for-invalid-attributes ',valid-names
,%NODE
)
134 (stp:with-attributes
,specs
,%NODE
137 (defun map-pipe-eagerly (fn pipe
)
138 (xpath::enumerate pipe
:key fn
:result nil
))
140 (defmacro do-pipe
((var pipe
&optional result
) &body body
)
142 (map-pipe-eagerly #'(lambda (,var
) ,@body
) ,pipe
)
146 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
148 (defparameter *namespaces
*
150 ("xmlns" .
#"http://www.w3.org/2000/xmlns/")
151 ("xml" .
#"http://www.w3.org/XML/1998/namespace")))
153 (defvar *global-variable-declarations
*)
154 (defvar *lexical-variable-declarations
*)
156 (defvar *global-variable-values
*)
157 (defvar *lexical-variable-values
*)
159 (defclass xslt-environment
() ())
161 (defun split-qname (str)
163 (multiple-value-bind (prefix local-name
)
164 (cxml::split-qname str
)
166 ;; FIXME: cxml should really offer a function that does
167 ;; checks for NCName and QName in a sensible way for user code.
168 ;; cxml::split-qname is tailored to the needs of the parser.
170 ;; For now, let's just check the syntax explicitly.
171 (and (or (null prefix
) (xpath::nc-name-p prefix
))
172 (xpath::nc-name-p local-name
))
173 (xslt-error "not a qname: ~A" str
))
174 (values prefix local-name
))
175 (cxml:well-formedness-violation
()
176 (xslt-error "not a qname: ~A" str
))))
178 (defun decode-qname (qname env attributep
)
179 (multiple-value-bind (prefix local-name
)
182 (if (or prefix
(not attributep
))
183 (xpath-sys:environment-find-namespace env
(or prefix
""))
187 (defmethod xpath-sys:environment-find-namespace
((env xslt-environment
) prefix
)
188 (or (cdr (assoc prefix
*namespaces
* :test
'equal
))
190 ;; Change the entire code base to represent "no prefix" as the
191 ;; empty string consistently. unparse.lisp has already been changed.
192 (and (equal prefix
"")
193 (cdr (assoc nil
*namespaces
* :test
'equal
)))
194 (and (eql prefix nil
)
195 (cdr (assoc "" *namespaces
* :test
'equal
)))))
197 (defun find-variable-index (local-name uri table
)
198 (position (cons local-name uri
) table
:test
'equal
))
200 (defun intern-global-variable (local-name uri
)
201 (or (find-variable-index local-name uri
*global-variable-declarations
*)
202 (push-variable local-name uri
*global-variable-declarations
*)))
204 (defun push-variable (local-name uri table
)
207 (vector-push-extend (cons local-name uri
) table
)))
209 (defun lexical-variable-value (index &optional
(errorp t
))
210 (let ((result (svref *lexical-variable-values
* index
)))
212 (assert (not (eq result
'unbound
))))
215 (defun (setf lexical-variable-value
) (newval index
)
216 (assert (not (eq newval
'unbound
)))
217 (setf (svref *lexical-variable-values
* index
) newval
))
219 (defun global-variable-value (index &optional
(errorp t
))
220 (let ((result (svref *global-variable-values
* index
)))
222 (assert (not (eq result
'unbound
))))
225 (defun (setf global-variable-value
) (newval index
)
226 (assert (not (eq newval
'unbound
)))
227 (setf (svref *global-variable-values
* index
) newval
))
229 (defmethod xpath-sys:environment-find-function
230 ((env xslt-environment
) lname uri
)
232 (or (xpath-sys:find-xpath-function lname
*xsl
*)
233 (xpath-sys:find-xpath-function lname uri
))
234 (xpath-sys:find-xpath-function lname uri
)))
236 (defmethod xpath-sys:environment-find-variable
237 ((env xslt-environment
) lname uri
)
239 (find-variable-index lname uri
*lexical-variable-declarations
*)))
242 (declare (ignore ctx
))
243 (svref *lexical-variable-values
* index
)))))
245 (defclass lexical-xslt-environment
(xslt-environment) ())
247 (defmethod xpath-sys:environment-find-variable
248 ((env lexical-xslt-environment
) lname uri
)
249 (or (call-next-method)
251 (find-variable-index lname uri
*global-variable-declarations
*)))
255 (declare (ignore ctx
))
256 (svref *global-variable-values
* index
))
257 "global ~s (uri ~s) = ~s" lname uri
:result
)))))
259 (defclass global-variable-environment
(xslt-environment)
260 ((initial-global-variable-thunks
261 :initarg
:initial-global-variable-thunks
262 :accessor initial-global-variable-thunks
)))
264 (defmethod xpath-sys:environment-find-variable
265 ((env global-variable-environment
) lname uri
)
266 (or (call-next-method)
267 (gethash (cons lname uri
) (initial-global-variable-thunks env
))))
270 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
272 ;;;; A sink that serializes only text not contained in any element.
274 (defmacro with-toplevel-text-output-sink
((var) &body body
)
275 `(invoke-with-toplevel-text-output-sink (lambda (,var
) ,@body
)))
277 (defclass toplevel-text-output-sink
(sax:default-handler
)
278 ((target :initarg
:target
:accessor text-output-sink-target
)
279 (depth :initform
0 :accessor textoutput-sink-depth
)))
281 (defmethod sax:start-element
((sink toplevel-text-output-sink
)
282 namespace-uri local-name qname attributes
)
283 (declare (ignore namespace-uri local-name qname attributes
))
284 (incf (textoutput-sink-depth sink
)))
286 (defmethod sax:characters
((sink toplevel-text-output-sink
) data
)
287 (when (zerop (textoutput-sink-depth sink
))
288 (write-string data
(text-output-sink-target sink
))))
290 (defmethod sax:unescaped
((sink toplevel-text-output-sink
) data
)
291 (sax:characters sink data
))
293 (defmethod sax:end-element
((sink toplevel-text-output-sink
)
294 namespace-uri local-name qname
)
295 (declare (ignore namespace-uri local-name qname
))
296 (decf (textoutput-sink-depth sink
)))
298 (defun invoke-with-toplevel-text-output-sink (fn)
299 (with-output-to-string (s)
300 (funcall fn
(make-instance 'toplevel-text-output-sink
:target s
))))
305 ;;;; A sink that passes through only text (at any level) and turns to
306 ;;;; into unescaped characters.
308 (defclass text-filter
(sax:default-handler
)
309 ((target :initarg
:target
:accessor text-filter-target
)))
311 (defmethod sax:characters
((sink text-filter
) data
)
312 (sax:unescaped
(text-filter-target sink
) data
))
314 (defmethod sax:unescaped
((sink text-filter
) data
)
315 (sax:unescaped
(text-filter-target sink
) data
))
317 (defmethod sax:end-document
((sink text-filter
))
318 (sax:end-document
(text-filter-target sink
)))
320 (defun make-text-filter (target)
321 (make-instance 'text-filter
:target target
))
326 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
329 (defclass escaper
(cxml:broadcast-handler
)
332 (defmethod sax:unescaped
((sink escaper
) data
)
333 (sax:characters sink data
))
335 (defun make-escaper (target)
336 (make-instance 'escaper
:handlers
(list target
)))
341 (defun of-name (local-name)
342 (stp:of-name local-name
*xsl
*))
344 (defun namep (node local-name
)
345 (and (typep node
'(or stp
:element stp
:attribute
))
346 (equal (stp:namespace-uri node
) *xsl
*)
347 (equal (stp:local-name node
) local-name
)))
350 ;;;; PARSE-STYLESHEET
352 (defstruct stylesheet
353 (modes (make-hash-table :test
'equal
))
354 (global-variables (make-empty-declaration-array))
355 (output-specification (make-output-specification))
357 (named-templates (make-hash-table :test
'equal
))
358 (attribute-sets (make-hash-table :test
'equal
))
359 (keys (make-hash-table :test
'equal
))
360 (namespace-aliases (make-hash-table :test
'equal
))
361 (decimal-formats (make-hash-table :test
'equal
))
362 (initial-global-variable-thunks (make-hash-table :test
'equal
)))
366 (match-thunk (lambda (ignore) (declare (ignore ignore
)) nil
)))
368 (defun find-mode (stylesheet local-name
&optional uri
)
369 (gethash (cons local-name uri
) (stylesheet-modes stylesheet
)))
371 (defun ensure-mode (stylesheet &optional local-name uri
)
372 (or (find-mode stylesheet local-name uri
)
373 (setf (gethash (cons local-name uri
) (stylesheet-modes stylesheet
))
376 (defun ensure-mode/qname
(stylesheet qname env
)
378 (multiple-value-bind (local-name uri
)
379 (decode-qname qname env nil
)
380 (ensure-mode stylesheet local-name uri
))
381 (find-mode stylesheet nil
)))
383 (defun acons-namespaces (element &optional
(bindings *namespaces
*))
384 (map-namespace-declarations (lambda (prefix uri
)
385 (push (cons prefix uri
) bindings
))
389 (defun find-key (name stylesheet
)
390 (or (gethash name
(stylesheet-keys stylesheet
))
391 (xslt-error "unknown key: ~a" name
)))
393 (defun make-key (match use
) (cons match use
))
395 (defun key-match (key) (car key
))
397 (defun key-use (key) (cdr key
))
399 (defun add-key (stylesheet name match use
)
400 (if (gethash name
(stylesheet-keys stylesheet
))
401 (xslt-error "duplicate key: ~a" name
)
402 (setf (gethash name
(stylesheet-keys stylesheet
))
403 (make-key match use
))))
405 (defvar *excluded-namespaces
* (list *xsl
*))
406 (defvar *empty-mode
*)
407 (defvar *default-mode
*)
409 (defvar *xsl-include-stack
* nil
)
411 (defun uri-to-pathname (uri)
412 (cxml::uri-to-pathname
(puri:parse-uri uri
)))
414 (defun unwrap-2.3
(document)
415 (let ((literal-result-element (stp:document-element document
))
416 (new-template (stp:make-element
"template" *xsl
*))
417 (new-document-element (stp:make-element
"stylesheet" *xsl
*)))
418 (setf (stp:attribute-value new-document-element
"version")
419 (or (stp:attribute-value literal-result-element
"version" *xsl
*)
420 (xslt-error "not a stylesheet: root element lacks xsl:version")))
421 (setf (stp:attribute-value new-template
"match") "/")
422 (setf (stp:document-element document
) new-document-element
)
423 (stp:append-child new-document-element new-template
)
424 (stp:append-child new-template literal-result-element
)
425 new-document-element
))
427 (defun parse-stylesheet-to-stp (input uri-resolver
)
428 (let* ((d (cxml:parse input
(make-text-normalizer (cxml-stp:make-builder
))))
429 (<transform
> (stp:document-element d
)))
430 (unless (equal (stp:namespace-uri
<transform
>) *xsl
*)
431 (setf <transform
> (unwrap-2.3 d
)))
432 (strip-stylesheet <transform
>)
433 (unless (and (equal (stp:namespace-uri
<transform
>) *xsl
*)
434 (or (equal (stp:local-name
<transform
>) "transform")
435 (equal (stp:local-name
<transform
>) "stylesheet")))
436 (xslt-error "not a stylesheet"))
437 (check-for-invalid-attributes '(("version" .
"")
438 ("exclude-result-prefixes" .
"")
439 ("extension-element-prefixes" .
""))
442 (or (stp:find-child-if
(of-name "stylesheet") <transform
>)
443 (stp:find-child-if
(of-name "transform") <transform
>))))
445 (xslt-error "invalid top-level element ~A" (stp:local-name invalid
))))
446 (dolist (include (stp:filter-children
(of-name "include") <transform
>))
447 (let* ((uri (puri:merge-uris
(stp:attribute-value include
"href")
448 (stp:base-uri include
)))
449 (uri (if uri-resolver
450 (funcall uri-resolver
(puri:render-uri uri nil
))
452 (str (puri:render-uri uri nil
))
455 (uri-to-pathname uri
)
456 (cxml:xml-parse-error
(c)
457 (xslt-error "cannot find included stylesheet ~A: ~A"
461 :element-type
'(unsigned-byte 8)
462 :if-does-not-exist nil
)
464 (xslt-error "cannot find included stylesheet ~A at ~A"
466 (when (find str
*xsl-include-stack
* :test
#'equal
)
467 (xslt-error "recursive inclusion of ~A" uri
))
468 (let* ((*xsl-include-stack
* (cons str
*xsl-include-stack
*))
469 (<transform
>2 (parse-stylesheet-to-stp stream uri-resolver
)))
470 (stp:insert-child-after
<transform
>
471 (stp:copy
<transform
>2)
473 (stp:detach include
)))))
476 (defvar *instruction-base-uri
*) ;misnamed, is also used in other attributes
477 (defvar *apply-imports-limit
*)
478 (defvar *import-priority
*)
479 (defvar *extension-namespaces
*)
480 (defvar *forwards-compatible-p
*)
482 (defmacro do-toplevel
((var xpath
<transform
>) &body body
)
483 `(map-toplevel (lambda (,var
) ,@body
) ,xpath
,<transform
>))
485 (defun map-toplevel (fn xpath
<transform
>)
486 (dolist (node (list-toplevel xpath
<transform
>))
487 (let ((*namespaces
* *namespaces
*))
488 (xpath:do-node-set
(ancestor (xpath:evaluate
"ancestor::node()" node
))
489 (when (xpath-protocol:node-type-p ancestor
:element
)
490 (setf *namespaces
* (acons-namespaces ancestor
))))
493 (defun list-toplevel (xpath <transform
>)
494 (labels ((recurse (sub)
497 (xpath:evaluate
"transform|stylesheet" sub
))))
499 (xpath-sys:pipe-of
(xpath:evaluate xpath sub
))
500 (xpath::mappend-pipe
#'recurse subsubs
)))))
501 (xpath::sort-nodes
(recurse <transform
>))))
503 (defmacro with-import-magic
((node env
) &body body
)
504 `(invoke-with-import-magic (lambda () ,@body
) ,node
,env
))
506 (defun invoke-with-import-magic (fn node env
)
507 (unless (or (namep node
"stylesheet") (namep node
"transform"))
508 (setf node
(stp:parent node
)))
509 (let ((*excluded-namespaces
* (list *xsl
*))
510 (*extension-namespaces
* '())
511 (*forwards-compatible-p
*
512 (not (equal (stp:attribute-value node
"version") "1.0"))))
513 (parse-exclude-result-prefixes! node env
)
514 (parse-extension-element-prefixes! node env
)
517 (defun parse-1-stylesheet (env stylesheet designator uri-resolver
)
518 (let* ((<transform
> (parse-stylesheet-to-stp designator uri-resolver
))
519 (instruction-base-uri (stp:base-uri
<transform
>))
520 (namespaces (acons-namespaces <transform
>))
521 (apply-imports-limit (1+ *import-priority
*))
523 (let ((*namespaces
* namespaces
))
524 (invoke-with-import-magic (constantly t
) <transform
> env
))
525 (do-toplevel (elt "node()" <transform
>)
526 (when (equal (stp:attribute-value
(stp:parent elt
) "version") "1.0")
527 (if (typep elt
'stp
:element
)
528 (when (or (equal (stp:namespace-uri elt
) "")
529 (and (equal (stp:namespace-uri elt
) *xsl
*)
530 (not (find (stp:local-name elt
)
531 '("key" "template" "output" "strip-space"
532 "preserve-space" "attribute-set"
533 "namespace-alias" "decimal-format"
534 "variable" "param" "import" "include"
535 ;; for include handling:
536 "stylesheet" "transform")
538 (xslt-error "unknown top-level element ~A" (stp:local-name elt
)))
539 (xslt-error "text at top-level"))))
540 (macrolet ((with-specials ((&optional
) &body body
)
541 `(let ((*instruction-base-uri
* instruction-base-uri
)
542 (*namespaces
* namespaces
)
543 (*apply-imports-limit
* apply-imports-limit
))
546 (do-toplevel (import "import" <transform
>)
547 (let ((uri (puri:merge-uris
(stp:attribute-value import
"href")
548 (stp:base-uri import
))))
549 (push (parse-imported-stylesheet env stylesheet uri uri-resolver
)
551 (let ((import-priority
552 (incf *import-priority
*))
553 (var-cont (prepare-global-variables stylesheet
<transform
>)))
554 ;; delay the rest of compilation until we've seen all global
557 (mapc #'funcall
(nreverse continuations
))
559 (let ((*import-priority
* import-priority
))
561 (parse-keys! stylesheet
<transform
> env
)
562 (parse-templates! stylesheet
<transform
> env
)
563 (parse-output! stylesheet
<transform
>)
564 (parse-strip/preserve-space
! stylesheet
<transform
> env
)
565 (parse-attribute-sets! stylesheet
<transform
> env
)
566 (parse-namespace-aliases! stylesheet
<transform
> env
)
567 (parse-decimal-formats! stylesheet
<transform
> env
))))))))
569 (defvar *xsl-import-stack
* nil
)
571 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver
)
572 (let* ((uri (if uri-resolver
573 (funcall uri-resolver
(puri:render-uri uri nil
))
575 (str (puri:render-uri uri nil
))
578 (uri-to-pathname uri
)
579 (cxml:xml-parse-error
(c)
580 (xslt-error "cannot find imported stylesheet ~A: ~A"
584 :element-type
'(unsigned-byte 8)
585 :if-does-not-exist nil
)
587 (xslt-error "cannot find imported stylesheet ~A at ~A"
589 (when (find str
*xsl-import-stack
* :test
#'equal
)
590 (xslt-error "recursive inclusion of ~A" uri
))
591 (let ((*xsl-import-stack
* (cons str
*xsl-import-stack
*)))
592 (parse-1-stylesheet env stylesheet stream uri-resolver
)))))
594 (defun parse-stylesheet (designator &key uri-resolver
)
595 (with-xpath-errors ()
596 (xpath:with-namespaces
((nil #.
*xsl
*))
597 (let* ((*import-priority
* 0)
598 (xpath:*allow-variables-in-patterns
* nil
)
599 (puri:*strict-parse
* nil
)
600 (stylesheet (make-stylesheet))
601 (env (make-instance 'lexical-xslt-environment
))
602 (*excluded-namespaces
* *excluded-namespaces
*)
603 (*global-variable-declarations
* (make-empty-declaration-array)))
604 (ensure-mode stylesheet nil
)
605 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver
))
606 ;; reverse attribute sets:
607 (let ((table (stylesheet-attribute-sets stylesheet
)))
608 (maphash (lambda (k v
)
609 (setf (gethash k table
) (nreverse v
)))
612 (unless (find-decimal-format "" "" stylesheet nil
)
613 (setf (find-decimal-format "" "" stylesheet
)
614 (make-decimal-format)))
615 ;; compile a template matcher for each mode:
617 for mode being each hash-value in
(stylesheet-modes stylesheet
)
619 (setf (mode-match-thunk mode
)
620 (xpath:make-pattern-matcher
621 (mapcar #'template-compiled-pattern
622 (mode-templates mode
)))))
625 (defun parse-attribute-sets! (stylesheet <transform
> env
)
626 (do-toplevel (elt "attribute-set" <transform
>)
627 (with-import-magic (elt env
)
629 (mapcar (lambda (qname)
630 (multiple-value-list (decode-qname qname env nil
)))
632 (stp:attribute-value elt
"use-attribute-sets"))))
638 (and (typep child
'stp
:element
)
639 (or (and (equal (stp:namespace-uri child
) *xsl
*)
640 (equal (stp:local-name child
)
642 (find (stp:namespace-uri child
)
643 *extension-namespaces
*
645 (xslt-error "non-attribute found in attribute set"))
646 (parse-instruction child
))
648 (*lexical-variable-declarations
*
649 (make-empty-declaration-array))
651 (compile-instruction `(progn ,@instructions
) env
))
652 (n-variables (length *lexical-variable-declarations
*)))
655 (loop for
(local-name uri nil
) in sets do
656 (dolist (thunk (find-attribute-set local-name uri
))
657 (funcall thunk ctx
)))
658 (let ((*lexical-variable-values
*
659 (make-variable-value-array n-variables
)))
660 (funcall thunk ctx
)))))
661 (gethash (multiple-value-bind (local-name uri
)
662 (decode-qname (stp:attribute-value elt
"name") env nil
)
663 (cons local-name uri
))
664 (stylesheet-attribute-sets stylesheet
))))))
666 (defun parse-namespace-aliases! (stylesheet <transform
> env
)
667 (do-toplevel (elt "namespace-alias" <transform
>)
668 (stp:with-attributes
(stylesheet-prefix result-prefix
) elt
670 (xpath-sys:environment-find-namespace env stylesheet-prefix
)
671 (stylesheet-namespace-aliases stylesheet
))
672 (xpath-sys:environment-find-namespace
674 (if (equal result-prefix
"#default")
678 (defun parse-decimal-formats! (stylesheet <transform
> env
)
679 (do-toplevel (elt "decimal-format" <transform
>)
680 (stp:with-attributes
(name
694 (multiple-value-bind (local-name uri
)
696 (decode-qname name env nil
)
698 (let ((current (find-decimal-format local-name uri stylesheet nil
))
703 (unless (eql (length x
) 1)
704 (xslt-error "not a single character: ~A" x
))
705 (let ((chr (elt x
0)))
706 (when (find chr seen
)
708 "conflicting decimal format characters: ~A"
715 (apply #'make-decimal-format
716 (append (str :infinity infinity
)
718 (chr :decimal-separator decimal-separator
)
719 (chr :grouping-separator grouping-separator
)
720 (chr :zero-digit zero-digit
)
721 (chr :percent percent
)
722 (chr :per-mille per-mille
)
724 (chr :pattern-separator pattern-separator
)
725 (chr :minus-sign minus-sign
)))))))
727 (unless (decimal-format= current new
)
728 (xslt-error "decimal format mismatch for ~S" local-name
))
729 (setf (find-decimal-format local-name uri stylesheet
) new
)))))))
731 (defun parse-exclude-result-prefixes! (node env
)
732 (stp:with-attributes
(exclude-result-prefixes)
734 (dolist (prefix (words (or exclude-result-prefixes
"")))
735 (if (equal prefix
"#default")
737 (unless (cxml-stp-impl::nc-name-p prefix
)
738 (xslt-error "invalid prefix: ~A" prefix
)))
739 (push (or (xpath-sys:environment-find-namespace env prefix
)
740 (xslt-error "namespace not found: ~A" prefix
))
741 *excluded-namespaces
*))))
743 (defun parse-extension-element-prefixes! (node env
)
744 (stp:with-attributes
(extension-element-prefixes)
746 (dolist (prefix (words (or extension-element-prefixes
"")))
747 (if (equal prefix
"#default")
749 (unless (cxml-stp-impl::nc-name-p prefix
)
750 (xslt-error "invalid prefix: ~A" prefix
)))
752 (or (xpath-sys:environment-find-namespace env prefix
)
753 (xslt-error "namespace not found: ~A" prefix
))))
754 (unless (equal uri
*xsl
*)
755 (push uri
*extension-namespaces
*)
756 (push uri
*excluded-namespaces
*))))))
758 (defun parse-strip/preserve-space
! (stylesheet <transform
> env
)
759 (xpath:with-namespaces
((nil #.
*xsl
*))
760 (do-toplevel (elt "strip-space|preserve-space" <transform
>)
761 (let ((*namespaces
* (acons-namespaces elt
))
763 (if (equal (stp:local-name elt
) "strip-space")
766 (dolist (name-test (words (stp:attribute-value elt
"elements")))
767 (let* ((pos (search ":*" name-test
))
770 ((eql pos
(- (length name-test
) 2))
771 (let* ((prefix (subseq name-test
0 pos
))
773 (xpath-sys:environment-find-namespace env prefix
)))
774 (unless (xpath::nc-name-p prefix
)
775 (xslt-error "not an NCName: ~A" prefix
))
776 (lambda (local-name uri
)
777 (declare (ignore local-name
))
778 (if (equal uri name-test-uri
)
781 ((equal name-test
"*")
782 (lambda (local-name uri
)
783 (declare (ignore local-name uri
))
786 (multiple-value-bind (name-test-local-name name-test-uri
)
787 (decode-qname name-test env nil
)
788 (lambda (local-name uri
)
789 (if (and (equal local-name name-test-local-name
)
790 (equal uri name-test-uri
))
793 (push test-function
(stylesheet-strip-tests stylesheet
))))))))
795 (defstruct (output-specification
796 (:conc-name
"OUTPUT-"))
804 (defun parse-output! (stylesheet <transform
>)
805 (dolist (<output
> (list-toplevel "output" <transform
>))
806 (let ((spec (stylesheet-output-specification stylesheet
)))
807 (stp:with-attributes
( ;; version
816 ;;; cdata-section-elements
820 (setf (output-method spec
) method
))
822 (setf (output-indent spec
) indent
))
824 (setf (output-encoding spec
) encoding
))
826 (setf (output-doctype-system spec
) doctype-system
))
828 (setf (output-doctype-public spec
) doctype-public
))
829 (when omit-xml-declaration
830 (setf (output-omit-xml-declaration spec
) omit-xml-declaration
))
831 ;;; (when cdata-section-elements
832 ;;; (setf (output-cdata-section-elements spec)
833 ;;; (concatenate 'string
834 ;;; (output-cdata-section-elements spec)
836 ;;; cdata-section-elements)))
839 (defun make-empty-declaration-array ()
840 (make-array 1 :fill-pointer
0 :adjustable t
))
842 (defun make-variable-value-array (n-lexical-variables)
843 (make-array n-lexical-variables
:initial-element
'unbound
))
845 (defun compile-global-variable (<variable
> env
) ;; also for <param>
846 (stp:with-attributes
(name select
) <variable
>
847 (when (and select
(stp:list-children
<variable
>))
848 (xslt-error "variable with select and body"))
849 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
852 (compile-xpath select env
))
853 ((stp:list-children
<variable
>)
854 (let* ((inner-sexpr `(progn ,@(parse-body <variable
>)))
855 (inner-thunk (compile-instruction inner-sexpr env
)))
857 (apply-to-result-tree-fragment ctx inner-thunk
))))
860 (declare (ignore ctx
))
862 (n-lexical-variables (length *lexical-variable-declarations
*)))
865 (let* ((*lexical-variable-values
*
866 (make-variable-value-array n-lexical-variables
)))
867 (funcall inner ctx
)))
868 "global ~s (~s) = ~s" name select
:result
))))
870 (defstruct (variable-chain
871 (:constructor make-variable-chain
)
872 (:conc-name
"VARIABLE-CHAIN-"))
879 (defstruct (import-variable
880 (:constructor make-variable
)
881 (:conc-name
"VARIABLE-"))
886 (defun parse-global-variable! (stylesheet <variable
> global-env
)
887 (let* ((*namespaces
* (acons-namespaces <variable
>))
888 (instruction-base-uri (stp:base-uri
<variable
>))
889 (*instruction-base-uri
* instruction-base-uri
)
890 (*excluded-namespaces
* (list *xsl
*))
891 (*extension-namespaces
* '())
892 (qname (stp:attribute-value
<variable
> "name")))
893 (with-import-magic (<variable
> global-env
)
895 (xslt-error "name missing in ~A" (stp:local-name
<variable
>)))
896 (multiple-value-bind (local-name uri
)
897 (decode-qname qname global-env nil
)
898 ;; For the normal compilation environment of templates, install it
899 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
900 (let ((index (intern-global-variable local-name uri
)))
901 ;; For the evaluation of a global variable itself, build a thunk
902 ;; that lazily resolves other variables, stored into
903 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
904 (let* ((value-thunk :unknown
)
905 (sgv (stylesheet-global-variables stylesheet
))
907 (if (< index
(length sgv
))
911 :local-name local-name
913 (next (car (variable-chain-definitions chain
)))
914 (global-variable-thunk
916 (let ((v (global-variable-value index nil
)))
920 (xslt-error "no next definition for: ~A"
922 (funcall (variable-value-thunk next
) ctx
))
924 (setf (global-variable-value index
) 'seen
)
925 (setf (global-variable-value index
)
926 (funcall value-thunk ctx
)))
929 (excluded-namespaces *excluded-namespaces
*)
930 (extension-namespaces *extension-namespaces
*)
932 (make-variable :param-p
(namep <variable
> "param")))
935 (let* ((*instruction-base-uri
* instruction-base-uri
)
936 (*excluded-namespaces
* excluded-namespaces
)
937 (*extension-namespaces
* extension-namespaces
)
939 (compile-global-variable <variable
> global-env
)))
940 (setf value-thunk fn
)
941 (setf (variable-value-thunk variable
) fn
)))))
942 (setf (variable-value-thunk-setter variable
)
944 (setf (gethash (cons local-name uri
)
945 (initial-global-variable-thunks global-env
))
946 global-variable-thunk
)
947 (setf (variable-chain-thunk chain
) global-variable-thunk
)
948 (push variable
(variable-chain-definitions chain
))
951 (defun parse-keys! (stylesheet <transform
> env
)
952 (xpath:with-namespaces
((nil #.
*xsl
*))
953 (do-toplevel (<key
> "key" <transform
>)
954 (let ((*instruction-base-uri
* (stp:base-uri
<key
>)))
955 (stp:with-attributes
(name match use
) <key
>
956 (unless name
(xslt-error "key name attribute not specified"))
957 (unless match
(xslt-error "key match attribute not specified"))
958 (unless use
(xslt-error "key use attribute not specified"))
959 (multiple-value-bind (local-name uri
)
960 (decode-qname name env nil
)
962 (cons local-name uri
)
963 (compile-xpath `(xpath:xpath
,(parse-key-pattern match
)) env
)
964 (compile-xpath use env
))))))))
966 (defun prepare-global-variables (stylesheet <transform
>)
967 (xpath:with-namespaces
((nil #.
*xsl
*))
968 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet
))
969 (global-env (make-instance 'global-variable-environment
970 :initial-global-variable-thunks igvt
))
972 (do-toplevel (<variable
> "variable|param" <transform
>)
974 (parse-global-variable! stylesheet
<variable
> global-env
)))
975 (xslt-trace "parsing global variable ~s (uri ~s)"
976 (variable-chain-local-name chain
)
977 (variable-chain-uri chain
))
981 (and (equal (variable-chain-local-name a
)
982 (variable-chain-local-name b
))
983 (equal (variable-chain-uri a
)
984 (variable-chain-uri b
)))))
985 (xslt-error "duplicate definition for global variable ~A"
986 (variable-chain-local-name chain
)))
987 (push chain chains
)))
988 (setf chains
(nreverse chains
))
989 (let ((table (stylesheet-global-variables stylesheet
))
990 (newlen (length *global-variable-declarations
*)))
991 (adjust-array table newlen
:fill-pointer newlen
)
992 (dolist (chain chains
)
993 (setf (elt table
(variable-chain-index chain
)) chain
)))
995 ;; now that the global environment knows about all variables, run the
996 ;; thunk setters to perform their compilation
997 (mapc (lambda (chain)
998 (dolist (var (variable-chain-definitions chain
))
999 (funcall (variable-value-thunk-setter var
))))
1002 (defun parse-templates! (stylesheet <transform
> env
)
1004 (do-toplevel (<template
> "template" <transform
>)
1005 (let ((*namespaces
* (acons-namespaces <template
>))
1006 (*instruction-base-uri
* (stp:base-uri
<template
>)))
1007 (with-import-magic (<template
> env
)
1008 (dolist (template (compile-template <template
> env i
))
1009 (let ((name (template-name template
)))
1011 (let* ((table (stylesheet-named-templates stylesheet
))
1012 (head (car (gethash name table
))))
1013 (when (and head
(eql (template-import-priority head
)
1014 (template-import-priority template
)))
1015 ;; fixme: is this supposed to be a run-time error?
1016 (xslt-error "conflicting templates for ~A" name
))
1017 (push template
(gethash name table
)))
1018 (let ((mode (ensure-mode/qname stylesheet
1019 (template-mode-qname template
)
1021 (setf (template-mode template
) mode
)
1022 (push template
(mode-templates mode
))))))))
1026 ;;;; APPLY-STYLESHEET
1028 (defvar *stylesheet
*)
1030 (deftype xml-designator
() '(or runes
:xstream runes
:rod array stream pathname
))
1032 (defun unalias-uri (uri)
1034 (gethash uri
(stylesheet-namespace-aliases *stylesheet
*)
1036 (check-type result string
)
1039 (defstruct (parameter
1040 (:constructor make-parameter
(value local-name
&optional uri
)))
1045 (defun find-parameter-value (local-name uri parameters
)
1046 (dolist (p parameters
)
1047 (when (and (equal (parameter-local-name p
) local-name
)
1048 (equal (parameter-uri p
) uri
))
1049 (return (parameter-value p
)))))
1051 (defvar *uri-resolver
*)
1053 (defun parse-allowing-microsoft-bom (pathname handler
)
1054 (with-open-file (s pathname
:element-type
'(unsigned-byte 8))
1055 (unless (and (eql (read-byte s nil
) #xef
)
1056 (eql (read-byte s nil
) #xbb
)
1057 (eql (read-byte s nil
) #xbf
))
1058 (file-position s
0))
1059 (cxml:parse s handler
)))
1061 (defvar *documents
*)
1063 (defun %document
(uri-string base-uri
)
1064 (let* ((absolute-uri
1065 (puri:merge-uris uri-string
(or base-uri
"")))
1068 (funcall *uri-resolver
* (puri:render-uri absolute-uri nil
))
1072 (uri-to-pathname resolved-uri
)
1073 (cxml:xml-parse-error
(c)
1074 (xslt-error "cannot find referenced document ~A: ~A"
1077 (or (gethash pathname
*documents
*)
1078 (setf (gethash pathname
*documents
*)
1079 (make-whitespace-stripper
1081 (parse-allowing-microsoft-bom pathname
1083 ((or file-error cxml
:xml-parse-error
) (c)
1084 (xslt-error "cannot parse referenced document ~A: ~A"
1086 (stylesheet-strip-tests *stylesheet
*))))))
1087 (when (puri:uri-fragment absolute-uri
)
1088 (xslt-error "use of fragment identifiers in document() not supported"))
1091 (xpath-sys:define-extension xslt
*xsl
*)
1093 (defun document-base-uri (node)
1094 (xpath-protocol:base-uri
1096 ((xpath-protocol:node-type-p node
:document
)
1097 (xpath::find-in-pipe-if
1099 (xpath-protocol:node-type-p x
:element
))
1100 (xpath-protocol:child-pipe node
)))
1101 ((xpath-protocol:node-type-p node
:element
)
1104 (xpath-protocol:parent-node node
)))))
1106 (xpath-sys:define-xpath-function
/lazy
1108 (object &optional node-set
)
1109 (let ((instruction-base-uri *instruction-base-uri
*))
1111 (let* ((object (funcall object ctx
))
1112 (node-set (and node-set
(funcall node-set ctx
)))
1115 (document-base-uri (xpath::textually-first-node node-set
))
1116 instruction-base-uri
)))
1117 (xpath-sys:make-node-set
1118 (if (xpath:node-set-p object
)
1119 (xpath:map-node-set-
>list
1121 (%document
(xpath:string-value node
)
1124 (document-base-uri node
))))
1126 (list (%document
(xpath:string-value object
) base-uri
))))))))
1128 (xpath-sys:define-xpath-function
/lazy xslt
:key
(name object
)
1129 (let ((namespaces *namespaces
*))
1131 (let* ((qname (xpath:string-value
(funcall name ctx
)))
1132 (object (funcall object ctx
))
1134 (multiple-value-bind (local-name uri
)
1135 (decode-qname/runtime qname namespaces nil
)
1136 (cons local-name uri
)))
1137 (key (find-key expanded-name
*stylesheet
*)))
1138 (labels ((get-by-key (value)
1139 (let ((value (xpath:string-value value
)))
1143 (xpath:evaluate-compiled
(key-use key
) node
)))
1144 (if (xpath:node-set-p uses
)
1145 (xpath::find-in-pipe
1147 (xpath-sys:pipe-of uses
)
1148 :key
#'xpath
:string-value
1150 (equal value
(xpath:string-value uses
)))))
1152 (xpath:node-set-value
1153 (xpath:evaluate-compiled
(key-match key
) ctx
)))))))
1154 (xpath-sys:make-node-set
1156 (if (xpath:node-set-p object
)
1157 (xpath::mappend-pipe
#'get-by-key
(xpath-sys:pipe-of object
))
1158 (get-by-key object
)))))))))
1160 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1162 (xpath-sys:define-xpath-function
/lazy xslt
:current
()
1164 (xpath-sys:make-node-set
1165 (xpath-sys:make-pipe
1166 (xpath:context-starting-node ctx
)
1169 (xpath-sys:define-xpath-function
/lazy xslt
:unparsed-entity-uri
(name)
1171 (or (xpath-protocol:unparsed-entity-uri
(xpath:context-node ctx
)
1175 (defun %get-node-id
(node)
1176 (when (xpath:node-set-p node
)
1177 (setf node
(xpath::textually-first-node node
)))
1179 (let ((id (xpath-sys:get-node-id node
))
1182 for parent
= node then next
1183 for next
= (xpath-protocol:parent-node parent
)
1184 for this-base-uri
= (xpath-protocol:base-uri parent
)
1185 for highest-base-uri
= (if (plusp (length this-base-uri
))
1189 finally
(return highest-base-uri
))))
1190 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1191 ;; checked only if everything else matches.
1193 ;; This might be pointless premature optimization, but I like the idea :-)
1194 (nreverse (concatenate 'string highest-base-uri
"//" id
)))))
1196 (xpath-sys:define-xpath-function
/lazy xslt
:generate-id
(&optional node-set-thunk
)
1199 (%get-node-id
(xpath:node-set-value
(funcall node-set-thunk ctx
))))
1201 (%get-node-id
(xpath:context-node ctx
)))))
1203 (declaim (special *available-instructions
*))
1205 (xpath-sys:define-xpath-function
/lazy xslt
:element-available
(qname)
1206 (let ((namespaces *namespaces
*))
1208 (let ((qname (funcall qname ctx
)))
1209 (multiple-value-bind (local-name uri
)
1210 (decode-qname/runtime qname namespaces nil
)
1211 (and (equal uri
*xsl
*)
1212 (gethash local-name
*available-instructions
*)
1215 (xpath-sys:define-xpath-function
/lazy xslt
:function-available
(qname)
1216 (let ((namespaces *namespaces
*))
1218 (let ((qname (funcall qname ctx
)))
1219 (multiple-value-bind (local-name uri
)
1220 (decode-qname/runtime qname namespaces nil
)
1221 (and (zerop (length uri
))
1222 (or (xpath-sys:find-xpath-function local-name
*xsl
*)
1223 (xpath-sys:find-xpath-function local-name uri
))
1226 (xpath-sys:define-xpath-function
/lazy xslt
:system-property
(qname)
1227 (let ((namespaces *namespaces
*))
1229 (let ((qname (funcall qname ctx
)))
1230 (multiple-value-bind (local-name uri
)
1231 (decode-qname/runtime qname namespaces nil
)
1232 (if (equal uri
*xsl
*)
1234 ((equal local-name
"version")
1236 ((equal local-name
"vendor")
1238 ((equal local-name
"vendor-uri")
1239 "http://repo.or.cz/w/xuriella.git")
1244 (defun apply-stylesheet
1245 (stylesheet source-designator
1246 &key output parameters uri-resolver navigator
)
1247 (when (typep stylesheet
'xml-designator
)
1250 ((cxml:xml-parse-error
1252 (xslt-error "cannot parse stylesheet: ~A" c
))))
1253 (parse-stylesheet stylesheet
))))
1254 (invoke-with-output-sink
1256 (with-xpath-errors ()
1257 (let* ((*documents
* (make-hash-table :test
'equal
))
1258 (xpath:*navigator
* (or navigator
:default-navigator
))
1259 (puri:*strict-parse
* nil
)
1260 (*stylesheet
* stylesheet
)
1261 (*empty-mode
* (make-mode))
1262 (*default-mode
* (find-mode stylesheet nil
))
1263 (global-variable-chains
1264 (stylesheet-global-variables stylesheet
))
1265 (*global-variable-values
*
1266 (make-variable-value-array (length global-variable-chains
)))
1267 (*uri-resolver
* uri-resolver
)
1269 (if (typep source-designator
'xml-designator
)
1270 (cxml:parse source-designator
(stp:make-builder
))
1273 (make-whitespace-stripper
1275 (stylesheet-strip-tests stylesheet
)))
1276 (ctx (xpath:make-context xpath-root-node
)))
1277 (when (pathnamep source-designator
)
1278 (setf (gethash source-designator
*documents
*) xpath-root-node
))
1281 (let ((head (car (variable-chain-definitions chain
))))
1282 (when (variable-param-p head
)
1284 (find-parameter-value
1285 (variable-chain-local-name chain
)
1286 (variable-chain-uri chain
)
1289 (setf (global-variable-value
1290 (variable-chain-index chain
))
1292 global-variable-chains
)
1295 (funcall (variable-chain-thunk chain
) ctx
))
1296 global-variable-chains
)
1297 ;; zzz we wouldn't have to mask float traps here if we used the
1298 ;; XPath API properly. Unfortunately I've been using FUNCALL
1299 ;; everywhere instead of EVALUATE, so let's paper over that
1300 ;; at a central place to be sure:
1301 (xpath::with-float-traps-masked
()
1302 (apply-templates ctx
:mode
*default-mode
*)))))
1303 (stylesheet-output-specification stylesheet
)
1306 (defun find-attribute-set (local-name uri
)
1307 (or (gethash (cons local-name uri
) (stylesheet-attribute-sets *stylesheet
*))
1308 (xslt-error "no such attribute set: ~A/~A" local-name uri
)))
1310 (defun apply-templates/list
(list &key param-bindings sort-predicate mode
)
1311 (when sort-predicate
1313 (mapcar #'xpath
:context-node
1314 (stable-sort (contextify-node-list list
)
1316 (let* ((n (length list
))
1317 (s/d
(lambda () n
)))
1322 (apply-templates (xpath:make-context child s
/d i
)
1323 :param-bindings param-bindings
1326 (defvar *stack-limit
* 200)
1328 (defun invoke-with-stack-limit (fn)
1329 (let ((*stack-limit
* (1- *stack-limit
*)))
1330 (unless (plusp *stack-limit
*)
1331 (xslt-error "*stack-limit* reached; stack overflow"))
1334 (defun invoke-template (ctx template param-bindings
)
1335 (let ((*lexical-variable-values
*
1336 (make-variable-value-array (template-n-variables template
))))
1337 (with-stack-limit ()
1339 for
(name-cons value
) in param-bindings
1340 for
(nil index nil
) = (find name-cons
1341 (template-params template
)
1346 (setf (lexical-variable-value index
) value
)))
1347 (funcall (template-body template
) ctx
))))
1349 (defun apply-default-templates (ctx mode
)
1350 (let ((node (xpath:context-node ctx
)))
1352 ((or (xpath-protocol:node-type-p node
:processing-instruction
)
1353 (xpath-protocol:node-type-p node
:comment
)))
1354 ((or (xpath-protocol:node-type-p node
:text
)
1355 (xpath-protocol:node-type-p node
:attribute
))
1356 (write-text (xpath-protocol:node-text node
)))
1358 (apply-templates/list
1360 (xpath-protocol:child-pipe node
))
1363 (defvar *apply-imports
*)
1365 (defun apply-applicable-templates (ctx templates param-bindings finally
)
1366 (labels ((apply-imports (&optional actual-param-bindings
)
1368 (let* ((this (pop templates
))
1369 (low (template-apply-imports-limit this
))
1370 (high (template-import-priority this
)))
1374 (<= low
(template-import-priority x
) high
))
1376 (invoke-template ctx this actual-param-bindings
))
1377 (funcall finally
))))
1378 (let ((*apply-imports
* #'apply-imports
))
1379 (apply-imports param-bindings
))))
1381 (defun apply-templates (ctx &key param-bindings mode
)
1382 (apply-applicable-templates ctx
1383 (find-templates ctx
(or mode
*default-mode
*))
1386 (apply-default-templates ctx mode
))))
1388 (defun call-template (ctx name
&optional param-bindings
)
1389 (apply-applicable-templates ctx
1390 (find-named-templates name
)
1393 (error "cannot find named template: ~s"
1396 (defun find-templates (ctx mode
)
1397 (let* ((matching-candidates
1398 (xpath:matching-values
(mode-match-thunk mode
)
1399 (xpath:context-node ctx
)))
1401 (if matching-candidates
1404 :key
#'template-import-priority
))
1406 (priority-groups (make-array npriorities
:initial-element nil
)))
1407 (dolist (template matching-candidates
)
1409 (elt priority-groups
(template-import-priority template
))))
1411 for i from
(1- npriorities
) downto
0
1412 for group
= (elt priority-groups i
)
1413 for template
= (maximize #'template
< group
)
1417 (defun find-named-templates (name)
1418 (gethash name
(stylesheet-named-templates *stylesheet
*)))
1420 (defun template< (a b
) ;assuming same import priority
1421 (let ((p (template-priority a
))
1422 (q (template-priority b
)))
1427 (xslt-cerror "conflicting templates:~_~A,~_~A"
1428 (template-match-expression a
)
1429 (template-match-expression b
))
1430 (< (template-position a
) (template-position b
))))))
1432 (defun maximize (< things
)
1434 (let ((max (car things
)))
1435 (dolist (other (cdr things
))
1436 (when (funcall < max other
)
1440 (defun invoke-with-output-sink (fn output-spec output
)
1443 (with-open-file (s output
1445 :element-type
'(unsigned-byte 8)
1446 :if-exists
:rename-and-delete
)
1447 (invoke-with-output-sink fn output-spec s
)))
1449 (invoke-with-output-sink fn
1451 (make-output-sink output-spec output
)))
1452 ((or hax
:abstract-handler sax
:abstract-handler
)
1453 (with-xml-output output
1454 (when (typep output
'(or combi-sink auto-detect-sink
))
1455 (sax:start-dtd output
1456 :autodetect-me-please
1457 (output-doctype-public output-spec
)
1458 (output-doctype-system output-spec
)))
1461 (defun make-output-sink (output-spec stream
)
1464 (let ((et (stream-element-type stream
)))
1466 ((or (null et
) (subtypep et
'(unsigned-byte 8)))
1467 (runes:make-octet-stream-ystream stream
))
1468 ((subtypep et
'character
)
1469 (runes:make-character-stream-ystream stream
))))
1470 (runes:make-rod-ystream
)))
1471 (omit-xml-declaration-p
1472 (equal (output-omit-xml-declaration output-spec
) "yes"))
1474 (make-instance 'cxml
::sink
1476 :omit-xml-declaration-p omit-xml-declaration-p
)))
1477 (flet ((make-combi-sink ()
1478 (make-instance 'combi-sink
1479 :hax-target
(make-instance 'chtml
::sink
1481 :sax-target sax-target
1482 :encoding
(output-encoding output-spec
))))
1485 ((equalp (output-method output-spec
) "HTML") :html
)
1486 ((equalp (output-method output-spec
) "TEXT") :text
)
1487 ((equalp (output-method output-spec
) "XML") :xml
)
1490 ((and (eq method-key
:html
)
1491 (null (output-doctype-system output-spec
))
1492 (null (output-doctype-public output-spec
)))
1494 ((eq method-key
:text
)
1495 (make-text-filter sax-target
))
1496 ((and (eq method-key
:xml
)
1497 (null (output-doctype-system output-spec
)))
1500 (make-auto-detect-sink (make-combi-sink) method-key
)))))))
1516 (defun expression-priority (form)
1517 (let ((step (second form
)))
1518 (if (and (null (cddr form
))
1520 (member (car step
) '(:child
:attribute
))
1522 (let ((name (second step
)))
1526 (or (eq (car name
) :qname
)
1527 (eq (car name
) :processing-instruction
))))
1530 (or (eq (car name
) :namespace
)
1531 (eq (car name
) '*)))
1537 (defun parse-xpath (str)
1538 (with-xpath-errors ()
1539 (xpath:parse-xpath str
)))
1541 (defun parse-key-pattern (str)
1543 (mapcar #'(lambda (item)
1544 `(:path
(:root
:node
)
1545 (:descendant-or-self
*)
1547 (parse-pattern str
))))
1548 (if (null (rest parsed
))
1550 `(:union
,@parsed
))))
1552 (defun parse-pattern (str)
1553 (with-xpath-errors ()
1554 (cdr (xpath::parse-pattern-expression str
))))
1556 (defun compile-value-thunk (value env
)
1557 (if (and (listp value
) (eq (car value
) 'progn
))
1558 (let ((inner-thunk (compile-instruction value env
)))
1560 (apply-to-result-tree-fragment ctx inner-thunk
)))
1561 (compile-xpath value env
)))
1563 (defun compile-var-binding (name value env
)
1564 (multiple-value-bind (local-name uri
)
1565 (decode-qname name env nil
)
1566 (let ((thunk (xslt-trace-thunk
1567 (compile-value-thunk value env
)
1568 "local variable ~s = ~s" name
:result
)))
1569 (list (cons local-name uri
)
1570 (push-variable local-name
1572 *lexical-variable-declarations
*)
1575 (defun compile-var-bindings (forms env
)
1577 for
(name value
) in forms
1578 collect
(compile-var-binding name value env
)))
1580 (defun compile-template (<template
> env position
)
1581 (stp:with-attributes
(match name priority mode
) <template
>
1582 (unless (or name match
)
1583 (xslt-error "missing match in template"))
1584 (multiple-value-bind (params body-pos
)
1587 for child in
(stp:list-children
<template
>)
1588 while
(namep child
"param")
1589 collect
(parse-param child
) into params
1590 finally
(return (values params i
)))
1591 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1592 (param-bindings (compile-var-bindings params env
))
1593 (body (parse-body <template
> body-pos
(mapcar #'car params
)))
1594 (body-thunk (compile-instruction `(progn ,@body
) env
))
1600 ;; set params that weren't initialized by apply-templates
1601 (loop for
(name index param-thunk
) in param-bindings
1602 when
(eq (lexical-variable-value index nil
) 'unbound
)
1603 do
(setf (lexical-variable-value index
)
1604 (funcall param-thunk ctx
)))
1605 (funcall body-thunk ctx
))))
1606 "template: match = ~s name = ~s" match name
))
1607 (n-variables (length *lexical-variable-declarations
*)))
1610 (multiple-value-bind (local-name uri
)
1611 (decode-qname name env nil
)
1613 (make-template :name
(cons local-name uri
)
1614 :import-priority
*import-priority
*
1615 :apply-imports-limit
*apply-imports-limit
*
1616 :params param-bindings
1617 :body outer-body-thunk
1618 :n-variables n-variables
))))
1620 (mapcar (lambda (expression)
1621 (let* ((compiled-pattern
1623 (car (xpath:compute-patterns
1624 `(:patterns
,expression
)
1628 "match-thunk for template (match ~s): ~s --> ~s"
1629 match expression
:result
))
1631 (parse-number:parse-number priority
)
1632 (expression-priority expression
)))
1634 (make-template :match-expression expression
1635 :compiled-pattern compiled-pattern
1636 :import-priority
*import-priority
*
1637 :apply-imports-limit
*apply-imports-limit
*
1641 :params param-bindings
1642 :body outer-body-thunk
1643 :n-variables n-variables
)))
1644 (setf (xpath:pattern-value compiled-pattern
)
1647 (cdr (xpath:parse-pattern-expression match
)))))))))
1649 (xuriella::parse-stylesheet
#p
"/home/david/src/lisp/xuriella/test.xsl")