strip-/preserve-space conflict resolution
[xuriella.git] / xslt.lisp
bloba302721ce81df44980430cf4bf7c92a5d05d6492
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
8 ;;; are met:
9 ;;;
10 ;;; * Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
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.
17 ;;;
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)
32 #+sbcl
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"))
42 ;;;; XSLT-ERROR
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
65 ;; everywhere.
66 (defun xslt-cerror (fmt &rest args)
67 (declare (ignore fmt args))
68 #+(or)
69 (with-simple-restart (recover "recover")
70 (error 'recoverable-xslt-error
71 :format-control fmt
72 :format-arguments args)))
74 (defvar *debug* nil)
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
80 ;; important.)
81 (let ((doit (gensym)))
82 `(flet ((,doit () ,form))
83 (if *debug*
84 (,doit)
85 (handler-case
86 (,doit)
87 ,@clauses)))))
89 (defmacro with-resignalled-errors ((&optional) &body body)
90 `(invoke-with-resignalled-errors (lambda () ,@body)))
92 (defun invoke-with-resignalled-errors (fn)
93 (handler-bind
94 ((xpath:xpath-error
95 (lambda (c)
96 (xslt-error "~A" c)))
97 (babel-encodings:character-encoding-error
98 (lambda (c)
99 (xslt-error "~A" c))))
100 (funcall fn)))
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)
114 (unless
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)
118 valid-names
119 :test #'equal)))
120 (xslt-error "attribute ~A not allowed on ~A"
121 (stp:local-name a)
122 (stp:local-name node)))))
123 (stp:map-attributes nil #'check-attribute node)))
125 (defmacro only-with-attributes ((&rest specs) node &body body)
126 (let ((valid-names
127 (mapcar (lambda (entry)
128 (if (and (listp entry) (cdr entry))
129 (destructuring-bind (name &optional (uri ""))
130 (cdr entry)
131 (cons name uri))
132 (cons (string-downcase
133 (princ-to-string
134 (symbol-name entry)))
135 "")))
136 specs))
137 (%node (gensym)))
138 `(let ((,%NODE ,node))
139 (check-for-invalid-attributes ',valid-names ,%NODE)
140 (stp:with-attributes ,specs ,%NODE
141 ,@body))))
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)
147 `(block nil
148 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
149 ,result))
152 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
154 (defparameter *namespaces*
155 '((nil . "")
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)
168 (handler-case
169 (multiple-value-bind (prefix local-name)
170 (cxml::split-qname str)
171 (unless
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)
186 (split-qname qname)
187 (values local-name
188 (if (or prefix (not attributep))
189 (xpath-sys:environment-find-namespace env (or prefix ""))
191 prefix)))
193 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
194 (or (cdr (assoc prefix *namespaces* :test 'equal))
195 ;; zzz gross hack.
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)
211 (prog1
212 (length 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)))
217 (when errorp
218 (assert (not (eq result 'unbound))))
219 result))
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)))
227 (when errorp
228 (assert (not (eq result 'unbound))))
229 result))
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)
237 (if (string= 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)
244 (let ((index
245 (find-variable-index lname uri *lexical-variable-declarations*)))
246 (when index
247 (lambda (ctx)
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)
256 (let ((index
257 (find-variable-index lname uri *global-variable-declarations*)))
258 (when index
259 (xslt-trace-thunk
260 (lambda (ctx)
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
277 ;;;;
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))))
309 ;;;; TEXT-FILTER
310 ;;;;
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))
330 ;;;; ESCAPER
331 ;;;;
332 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
333 ;;;; XSLT 16.4.
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)))
345 ;;;; Names
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))
362 (strip-tests nil)
363 (strip-thunk nil)
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)))
371 (defstruct mode
372 (templates nil)
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))
381 (make-mode))))
383 (defun ensure-mode/qname (stylesheet qname env)
384 (if qname
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))
393 element)
394 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" . ""))
447 <transform>)
448 (let ((invalid
449 (or (stp:find-child-if (of-name "stylesheet") <transform>)
450 (stp:find-child-if (of-name "transform") <transform>))))
451 (when invalid
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))
458 uri))
459 (str (puri:render-uri uri nil))
460 (pathname
461 (handler-case
462 (uri-to-pathname uri)
463 (cxml:xml-parse-error (c)
464 (xslt-error "cannot find included stylesheet ~A: ~A"
465 uri c)))))
466 (with-open-file
467 (stream pathname
468 :element-type '(unsigned-byte 8)
469 :if-does-not-exist nil)
470 (unless stream
471 (xslt-error "cannot find included stylesheet ~A at ~A"
472 uri pathname))
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)
479 include)
480 (stp:detach include)))))
481 <transform>))
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))))
498 (funcall fn node))))
500 (defun list-toplevel (xpath <transform>)
501 (labels ((recurse (sub)
502 (let ((subsubs
503 (xpath-sys:pipe-of
504 (xpath:evaluate "transform|stylesheet" sub))))
505 (xpath::append-pipes
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)
522 (funcall fn)))
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*))
529 (continuations '()))
530 (let ((*namespaces* namespaces))
531 (invoke-with-import-magic (constantly t) <transform> env))
532 (do-toplevel (elt "node()" <transform>)
533 (when (equal (stp:attribute-value (stp:parent elt) "version") "1.0")
534 (if (typep elt 'stp:element)
535 (when (or (equal (stp:namespace-uri elt) "")
536 (and (equal (stp:namespace-uri elt) *xsl*)
537 (not (find (stp:local-name elt)
538 '("key" "template" "output" "strip-space"
539 "preserve-space" "attribute-set"
540 "namespace-alias" "decimal-format"
541 "variable" "param" "import" "include"
542 ;; for include handling:
543 "stylesheet" "transform")
544 :test #'equal))))
545 (xslt-error "unknown top-level element ~A" (stp:local-name elt)))
546 (xslt-error "text at top-level"))))
547 (macrolet ((with-specials ((&optional) &body body)
548 `(let ((*instruction-base-uri* instruction-base-uri)
549 (*namespaces* namespaces)
550 (*apply-imports-limit* apply-imports-limit))
551 ,@body)))
552 (with-specials ()
553 (do-toplevel (import "import" <transform>)
554 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
555 (stp:base-uri import))))
556 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
557 continuations))))
558 (let ((import-priority
559 (incf *import-priority*))
560 (var-cont (prepare-global-variables stylesheet <transform>)))
561 ;; delay the rest of compilation until we've seen all global
562 ;; variables:
563 (lambda ()
564 (mapc #'funcall (nreverse continuations))
565 (with-specials ()
566 (let ((*import-priority* import-priority))
567 (funcall var-cont)
568 (parse-keys! stylesheet <transform> env)
569 (parse-templates! stylesheet <transform> env)
570 (parse-output! stylesheet <transform>)
571 (parse-strip/preserve-space! stylesheet <transform> env)
572 (parse-attribute-sets! stylesheet <transform> env)
573 (parse-namespace-aliases! stylesheet <transform> env)
574 (parse-decimal-formats! stylesheet <transform> env))))))))
576 (defvar *xsl-import-stack* nil)
578 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
579 (let* ((uri (if uri-resolver
580 (funcall uri-resolver (puri:render-uri uri nil))
581 uri))
582 (str (puri:render-uri uri nil))
583 (pathname
584 (handler-case
585 (uri-to-pathname uri)
586 (cxml:xml-parse-error (c)
587 (xslt-error "cannot find imported stylesheet ~A: ~A"
588 uri c)))))
589 (with-open-file
590 (stream pathname
591 :element-type '(unsigned-byte 8)
592 :if-does-not-exist nil)
593 (unless stream
594 (xslt-error "cannot find imported stylesheet ~A at ~A"
595 uri pathname))
596 (when (find str *xsl-import-stack* :test #'equal)
597 (xslt-error "recursive inclusion of ~A" uri))
598 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
599 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
601 (defun parse-stylesheet (designator &key uri-resolver)
602 (with-resignalled-errors ()
603 (xpath:with-namespaces ((nil #.*xsl*))
604 (let* ((*import-priority* 0)
605 (xpath:*allow-variables-in-patterns* nil)
606 (puri:*strict-parse* nil)
607 (stylesheet (make-stylesheet))
608 (env (make-instance 'lexical-xslt-environment))
609 (*excluded-namespaces* *excluded-namespaces*)
610 (*global-variable-declarations* (make-empty-declaration-array)))
611 (ensure-mode stylesheet nil)
612 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
613 ;; reverse attribute sets:
614 (let ((table (stylesheet-attribute-sets stylesheet)))
615 (maphash (lambda (k v)
616 (setf (gethash k table) (nreverse v)))
617 table))
618 ;; add default df
619 (unless (find-decimal-format "" "" stylesheet nil)
620 (setf (find-decimal-format "" "" stylesheet)
621 (make-decimal-format)))
622 ;; compile a template matcher for each mode:
623 (loop
624 for mode being each hash-value in (stylesheet-modes stylesheet)
626 (setf (mode-match-thunk mode)
627 (xpath:make-pattern-matcher
628 (mapcar #'template-compiled-pattern
629 (mode-templates mode)))))
630 ;; and for the strip tests
631 (setf (stylesheet-strip-thunk stylesheet)
632 (let ((patterns (stylesheet-strip-tests stylesheet)))
633 (and patterns
634 (xpath:make-pattern-matcher
635 (mapcar #'strip-test-compiled-pattern patterns)))))
636 stylesheet))))
638 (defun parse-attribute-sets! (stylesheet <transform> env)
639 (do-toplevel (elt "attribute-set" <transform>)
640 (with-import-magic (elt env)
641 (push (let* ((sets
642 (mapcar (lambda (qname)
643 (multiple-value-list (decode-qname qname env nil)))
644 (words
645 (stp:attribute-value elt "use-attribute-sets"))))
646 (instructions
647 (stp:map-children
648 'list
649 (lambda (child)
650 (unless
651 (and (typep child 'stp:element)
652 (or (and (equal (stp:namespace-uri child) *xsl*)
653 (equal (stp:local-name child)
654 "attribute"))
655 (find (stp:namespace-uri child)
656 *extension-namespaces*
657 :test 'equal)))
658 (xslt-error "non-attribute found in attribute set"))
659 (parse-instruction child))
660 elt))
661 (*lexical-variable-declarations*
662 (make-empty-declaration-array))
663 (thunk
664 (compile-instruction `(progn ,@instructions) env))
665 (n-variables (length *lexical-variable-declarations*)))
666 (lambda (ctx)
667 (with-stack-limit ()
668 (loop for (local-name uri nil) in sets do
669 (dolist (thunk (find-attribute-set local-name uri))
670 (funcall thunk ctx)))
671 (let ((*lexical-variable-values*
672 (make-variable-value-array n-variables)))
673 (funcall thunk ctx)))))
674 (gethash (multiple-value-bind (local-name uri)
675 (decode-qname (stp:attribute-value elt "name") env nil)
676 (cons local-name uri))
677 (stylesheet-attribute-sets stylesheet))))))
679 (defun parse-namespace-aliases! (stylesheet <transform> env)
680 (do-toplevel (elt "namespace-alias" <transform>)
681 (stp:with-attributes (stylesheet-prefix result-prefix) elt
682 (setf (gethash
683 (if (equal stylesheet-prefix "#default")
685 (xpath-sys:environment-find-namespace env stylesheet-prefix))
686 (stylesheet-namespace-aliases stylesheet))
687 (xpath-sys:environment-find-namespace
689 (if (equal result-prefix "#default")
691 result-prefix))))))
693 (defun parse-decimal-formats! (stylesheet <transform> env)
694 (do-toplevel (elt "decimal-format" <transform>)
695 (stp:with-attributes (name
696 ;; strings
697 infinity
698 (nan "NaN")
699 ;; characters:
700 decimal-separator
701 grouping-separator
702 zero-digit
703 percent
704 per-mille
705 digit
706 pattern-separator
707 minus-sign)
709 (multiple-value-bind (local-name uri)
710 (if name
711 (decode-qname name env nil)
712 (values "" ""))
713 (let ((current (find-decimal-format local-name uri stylesheet nil))
714 (new
715 (let ((seen '()))
716 (flet ((chr (key x)
717 (when x
718 (unless (eql (length x) 1)
719 (xslt-error "not a single character: ~A" x))
720 (let ((chr (elt x 0)))
721 (when (find chr seen)
722 (xslt-error
723 "conflicting decimal format characters: ~A"
724 chr))
725 (push chr seen)
726 (list key chr))))
727 (str (key x)
728 (when x
729 (list key x))))
730 (apply #'make-decimal-format
731 (append (str :infinity infinity)
732 (str :nan nan)
733 (chr :decimal-separator decimal-separator)
734 (chr :grouping-separator grouping-separator)
735 (chr :zero-digit zero-digit)
736 (chr :percent percent)
737 (chr :per-mille per-mille)
738 (chr :digit digit)
739 (chr :pattern-separator pattern-separator)
740 (chr :minus-sign minus-sign)))))))
741 (if current
742 (unless (decimal-format= current new)
743 (xslt-error "decimal format mismatch for ~S" local-name))
744 (setf (find-decimal-format local-name uri stylesheet) new)))))))
746 (defun parse-exclude-result-prefixes! (node env)
747 (stp:with-attributes (exclude-result-prefixes)
748 node
749 (dolist (prefix (words (or exclude-result-prefixes "")))
750 (if (equal prefix "#default")
751 (setf prefix nil)
752 (unless (cxml-stp-impl::nc-name-p prefix)
753 (xslt-error "invalid prefix: ~A" prefix)))
754 (push (or (xpath-sys:environment-find-namespace env prefix)
755 (xslt-error "namespace not found: ~A" prefix))
756 *excluded-namespaces*))))
758 (defun parse-extension-element-prefixes! (node env)
759 (stp:with-attributes (extension-element-prefixes)
760 node
761 (dolist (prefix (words (or extension-element-prefixes "")))
762 (if (equal prefix "#default")
763 (setf prefix nil)
764 (unless (cxml-stp-impl::nc-name-p prefix)
765 (xslt-error "invalid prefix: ~A" prefix)))
766 (let ((uri
767 (or (xpath-sys:environment-find-namespace env prefix)
768 (xslt-error "namespace not found: ~A" prefix))))
769 (unless (equal uri *xsl*)
770 (push uri *extension-namespaces*)
771 (push uri *excluded-namespaces*))))))
773 (defun parse-nametest-tokens (str)
774 (labels ((check (boolean)
775 (unless boolean
776 (xslt-error "invalid nametest token")))
777 (check-null (boolean)
778 (check (not boolean))))
779 (cons
780 :patterns
781 (mapcar (lambda (name-test)
782 (destructuring-bind (&optional path &rest junk)
783 (cdr (xpath:parse-pattern-expression name-test))
784 (check-null junk)
785 (check (eq (car path) :path))
786 (destructuring-bind (&optional child &rest junk) (cdr path)
787 (check-null junk)
788 (check (eq (car child) :child))
789 (destructuring-bind (nodetest &rest junk) (cdr child)
790 (check-null junk)
791 (check (or (stringp nodetest)
792 (eq nodetest '*)
793 (and (consp nodetest)
794 (or (eq (car nodetest) :namespace)
795 (eq (car nodetest) :qname)))))))
796 path))
797 (words str)))))
799 (defstruct strip-test
800 compiled-pattern
801 priority
802 position
803 value)
805 (defun parse-strip/preserve-space! (stylesheet <transform> env)
806 (let ((i 0))
807 (do-toplevel (elt "strip-space|preserve-space" <transform>)
808 (let ((*namespaces* (acons-namespaces elt))
809 (value
810 (if (equal (stp:local-name elt) "strip-space")
811 :strip
812 :preserve)))
813 (dolist (expression
814 (cdr (parse-nametest-tokens
815 (stp:attribute-value elt "elements"))))
816 (let* ((compiled-pattern
817 (car (xpath:compute-patterns
818 `(:patterns ,expression)
819 *import-priority*
820 "will set below"
821 env)))
822 (strip-test
823 (make-strip-test :compiled-pattern compiled-pattern
824 :priority (expression-priority expression)
825 :position i
826 :value value)))
827 (setf (xpath:pattern-value compiled-pattern) strip-test)
828 (push strip-test (stylesheet-strip-tests stylesheet)))))
829 (incf i))))
831 (defstruct (output-specification
832 (:conc-name "OUTPUT-"))
833 method
834 indent
835 omit-xml-declaration
836 encoding
837 doctype-system
838 doctype-public)
840 (defun parse-output! (stylesheet <transform>)
841 (dolist (<output> (list-toplevel "output" <transform>))
842 (let ((spec (stylesheet-output-specification stylesheet)))
843 (stp:with-attributes ( ;; version
844 method
845 indent
846 encoding
847 ;;; media-type
848 doctype-system
849 doctype-public
850 omit-xml-declaration
851 ;;; standalone
852 ;;; cdata-section-elements
854 <output>
855 (when method
856 (setf (output-method spec) method))
857 (when indent
858 (setf (output-indent spec) indent))
859 (when encoding
860 (setf (output-encoding spec) encoding))
861 (when doctype-system
862 (setf (output-doctype-system spec) doctype-system))
863 (when doctype-public
864 (setf (output-doctype-public spec) doctype-public))
865 (when omit-xml-declaration
866 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
867 ;;; (when cdata-section-elements
868 ;;; (setf (output-cdata-section-elements spec)
869 ;;; (concatenate 'string
870 ;;; (output-cdata-section-elements spec)
871 ;;; " "
872 ;;; cdata-section-elements)))
873 ))))
875 (defun make-empty-declaration-array ()
876 (make-array 1 :fill-pointer 0 :adjustable t))
878 (defun make-variable-value-array (n-lexical-variables)
879 (make-array n-lexical-variables :initial-element 'unbound))
881 (defun compile-global-variable (<variable> env) ;; also for <param>
882 (stp:with-attributes (name select) <variable>
883 (when (and select (stp:list-children <variable>))
884 (xslt-error "variable with select and body"))
885 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
886 (inner (cond
887 (select
888 (compile-xpath select env))
889 ((stp:list-children <variable>)
890 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
891 (inner-thunk (compile-instruction inner-sexpr env)))
892 (lambda (ctx)
893 (apply-to-result-tree-fragment ctx inner-thunk))))
895 (lambda (ctx)
896 (declare (ignore ctx))
897 ""))))
898 (n-lexical-variables (length *lexical-variable-declarations*)))
899 (xslt-trace-thunk
900 (lambda (ctx)
901 (let* ((*lexical-variable-values*
902 (make-variable-value-array n-lexical-variables)))
903 (funcall inner ctx)))
904 "global ~s (~s) = ~s" name select :result))))
906 (defstruct (variable-chain
907 (:constructor make-variable-chain)
908 (:conc-name "VARIABLE-CHAIN-"))
909 definitions
910 index
911 local-name
912 thunk
913 uri)
915 (defstruct (import-variable
916 (:constructor make-variable)
917 (:conc-name "VARIABLE-"))
918 value-thunk
919 value-thunk-setter
920 param-p)
922 (defun parse-global-variable! (stylesheet <variable> global-env)
923 (let* ((*namespaces* (acons-namespaces <variable>))
924 (instruction-base-uri (stp:base-uri <variable>))
925 (*instruction-base-uri* instruction-base-uri)
926 (*excluded-namespaces* (list *xsl*))
927 (*extension-namespaces* '())
928 (qname (stp:attribute-value <variable> "name")))
929 (with-import-magic (<variable> global-env)
930 (unless qname
931 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
932 (multiple-value-bind (local-name uri)
933 (decode-qname qname global-env nil)
934 ;; For the normal compilation environment of templates, install it
935 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
936 (let ((index (intern-global-variable local-name uri)))
937 ;; For the evaluation of a global variable itself, build a thunk
938 ;; that lazily resolves other variables, stored into
939 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
940 (let* ((value-thunk :unknown)
941 (sgv (stylesheet-global-variables stylesheet))
942 (chain
943 (if (< index (length sgv))
944 (elt sgv index)
945 (make-variable-chain
946 :index index
947 :local-name local-name
948 :uri uri)))
949 (next (car (variable-chain-definitions chain)))
950 (global-variable-thunk
951 (lambda (ctx)
952 (let ((v (global-variable-value index nil)))
953 (cond
954 ((eq v 'seen)
955 (unless next
956 (xslt-error "no next definition for: ~A"
957 local-name))
958 (funcall (variable-value-thunk next) ctx))
959 ((eq v 'unbound)
960 (setf (global-variable-value index) 'seen)
961 (setf (global-variable-value index)
962 (funcall value-thunk ctx)))
964 v)))))
965 (excluded-namespaces *excluded-namespaces*)
966 (extension-namespaces *extension-namespaces*)
967 (variable
968 (make-variable :param-p (namep <variable> "param")))
969 (value-thunk-setter
970 (lambda ()
971 (let* ((*instruction-base-uri* instruction-base-uri)
972 (*excluded-namespaces* excluded-namespaces)
973 (*extension-namespaces* extension-namespaces)
975 (compile-global-variable <variable> global-env)))
976 (setf value-thunk fn)
977 (setf (variable-value-thunk variable) fn)))))
978 (setf (variable-value-thunk-setter variable)
979 value-thunk-setter)
980 (setf (gethash (cons local-name uri)
981 (initial-global-variable-thunks global-env))
982 global-variable-thunk)
983 (setf (variable-chain-thunk chain) global-variable-thunk)
984 (push variable (variable-chain-definitions chain))
985 chain))))))
987 (defun parse-keys! (stylesheet <transform> env)
988 (xpath:with-namespaces ((nil #.*xsl*))
989 (do-toplevel (<key> "key" <transform>)
990 (let ((*instruction-base-uri* (stp:base-uri <key>)))
991 (stp:with-attributes (name match use) <key>
992 (unless name (xslt-error "key name attribute not specified"))
993 (unless match (xslt-error "key match attribute not specified"))
994 (unless use (xslt-error "key use attribute not specified"))
995 (multiple-value-bind (local-name uri)
996 (decode-qname name env nil)
997 (add-key stylesheet
998 (cons local-name uri)
999 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
1000 (compile-xpath use env))))))))
1002 (defun prepare-global-variables (stylesheet <transform>)
1003 (xpath:with-namespaces ((nil #.*xsl*))
1004 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet))
1005 (global-env (make-instance 'global-variable-environment
1006 :initial-global-variable-thunks igvt))
1007 (chains '()))
1008 (do-toplevel (<variable> "variable|param" <transform>)
1009 (let ((chain
1010 (parse-global-variable! stylesheet <variable> global-env)))
1011 (xslt-trace "parsing global variable ~s (uri ~s)"
1012 (variable-chain-local-name chain)
1013 (variable-chain-uri chain))
1014 (when (find chain
1015 chains
1016 :test (lambda (a b)
1017 (and (equal (variable-chain-local-name a)
1018 (variable-chain-local-name b))
1019 (equal (variable-chain-uri a)
1020 (variable-chain-uri b)))))
1021 (xslt-error "duplicate definition for global variable ~A"
1022 (variable-chain-local-name chain)))
1023 (push chain chains)))
1024 (setf chains (nreverse chains))
1025 (let ((table (stylesheet-global-variables stylesheet))
1026 (newlen (length *global-variable-declarations*)))
1027 (adjust-array table newlen :fill-pointer newlen)
1028 (dolist (chain chains)
1029 (setf (elt table (variable-chain-index chain)) chain)))
1030 (lambda ()
1031 ;; now that the global environment knows about all variables, run the
1032 ;; thunk setters to perform their compilation
1033 (mapc (lambda (chain)
1034 (dolist (var (variable-chain-definitions chain))
1035 (funcall (variable-value-thunk-setter var))))
1036 chains)))))
1038 (defun parse-templates! (stylesheet <transform> env)
1039 (let ((i 0))
1040 (do-toplevel (<template> "template" <transform>)
1041 (let ((*namespaces* (acons-namespaces <template>))
1042 (*instruction-base-uri* (stp:base-uri <template>)))
1043 (with-import-magic (<template> env)
1044 (dolist (template (compile-template <template> env i))
1045 (let ((name (template-name template)))
1046 (if name
1047 (let* ((table (stylesheet-named-templates stylesheet))
1048 (head (car (gethash name table))))
1049 (when (and head (eql (template-import-priority head)
1050 (template-import-priority template)))
1051 ;; fixme: is this supposed to be a run-time error?
1052 (xslt-error "conflicting templates for ~A" name))
1053 (push template (gethash name table)))
1054 (let ((mode (ensure-mode/qname stylesheet
1055 (template-mode-qname template)
1056 env)))
1057 (setf (template-mode template) mode)
1058 (push template (mode-templates mode))))))))
1059 (incf i))))
1062 ;;;; APPLY-STYLESHEET
1064 (defvar *stylesheet*)
1066 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
1068 (defun unalias-uri (uri)
1069 (let ((result
1070 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
1071 uri)))
1072 (check-type result string)
1073 result))
1075 (defstruct (parameter
1076 (:constructor make-parameter (value local-name &optional uri)))
1077 (uri "")
1078 local-name
1079 value)
1081 (defun find-parameter-value (local-name uri parameters)
1082 (dolist (p parameters)
1083 (when (and (equal (parameter-local-name p) local-name)
1084 (equal (parameter-uri p) uri))
1085 (return (parameter-value p)))))
1087 (defvar *uri-resolver*)
1089 (defun parse-allowing-microsoft-bom (pathname handler)
1090 (with-open-file (s pathname :element-type '(unsigned-byte 8))
1091 (unless (and (eql (read-byte s nil) #xef)
1092 (eql (read-byte s nil) #xbb)
1093 (eql (read-byte s nil) #xbf))
1094 (file-position s 0))
1095 (cxml:parse s handler)))
1097 (defvar *documents*)
1099 (defun %document (uri-string base-uri)
1100 (let* ((absolute-uri
1101 (puri:merge-uris uri-string (or base-uri "")))
1102 (resolved-uri
1103 (if *uri-resolver*
1104 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
1105 absolute-uri))
1106 (pathname
1107 (handler-case
1108 (uri-to-pathname resolved-uri)
1109 (cxml:xml-parse-error (c)
1110 (xslt-error "cannot find referenced document ~A: ~A"
1111 resolved-uri c))))
1112 (xpath-root-node
1113 (or (gethash pathname *documents*)
1114 (setf (gethash pathname *documents*)
1115 (make-whitespace-stripper
1116 (handler-case
1117 (parse-allowing-microsoft-bom pathname
1118 (stp:make-builder))
1119 ((or file-error cxml:xml-parse-error) (c)
1120 (xslt-error "cannot parse referenced document ~A: ~A"
1121 pathname c)))
1122 (stylesheet-strip-thunk *stylesheet*))))))
1123 (when (puri:uri-fragment absolute-uri)
1124 (xslt-error "use of fragment identifiers in document() not supported"))
1125 xpath-root-node))
1127 (xpath-sys:define-extension xslt *xsl*)
1129 (defun document-base-uri (node)
1130 (xpath-protocol:base-uri
1131 (cond
1132 ((xpath-protocol:node-type-p node :document)
1133 (xpath::find-in-pipe-if
1134 (lambda (x)
1135 (xpath-protocol:node-type-p x :element))
1136 (xpath-protocol:child-pipe node)))
1137 ((xpath-protocol:node-type-p node :element)
1138 node)
1140 (xpath-protocol:parent-node node)))))
1142 (xpath-sys:define-xpath-function/lazy
1143 xslt :document
1144 (object &optional node-set)
1145 (let ((instruction-base-uri *instruction-base-uri*))
1146 (lambda (ctx)
1147 (let* ((object (funcall object ctx))
1148 (node-set (and node-set (funcall node-set ctx)))
1149 (base-uri
1150 (if node-set
1151 (document-base-uri (xpath::textually-first-node node-set))
1152 instruction-base-uri)))
1153 (xpath-sys:make-node-set
1154 (if (xpath:node-set-p object)
1155 (xpath:map-node-set->list
1156 (lambda (node)
1157 (%document (xpath:string-value node)
1158 (if node-set
1159 base-uri
1160 (document-base-uri node))))
1161 object)
1162 (list (%document (xpath:string-value object) base-uri))))))))
1164 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1165 (let ((namespaces *namespaces*))
1166 (lambda (ctx)
1167 (let* ((qname (xpath:string-value (funcall name ctx)))
1168 (object (funcall object ctx))
1169 (expanded-name
1170 (multiple-value-bind (local-name uri)
1171 (decode-qname/runtime qname namespaces nil)
1172 (cons local-name uri)))
1173 (key (find-key expanded-name *stylesheet*)))
1174 (labels ((get-by-key (value)
1175 (let ((value (xpath:string-value value)))
1176 (xpath::filter-pipe
1177 #'(lambda (node)
1178 (let ((uses
1179 (xpath:evaluate-compiled (key-use key) node)))
1180 (if (xpath:node-set-p uses)
1181 (xpath::find-in-pipe
1182 value
1183 (xpath-sys:pipe-of uses)
1184 :key #'xpath:string-value
1185 :test #'equal)
1186 (equal value (xpath:string-value uses)))))
1187 (xpath-sys:pipe-of
1188 (xpath:node-set-value
1189 (xpath:evaluate-compiled (key-match key) ctx)))))))
1190 (xpath-sys:make-node-set
1191 (xpath::sort-pipe
1192 (if (xpath:node-set-p object)
1193 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1194 (get-by-key object)))))))))
1196 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1198 (xpath-sys:define-xpath-function/lazy xslt :current ()
1199 #'(lambda (ctx)
1200 (xpath-sys:make-node-set
1201 (xpath-sys:make-pipe
1202 (xpath:context-starting-node ctx)
1203 nil))))
1205 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1206 #'(lambda (ctx)
1207 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1208 (funcall name ctx))
1209 "")))
1211 (defun %get-node-id (node)
1212 (when (xpath:node-set-p node)
1213 (setf node (xpath::textually-first-node node)))
1214 (when node
1215 (let ((id (xpath-sys:get-node-id node))
1216 (highest-base-uri
1217 (loop
1218 for parent = node then next
1219 for next = (xpath-protocol:parent-node parent)
1220 for this-base-uri = (xpath-protocol:base-uri parent)
1221 for highest-base-uri = (if (plusp (length this-base-uri))
1222 this-base-uri
1223 highest-base-uri)
1224 while next
1225 finally (return highest-base-uri))))
1226 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1227 ;; checked only if everything else matches.
1229 ;; This might be pointless premature optimization, but I like the idea :-)
1230 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1232 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1233 (if node-set-thunk
1234 #'(lambda (ctx)
1235 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1236 #'(lambda (ctx)
1237 (%get-node-id (xpath:context-node ctx)))))
1239 (declaim (special *available-instructions*))
1241 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1242 (let ((namespaces *namespaces*))
1243 #'(lambda (ctx)
1244 (let ((qname (funcall qname ctx)))
1245 (multiple-value-bind (local-name uri)
1246 (decode-qname/runtime qname namespaces nil)
1247 (and (equal uri *xsl*)
1248 (gethash local-name *available-instructions*)
1249 t))))))
1251 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1252 (let ((namespaces *namespaces*))
1253 #'(lambda (ctx)
1254 (let ((qname (funcall qname ctx)))
1255 (multiple-value-bind (local-name uri)
1256 (decode-qname/runtime qname namespaces nil)
1257 (and (zerop (length uri))
1258 (or (xpath-sys:find-xpath-function local-name *xsl*)
1259 (xpath-sys:find-xpath-function local-name uri))
1260 t))))))
1262 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1263 (let ((namespaces *namespaces*))
1264 (lambda (ctx)
1265 (let ((qname (funcall qname ctx)))
1266 (multiple-value-bind (local-name uri)
1267 (decode-qname/runtime qname namespaces nil)
1268 (if (equal uri *xsl*)
1269 (cond
1270 ((equal local-name "version")
1271 "1")
1272 ((equal local-name "vendor")
1273 "Xuriella")
1274 ((equal local-name "vendor-uri")
1275 "http://repo.or.cz/w/xuriella.git")
1277 ""))
1278 ""))))))
1280 (defun apply-stylesheet
1281 (stylesheet source-designator
1282 &key output parameters uri-resolver navigator)
1283 (when (typep stylesheet 'xml-designator)
1284 (setf stylesheet
1285 (handler-bind
1286 ((cxml:xml-parse-error
1287 (lambda (c)
1288 (xslt-error "cannot parse stylesheet: ~A" c))))
1289 (parse-stylesheet stylesheet))))
1290 (with-resignalled-errors ()
1291 (invoke-with-output-sink
1292 (lambda ()
1293 (let* ((*documents* (make-hash-table :test 'equal))
1294 (xpath:*navigator* (or navigator :default-navigator))
1295 (puri:*strict-parse* nil)
1296 (*stylesheet* stylesheet)
1297 (*empty-mode* (make-mode))
1298 (*default-mode* (find-mode stylesheet nil))
1299 (global-variable-chains
1300 (stylesheet-global-variables stylesheet))
1301 (*global-variable-values*
1302 (make-variable-value-array (length global-variable-chains)))
1303 (*uri-resolver* uri-resolver)
1304 (source-document
1305 (if (typep source-designator 'xml-designator)
1306 (cxml:parse source-designator (stp:make-builder))
1307 source-designator))
1308 (xpath-root-node
1309 (make-whitespace-stripper
1310 source-document
1311 (stylesheet-strip-thunk stylesheet)))
1312 (ctx (xpath:make-context xpath-root-node)))
1313 (when (pathnamep source-designator)
1314 (setf (gethash source-designator *documents*) xpath-root-node))
1315 (map nil
1316 (lambda (chain)
1317 (let ((head (car (variable-chain-definitions chain))))
1318 (when (variable-param-p head)
1319 (let ((value
1320 (find-parameter-value
1321 (variable-chain-local-name chain)
1322 (variable-chain-uri chain)
1323 parameters)))
1324 (when value
1325 (setf (global-variable-value
1326 (variable-chain-index chain))
1327 value))))))
1328 global-variable-chains)
1329 (map nil
1330 (lambda (chain)
1331 (funcall (variable-chain-thunk chain) ctx))
1332 global-variable-chains)
1333 ;; zzz we wouldn't have to mask float traps here if we used the
1334 ;; XPath API properly. Unfortunately I've been using FUNCALL
1335 ;; everywhere instead of EVALUATE, so let's paper over that
1336 ;; at a central place to be sure:
1337 (xpath::with-float-traps-masked ()
1338 (apply-templates ctx :mode *default-mode*))))
1339 (stylesheet-output-specification stylesheet)
1340 output)))
1342 (defun find-attribute-set (local-name uri)
1343 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1344 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1346 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1347 (when sort-predicate
1348 (setf list
1349 (mapcar #'xpath:context-node
1350 (stable-sort (contextify-node-list list)
1351 sort-predicate))))
1352 (let* ((n (length list))
1353 (s/d (lambda () n)))
1354 (loop
1355 for i from 1
1356 for child in list
1358 (apply-templates (xpath:make-context child s/d i)
1359 :param-bindings param-bindings
1360 :mode mode))))
1362 (defvar *stack-limit* 200)
1364 (defun invoke-with-stack-limit (fn)
1365 (let ((*stack-limit* (1- *stack-limit*)))
1366 (unless (plusp *stack-limit*)
1367 (xslt-error "*stack-limit* reached; stack overflow"))
1368 (funcall fn)))
1370 (defun invoke-template (ctx template param-bindings)
1371 (let ((*lexical-variable-values*
1372 (make-variable-value-array (template-n-variables template))))
1373 (with-stack-limit ()
1374 (loop
1375 for (name-cons value) in param-bindings
1376 for (nil index nil) = (find name-cons
1377 (template-params template)
1378 :test #'equal
1379 :key #'car)
1381 (when index
1382 (setf (lexical-variable-value index) value)))
1383 (funcall (template-body template) ctx))))
1385 (defun apply-default-templates (ctx mode)
1386 (let ((node (xpath:context-node ctx)))
1387 (cond
1388 ((or (xpath-protocol:node-type-p node :processing-instruction)
1389 (xpath-protocol:node-type-p node :comment)))
1390 ((or (xpath-protocol:node-type-p node :text)
1391 (xpath-protocol:node-type-p node :attribute))
1392 (write-text (xpath-protocol:node-text node)))
1394 (apply-templates/list
1395 (xpath::force
1396 (xpath-protocol:child-pipe node))
1397 :mode mode)))))
1399 (defvar *apply-imports*)
1401 (defun apply-applicable-templates (ctx templates param-bindings finally)
1402 (labels ((apply-imports (&optional actual-param-bindings)
1403 (if templates
1404 (let* ((this (pop templates))
1405 (low (template-apply-imports-limit this))
1406 (high (template-import-priority this)))
1407 (setf templates
1408 (remove-if-not
1409 (lambda (x)
1410 (<= low (template-import-priority x) high))
1411 templates))
1412 (invoke-template ctx this actual-param-bindings))
1413 (funcall finally))))
1414 (let ((*apply-imports* #'apply-imports))
1415 (apply-imports param-bindings))))
1417 (defun apply-templates (ctx &key param-bindings mode)
1418 (apply-applicable-templates ctx
1419 (find-templates ctx (or mode *default-mode*))
1420 param-bindings
1421 (lambda ()
1422 (apply-default-templates ctx mode))))
1424 (defun call-template (ctx name &optional param-bindings)
1425 (apply-applicable-templates ctx
1426 (find-named-templates name)
1427 param-bindings
1428 (lambda ()
1429 (error "cannot find named template: ~s"
1430 name))))
1432 (defun find-templates (ctx mode)
1433 (let* ((matching-candidates
1434 (xpath:matching-values (mode-match-thunk mode)
1435 (xpath:context-node ctx)))
1436 (npriorities
1437 (if matching-candidates
1438 (1+ (reduce #'max
1439 matching-candidates
1440 :key #'template-import-priority))
1442 (priority-groups (make-array npriorities :initial-element nil)))
1443 (dolist (template matching-candidates)
1444 (push template
1445 (elt priority-groups (template-import-priority template))))
1446 (loop
1447 for i from (1- npriorities) downto 0
1448 for group = (elt priority-groups i)
1449 for template = (maximize #'template< group)
1450 when template
1451 collect template)))
1453 (defun find-named-templates (name)
1454 (gethash name (stylesheet-named-templates *stylesheet*)))
1456 (defun template< (a b) ;assuming same import priority
1457 (let ((p (template-priority a))
1458 (q (template-priority b)))
1459 (cond
1460 ((< p q) t)
1461 ((> p q) nil)
1463 (xslt-cerror "conflicting templates:~_~A,~_~A"
1464 (template-match-expression a)
1465 (template-match-expression b))
1466 (< (template-position a) (template-position b))))))
1468 (defun maximize (< things)
1469 (when things
1470 (let ((max (car things)))
1471 (dolist (other (cdr things))
1472 (when (funcall < max other)
1473 (setf max other)))
1474 max)))
1476 (defun invoke-with-output-sink (fn output-spec output)
1477 (etypecase output
1478 (pathname
1479 (with-open-file (s output
1480 :direction :output
1481 :element-type '(unsigned-byte 8)
1482 :if-exists :rename-and-delete)
1483 (invoke-with-output-sink fn output-spec s)))
1484 ((or stream null)
1485 (invoke-with-output-sink fn
1486 output-spec
1487 (make-output-sink output-spec output)))
1488 ((or hax:abstract-handler sax:abstract-handler)
1489 (with-xml-output output
1490 (when (typep output '(or combi-sink auto-detect-sink))
1491 (sax:start-dtd output
1492 :autodetect-me-please
1493 (output-doctype-public output-spec)
1494 (output-doctype-system output-spec)))
1495 (funcall fn)))))
1497 (defun make-output-sink (output-spec stream)
1498 (let* ((ystream
1499 (if stream
1500 (let ((et (stream-element-type stream)))
1501 (cond
1502 ((or (null et) (subtypep et '(unsigned-byte 8)))
1503 (runes:make-octet-stream-ystream stream))
1504 ((subtypep et 'character)
1505 (runes:make-character-stream-ystream stream))))
1506 (runes:make-rod-ystream)))
1507 (omit-xml-declaration-p
1508 (equal (output-omit-xml-declaration output-spec) "yes"))
1509 (sink-encoding (or (output-encoding output-spec) "UTF-8"))
1510 (sax-target
1511 (progn
1512 (setf (runes:ystream-encoding ystream)
1513 (cxml::find-output-encoding sink-encoding))
1514 (make-instance 'cxml::sink
1515 :ystream ystream
1516 :omit-xml-declaration-p omit-xml-declaration-p
1517 :encoding sink-encoding))))
1518 (flet ((make-combi-sink ()
1519 (make-instance 'combi-sink
1520 :hax-target (make-instance 'chtml::sink
1521 :ystream ystream)
1522 :sax-target sax-target
1523 :encoding sink-encoding)))
1524 (let ((method-key
1525 (cond
1526 ((equalp (output-method output-spec) "HTML") :html)
1527 ((equalp (output-method output-spec) "TEXT") :text)
1528 ((equalp (output-method output-spec) "XML") :xml)
1529 (t nil))))
1530 (cond
1531 ((and (eq method-key :html)
1532 (null (output-doctype-system output-spec))
1533 (null (output-doctype-public output-spec)))
1534 (make-combi-sink))
1535 ((eq method-key :text)
1536 (make-text-filter sax-target))
1537 ((and (eq method-key :xml)
1538 (null (output-doctype-system output-spec)))
1539 sax-target)
1541 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1543 (defstruct template
1544 match-expression
1545 compiled-pattern
1546 name
1547 import-priority
1548 apply-imports-limit
1549 priority
1550 position
1551 mode
1552 mode-qname
1553 params
1554 body
1555 n-variables)
1557 (defun expression-priority (form)
1558 (let ((step (second form)))
1559 (if (and (null (cddr form))
1560 (listp step)
1561 (member (car step) '(:child :attribute))
1562 (null (cddr step)))
1563 (let ((name (second step)))
1564 (cond
1565 ((or (stringp name)
1566 (and (consp name)
1567 (or (eq (car name) :qname)
1568 (eq (car name) :processing-instruction))))
1569 0.0)
1570 ((and (consp name)
1571 (or (eq (car name) :namespace)
1572 (eq (car name) '*)))
1573 -0.25)
1575 -0.5)))
1576 0.5)))
1578 (defun parse-xpath (str)
1579 (with-resignalled-errors ()
1580 (xpath:parse-xpath str)))
1582 (defun parse-key-pattern (str)
1583 (let ((parsed
1584 (mapcar #'(lambda (item)
1585 `(:path (:root :node)
1586 (:descendant-or-self *)
1587 ,@(cdr item)))
1588 (parse-pattern str))))
1589 (if (null (rest parsed))
1590 (first parsed)
1591 `(:union ,@parsed))))
1593 (defun parse-pattern (str)
1594 (with-resignalled-errors ()
1595 (cdr (xpath::parse-pattern-expression str))))
1597 (defun compile-value-thunk (value env)
1598 (if (and (listp value) (eq (car value) 'progn))
1599 (let ((inner-thunk (compile-instruction value env)))
1600 (lambda (ctx)
1601 (apply-to-result-tree-fragment ctx inner-thunk)))
1602 (compile-xpath value env)))
1604 (defun compile-var-binding (name value env)
1605 (multiple-value-bind (local-name uri)
1606 (decode-qname name env nil)
1607 (let ((thunk (xslt-trace-thunk
1608 (compile-value-thunk value env)
1609 "local variable ~s = ~s" name :result)))
1610 (list (cons local-name uri)
1611 (push-variable local-name
1613 *lexical-variable-declarations*)
1614 thunk))))
1616 (defun compile-var-bindings (forms env)
1617 (loop
1618 for (name value) in forms
1619 collect (compile-var-binding name value env)))
1621 (defun compile-template (<template> env position)
1622 (stp:with-attributes (match name priority mode) <template>
1623 (unless (or name match)
1624 (xslt-error "missing match in template"))
1625 (multiple-value-bind (params body-pos)
1626 (loop
1627 for i from 0
1628 for child in (stp:list-children <template>)
1629 while (namep child "param")
1630 collect (parse-param child) into params
1631 finally (return (values params i)))
1632 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1633 (param-bindings (compile-var-bindings params env))
1634 (body (parse-body <template> body-pos (mapcar #'car params)))
1635 (body-thunk (compile-instruction `(progn ,@body) env))
1636 (outer-body-thunk
1637 (xslt-trace-thunk
1638 #'(lambda (ctx)
1639 (unwind-protect
1640 (progn
1641 ;; set params that weren't initialized by apply-templates
1642 (loop for (name index param-thunk) in param-bindings
1643 when (eq (lexical-variable-value index nil) 'unbound)
1644 do (setf (lexical-variable-value index)
1645 (funcall param-thunk ctx)))
1646 (funcall body-thunk ctx))))
1647 "template: match = ~s name = ~s" match name))
1648 (n-variables (length *lexical-variable-declarations*)))
1649 (append
1650 (when name
1651 (multiple-value-bind (local-name uri)
1652 (decode-qname name env nil)
1653 (list
1654 (make-template :name (cons local-name uri)
1655 :import-priority *import-priority*
1656 :apply-imports-limit *apply-imports-limit*
1657 :params param-bindings
1658 :body outer-body-thunk
1659 :n-variables n-variables))))
1660 (when match
1661 (mapcar (lambda (expression)
1662 (let* ((compiled-pattern
1663 (xslt-trace-thunk
1664 (car (xpath:compute-patterns
1665 `(:patterns ,expression)
1667 :dummy
1668 env))
1669 "match-thunk for template (match ~s): ~s --> ~s"
1670 match expression :result))
1671 (p (if priority
1672 (xpath::parse-xnum priority)
1673 (expression-priority expression)))
1675 (progn
1676 (unless (and (numberp p)
1677 (not (xpath::inf-p p))
1678 (not (xpath::nan-p p)))
1679 (xslt-error "failed to parse priority"))
1680 (float p 1.0d0)))
1681 (template
1682 (make-template :match-expression expression
1683 :compiled-pattern compiled-pattern
1684 :import-priority *import-priority*
1685 :apply-imports-limit *apply-imports-limit*
1686 :priority p
1687 :position position
1688 :mode-qname mode
1689 :params param-bindings
1690 :body outer-body-thunk
1691 :n-variables n-variables)))
1692 (setf (xpath:pattern-value compiled-pattern)
1693 template)
1694 template))
1695 (cdr (xpath:parse-pattern-expression match)))))))))
1696 #+(or)
1697 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")