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 (defun xslt-cerror (fmt &rest args
)
56 (with-simple-restart (recover "recover")
57 (error 'recoverable-xslt-error
59 :format-arguments args
)))
63 (defmacro handler-case
* (form &rest clauses
)
64 ;; like HANDLER-CASE if *DEBUG* is off. If it's on, don't establish
65 ;; a handler at all so that we see the real stack traces. (We could use
66 ;; HANDLER-BIND here and check at signalling time, but doesn't seem
68 (let ((doit (gensym)))
69 `(flet ((,doit
() ,form
))
76 (defun compile-xpath (xpath &optional env
)
78 (xpath:compile-xpath xpath env
)
79 (xpath:xpath-error
(c)
80 (xslt-error "~A" c
))))
82 (defmacro with-stack-limit
((&optional
) &body body
)
83 `(invoke-with-stack-limit (lambda () ,@body
)))
86 ;;;; Helper functions and macros
88 (defun check-for-invalid-attributes (valid-names node
)
89 (labels ((check-attribute (a)
91 (let ((uri (stp:namespace-uri a
)))
92 (or (and (plusp (length uri
)) (not (equal uri
*xsl
*)))
93 (find (cons (stp:local-name a
) uri
)
96 (xslt-error "attribute ~A not allowed on ~A"
98 (stp:local-name node
)))))
99 (stp:map-attributes nil
#'check-attribute node
)))
101 (defmacro only-with-attributes
((&rest specs
) node
&body body
)
103 (mapcar (lambda (entry)
104 (if (and (listp entry
) (cdr entry
))
105 (destructuring-bind (name &optional
(uri ""))
108 (cons (string-downcase
110 (symbol-name entry
)))
114 `(let ((,%NODE
,node
))
115 (check-for-invalid-attributes ',valid-names
,%NODE
)
116 (stp:with-attributes
,specs
,%NODE
119 (defun map-pipe-eagerly (fn pipe
)
120 (xpath::enumerate pipe
:key fn
:result nil
))
122 (defmacro do-pipe
((var pipe
&optional result
) &body body
)
124 (map-pipe-eagerly #'(lambda (,var
) ,@body
) ,pipe
)
128 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
130 (defparameter *namespaces
*
132 ("xmlns" .
#"http://www.w3.org/2000/xmlns/")
133 ("xml" .
#"http://www.w3.org/XML/1998/namespace")))
135 (defvar *global-variable-declarations
*)
136 (defvar *lexical-variable-declarations
*)
138 (defvar *global-variable-values
*)
139 (defvar *lexical-variable-values
*)
141 (defclass xslt-environment
() ())
143 (defun split-qname (str)
145 (multiple-value-bind (prefix local-name
)
146 (cxml::split-qname str
)
148 ;; FIXME: cxml should really offer a function that does
149 ;; checks for NCName and QName in a sensible way for user code.
150 ;; cxml::split-qname is tailored to the needs of the parser.
152 ;; For now, let's just check the syntax explicitly.
153 (and (or (null prefix
) (xpath::nc-name-p prefix
))
154 (xpath::nc-name-p local-name
))
155 (xslt-error "not a qname: ~A" str
))
156 (values prefix local-name
))
157 (cxml:well-formedness-violation
()
158 (xslt-error "not a qname: ~A" str
))))
160 (defun decode-qname (qname env attributep
)
161 (multiple-value-bind (prefix local-name
)
164 (if (or prefix
(not attributep
))
165 (xpath-sys:environment-find-namespace env
(or prefix
""))
169 (defmethod xpath-sys:environment-find-namespace
((env xslt-environment
) prefix
)
170 (or (cdr (assoc prefix
*namespaces
* :test
'equal
))
172 ;; Change the entire code base to represent "no prefix" as the
173 ;; empty string consistently. unparse.lisp has already been changed.
174 (and (equal prefix
"")
175 (cdr (assoc nil
*namespaces
* :test
'equal
)))
176 (and (eql prefix nil
)
177 (cdr (assoc "" *namespaces
* :test
'equal
)))))
179 (defun find-variable-index (local-name uri table
)
180 (position (cons local-name uri
) table
:test
'equal
))
182 (defun intern-global-variable (local-name uri
)
183 (or (find-variable-index local-name uri
*global-variable-declarations
*)
184 (push-variable local-name uri
*global-variable-declarations
*)))
186 (defun push-variable (local-name uri table
)
189 (vector-push-extend (cons local-name uri
) table
)))
191 (defun lexical-variable-value (index &optional
(errorp t
))
192 (let ((result (svref *lexical-variable-values
* index
)))
194 (assert (not (eq result
'unbound
))))
197 (defun (setf lexical-variable-value
) (newval index
)
198 (assert (not (eq newval
'unbound
)))
199 (setf (svref *lexical-variable-values
* index
) newval
))
201 (defun global-variable-value (index &optional
(errorp t
))
202 (let ((result (svref *global-variable-values
* index
)))
204 (assert (not (eq result
'unbound
))))
207 (defun (setf global-variable-value
) (newval index
)
208 (assert (not (eq newval
'unbound
)))
209 (setf (svref *global-variable-values
* index
) newval
))
211 (defmethod xpath-sys:environment-find-function
212 ((env xslt-environment
) lname uri
)
214 (or (xpath-sys:find-xpath-function lname
*xsl
*)
215 (xpath-sys:find-xpath-function lname uri
))
216 (xpath-sys:find-xpath-function lname uri
)))
218 (defmethod xpath-sys:environment-find-variable
219 ((env xslt-environment
) lname uri
)
221 (find-variable-index lname uri
*lexical-variable-declarations
*)))
224 (declare (ignore ctx
))
225 (svref *lexical-variable-values
* index
)))))
227 (defclass lexical-xslt-environment
(xslt-environment) ())
229 (defmethod xpath-sys:environment-find-variable
230 ((env lexical-xslt-environment
) lname uri
)
231 (or (call-next-method)
233 (find-variable-index lname uri
*global-variable-declarations
*)))
237 (declare (ignore ctx
))
238 (svref *global-variable-values
* index
))
239 "global ~s (uri ~s) = ~s" lname uri
:result
)))))
241 (defclass global-variable-environment
(xslt-environment)
242 ((initial-global-variable-thunks
243 :initarg
:initial-global-variable-thunks
244 :accessor initial-global-variable-thunks
)))
246 (defmethod xpath-sys:environment-find-variable
247 ((env global-variable-environment
) lname uri
)
248 (or (call-next-method)
249 (gethash (cons lname uri
) (initial-global-variable-thunks env
))))
252 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
254 ;;;; A sink that serializes only text not contained in any element.
256 (defmacro with-toplevel-text-output-sink
((var) &body body
)
257 `(invoke-with-toplevel-text-output-sink (lambda (,var
) ,@body
)))
259 (defclass toplevel-text-output-sink
(sax:default-handler
)
260 ((target :initarg
:target
:accessor text-output-sink-target
)
261 (depth :initform
0 :accessor textoutput-sink-depth
)))
263 (defmethod sax:start-element
((sink toplevel-text-output-sink
)
264 namespace-uri local-name qname attributes
)
265 (declare (ignore namespace-uri local-name qname attributes
))
266 (incf (textoutput-sink-depth sink
)))
268 (defmethod sax:characters
((sink toplevel-text-output-sink
) data
)
269 (when (zerop (textoutput-sink-depth sink
))
270 (write-string data
(text-output-sink-target sink
))))
272 (defmethod sax:unescaped
((sink toplevel-text-output-sink
) data
)
273 (sax:characters sink data
))
275 (defmethod sax:end-element
((sink toplevel-text-output-sink
)
276 namespace-uri local-name qname
)
277 (declare (ignore namespace-uri local-name qname
))
278 (decf (textoutput-sink-depth sink
)))
280 (defun invoke-with-toplevel-text-output-sink (fn)
281 (with-output-to-string (s)
282 (funcall fn
(make-instance 'toplevel-text-output-sink
:target s
))))
287 ;;;; A sink that passes through only text (at any level) and turns to
288 ;;;; into unescaped characters.
290 (defclass text-filter
(sax:default-handler
)
291 ((target :initarg
:target
:accessor text-filter-target
)))
293 (defmethod sax:characters
((sink text-filter
) data
)
294 (sax:unescaped
(text-filter-target sink
) data
))
296 (defmethod sax:unescaped
((sink text-filter
) data
)
297 (sax:unescaped
(text-filter-target sink
) data
))
299 (defmethod sax:end-document
((sink text-filter
))
300 (sax:end-document
(text-filter-target sink
)))
302 (defun make-text-filter (target)
303 (make-instance 'text-filter
:target target
))
308 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
311 (defclass escaper
(cxml:broadcast-handler
)
314 (defmethod sax:unescaped
((sink escaper
) data
)
315 (sax:characters sink data
))
317 (defun make-escaper (target)
318 (make-instance 'escaper
:handlers
(list target
)))
323 (defun of-name (local-name)
324 (stp:of-name local-name
*xsl
*))
326 (defun namep (node local-name
)
327 (and (typep node
'(or stp
:element stp
:attribute
))
328 (equal (stp:namespace-uri node
) *xsl
*)
329 (equal (stp:local-name node
) local-name
)))
332 ;;;; PARSE-STYLESHEET
334 (defstruct stylesheet
335 (modes (make-hash-table :test
'equal
))
336 (global-variables (make-empty-declaration-array))
337 (output-specification (make-output-specification))
339 (named-templates (make-hash-table :test
'equal
))
340 (attribute-sets (make-hash-table :test
'equal
))
341 (keys (make-hash-table :test
'equal
))
342 (namespace-aliases (make-hash-table :test
'equal
))
343 (decimal-formats (make-hash-table :test
'equal
))
344 (initial-global-variable-thunks (make-hash-table :test
'equal
)))
346 (defstruct mode
(templates nil
))
348 (defun find-mode (stylesheet local-name
&optional uri
)
349 (gethash (cons local-name uri
) (stylesheet-modes stylesheet
)))
351 (defun ensure-mode (stylesheet &optional local-name uri
)
352 (or (find-mode stylesheet local-name uri
)
353 (setf (gethash (cons local-name uri
) (stylesheet-modes stylesheet
))
356 (defun ensure-mode/qname
(stylesheet qname env
)
358 (multiple-value-bind (local-name uri
)
359 (decode-qname qname env nil
)
360 (ensure-mode stylesheet local-name uri
))
361 (find-mode stylesheet nil
)))
363 (defun acons-namespaces (element &optional
(bindings *namespaces
*))
364 (map-namespace-declarations (lambda (prefix uri
)
365 (push (cons prefix uri
) bindings
))
369 (defun find-key (name stylesheet
)
370 (or (gethash name
(stylesheet-keys stylesheet
))
371 (xslt-error "unknown key: ~a" name
)))
373 (defun make-key (match use
) (cons match use
))
375 (defun key-match (key) (car key
))
377 (defun key-use (key) (cdr key
))
379 (defun add-key (stylesheet name match use
)
380 (if (gethash name
(stylesheet-keys stylesheet
))
381 (xslt-error "duplicate key: ~a" name
)
382 (setf (gethash name
(stylesheet-keys stylesheet
))
383 (make-key match use
))))
385 (defvar *excluded-namespaces
* (list *xsl
*))
386 (defvar *empty-mode
*)
387 (defvar *default-mode
*)
389 (defvar *xsl-include-stack
* nil
)
391 (defun uri-to-pathname (uri)
392 (cxml::uri-to-pathname
(puri:parse-uri uri
)))
394 (defun unwrap-2.3
(document)
395 (let ((literal-result-element (stp:document-element document
))
396 (new-template (stp:make-element
"template" *xsl
*))
397 (new-document-element (stp:make-element
"stylesheet" *xsl
*)))
398 (setf (stp:attribute-value new-document-element
"version")
399 (or (stp:attribute-value literal-result-element
"version" *xsl
*)
400 (xslt-error "not a stylesheet: root element lacks xsl:version")))
401 (setf (stp:attribute-value new-template
"match") "/")
402 (setf (stp:document-element document
) new-document-element
)
403 (stp:append-child new-document-element new-template
)
404 (stp:append-child new-template literal-result-element
)
405 new-document-element
))
407 (defun parse-stylesheet-to-stp (input uri-resolver
)
408 (let* ((d (cxml:parse input
(make-text-normalizer (cxml-stp:make-builder
))))
409 (<transform
> (stp:document-element d
)))
410 (unless (equal (stp:namespace-uri
<transform
>) *xsl
*)
411 (setf <transform
> (unwrap-2.3 d
)))
412 (strip-stylesheet <transform
>)
413 (unless (and (equal (stp:namespace-uri
<transform
>) *xsl
*)
414 (or (equal (stp:local-name
<transform
>) "transform")
415 (equal (stp:local-name
<transform
>) "stylesheet")))
416 (xslt-error "not a stylesheet"))
417 (check-for-invalid-attributes '(("version" .
"")
418 ("exclude-result-prefixes" .
"")
419 ("extension-element-prefixes" .
""))
422 (or (stp:find-child-if
(of-name "stylesheet") <transform
>)
423 (stp:find-child-if
(of-name "transform") <transform
>))))
425 (xslt-error "invalid top-level element ~A" (stp:local-name invalid
))))
426 (dolist (include (stp:filter-children
(of-name "include") <transform
>))
427 (let* ((uri (puri:merge-uris
(stp:attribute-value include
"href")
428 (stp:base-uri include
)))
429 (uri (if uri-resolver
430 (funcall uri-resolver
(puri:render-uri uri nil
))
432 (str (puri:render-uri uri nil
))
435 (uri-to-pathname uri
)
436 (cxml:xml-parse-error
(c)
437 (xslt-error "cannot find included stylesheet ~A: ~A"
441 :element-type
'(unsigned-byte 8)
442 :if-does-not-exist nil
)
444 (xslt-error "cannot find included stylesheet ~A at ~A"
446 (when (find str
*xsl-include-stack
* :test
#'equal
)
447 (xslt-error "recursive inclusion of ~A" uri
))
448 (let* ((*xsl-include-stack
* (cons str
*xsl-include-stack
*))
449 (<transform
>2 (parse-stylesheet-to-stp stream uri-resolver
)))
450 (stp:insert-child-after
<transform
>
451 (stp:copy
<transform
>2)
453 (stp:detach include
)))))
456 (defvar *instruction-base-uri
*) ;misnamed, is also used in other attributes
457 (defvar *apply-imports-limit
*)
458 (defvar *import-priority
*)
459 (defvar *extension-namespaces
*)
460 (defvar *forwards-compatible-p
*)
462 (defmacro do-toplevel
((var xpath
<transform
>) &body body
)
463 `(map-toplevel (lambda (,var
) ,@body
) ,xpath
,<transform
>))
465 (defun map-toplevel (fn xpath
<transform
>)
466 (dolist (node (list-toplevel xpath
<transform
>))
467 (let ((*namespaces
* *namespaces
*))
468 (xpath:do-node-set
(ancestor (xpath:evaluate
"ancestor::node()" node
))
469 (when (xpath-protocol:node-type-p ancestor
:element
)
470 (setf *namespaces
* (acons-namespaces ancestor
))))
473 (defun list-toplevel (xpath <transform
>)
474 (labels ((recurse (sub)
477 (xpath:evaluate
"transform|stylesheet" sub
))))
479 (xpath-sys:pipe-of
(xpath:evaluate xpath sub
))
480 (xpath::mappend-pipe
#'recurse subsubs
)))))
481 (xpath::sort-nodes
(recurse <transform
>))))
483 (defmacro with-import-magic
((node env
) &body body
)
484 `(invoke-with-import-magic (lambda () ,@body
) ,node
,env
))
486 (defun invoke-with-import-magic (fn node env
)
487 (unless (or (namep node
"stylesheet") (namep node
"transform"))
488 (setf node
(stp:parent node
)))
489 (let ((*excluded-namespaces
* (list *xsl
*))
490 (*extension-namespaces
* '())
491 (*forwards-compatible-p
*
492 (not (equal (stp:attribute-value node
"version") "1.0"))))
493 (parse-exclude-result-prefixes! node env
)
494 (parse-extension-element-prefixes! node env
)
497 (defun parse-1-stylesheet (env stylesheet designator uri-resolver
)
498 (let* ((<transform
> (parse-stylesheet-to-stp designator uri-resolver
))
499 (instruction-base-uri (stp:base-uri
<transform
>))
500 (namespaces (acons-namespaces <transform
>))
501 (apply-imports-limit (1+ *import-priority
*))
503 (let ((*namespaces
* namespaces
))
504 (invoke-with-import-magic (constantly t
) <transform
> env
))
505 (do-toplevel (elt "node()" <transform
>)
506 (when (equal (stp:attribute-value
(stp:parent elt
) "version") "1.0")
507 (if (typep elt
'stp
:element
)
508 (when (or (equal (stp:namespace-uri elt
) "")
509 (and (equal (stp:namespace-uri elt
) *xsl
*)
510 (not (find (stp:local-name elt
)
511 '("key" "template" "output" "strip-space"
512 "preserve-space" "attribute-set"
513 "namespace-alias" "decimal-format"
514 "variable" "param" "import" "include"
515 ;; for include handling:
516 "stylesheet" "transform")
518 (xslt-error "unknown top-level element ~A" (stp:local-name elt
)))
519 (xslt-error "text at top-level"))))
520 (macrolet ((with-specials ((&optional
) &body body
)
521 `(let ((*instruction-base-uri
* instruction-base-uri
)
522 (*namespaces
* namespaces
)
523 (*apply-imports-limit
* apply-imports-limit
))
526 (do-toplevel (import "import" <transform
>)
527 (let ((uri (puri:merge-uris
(stp:attribute-value import
"href")
528 (stp:base-uri import
))))
529 (push (parse-imported-stylesheet env stylesheet uri uri-resolver
)
531 (let ((import-priority
532 (incf *import-priority
*))
533 (var-cont (prepare-global-variables stylesheet
<transform
>)))
534 ;; delay the rest of compilation until we've seen all global
537 (mapc #'funcall
(nreverse continuations
))
539 (let ((*import-priority
* import-priority
))
541 (parse-keys! stylesheet
<transform
> env
)
542 (parse-templates! stylesheet
<transform
> env
)
543 (parse-output! stylesheet
<transform
>)
544 (parse-strip/preserve-space
! stylesheet
<transform
> env
)
545 (parse-attribute-sets! stylesheet
<transform
> env
)
546 (parse-namespace-aliases! stylesheet
<transform
> env
)
547 (parse-decimal-formats! stylesheet
<transform
> env
))))))))
549 (defvar *xsl-import-stack
* nil
)
551 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver
)
552 (let* ((uri (if uri-resolver
553 (funcall uri-resolver
(puri:render-uri uri nil
))
555 (str (puri:render-uri uri nil
))
558 (uri-to-pathname uri
)
559 (cxml:xml-parse-error
(c)
560 (xslt-error "cannot find imported stylesheet ~A: ~A"
564 :element-type
'(unsigned-byte 8)
565 :if-does-not-exist nil
)
567 (xslt-error "cannot find imported stylesheet ~A at ~A"
569 (when (find str
*xsl-import-stack
* :test
#'equal
)
570 (xslt-error "recursive inclusion of ~A" uri
))
571 (let ((*xsl-import-stack
* (cons str
*xsl-import-stack
*)))
572 (parse-1-stylesheet env stylesheet stream uri-resolver
)))))
574 (defun parse-stylesheet (designator &key uri-resolver
)
575 (xpath:with-namespaces
((nil #.
*xsl
*))
576 (let* ((*import-priority
* 0)
577 (puri:*strict-parse
* nil
)
578 (stylesheet (make-stylesheet))
579 (env (make-instance 'lexical-xslt-environment
))
580 (*excluded-namespaces
* *excluded-namespaces
*)
581 (*global-variable-declarations
* (make-empty-declaration-array)))
582 (ensure-mode stylesheet nil
)
583 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver
))
584 ;; reverse attribute sets:
585 (let ((table (stylesheet-attribute-sets stylesheet
)))
586 (maphash (lambda (k v
)
587 (setf (gethash k table
) (nreverse v
)))
590 (unless (find-decimal-format "" "" stylesheet nil
)
591 (setf (find-decimal-format "" "" stylesheet
)
592 (make-decimal-format)))
595 (defun parse-attribute-sets! (stylesheet <transform
> env
)
596 (do-toplevel (elt "attribute-set" <transform
>)
597 (with-import-magic (elt env
)
599 (mapcar (lambda (qname)
600 (multiple-value-list (decode-qname qname env nil
)))
602 (stp:attribute-value elt
"use-attribute-sets"))))
608 (and (typep child
'stp
:element
)
609 (or (and (equal (stp:namespace-uri child
) *xsl
*)
610 (equal (stp:local-name child
)
612 (find (stp:namespace-uri child
)
613 *extension-namespaces
*
615 (xslt-error "non-attribute found in attribute set"))
616 (parse-instruction child
))
618 (*lexical-variable-declarations
*
619 (make-empty-declaration-array))
621 (compile-instruction `(progn ,@instructions
) env
))
622 (n-variables (length *lexical-variable-declarations
*)))
625 (loop for
(local-name uri nil
) in sets do
626 (dolist (thunk (find-attribute-set local-name uri
))
627 (funcall thunk ctx
)))
628 (let ((*lexical-variable-values
*
629 (make-variable-value-array n-variables
)))
630 (funcall thunk ctx
)))))
631 (gethash (multiple-value-bind (local-name uri
)
632 (decode-qname (stp:attribute-value elt
"name") env nil
)
633 (cons local-name uri
))
634 (stylesheet-attribute-sets stylesheet
))))))
636 (defun parse-namespace-aliases! (stylesheet <transform
> env
)
637 (do-toplevel (elt "namespace-alias" <transform
>)
638 (stp:with-attributes
(stylesheet-prefix result-prefix
) elt
640 (xpath-sys:environment-find-namespace env stylesheet-prefix
)
641 (stylesheet-namespace-aliases stylesheet
))
642 (xpath-sys:environment-find-namespace
644 (if (equal result-prefix
"#default")
648 (defun parse-decimal-formats! (stylesheet <transform
> env
)
649 (do-toplevel (elt "decimal-format" <transform
>)
650 (stp:with-attributes
(name
664 (multiple-value-bind (local-name uri
)
666 (decode-qname name env nil
)
668 (let ((current (find-decimal-format local-name uri stylesheet nil
))
673 (unless (eql (length x
) 1)
674 (xslt-error "not a single character: ~A" x
))
675 (let ((chr (elt x
0)))
676 (when (find chr seen
)
678 "conflicting decimal format characters: ~A"
685 (apply #'make-decimal-format
686 (append (str :infinity infinity
)
688 (chr :decimal-separator decimal-separator
)
689 (chr :grouping-separator grouping-separator
)
690 (chr :zero-digit zero-digit
)
691 (chr :percent percent
)
692 (chr :per-mille per-mille
)
694 (chr :pattern-separator pattern-separator
)
695 (chr :minus-sign minus-sign
)))))))
697 (unless (decimal-format= current new
)
698 (xslt-error "decimal format mismatch for ~S" local-name
))
699 (setf (find-decimal-format local-name uri stylesheet
) new
)))))))
701 (defun parse-exclude-result-prefixes! (node env
)
702 (stp:with-attributes
(exclude-result-prefixes)
704 (dolist (prefix (words (or exclude-result-prefixes
"")))
705 (if (equal prefix
"#default")
707 (unless (cxml-stp-impl::nc-name-p prefix
)
708 (xslt-error "invalid prefix: ~A" prefix
)))
709 (push (or (xpath-sys:environment-find-namespace env prefix
)
710 (xslt-error "namespace not found: ~A" prefix
))
711 *excluded-namespaces
*))))
713 (defun parse-extension-element-prefixes! (node env
)
714 (stp:with-attributes
(extension-element-prefixes)
716 (dolist (prefix (words (or extension-element-prefixes
"")))
717 (if (equal prefix
"#default")
719 (unless (cxml-stp-impl::nc-name-p prefix
)
720 (xslt-error "invalid prefix: ~A" prefix
)))
722 (or (xpath-sys:environment-find-namespace env prefix
)
723 (xslt-error "namespace not found: ~A" prefix
))))
724 (unless (equal uri
*xsl
*)
725 (push uri
*extension-namespaces
*)
726 (push uri
*excluded-namespaces
*))))))
728 (defun parse-strip/preserve-space
! (stylesheet <transform
> env
)
729 (xpath:with-namespaces
((nil #.
*xsl
*))
730 (do-toplevel (elt "strip-space|preserve-space" <transform
>)
731 (let ((*namespaces
* (acons-namespaces elt
))
733 (if (equal (stp:local-name elt
) "strip-space")
736 (dolist (name-test (words (stp:attribute-value elt
"elements")))
737 (let* ((pos (search ":*" name-test
))
740 ((eql pos
(- (length name-test
) 2))
741 (let* ((prefix (subseq name-test
0 pos
))
743 (xpath-sys:environment-find-namespace env prefix
)))
744 (unless (xpath::nc-name-p prefix
)
745 (xslt-error "not an NCName: ~A" prefix
))
746 (lambda (local-name uri
)
747 (declare (ignore local-name
))
748 (if (equal uri name-test-uri
)
751 ((equal name-test
"*")
752 (lambda (local-name uri
)
753 (declare (ignore local-name uri
))
756 (multiple-value-bind (name-test-local-name name-test-uri
)
757 (decode-qname name-test env nil
)
758 (lambda (local-name uri
)
759 (if (and (equal local-name name-test-local-name
)
760 (equal uri name-test-uri
))
763 (push test-function
(stylesheet-strip-tests stylesheet
))))))))
765 (defstruct (output-specification
766 (:conc-name
"OUTPUT-"))
774 (defun parse-output! (stylesheet <transform
>)
775 (dolist (<output
> (list-toplevel "output" <transform
>))
776 (let ((spec (stylesheet-output-specification stylesheet
)))
777 (stp:with-attributes
( ;; version
786 ;;; cdata-section-elements
790 (setf (output-method spec
) method
))
792 (setf (output-indent spec
) indent
))
794 (setf (output-encoding spec
) encoding
))
796 (setf (output-doctype-system spec
) doctype-system
))
798 (setf (output-doctype-public spec
) doctype-public
))
799 (when omit-xml-declaration
800 (setf (output-omit-xml-declaration spec
) omit-xml-declaration
))
801 ;;; (when cdata-section-elements
802 ;;; (setf (output-cdata-section-elements spec)
803 ;;; (concatenate 'string
804 ;;; (output-cdata-section-elements spec)
806 ;;; cdata-section-elements)))
809 (defun make-empty-declaration-array ()
810 (make-array 1 :fill-pointer
0 :adjustable t
))
812 (defun make-variable-value-array (n-lexical-variables)
813 (make-array n-lexical-variables
:initial-element
'unbound
))
815 (defun compile-global-variable (<variable
> env
) ;; also for <param>
816 (stp:with-attributes
(name select
) <variable
>
817 (when (and select
(stp:list-children
<variable
>))
818 (xslt-error "variable with select and body"))
819 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
822 (compile-xpath select env
))
823 ((stp:list-children
<variable
>)
824 (let* ((inner-sexpr `(progn ,@(parse-body <variable
>)))
825 (inner-thunk (compile-instruction inner-sexpr env
)))
827 (apply-to-result-tree-fragment ctx inner-thunk
))))
830 (declare (ignore ctx
))
832 (n-lexical-variables (length *lexical-variable-declarations
*)))
835 (let* ((*lexical-variable-values
*
836 (make-variable-value-array n-lexical-variables
)))
837 (funcall inner ctx
)))
838 "global ~s (~s) = ~s" name select
:result
))))
840 (defstruct (variable-chain
841 (:constructor make-variable-chain
)
842 (:conc-name
"VARIABLE-CHAIN-"))
849 (defstruct (import-variable
850 (:constructor make-variable
)
851 (:conc-name
"VARIABLE-"))
856 (defun parse-global-variable! (stylesheet <variable
> global-env
)
857 (let* ((*namespaces
* (acons-namespaces <variable
>))
858 (instruction-base-uri (stp:base-uri
<variable
>))
859 (*instruction-base-uri
* instruction-base-uri
)
860 (*excluded-namespaces
* (list *xsl
*))
861 (*extension-namespaces
* '())
862 (qname (stp:attribute-value
<variable
> "name")))
863 (with-import-magic (<variable
> global-env
)
865 (xslt-error "name missing in ~A" (stp:local-name
<variable
>)))
866 (multiple-value-bind (local-name uri
)
867 (decode-qname qname global-env nil
)
868 ;; For the normal compilation environment of templates, install it
869 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
870 (let ((index (intern-global-variable local-name uri
)))
871 ;; For the evaluation of a global variable itself, build a thunk
872 ;; that lazily resolves other variables, stored into
873 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
874 (let* ((value-thunk :unknown
)
875 (sgv (stylesheet-global-variables stylesheet
))
877 (if (< index
(length sgv
))
881 :local-name local-name
883 (next (car (variable-chain-definitions chain
)))
884 (global-variable-thunk
886 (let ((v (global-variable-value index nil
)))
890 (xslt-error "no next definition for: ~A"
892 (funcall (variable-value-thunk next
) ctx
))
894 (setf (global-variable-value index
) 'seen
)
895 (setf (global-variable-value index
)
896 (funcall value-thunk ctx
)))
899 (excluded-namespaces *excluded-namespaces
*)
900 (extension-namespaces *extension-namespaces
*)
902 (make-variable :param-p
(namep <variable
> "param")))
905 (let* ((*instruction-base-uri
* instruction-base-uri
)
906 (*excluded-namespaces
* excluded-namespaces
)
907 (*extension-namespaces
* extension-namespaces
)
909 (compile-global-variable <variable
> global-env
)))
910 (setf value-thunk fn
)
911 (setf (variable-value-thunk variable
) fn
)))))
912 (setf (variable-value-thunk-setter variable
)
914 (setf (gethash (cons local-name uri
)
915 (initial-global-variable-thunks global-env
))
916 global-variable-thunk
)
917 (setf (variable-chain-thunk chain
) global-variable-thunk
)
918 (push variable
(variable-chain-definitions chain
))
921 (defun parse-keys! (stylesheet <transform
> env
)
922 (xpath:with-namespaces
((nil #.
*xsl
*))
923 (do-toplevel (<key
> "key" <transform
>)
924 (let ((*instruction-base-uri
* (stp:base-uri
<key
>)))
925 (stp:with-attributes
(name match use
) <key
>
926 (unless name
(xslt-error "key name attribute not specified"))
927 (unless match
(xslt-error "key match attribute not specified"))
928 (unless use
(xslt-error "key use attribute not specified"))
929 (multiple-value-bind (local-name uri
)
930 (decode-qname name env nil
)
932 (cons local-name uri
)
933 (compile-xpath `(xpath:xpath
,(parse-key-pattern match
)) env
)
934 (compile-xpath use env
))))))))
936 (defun prepare-global-variables (stylesheet <transform
>)
937 (xpath:with-namespaces
((nil #.
*xsl
*))
938 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet
))
939 (global-env (make-instance 'global-variable-environment
940 :initial-global-variable-thunks igvt
))
942 (do-toplevel (<variable
> "variable|param" <transform
>)
944 (parse-global-variable! stylesheet
<variable
> global-env
)))
945 (xslt-trace "parsing global variable ~s (uri ~s)"
946 (variable-chain-local-name chain
)
947 (variable-chain-uri chain
))
951 (and (equal (variable-chain-local-name a
)
952 (variable-chain-local-name b
))
953 (equal (variable-chain-uri a
)
954 (variable-chain-uri b
)))))
955 (xslt-error "duplicate definition for global variable ~A"
956 (variable-chain-local-name chain
)))
957 (push chain chains
)))
958 (setf chains
(nreverse chains
))
959 (let ((table (stylesheet-global-variables stylesheet
))
960 (newlen (length *global-variable-declarations
*)))
961 (adjust-array table newlen
:fill-pointer newlen
)
962 (dolist (chain chains
)
963 (setf (elt table
(variable-chain-index chain
)) chain
)))
965 ;; now that the global environment knows about all variables, run the
966 ;; thunk setters to perform their compilation
967 (mapc (lambda (chain)
968 (dolist (var (variable-chain-definitions chain
))
969 (funcall (variable-value-thunk-setter var
))))
972 (defun parse-templates! (stylesheet <transform
> env
)
974 (do-toplevel (<template
> "template" <transform
>)
975 (let ((*namespaces
* (acons-namespaces <template
>))
976 (*instruction-base-uri
* (stp:base-uri
<template
>)))
977 (with-import-magic (<template
> env
)
978 (dolist (template (compile-template <template
> env i
))
979 (let ((name (template-name template
)))
981 (let* ((table (stylesheet-named-templates stylesheet
))
982 (head (car (gethash name table
))))
983 (when (and head
(eql (template-import-priority head
)
984 (template-import-priority template
)))
985 ;; fixme: is this supposed to be a run-time error?
986 (xslt-error "conflicting templates for ~A" name
))
987 (push template
(gethash name table
)))
988 (let ((mode (ensure-mode/qname stylesheet
989 (template-mode-qname template
)
991 (setf (template-mode template
) mode
)
992 (push template
(mode-templates mode
))))))))
996 ;;;; APPLY-STYLESHEET
998 (defvar *stylesheet
*)
1000 (deftype xml-designator
() '(or runes
:xstream runes
:rod array stream pathname
))
1002 (defun unalias-uri (uri)
1004 (gethash uri
(stylesheet-namespace-aliases *stylesheet
*)
1006 (check-type result string
)
1009 (defstruct (parameter
1010 (:constructor make-parameter
(value local-name
&optional uri
)))
1015 (defun find-parameter-value (local-name uri parameters
)
1016 (dolist (p parameters
)
1017 (when (and (equal (parameter-local-name p
) local-name
)
1018 (equal (parameter-uri p
) uri
))
1019 (return (parameter-value p
)))))
1021 (defvar *uri-resolver
*)
1023 (defun parse-allowing-microsoft-bom (pathname handler
)
1024 (with-open-file (s pathname
:element-type
'(unsigned-byte 8))
1025 (unless (and (eql (read-byte s nil
) #xef
)
1026 (eql (read-byte s nil
) #xbb
)
1027 (eql (read-byte s nil
) #xbf
))
1028 (file-position s
0))
1029 (cxml:parse s handler
)))
1031 (defvar *documents
*)
1033 (defun %document
(uri-string base-uri
)
1034 (let* ((absolute-uri
1035 (puri:merge-uris uri-string
(or base-uri
"")))
1038 (funcall *uri-resolver
* (puri:render-uri absolute-uri nil
))
1042 (uri-to-pathname resolved-uri
)
1043 (cxml:xml-parse-error
(c)
1044 (xslt-error "cannot find referenced document ~A: ~A"
1047 (or (gethash pathname
*documents
*)
1048 (setf (gethash pathname
*documents
*)
1049 (make-whitespace-stripper
1051 (parse-allowing-microsoft-bom pathname
1053 ((or file-error cxml
:xml-parse-error
) (c)
1054 (xslt-error "cannot parse referenced document ~A: ~A"
1056 (stylesheet-strip-tests *stylesheet
*))))))
1057 (when (puri:uri-fragment absolute-uri
)
1058 (xslt-error "use of fragment identifiers in document() not supported"))
1061 (xpath-sys:define-extension xslt
*xsl
*)
1063 (defun document-base-uri (node)
1064 (xpath-protocol:base-uri
1066 ((xpath-protocol:node-type-p node
:document
)
1067 (xpath::find-in-pipe-if
1069 (xpath-protocol:node-type-p x
:element
))
1070 (xpath-protocol:child-pipe node
)))
1071 ((xpath-protocol:node-type-p node
:element
)
1074 (xpath-protocol:parent-node node
)))))
1076 (xpath-sys:define-xpath-function
/lazy
1078 (object &optional node-set
)
1079 (let ((instruction-base-uri *instruction-base-uri
*))
1081 (let* ((object (funcall object ctx
))
1082 (node-set (and node-set
(funcall node-set ctx
)))
1085 (document-base-uri (xpath::textually-first-node node-set
))
1086 instruction-base-uri
)))
1087 (xpath-sys:make-node-set
1088 (if (xpath:node-set-p object
)
1089 (xpath:map-node-set-
>list
1091 (%document
(xpath:string-value node
)
1094 (document-base-uri node
))))
1096 (list (%document
(xpath:string-value object
) base-uri
))))))))
1098 (xpath-sys:define-xpath-function
/lazy xslt
:key
(name object
)
1099 (let ((namespaces *namespaces
*))
1101 (let* ((qname (xpath:string-value
(funcall name ctx
)))
1102 (object (funcall object ctx
))
1104 (multiple-value-bind (local-name uri
)
1105 (decode-qname/runtime qname namespaces nil
)
1106 (cons local-name uri
)))
1107 (key (find-key expanded-name
*stylesheet
*)))
1108 (labels ((get-by-key (value)
1109 (let ((value (xpath:string-value value
)))
1113 (xpath:evaluate-compiled
(key-use key
) node
)))
1114 (if (xpath:node-set-p uses
)
1115 (xpath::find-in-pipe
1117 (xpath-sys:pipe-of uses
)
1118 :key
#'xpath
:string-value
1120 (equal value
(xpath:string-value uses
)))))
1122 (xpath:node-set-value
1123 (xpath:evaluate-compiled
(key-match key
) ctx
)))))))
1124 (xpath-sys:make-node-set
1126 (if (xpath:node-set-p object
)
1127 (xpath::mappend-pipe
#'get-by-key
(xpath-sys:pipe-of object
))
1128 (get-by-key object
)))))))))
1130 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1132 (xpath-sys:define-xpath-function
/lazy xslt
:current
()
1134 (xpath-sys:make-node-set
1135 (xpath-sys:make-pipe
1136 (xpath:context-starting-node ctx
)
1139 (xpath-sys:define-xpath-function
/lazy xslt
:unparsed-entity-uri
(name)
1141 (or (xpath-protocol:unparsed-entity-uri
(xpath:context-node ctx
)
1145 (defun %get-node-id
(node)
1146 (when (xpath:node-set-p node
)
1147 (setf node
(xpath::textually-first-node node
)))
1149 (let ((id (xpath-sys:get-node-id node
))
1152 for parent
= node then next
1153 for next
= (xpath-protocol:parent-node parent
)
1154 for this-base-uri
= (xpath-protocol:base-uri parent
)
1155 for highest-base-uri
= (if (plusp (length this-base-uri
))
1159 finally
(return highest-base-uri
))))
1160 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1161 ;; checked only if everything else matches.
1163 ;; This might be pointless premature optimization, but I like the idea :-)
1164 (nreverse (concatenate 'string highest-base-uri
"//" id
)))))
1166 (xpath-sys:define-xpath-function
/lazy xslt
:generate-id
(&optional node-set-thunk
)
1169 (%get-node-id
(xpath:node-set-value
(funcall node-set-thunk ctx
))))
1171 (%get-node-id
(xpath:context-node ctx
)))))
1173 (declaim (special *available-instructions
*))
1175 (xpath-sys:define-xpath-function
/lazy xslt
:element-available
(qname)
1176 (let ((namespaces *namespaces
*))
1178 (let ((qname (funcall qname ctx
)))
1179 (multiple-value-bind (local-name uri
)
1180 (decode-qname/runtime qname namespaces nil
)
1181 (and (equal uri
*xsl
*)
1182 (gethash local-name
*available-instructions
*)
1185 (xpath-sys:define-xpath-function
/lazy xslt
:function-available
(qname)
1186 (let ((namespaces *namespaces
*))
1188 (let ((qname (funcall qname ctx
)))
1189 (multiple-value-bind (local-name uri
)
1190 (decode-qname/runtime qname namespaces nil
)
1191 (and (zerop (length uri
))
1192 (or (xpath-sys:find-xpath-function local-name
*xsl
*)
1193 (xpath-sys:find-xpath-function local-name uri
))
1196 (xpath-sys:define-xpath-function
/lazy xslt
:system-property
(qname)
1197 (let ((namespaces *namespaces
*))
1199 (let ((qname (funcall qname ctx
)))
1200 (multiple-value-bind (local-name uri
)
1201 (decode-qname/runtime qname namespaces nil
)
1202 (if (equal uri
*xsl
*)
1204 ((equal local-name
"version")
1206 ((equal local-name
"vendor")
1208 ((equal local-name
"vendor-uri")
1209 "http://repo.or.cz/w/xuriella.git")
1214 (defun apply-stylesheet
1215 (stylesheet source-designator
1216 &key output parameters uri-resolver navigator
)
1217 (when (typep stylesheet
'xml-designator
)
1220 ((cxml:xml-parse-error
1222 (xslt-error "cannot parse stylesheet: ~A" c
))))
1223 (parse-stylesheet stylesheet
))))
1224 (invoke-with-output-sink
1227 (let* ((*documents
* (make-hash-table :test
'equal
))
1228 (xpath:*navigator
* (or navigator
:default-navigator
))
1229 (puri:*strict-parse
* nil
)
1230 (*stylesheet
* stylesheet
)
1231 (*empty-mode
* (make-mode))
1232 (*default-mode
* (find-mode stylesheet nil
))
1233 (global-variable-chains
1234 (stylesheet-global-variables stylesheet
))
1235 (*global-variable-values
*
1236 (make-variable-value-array (length global-variable-chains
)))
1237 (*uri-resolver
* uri-resolver
)
1239 (if (typep source-designator
'xml-designator
)
1240 (cxml:parse source-designator
(stp:make-builder
))
1243 (make-whitespace-stripper
1245 (stylesheet-strip-tests stylesheet
)))
1246 (ctx (xpath:make-context xpath-root-node
)))
1247 (when (pathnamep source-designator
)
1248 (setf (gethash source-designator
*documents
*) xpath-root-node
))
1251 (let ((head (car (variable-chain-definitions chain
))))
1252 (when (variable-param-p head
)
1254 (find-parameter-value
1255 (variable-chain-local-name chain
)
1256 (variable-chain-uri chain
)
1259 (setf (global-variable-value
1260 (variable-chain-index chain
))
1262 global-variable-chains
)
1265 (funcall (variable-chain-thunk chain
) ctx
))
1266 global-variable-chains
)
1267 ;; zzz we wouldn't have to mask float traps here if we used the
1268 ;; XPath API properly. Unfortunately I've been using FUNCALL
1269 ;; everywhere instead of EVALUATE, so let's paper over that
1270 ;; at a central place to be sure:
1271 (xpath::with-float-traps-masked
()
1272 (apply-templates ctx
:mode
*default-mode
*)))
1273 (xpath:xpath-error
(c)
1274 (xslt-error "~A" c
))))
1275 (stylesheet-output-specification stylesheet
)
1278 (defun find-attribute-set (local-name uri
)
1279 (or (gethash (cons local-name uri
) (stylesheet-attribute-sets *stylesheet
*))
1280 (xslt-error "no such attribute set: ~A/~A" local-name uri
)))
1282 (defun apply-templates/list
(list &key param-bindings sort-predicate mode
)
1283 (when sort-predicate
1285 (mapcar #'xpath
:context-node
1286 (stable-sort (contextify-node-list list
)
1288 (let* ((n (length list
))
1289 (s/d
(lambda () n
)))
1294 (apply-templates (xpath:make-context child s
/d i
)
1295 :param-bindings param-bindings
1298 (defvar *stack-limit
* 200)
1300 (defun invoke-with-stack-limit (fn)
1301 (let ((*stack-limit
* (1- *stack-limit
*)))
1302 (unless (plusp *stack-limit
*)
1303 (xslt-error "*stack-limit* reached; stack overflow"))
1306 (defun invoke-template (ctx template param-bindings
)
1307 (let ((*lexical-variable-values
*
1308 (make-variable-value-array (template-n-variables template
))))
1309 (with-stack-limit ()
1311 for
(name-cons value
) in param-bindings
1312 for
(nil index nil
) = (find name-cons
1313 (template-params template
)
1318 (setf (lexical-variable-value index
) value
)))
1319 (funcall (template-body template
) ctx
))))
1321 (defun apply-default-templates (ctx mode
)
1322 (let ((node (xpath:context-node ctx
)))
1324 ((or (xpath-protocol:node-type-p node
:processing-instruction
)
1325 (xpath-protocol:node-type-p node
:comment
)))
1326 ((or (xpath-protocol:node-type-p node
:text
)
1327 (xpath-protocol:node-type-p node
:attribute
))
1328 (write-text (xpath-protocol:node-text node
)))
1330 (apply-templates/list
1332 (xpath-protocol:child-pipe node
))
1335 (defvar *apply-imports
*)
1337 (defun apply-applicable-templates (ctx templates param-bindings finally
)
1338 (labels ((apply-imports (&optional actual-param-bindings
)
1340 (let* ((this (pop templates
))
1341 (low (template-apply-imports-limit this
))
1342 (high (template-import-priority this
)))
1346 (<= low
(template-import-priority x
) high
))
1348 (invoke-template ctx this actual-param-bindings
))
1349 (funcall finally
))))
1350 (let ((*apply-imports
* #'apply-imports
))
1351 (apply-imports param-bindings
))))
1353 (defun apply-templates (ctx &key param-bindings mode
)
1354 (apply-applicable-templates ctx
1355 (find-templates ctx
(or mode
*default-mode
*))
1358 (apply-default-templates ctx mode
))))
1360 (defun call-template (ctx name
&optional param-bindings
)
1361 (apply-applicable-templates ctx
1362 (find-named-templates name
)
1365 (error "cannot find named template: ~s"
1368 (defun find-templates (ctx mode
)
1369 (let* ((matching-candidates
1370 (remove-if-not (lambda (template)
1371 (template-matches-p template ctx
))
1372 (mode-templates mode
)))
1374 (if matching-candidates
1377 :key
#'template-import-priority
))
1379 (priority-groups (make-array npriorities
:initial-element nil
)))
1380 (dolist (template matching-candidates
)
1382 (elt priority-groups
(template-import-priority template
))))
1384 for i from
(1- npriorities
) downto
0
1385 for group
= (elt priority-groups i
)
1386 for template
= (maximize #'template
< group
)
1390 (defun find-named-templates (name)
1391 (gethash name
(stylesheet-named-templates *stylesheet
*)))
1393 (defun template< (a b
) ;assuming same import priority
1394 (let ((p (template-priority a
))
1395 (q (template-priority b
)))
1400 (xslt-cerror "conflicting templates:~_~A,~_~A"
1401 (template-match-expression a
)
1402 (template-match-expression b
))
1403 (< (template-position a
) (template-position b
))))))
1405 (defun maximize (< things
)
1407 (let ((max (car things
)))
1408 (dolist (other (cdr things
))
1409 (when (funcall < max other
)
1413 (defun template-matches-p (template ctx
)
1414 (find (xpath:context-node ctx
)
1415 (xpath:all-nodes
(funcall (template-match-thunk template
) ctx
))
1416 :test
#'xpath-protocol
:node-equal
))
1418 (defun invoke-with-output-sink (fn output-spec output
)
1421 (with-open-file (s output
1423 :element-type
'(unsigned-byte 8)
1424 :if-exists
:rename-and-delete
)
1425 (invoke-with-output-sink fn output-spec s
)))
1427 (invoke-with-output-sink fn
1429 (make-output-sink output-spec output
)))
1430 ((or hax
:abstract-handler sax
:abstract-handler
)
1431 (with-xml-output output
1432 (when (typep output
'(or combi-sink auto-detect-sink
))
1433 (sax:start-dtd output
1434 :autodetect-me-please
1435 (output-doctype-public output-spec
)
1436 (output-doctype-system output-spec
)))
1439 (defun make-output-sink (output-spec stream
)
1442 (let ((et (stream-element-type stream
)))
1444 ((or (null et
) (subtypep et
'(unsigned-byte 8)))
1445 (runes:make-octet-stream-ystream stream
))
1446 ((subtypep et
'character
)
1447 (runes:make-character-stream-ystream stream
))))
1448 (runes:make-rod-ystream
)))
1449 (omit-xml-declaration-p
1450 (equal (output-omit-xml-declaration output-spec
) "yes"))
1452 (make-instance 'cxml
::sink
1454 :omit-xml-declaration-p omit-xml-declaration-p
)))
1455 (flet ((make-combi-sink ()
1456 (make-instance 'combi-sink
1457 :hax-target
(make-instance 'chtml
::sink
1459 :sax-target sax-target
1460 :encoding
(output-encoding output-spec
))))
1463 ((equalp (output-method output-spec
) "HTML") :html
)
1464 ((equalp (output-method output-spec
) "TEXT") :text
)
1465 ((equalp (output-method output-spec
) "XML") :xml
)
1468 ((and (eq method-key
:html
)
1469 (null (output-doctype-system output-spec
))
1470 (null (output-doctype-public output-spec
)))
1472 ((eq method-key
:text
)
1473 (make-text-filter sax-target
))
1474 ((and (eq method-key
:xml
)
1475 (null (output-doctype-system output-spec
)))
1478 (make-auto-detect-sink (make-combi-sink) method-key
)))))))
1494 (defun expression-priority (form)
1495 (let ((step (second form
)))
1496 (if (and (null (cddr form
))
1498 (member (car step
) '(:child
:attribute
))
1500 (let ((name (second step
)))
1504 (or (eq (car name
) :qname
)
1505 (eq (car name
) :processing-instruction
))))
1508 (or (eq (car name
) :namespace
)
1509 (eq (car name
) '*)))
1515 (defun valid-expression-p (expr)
1518 ((eq (first expr
) :path
)
1520 (let ((filter (third x
)))
1521 (or (null filter
) (valid-expression-p filter
))))
1523 ((eq (first expr
) :variable
) ;(!)
1526 (every #'valid-expression-p
(cdr expr
)))))
1528 (defun parse-xpath (str)
1530 (xpath:parse-xpath str
)
1531 (xpath:xpath-error
(c)
1532 (xslt-error "~A" c
))))
1534 ;; zzz also use naive-pattern-expression here?
1535 (defun parse-key-pattern (str)
1537 (mapcar #'(lambda (item)
1538 `(:path
(:root
:node
)
1539 (:descendant-or-self
*)
1541 (parse-pattern str
))))
1542 (if (null (rest parsed
))
1544 `(:union
,@parsed
))))
1546 (defun parse-pattern (str)
1547 ;; zzz check here for anything not allowed as an XSLT pattern
1548 ;; zzz can we hack id() and key() here?
1549 (let ((form (parse-xpath str
)))
1550 (unless (consp form
)
1551 (xslt-error "not a valid pattern: ~A" str
))
1552 (labels ((process-form (form)
1553 (cond ((eq (car form
) :union
)
1554 (alexandria:mappend
#'process-form
(rest form
)))
1555 ((not (or (eq (car form
) :path
)
1556 (and (eq (car form
) :filter
)
1557 (let ((filter (second form
)))
1559 (member (car filter
)
1561 (equal (third form
) '(:true
)))
1562 (member (car form
) '(:key
:id
))))
1563 (xslt-error "not a valid pattern: ~A ~A" str form
))
1564 ((not (valid-expression-p form
))
1565 (xslt-error "invalid filter"))
1567 (process-form form
))))
1569 (defun naive-pattern-expression (x)
1571 (:path
`(:path
(:ancestor-or-self
:node
) ,@(cdr x
)))
1572 ((:filter
:key
:id
) x
)))
1574 (defun compile-value-thunk (value env
)
1575 (if (and (listp value
) (eq (car value
) 'progn
))
1576 (let ((inner-thunk (compile-instruction value env
)))
1578 (apply-to-result-tree-fragment ctx inner-thunk
)))
1579 (compile-xpath value env
)))
1581 (defun compile-var-binding (name value env
)
1582 (multiple-value-bind (local-name uri
)
1583 (decode-qname name env nil
)
1584 (let ((thunk (xslt-trace-thunk
1585 (compile-value-thunk value env
)
1586 "local variable ~s = ~s" name
:result
)))
1587 (list (cons local-name uri
)
1588 (push-variable local-name
1590 *lexical-variable-declarations
*)
1593 (defun compile-var-bindings (forms env
)
1595 for
(name value
) in forms
1596 collect
(compile-var-binding name value env
)))
1598 (defun compile-template (<template
> env position
)
1599 (stp:with-attributes
(match name priority mode
) <template
>
1600 (unless (or name match
)
1601 (xslt-error "missing match in template"))
1602 (multiple-value-bind (params body-pos
)
1605 for child in
(stp:list-children
<template
>)
1606 while
(namep child
"param")
1607 collect
(parse-param child
) into params
1608 finally
(return (values params i
)))
1609 (let* ((*lexical-variable-declarations
* (make-empty-declaration-array))
1610 (param-bindings (compile-var-bindings params env
))
1611 (body (parse-body <template
> body-pos
(mapcar #'car params
)))
1612 (body-thunk (compile-instruction `(progn ,@body
) env
))
1618 ;; set params that weren't initialized by apply-templates
1619 (loop for
(name index param-thunk
) in param-bindings
1620 when
(eq (lexical-variable-value index nil
) 'unbound
)
1621 do
(setf (lexical-variable-value index
)
1622 (funcall param-thunk ctx
)))
1623 (funcall body-thunk ctx
))))
1624 "template: match = ~s name = ~s" match name
))
1625 (n-variables (length *lexical-variable-declarations
*)))
1628 (multiple-value-bind (local-name uri
)
1629 (decode-qname name env nil
)
1631 (make-template :name
(cons local-name uri
)
1632 :import-priority
*import-priority
*
1633 :apply-imports-limit
*apply-imports-limit
*
1634 :params param-bindings
1635 :body outer-body-thunk
1636 :n-variables n-variables
))))
1638 (mapcar (lambda (expression)
1643 ,(naive-pattern-expression expression
))
1645 "match-thunk for template (match ~s): ~s --> ~s"
1646 match expression
:result
))
1648 (parse-number:parse-number priority
)
1649 (expression-priority expression
))))
1650 (make-template :match-expression expression
1651 :match-thunk match-thunk
1652 :import-priority
*import-priority
*
1653 :apply-imports-limit
*apply-imports-limit
*
1657 :params param-bindings
1658 :body outer-body-thunk
1659 :n-variables n-variables
)))
1660 (parse-pattern match
))))))))
1662 (xuriella::parse-stylesheet
#p
"/home/david/src/lisp/xuriella/test.xsl")