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))
364 (named-templates (make-hash-table :test
'equal
))
365 (attribute-sets (make-hash-table :test
'equal
))
366 (keys (make-hash-table :test
'equal
))
367 (namespace-aliases (make-hash-table :test
'equal
))
368 (decimal-formats (make-hash-table :test
'equal
))
369 (initial-global-variable-thunks (make-hash-table :test
'equal
)))
373 (match-thunk (lambda (ignore) (declare (ignore ignore
)) nil
)))
375 (defun find-mode (stylesheet local-name
&optional uri
)
376 (gethash (cons local-name uri
) (stylesheet-modes stylesheet
)))
378 (defun ensure-mode (stylesheet &optional local-name uri
)
379 (or (find-mode stylesheet local-name uri
)
380 (setf (gethash (cons local-name uri
) (stylesheet-modes stylesheet
))
383 (defun ensure-mode/qname
(stylesheet qname env
)
385 (multiple-value-bind (local-name uri
)
386 (decode-qname qname env nil
)
387 (ensure-mode stylesheet local-name uri
))
388 (find-mode stylesheet nil
)))
390 (defun acons-namespaces (element &optional
(bindings *namespaces
*))
391 (map-namespace-declarations (lambda (prefix uri
)
392 (push (cons prefix uri
) bindings
))
396 (defun find-key (name stylesheet
)
397 (or (gethash name
(stylesheet-keys stylesheet
))
398 (xslt-error "unknown key: ~a" name
)))
400 (defun make-key (match use
) (cons match use
))
402 (defun key-match (key) (car key
))
404 (defun key-use (key) (cdr key
))
406 (defun add-key (stylesheet name match use
)
407 (if (gethash name
(stylesheet-keys stylesheet
))
408 (xslt-error "duplicate key: ~a" name
)
409 (setf (gethash name
(stylesheet-keys stylesheet
))
410 (make-key match use
))))
412 (defvar *excluded-namespaces
* (list *xsl
*))
413 (defvar *empty-mode
*)
414 (defvar *default-mode
*)
416 (defvar *xsl-include-stack
* nil
)
418 (defun uri-to-pathname (uri)
419 (cxml::uri-to-pathname
(puri:parse-uri uri
)))
421 (defun unwrap-2.3
(document)
422 (let ((literal-result-element (stp:document-element document
))
423 (new-template (stp:make-element
"template" *xsl
*))
424 (new-document-element (stp:make-element
"stylesheet" *xsl
*)))
425 (setf (stp:attribute-value new-document-element
"version")
426 (or (stp:attribute-value literal-result-element
"version" *xsl
*)
427 (xslt-error "not a stylesheet: root element lacks xsl:version")))
428 (setf (stp:attribute-value new-template
"match") "/")
429 (setf (stp:document-element document
) new-document-element
)
430 (stp:append-child new-document-element new-template
)
431 (stp:append-child new-template literal-result-element
)
432 new-document-element
))
434 (defun parse-stylesheet-to-stp (input uri-resolver
)
435 (let* ((d (cxml:parse input
(make-text-normalizer (cxml-stp:make-builder
))))
436 (<transform
> (stp:document-element d
)))
437 (unless (equal (stp:namespace-uri
<transform
>) *xsl
*)
438 (setf <transform
> (unwrap-2.3 d
)))
439 (strip-stylesheet <transform
>)
440 (unless (and (equal (stp:namespace-uri
<transform
>) *xsl
*)
441 (or (equal (stp:local-name
<transform
>) "transform")
442 (equal (stp:local-name
<transform
>) "stylesheet")))
443 (xslt-error "not a stylesheet"))
444 (check-for-invalid-attributes '(("version" .
"")
445 ("exclude-result-prefixes" .
"")
446 ("extension-element-prefixes" .
""))
449 (or (stp:find-child-if
(of-name "stylesheet") <transform
>)
450 (stp:find-child-if
(of-name "transform") <transform
>))))
452 (xslt-error "invalid top-level element ~A" (stp:local-name invalid
))))
453 (dolist (include (stp:filter-children
(of-name "include") <transform
>))
454 (let* ((uri (puri:merge-uris
(stp:attribute-value include
"href")
455 (stp:base-uri include
)))
456 (uri (if uri-resolver
457 (funcall uri-resolver
(puri:render-uri uri nil
))
459 (str (puri:render-uri uri nil
))
462 (uri-to-pathname uri
)
463 (cxml:xml-parse-error
(c)
464 (xslt-error "cannot find included stylesheet ~A: ~A"
468 :element-type
'(unsigned-byte 8)
469 :if-does-not-exist nil
)
471 (xslt-error "cannot find included stylesheet ~A at ~A"
473 (when (find str
*xsl-include-stack
* :test
#'equal
)
474 (xslt-error "recursive inclusion of ~A" uri
))
475 (let* ((*xsl-include-stack
* (cons str
*xsl-include-stack
*))
476 (<transform
>2 (parse-stylesheet-to-stp stream uri-resolver
)))
477 (stp:insert-child-after
<transform
>
478 (stp:copy
<transform
>2)
480 (stp:detach include
)))))
483 (defvar *instruction-base-uri
*) ;misnamed, is also used in other attributes
484 (defvar *apply-imports-limit
*)
485 (defvar *import-priority
*)
486 (defvar *extension-namespaces
*)
487 (defvar *forwards-compatible-p
*)
489 (defmacro do-toplevel
((var xpath
<transform
>) &body body
)
490 `(map-toplevel (lambda (,var
) ,@body
) ,xpath
,<transform
>))
492 (defun map-toplevel (fn xpath
<transform
>)
493 (dolist (node (list-toplevel xpath
<transform
>))
494 (let ((*namespaces
* *namespaces
*))
495 (xpath:do-node-set
(ancestor (xpath:evaluate
"ancestor::node()" node
))
496 (when (xpath-protocol:node-type-p ancestor
:element
)
497 (setf *namespaces
* (acons-namespaces ancestor
))))
500 (defun list-toplevel (xpath <transform
>)
501 (labels ((recurse (sub)
504 (xpath:evaluate
"transform|stylesheet" sub
))))
506 (xpath-sys:pipe-of
(xpath:evaluate xpath sub
))
507 (xpath::mappend-pipe
#'recurse subsubs
)))))
508 (xpath::sort-nodes
(recurse <transform
>))))
510 (defmacro with-import-magic
((node env
) &body body
)
511 `(invoke-with-import-magic (lambda () ,@body
) ,node
,env
))
513 (defun invoke-with-import-magic (fn node env
)
514 (unless (or (namep node
"stylesheet") (namep node
"transform"))
515 (setf node
(stp:parent node
)))
516 (let ((*excluded-namespaces
* (list *xsl
*))
517 (*extension-namespaces
* '())
518 (*forwards-compatible-p
*
519 (not (equal (stp:attribute-value node
"version") "1.0"))))
520 (parse-exclude-result-prefixes! node env
)
521 (parse-extension-element-prefixes! node env
)
524 (defun parse-1-stylesheet (env stylesheet designator uri-resolver
)
525 (let* ((<transform
> (parse-stylesheet-to-stp designator uri-resolver
))
526 (instruction-base-uri (stp:base-uri
<transform
>))
527 (namespaces (acons-namespaces <transform
>))
528 (apply-imports-limit (1+ *import-priority
*))
530 (let ((*namespaces
* namespaces
))
531 (invoke-with-import-magic (constantly t
) <transform
> env
))
532 (do-toplevel (elt "node()" <transform
>)
533 (let ((version (stp:attribute-value
(stp:parent elt
) "version")))
536 (xslt-error "stylesheet lacks version"))
537 ((equal version
"1.0")
538 (if (typep elt
'stp
:element
)
539 (when (or (equal (stp:namespace-uri elt
) "")
540 (and (equal (stp:namespace-uri elt
) *xsl
*)
541 (not (find (stp:local-name elt
)
542 '("key" "template" "output"
543 "strip-space" "preserve-space"
544 "attribute-set" "namespace-alias"
545 "decimal-format" "variable" "param"
547 ;; for include handling:
548 "stylesheet" "transform")
550 (xslt-error "unknown top-level element ~A" (stp:local-name elt
)))
551 (xslt-error "text at top-level"))))))
552 (macrolet ((with-specials ((&optional
) &body body
)
553 `(let ((*instruction-base-uri
* instruction-base-uri
)
554 (*namespaces
* namespaces
)
555 (*apply-imports-limit
* apply-imports-limit
))
558 (do-toplevel (import "import" <transform
>)
559 (let ((uri (puri:merge-uris
(stp:attribute-value import
"href")
560 (stp:base-uri import
))))
561 (push (parse-imported-stylesheet env stylesheet uri uri-resolver
)
563 (let ((import-priority
564 (incf *import-priority
*))
565 (var-cont (prepare-global-variables stylesheet
<transform
>)))
566 ;; delay the rest of compilation until we've seen all global
569 (mapc #'funcall
(nreverse continuations
))
571 (let ((*import-priority
* import-priority
))
573 (parse-keys! stylesheet
<transform
> env
)
574 (parse-templates! stylesheet
<transform
> env
)
575 (parse-output! stylesheet
<transform
>)
576 (parse-strip/preserve-space
! stylesheet
<transform
> env
)
577 (parse-attribute-sets! stylesheet
<transform
> env
)
578 (parse-namespace-aliases! stylesheet
<transform
> env
)
579 (parse-decimal-formats! stylesheet
<transform
> env
))))))))
581 (defvar *xsl-import-stack
* nil
)
583 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver
)
584 (let* ((uri (if uri-resolver
585 (funcall uri-resolver
(puri:render-uri uri nil
))
587 (str (puri:render-uri uri nil
))
590 (uri-to-pathname uri
)
591 (cxml:xml-parse-error
(c)
592 (xslt-error "cannot find imported stylesheet ~A: ~A"
596 :element-type
'(unsigned-byte 8)
597 :if-does-not-exist nil
)
599 (xslt-error "cannot find imported stylesheet ~A at ~A"
601 (when (find str
*xsl-import-stack
* :test
#'equal
)
602 (xslt-error "recursive inclusion of ~A" uri
))
603 (let ((*xsl-import-stack
* (cons str
*xsl-import-stack
*)))
604 (parse-1-stylesheet env stylesheet stream uri-resolver
)))))
606 (defvar *included-attribute-sets
*)
608 (defun parse-stylesheet (designator &key uri-resolver
)
609 (with-resignalled-errors ()
610 (xpath:with-namespaces
((nil #.
*xsl
*))
611 (let* ((*import-priority
* 0)
612 (xpath:*allow-variables-in-patterns
* nil
)
613 (puri:*strict-parse
* nil
)
614 (stylesheet (make-stylesheet))
615 (env (make-instance 'lexical-xslt-environment
))
616 (*excluded-namespaces
* *excluded-namespaces
*)
617 (*global-variable-declarations
* (make-empty-declaration-array))
618 (*included-attribute-sets
* nil
))
619 (ensure-mode stylesheet nil
)
620 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver
))
621 ;; reverse attribute sets:
622 (let ((table (stylesheet-attribute-sets stylesheet
)))
623 (maphash (lambda (k v
)
624 (setf (gethash k table
) (nreverse v
)))
627 (dolist (sets *included-attribute-sets
*)
628 (loop for
(local-name uri nil
) in sets do
629 (find-attribute-set local-name uri stylesheet
)))
631 (unless (find-decimal-format "" "" stylesheet nil
)
632 (setf (find-decimal-format "" "" stylesheet
)
633 (make-decimal-format)))
634 ;; compile a template matcher for each mode:
636 for mode being each hash-value in
(stylesheet-modes stylesheet
)
638 (setf (mode-match-thunk mode
)
639 (xpath:make-pattern-matcher
640 (mapcar #'template-compiled-pattern
641 (mode-templates mode
)))))
642 ;; and for the strip tests
643 (setf (stylesheet-strip-thunk stylesheet
)
644 (let ((patterns (stylesheet-strip-tests stylesheet
)))
646 (xpath:make-pattern-matcher
647 (mapcar #'strip-test-compiled-pattern patterns
)))))
650 (defun parse-attribute-sets! (stylesheet <transform
> env
)
651 (do-toplevel (elt "attribute-set" <transform
>)
652 (with-import-magic (elt env
)
654 (mapcar (lambda (qname)
655 (multiple-value-list (decode-qname qname env nil
)))
657 (stp:attribute-value elt
"use-attribute-sets"))))
663 (and (typep child
'stp
:element
)
664 (or (and (equal (stp:namespace-uri child
) *xsl
*)
665 (equal (stp:local-name child
)
667 (find (stp:namespace-uri child
)
668 *extension-namespaces
*
670 (xslt-error "non-attribute found in attribute set"))
671 (parse-instruction child
))
673 (*lexical-variable-declarations
*
674 (make-empty-declaration-array))
676 (compile-instruction `(progn ,@instructions
) env
))
677 (n-variables (length *lexical-variable-declarations
*)))
678 (push sets
*included-attribute-sets
*)
681 (loop for
(local-name uri nil
) in sets do
682 (dolist (thunk (find-attribute-set local-name uri
))
683 (funcall thunk ctx
)))
684 (let ((*lexical-variable-values
*
685 (make-variable-value-array n-variables
)))
686 (funcall thunk ctx
)))))
687 (gethash (multiple-value-bind (local-name uri
)
688 (decode-qname (or (stp:attribute-value elt
"name")
689 (xslt-error "missing name"))
692 (cons local-name uri
))
693 (stylesheet-attribute-sets stylesheet
))))))
695 (defun parse-namespace-aliases! (stylesheet <transform
> env
)
696 (do-toplevel (elt "namespace-alias" <transform
>)
697 (stp:with-attributes
(stylesheet-prefix result-prefix
) elt
699 (if (equal stylesheet-prefix
"#default")
701 (xpath-sys:environment-find-namespace env stylesheet-prefix
))
702 (stylesheet-namespace-aliases stylesheet
))
703 (xpath-sys:environment-find-namespace
705 (if (equal result-prefix
"#default")
709 (defun parse-decimal-formats! (stylesheet <transform
> env
)
710 (do-toplevel (elt "decimal-format" <transform
>)
711 (stp:with-attributes
(name
725 (multiple-value-bind (local-name uri
)
727 (decode-qname name env nil
)
729 (let ((current (find-decimal-format local-name uri stylesheet nil
))
734 (unless (eql (length x
) 1)
735 (xslt-error "not a single character: ~A" x
))
736 (let ((chr (elt x
0)))
737 (when (find chr seen
)
739 "conflicting decimal format characters: ~A"
746 (apply #'make-decimal-format
747 (append (str :infinity infinity
)
749 (chr :decimal-separator decimal-separator
)
750 (chr :grouping-separator grouping-separator
)
751 (chr :zero-digit zero-digit
)
752 (chr :percent percent
)
753 (chr :per-mille per-mille
)
755 (chr :pattern-separator pattern-separator
)
756 (chr :minus-sign minus-sign
)))))))
758 (unless (decimal-format= current new
)
759 (xslt-error "decimal format mismatch for ~S" local-name
))
760 (setf (find-decimal-format local-name uri stylesheet
) new
)))))))
762 (defun parse-exclude-result-prefixes! (node env
)
763 (stp:with-attributes
(exclude-result-prefixes)
765 (dolist (prefix (words (or exclude-result-prefixes
"")))
766 (if (equal prefix
"#default")
768 (unless (cxml-stp-impl::nc-name-p prefix
)
769 (xslt-error "invalid prefix: ~A" prefix
)))
770 (push (or (xpath-sys:environment-find-namespace env prefix
)
771 (xslt-error "namespace not found: ~A" prefix
))
772 *excluded-namespaces
*))))
774 (defun parse-extension-element-prefixes! (node env
)
775 (stp:with-attributes
(extension-element-prefixes)
777 (dolist (prefix (words (or extension-element-prefixes
"")))
778 (if (equal prefix
"#default")
780 (unless (cxml-stp-impl::nc-name-p prefix
)
781 (xslt-error "invalid prefix: ~A" prefix
)))
783 (or (xpath-sys:environment-find-namespace env prefix
)
784 (xslt-error "namespace not found: ~A" prefix
))))
785 (unless (equal uri
*xsl
*)
786 (push uri
*extension-namespaces
*)
787 (push uri
*excluded-namespaces
*))))))
789 (defun parse-nametest-tokens (str)
790 (labels ((check (boolean)
792 (xslt-error "invalid nametest token")))
793 (check-null (boolean)
794 (check (not boolean
))))
797 (mapcar (lambda (name-test)
798 (destructuring-bind (&optional path
&rest junk
)
799 (cdr (xpath:parse-pattern-expression name-test
))
801 (check (eq (car path
) :path
))
802 (destructuring-bind (&optional child
&rest junk
) (cdr path
)
804 (check (eq (car child
) :child
))
805 (destructuring-bind (nodetest &rest junk
) (cdr child
)
807 (check (or (stringp nodetest
)
809 (and (consp nodetest
)
810 (or (eq (car nodetest
) :namespace
)
811 (eq (car nodetest
) :qname
)))))))
815 (defstruct strip-test
821 (defun parse-strip/preserve-space
! (stylesheet <transform
> env
)
823 (do-toplevel (elt "strip-space|preserve-space" <transform
>)
824 (let ((*namespaces
* (acons-namespaces elt
))
826 (if (equal (stp:local-name elt
) "strip-space")
830 (cdr (parse-nametest-tokens
831 (stp:attribute-value elt
"elements"))))
832 (let* ((compiled-pattern
833 (car (xpath:compute-patterns
834 `(:patterns
,expression
)
839 (make-strip-test :compiled-pattern compiled-pattern
840 :priority
(expression-priority expression
)
843 (setf (xpath:pattern-value compiled-pattern
) strip-test
)
844 (push strip-test
(stylesheet-strip-tests stylesheet
)))))
847 (defstruct (output-specification
848 (:conc-name
"OUTPUT-"))
856 (defun parse-output! (stylesheet <transform
>)
857 (dolist (<output
> (list-toplevel "output" <transform
>))
858 (let ((spec (stylesheet-output-specification stylesheet
)))
859 (stp:with-attributes
( ;; version
868 ;;; cdata-section-elements
872 (setf (output-method spec
) method
))
874 (setf (output-indent spec
) indent
))
876 (setf (output-encoding spec
) encoding
))
878 (setf (output-doctype-system spec
) doctype-system
))
880 (setf (output-doctype-public spec
) doctype-public
))
881 (when omit-xml-declaration
882 (setf (output-omit-xml-declaration spec
) omit-xml-declaration
))
883 ;;; (when cdata-section-elements
884 ;;; (setf (output-cdata-section-elements spec)
885 ;;; (concatenate 'string
886 ;;; (output-cdata-section-elements spec)
888 ;;; cdata-section-elements)))
891 (defun make-empty-declaration-array ()
892 (make-array 1 :fill-pointer
0 :adjustable t
))
894 (defun make-variable-value-array (n-lexical-variables)
895 (make-array n-lexical-variables
:initial-element
'unbound
))
897 (defun compile-global-variable (<variable
> env
) ;; also for <param>
898 (stp:with-attributes
(name select
) <variable
>
899 (when (and select
(stp:list-children
<variable
>))
900 (xslt-error "variable with select and body"))
901 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
904 (compile-xpath select env
))
905 ((stp:list-children
<variable
>)
906 (let* ((inner-sexpr `(progn ,@(parse-body <variable
>)))
907 (inner-thunk (compile-instruction inner-sexpr env
)))
909 (apply-to-result-tree-fragment ctx inner-thunk
))))
912 (declare (ignore ctx
))
914 (n-lexical-variables (length *lexical-variable-declarations
*)))
917 (let* ((*lexical-variable-values
*
918 (make-variable-value-array n-lexical-variables
)))
919 (funcall inner ctx
)))
920 "global ~s (~s) = ~s" name select
:result
))))
922 (defstruct (variable-chain
923 (:constructor make-variable-chain
)
924 (:conc-name
"VARIABLE-CHAIN-"))
931 (defstruct (import-variable
932 (:constructor make-variable
)
933 (:conc-name
"VARIABLE-"))
938 (defun parse-global-variable! (stylesheet <variable
> global-env
)
939 (let* ((*namespaces
* (acons-namespaces <variable
>))
940 (instruction-base-uri (stp:base-uri
<variable
>))
941 (*instruction-base-uri
* instruction-base-uri
)
942 (*excluded-namespaces
* (list *xsl
*))
943 (*extension-namespaces
* '())
944 (qname (stp:attribute-value
<variable
> "name")))
945 (with-import-magic (<variable
> global-env
)
947 (xslt-error "name missing in ~A" (stp:local-name
<variable
>)))
948 (multiple-value-bind (local-name uri
)
949 (decode-qname qname global-env nil
)
950 ;; For the normal compilation environment of templates, install it
951 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
952 (let ((index (intern-global-variable local-name uri
)))
953 ;; For the evaluation of a global variable itself, build a thunk
954 ;; that lazily resolves other variables, stored into
955 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
956 (let* ((value-thunk :unknown
)
957 (sgv (stylesheet-global-variables stylesheet
))
959 (if (< index
(length sgv
))
963 :local-name local-name
965 (next (car (variable-chain-definitions chain
)))
966 (global-variable-thunk
968 (let ((v (global-variable-value index nil
)))
972 (xslt-error "no next definition for: ~A"
974 (funcall (variable-value-thunk next
) ctx
))
976 (setf (global-variable-value index
) 'seen
)
977 (setf (global-variable-value index
)
978 (funcall value-thunk ctx
)))
981 (excluded-namespaces *excluded-namespaces
*)
982 (extension-namespaces *extension-namespaces
*)
984 (make-variable :param-p
(namep <variable
> "param")))
987 (let* ((*instruction-base-uri
* instruction-base-uri
)
988 (*excluded-namespaces
* excluded-namespaces
)
989 (*extension-namespaces
* extension-namespaces
)
991 (compile-global-variable <variable
> global-env
)))
992 (setf value-thunk fn
)
993 (setf (variable-value-thunk variable
) fn
)))))
994 (setf (variable-value-thunk-setter variable
)
996 (setf (gethash (cons local-name uri
)
997 (initial-global-variable-thunks global-env
))
998 global-variable-thunk
)
999 (setf (variable-chain-thunk chain
) global-variable-thunk
)
1000 (push variable
(variable-chain-definitions chain
))
1003 (defun parse-keys! (stylesheet <transform
> env
)
1004 (xpath:with-namespaces
((nil #.
*xsl
*))
1005 (do-toplevel (<key
> "key" <transform
>)
1006 (let ((*instruction-base-uri
* (stp:base-uri
<key
>)))
1007 (stp:with-attributes
(name match use
) <key
>
1008 (unless name
(xslt-error "key name attribute not specified"))
1009 (unless match
(xslt-error "key match attribute not specified"))
1010 (unless use
(xslt-error "key use attribute not specified"))
1011 (multiple-value-bind (local-name uri
)
1012 (decode-qname name env nil
)
1014 (cons local-name uri
)
1015 (compile-xpath `(xpath:xpath
,(parse-key-pattern match
)) env
)
1016 (compile-xpath use env
))))))))
1018 (defun prepare-global-variables (stylesheet <transform
>)
1019 (xpath:with-namespaces
((nil #.
*xsl
*))
1020 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet
))
1021 (global-env (make-instance 'global-variable-environment
1022 :initial-global-variable-thunks igvt
))
1024 (do-toplevel (<variable
> "variable|param" <transform
>)
1026 (parse-global-variable! stylesheet
<variable
> global-env
)))
1027 (xslt-trace "parsing global variable ~s (uri ~s)"
1028 (variable-chain-local-name chain
)
1029 (variable-chain-uri chain
))
1033 (and (equal (variable-chain-local-name a
)
1034 (variable-chain-local-name b
))
1035 (equal (variable-chain-uri a
)
1036 (variable-chain-uri b
)))))
1037 (xslt-error "duplicate definition for global variable ~A"
1038 (variable-chain-local-name chain
)))
1039 (push chain chains
)))
1040 (setf chains
(nreverse chains
))
1041 (let ((table (stylesheet-global-variables stylesheet
))
1042 (newlen (length *global-variable-declarations
*)))
1043 (adjust-array table newlen
:fill-pointer newlen
)
1044 (dolist (chain chains
)
1045 (setf (elt table
(variable-chain-index chain
)) chain
)))
1047 ;; now that the global environment knows about all variables, run the
1048 ;; thunk setters to perform their compilation
1049 (mapc (lambda (chain)
1050 (dolist (var (variable-chain-definitions chain
))
1051 (funcall (variable-value-thunk-setter var
))))
1054 (defun parse-templates! (stylesheet <transform
> env
)
1056 (do-toplevel (<template
> "template" <transform
>)
1057 (let ((*namespaces
* (acons-namespaces <template
>))
1058 (*instruction-base-uri
* (stp:base-uri
<template
>)))
1059 (with-import-magic (<template
> env
)
1060 (dolist (template (compile-template <template
> env i
))
1061 (let ((name (template-name template
)))
1063 (let* ((table (stylesheet-named-templates stylesheet
))
1064 (head (car (gethash name table
))))
1065 (when (and head
(eql (template-import-priority head
)
1066 (template-import-priority template
)))
1067 ;; fixme: is this supposed to be a run-time error?
1068 (xslt-error "conflicting templates for ~A" name
))
1069 (push template
(gethash name table
)))
1070 (let ((mode (ensure-mode/qname stylesheet
1071 (template-mode-qname template
)
1073 (setf (template-mode template
) mode
)
1074 (push template
(mode-templates mode
))))))))
1078 ;;;; APPLY-STYLESHEET
1080 (defvar *stylesheet
*)
1082 (deftype xml-designator
() '(or runes
:xstream runes
:rod array stream pathname
))
1084 (defun unalias-uri (uri)
1086 (gethash uri
(stylesheet-namespace-aliases *stylesheet
*)
1088 (check-type result string
)
1091 (defstruct (parameter
1092 (:constructor make-parameter
(value local-name
&optional uri
)))
1097 (defun find-parameter-value (local-name uri parameters
)
1098 (dolist (p parameters
)
1099 (when (and (equal (parameter-local-name p
) local-name
)
1100 (equal (parameter-uri p
) uri
))
1101 (return (parameter-value p
)))))
1103 (defvar *uri-resolver
*)
1105 (defun parse-allowing-microsoft-bom (pathname handler
)
1106 (with-open-file (s pathname
:element-type
'(unsigned-byte 8))
1107 (unless (and (eql (read-byte s nil
) #xef
)
1108 (eql (read-byte s nil
) #xbb
)
1109 (eql (read-byte s nil
) #xbf
))
1110 (file-position s
0))
1111 (cxml:parse s handler
)))
1113 (defvar *documents
*)
1115 (defun %document
(uri-string base-uri
)
1116 (let* ((absolute-uri
1117 (puri:merge-uris uri-string
(or base-uri
"")))
1120 (funcall *uri-resolver
* (puri:render-uri absolute-uri nil
))
1124 (uri-to-pathname resolved-uri
)
1125 (cxml:xml-parse-error
(c)
1126 (xslt-error "cannot find referenced document ~A: ~A"
1129 (or (gethash pathname
*documents
*)
1130 (setf (gethash pathname
*documents
*)
1131 (make-whitespace-stripper
1133 (parse-allowing-microsoft-bom pathname
1135 ((or file-error cxml
:xml-parse-error
) (c)
1136 (xslt-error "cannot parse referenced document ~A: ~A"
1138 (stylesheet-strip-thunk *stylesheet
*))))))
1139 (when (puri:uri-fragment absolute-uri
)
1140 (xslt-error "use of fragment identifiers in document() not supported"))
1143 (xpath-sys:define-extension xslt
*xsl
*)
1145 (defun document-base-uri (node)
1146 (xpath-protocol:base-uri
1148 ((xpath-protocol:node-type-p node
:document
)
1149 (xpath::find-in-pipe-if
1151 (xpath-protocol:node-type-p x
:element
))
1152 (xpath-protocol:child-pipe node
)))
1153 ((xpath-protocol:node-type-p node
:element
)
1156 (xpath-protocol:parent-node node
)))))
1158 (xpath-sys:define-xpath-function
/lazy
1160 (object &optional node-set
)
1161 (let ((instruction-base-uri *instruction-base-uri
*))
1163 (let* ((object (funcall object ctx
))
1164 (node-set (and node-set
(funcall node-set ctx
)))
1167 (document-base-uri (xpath::textually-first-node node-set
))
1168 instruction-base-uri
)))
1169 (xpath-sys:make-node-set
1170 (if (xpath:node-set-p object
)
1171 (xpath:map-node-set-
>list
1173 (%document
(xpath:string-value node
)
1176 (document-base-uri node
))))
1178 (list (%document
(xpath:string-value object
) base-uri
))))))))
1180 (xpath-sys:define-xpath-function
/lazy xslt
:key
(name object
)
1181 (let ((namespaces *namespaces
*))
1183 (let* ((qname (xpath:string-value
(funcall name ctx
)))
1184 (object (funcall object ctx
))
1186 (multiple-value-bind (local-name uri
)
1187 (decode-qname/runtime qname namespaces nil
)
1188 (cons local-name uri
)))
1189 (key (find-key expanded-name
*stylesheet
*)))
1190 (labels ((get-by-key (value)
1191 (let ((value (xpath:string-value value
)))
1195 (xpath:evaluate-compiled
(key-use key
) node
)))
1196 (if (xpath:node-set-p uses
)
1197 (xpath::find-in-pipe
1199 (xpath-sys:pipe-of uses
)
1200 :key
#'xpath
:string-value
1202 (equal value
(xpath:string-value uses
)))))
1204 (xpath:node-set-value
1205 (xpath:evaluate-compiled
(key-match key
) ctx
)))))))
1206 (xpath-sys:make-node-set
1208 (if (xpath:node-set-p object
)
1209 (xpath::mappend-pipe
#'get-by-key
(xpath-sys:pipe-of object
))
1210 (get-by-key object
)))))))))
1212 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1214 (xpath-sys:define-xpath-function
/lazy xslt
:current
()
1216 (xpath-sys:make-node-set
1217 (xpath-sys:make-pipe
1218 (xpath:context-starting-node ctx
)
1221 (xpath-sys:define-xpath-function
/lazy xslt
:unparsed-entity-uri
(name)
1223 (or (xpath-protocol:unparsed-entity-uri
(xpath:context-node ctx
)
1227 (defun %get-node-id
(node)
1228 (when (xpath:node-set-p node
)
1229 (setf node
(xpath::textually-first-node node
)))
1231 (let ((id (xpath-sys:get-node-id node
))
1234 for parent
= node then next
1235 for next
= (xpath-protocol:parent-node parent
)
1236 for this-base-uri
= (xpath-protocol:base-uri parent
)
1237 for highest-base-uri
= (if (plusp (length this-base-uri
))
1241 finally
(return highest-base-uri
))))
1242 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1243 ;; checked only if everything else matches.
1245 ;; This might be pointless premature optimization, but I like the idea :-)
1246 (nreverse (concatenate 'string highest-base-uri
"//" id
)))))
1248 (xpath-sys:define-xpath-function
/lazy xslt
:generate-id
(&optional node-set-thunk
)
1251 (%get-node-id
(xpath:node-set-value
(funcall node-set-thunk ctx
))))
1253 (%get-node-id
(xpath:context-node ctx
)))))
1255 (declaim (special *available-instructions
*))
1257 (xpath-sys:define-xpath-function
/lazy xslt
:element-available
(qname)
1258 (let ((namespaces *namespaces
*))
1260 (let ((qname (funcall qname ctx
)))
1261 (multiple-value-bind (local-name uri
)
1262 (decode-qname/runtime qname namespaces nil
)
1263 (and (equal uri
*xsl
*)
1264 (gethash local-name
*available-instructions
*)
1267 (xpath-sys:define-xpath-function
/lazy xslt
:function-available
(qname)
1268 (let ((namespaces *namespaces
*))
1270 (let ((qname (funcall qname ctx
)))
1271 (multiple-value-bind (local-name uri
)
1272 (decode-qname/runtime qname namespaces nil
)
1273 (and (zerop (length uri
))
1274 (or (xpath-sys:find-xpath-function local-name
*xsl
*)
1275 (xpath-sys:find-xpath-function local-name uri
))
1278 (xpath-sys:define-xpath-function
/lazy xslt
:system-property
(qname)
1279 (let ((namespaces *namespaces
*))
1281 (let ((qname (funcall qname ctx
)))
1282 (multiple-value-bind (local-name uri
)
1283 (decode-qname/runtime qname namespaces nil
)
1284 (if (equal uri
*xsl
*)
1286 ((equal local-name
"version")
1288 ((equal local-name
"vendor")
1290 ((equal local-name
"vendor-uri")
1291 "http://repo.or.cz/w/xuriella.git")
1296 (defun apply-stylesheet
1297 (stylesheet source-designator
1298 &key output parameters uri-resolver navigator
)
1299 (when (typep stylesheet
'xml-designator
)
1302 ((cxml:xml-parse-error
1304 (xslt-error "cannot parse stylesheet: ~A" c
))))
1305 (parse-stylesheet stylesheet
))))
1306 (with-resignalled-errors ()
1307 (invoke-with-output-sink
1309 (let* ((*documents
* (make-hash-table :test
'equal
))
1310 (xpath:*navigator
* (or navigator
:default-navigator
))
1311 (puri:*strict-parse
* nil
)
1312 (*stylesheet
* stylesheet
)
1313 (*empty-mode
* (make-mode))
1314 (*default-mode
* (find-mode stylesheet nil
))
1315 (global-variable-chains
1316 (stylesheet-global-variables stylesheet
))
1317 (*global-variable-values
*
1318 (make-variable-value-array (length global-variable-chains
)))
1319 (*uri-resolver
* uri-resolver
)
1321 (if (typep source-designator
'xml-designator
)
1322 (cxml:parse source-designator
(stp:make-builder
))
1325 (make-whitespace-stripper
1327 (stylesheet-strip-thunk stylesheet
)))
1328 (ctx (xpath:make-context xpath-root-node
)))
1329 (when (pathnamep source-designator
)
1330 (setf (gethash source-designator
*documents
*) xpath-root-node
))
1333 (let ((head (car (variable-chain-definitions chain
))))
1334 (when (variable-param-p head
)
1336 (find-parameter-value
1337 (variable-chain-local-name chain
)
1338 (variable-chain-uri chain
)
1341 (setf (global-variable-value
1342 (variable-chain-index chain
))
1344 global-variable-chains
)
1347 (funcall (variable-chain-thunk chain
) ctx
))
1348 global-variable-chains
)
1349 ;; zzz we wouldn't have to mask float traps here if we used the
1350 ;; XPath API properly. Unfortunately I've been using FUNCALL
1351 ;; everywhere instead of EVALUATE, so let's paper over that
1352 ;; at a central place to be sure:
1353 (xpath::with-float-traps-masked
()
1354 (apply-templates ctx
:mode
*default-mode
*))))
1355 (stylesheet-output-specification stylesheet
)
1358 (defun find-attribute-set (local-name uri
&optional
(stylesheet *stylesheet
*))
1359 (or (gethash (cons local-name uri
) (stylesheet-attribute-sets stylesheet
))
1360 (xslt-error "no such attribute set: ~A/~A" local-name uri
)))
1362 (defun apply-templates/list
(list &key param-bindings sort-predicate mode
)
1363 (when sort-predicate
1365 (mapcar #'xpath
:context-node
1366 (stable-sort (contextify-node-list list
)
1368 (let* ((n (length list
))
1369 (s/d
(lambda () n
)))
1374 (apply-templates (xpath:make-context child s
/d i
)
1375 :param-bindings param-bindings
1378 (defvar *stack-limit
* 200)
1380 (defun invoke-with-stack-limit (fn)
1381 (let ((*stack-limit
* (1- *stack-limit
*)))
1382 (unless (plusp *stack-limit
*)
1383 (xslt-error "*stack-limit* reached; stack overflow"))
1386 (defun invoke-template (ctx template param-bindings
)
1387 (let ((*lexical-variable-values
*
1388 (make-variable-value-array (template-n-variables template
))))
1389 (with-stack-limit ()
1391 for
(name-cons value
) in param-bindings
1392 for
(nil index nil
) = (find name-cons
1393 (template-params template
)
1398 (setf (lexical-variable-value index
) value
)))
1399 (funcall (template-body template
) ctx
))))
1401 (defun apply-default-templates (ctx mode
)
1402 (let ((node (xpath:context-node ctx
)))
1404 ((or (xpath-protocol:node-type-p node
:processing-instruction
)
1405 (xpath-protocol:node-type-p node
:comment
)))
1406 ((or (xpath-protocol:node-type-p node
:text
)
1407 (xpath-protocol:node-type-p node
:attribute
))
1408 (write-text (xpath-protocol:node-text node
)))
1410 (apply-templates/list
1412 (xpath-protocol:child-pipe node
))
1415 (defvar *apply-imports
*)
1417 (defun apply-applicable-templates (ctx templates param-bindings finally
)
1418 (labels ((apply-imports (&optional actual-param-bindings
)
1420 (let* ((this (pop templates
))
1421 (low (template-apply-imports-limit this
))
1422 (high (template-import-priority this
)))
1426 (<= low
(template-import-priority x
) high
))
1428 (invoke-template ctx this actual-param-bindings
))
1429 (funcall finally
))))
1430 (let ((*apply-imports
* #'apply-imports
))
1431 (apply-imports param-bindings
))))
1433 (defun apply-templates (ctx &key param-bindings mode
)
1434 (apply-applicable-templates ctx
1435 (find-templates ctx
(or mode
*default-mode
*))
1438 (apply-default-templates ctx mode
))))
1440 (defun call-template (ctx name
&optional param-bindings
)
1441 (apply-applicable-templates ctx
1442 (find-named-templates name
)
1445 (error "cannot find named template: ~s"
1448 (defun find-templates (ctx mode
)
1449 (let* ((matching-candidates
1450 (xpath:matching-values
(mode-match-thunk mode
)
1451 (xpath:context-node ctx
)))
1453 (if matching-candidates
1456 :key
#'template-import-priority
))
1458 (priority-groups (make-array npriorities
:initial-element nil
)))
1459 (dolist (template matching-candidates
)
1461 (elt priority-groups
(template-import-priority template
))))
1463 for i from
(1- npriorities
) downto
0
1464 for group
= (elt priority-groups i
)
1465 for template
= (maximize #'template
< group
)
1469 (defun find-named-templates (name)
1470 (gethash name
(stylesheet-named-templates *stylesheet
*)))
1472 (defun template< (a b
) ;assuming same import priority
1473 (let ((p (template-priority a
))
1474 (q (template-priority b
)))
1479 (xslt-cerror "conflicting templates:~_~A,~_~A"
1480 (template-match-expression a
)
1481 (template-match-expression b
))
1482 (< (template-position a
) (template-position b
))))))
1484 (defun maximize (< things
)
1486 (let ((max (car things
)))
1487 (dolist (other (cdr things
))
1488 (when (funcall < max other
)
1492 (defun invoke-with-output-sink (fn output-spec output
)
1495 (with-open-file (s output
1497 :element-type
'(unsigned-byte 8)
1498 :if-exists
:rename-and-delete
)
1499 (invoke-with-output-sink fn output-spec s
)))
1501 (invoke-with-output-sink fn
1503 (make-output-sink output-spec output
)))
1504 ((or hax
:abstract-handler sax
:abstract-handler
)
1505 (with-xml-output output
1506 (when (typep output
'(or combi-sink auto-detect-sink
))
1507 (sax:start-dtd output
1508 :autodetect-me-please
1509 (output-doctype-public output-spec
)
1510 (output-doctype-system output-spec
)))
1513 (defun make-output-sink (output-spec stream
)
1516 (let ((et (stream-element-type stream
)))
1518 ((or (null et
) (subtypep et
'(unsigned-byte 8)))
1519 (runes:make-octet-stream-ystream stream
))
1520 ((subtypep et
'character
)
1521 (runes:make-character-stream-ystream stream
))))
1522 (runes:make-rod-ystream
)))
1523 (omit-xml-declaration-p
1524 (equal (output-omit-xml-declaration output-spec
) "yes"))
1525 (sink-encoding (or (output-encoding output-spec
) "UTF-8"))
1528 (setf (runes:ystream-encoding ystream
)
1529 (cxml::find-output-encoding sink-encoding
))
1530 (make-instance 'cxml
::sink
1532 :omit-xml-declaration-p omit-xml-declaration-p
1533 :encoding sink-encoding
))))
1534 (flet ((make-combi-sink ()
1535 (make-instance 'combi-sink
1536 :hax-target
(make-instance 'chtml
::sink
1538 :sax-target sax-target
1539 :encoding sink-encoding
)))
1542 ((equalp (output-method output-spec
) "HTML") :html
)
1543 ((equalp (output-method output-spec
) "TEXT") :text
)
1544 ((equalp (output-method output-spec
) "XML") :xml
)
1547 ((and (eq method-key
:html
)
1548 (null (output-doctype-system output-spec
))
1549 (null (output-doctype-public output-spec
)))
1551 ((eq method-key
:text
)
1552 (make-text-filter sax-target
))
1553 ((and (eq method-key
:xml
)
1554 (null (output-doctype-system output-spec
)))
1557 (make-auto-detect-sink (make-combi-sink) method-key
)))))))
1573 (defun expression-priority (form)
1574 (let ((step (second form
)))
1575 (if (and (null (cddr form
))
1577 (member (car step
) '(:child
:attribute
))
1579 (let ((name (second step
)))
1583 (or (eq (car name
) :qname
)
1584 (eq (car name
) :processing-instruction
))))
1587 (or (eq (car name
) :namespace
)
1588 (eq (car name
) '*)))
1594 (defun parse-xpath (str)
1595 (with-resignalled-errors ()
1596 (xpath:parse-xpath str
)))
1598 (defun parse-key-pattern (str)
1600 (mapcar #'(lambda (item)
1601 `(:path
(:root
:node
)
1602 (:descendant-or-self
*)
1604 (parse-pattern str
))))
1605 (if (null (rest parsed
))
1607 `(:union
,@parsed
))))
1609 (defun parse-pattern (str)
1610 (with-resignalled-errors ()
1611 (cdr (xpath::parse-pattern-expression str
))))
1613 (defun compile-value-thunk (value env
)
1614 (if (and (listp value
) (eq (car value
) 'progn
))
1615 (let ((inner-thunk (compile-instruction value env
)))
1617 (apply-to-result-tree-fragment ctx inner-thunk
)))
1618 (compile-xpath value env
)))
1620 (defun compile-var-binding (name value env
)
1621 (multiple-value-bind (local-name uri
)
1622 (decode-qname name env nil
)
1623 (let ((thunk (xslt-trace-thunk
1624 (compile-value-thunk value env
)
1625 "local variable ~s = ~s" name
:result
)))
1626 (list (cons local-name uri
)
1627 (push-variable local-name
1629 *lexical-variable-declarations
*)
1632 (defun compile-var-bindings (forms env
)
1634 for
(name value
) in forms
1635 collect
(compile-var-binding name value env
)))
1637 (defun compile-template (<template
> env position
)
1638 (stp:with-attributes
(match name priority mode
) <template
>
1639 (unless (or name match
)
1640 (xslt-error "missing match in template"))
1641 (multiple-value-bind (params body-pos
)
1644 for child in
(stp:list-children
<template
>)
1645 while
(namep child
"param")
1646 collect
(parse-param child
) into params
1647 finally
(return (values params i
)))
1648 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1649 (param-bindings (compile-var-bindings params env
))
1650 (body (parse-body <template
> body-pos
(mapcar #'car params
)))
1651 (body-thunk (compile-instruction `(progn ,@body
) env
))
1657 ;; set params that weren't initialized by apply-templates
1658 (loop for
(name index param-thunk
) in param-bindings
1659 when
(eq (lexical-variable-value index nil
) 'unbound
)
1660 do
(setf (lexical-variable-value index
)
1661 (funcall param-thunk ctx
)))
1662 (funcall body-thunk ctx
))))
1663 "template: match = ~s name = ~s" match name
))
1664 (n-variables (length *lexical-variable-declarations
*)))
1667 (multiple-value-bind (local-name uri
)
1668 (decode-qname name env nil
)
1670 (make-template :name
(cons local-name uri
)
1671 :import-priority
*import-priority
*
1672 :apply-imports-limit
*apply-imports-limit
*
1673 :params param-bindings
1674 :body outer-body-thunk
1675 :n-variables n-variables
))))
1677 (mapcar (lambda (expression)
1678 (let* ((compiled-pattern
1680 (car (xpath:compute-patterns
1681 `(:patterns
,expression
)
1685 "match-thunk for template (match ~s): ~s --> ~s"
1686 match expression
:result
))
1688 (xpath::parse-xnum priority
)
1689 (expression-priority expression
)))
1692 (unless (and (numberp p
)
1693 (not (xpath::inf-p p
))
1694 (not (xpath::nan-p p
)))
1695 (xslt-error "failed to parse priority"))
1698 (make-template :match-expression expression
1699 :compiled-pattern compiled-pattern
1700 :import-priority
*import-priority
*
1701 :apply-imports-limit
*apply-imports-limit
*
1705 :params param-bindings
1706 :body outer-body-thunk
1707 :n-variables n-variables
)))
1708 (setf (xpath:pattern-value compiled-pattern
)
1711 (cdr (xpath:parse-pattern-expression match
)))))))))
1713 (xuriella::parse-stylesheet
#p
"/home/david/src/lisp/xuriella/test.xsl")