Check included attribute sets at compile time like saxon
[xuriella.git] / xslt.lisp
blobca4d40569d2e76d47b80dc208e81e6cae48b7c15
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 (let ((version (stp:attribute-value (stp:parent elt) "version")))
534 (cond
535 ((null version)
536 (xslt-error "stylesheet lacks version"))
537 ((equal version "1.0")
538 (if (typep elt 'stp:element)
539 (when (or (equal (stp:namespace-uri elt) "")
540 (and (equal (stp:namespace-uri elt) *xsl*)
541 (not (find (stp:local-name elt)
542 '("key" "template" "output"
543 "strip-space" "preserve-space"
544 "attribute-set" "namespace-alias"
545 "decimal-format" "variable" "param"
546 "import" "include"
547 ;; for include handling:
548 "stylesheet" "transform")
549 :test #'equal))))
550 (xslt-error "unknown top-level element ~A" (stp:local-name elt)))
551 (xslt-error "text at top-level"))))))
552 (macrolet ((with-specials ((&optional) &body body)
553 `(let ((*instruction-base-uri* instruction-base-uri)
554 (*namespaces* namespaces)
555 (*apply-imports-limit* apply-imports-limit))
556 ,@body)))
557 (with-specials ()
558 (do-toplevel (import "import" <transform>)
559 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
560 (stp:base-uri import))))
561 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
562 continuations))))
563 (let ((import-priority
564 (incf *import-priority*))
565 (var-cont (prepare-global-variables stylesheet <transform>)))
566 ;; delay the rest of compilation until we've seen all global
567 ;; variables:
568 (lambda ()
569 (mapc #'funcall (nreverse continuations))
570 (with-specials ()
571 (let ((*import-priority* import-priority))
572 (funcall var-cont)
573 (parse-keys! stylesheet <transform> env)
574 (parse-templates! stylesheet <transform> env)
575 (parse-output! stylesheet <transform>)
576 (parse-strip/preserve-space! stylesheet <transform> env)
577 (parse-attribute-sets! stylesheet <transform> env)
578 (parse-namespace-aliases! stylesheet <transform> env)
579 (parse-decimal-formats! stylesheet <transform> env))))))))
581 (defvar *xsl-import-stack* nil)
583 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
584 (let* ((uri (if uri-resolver
585 (funcall uri-resolver (puri:render-uri uri nil))
586 uri))
587 (str (puri:render-uri uri nil))
588 (pathname
589 (handler-case
590 (uri-to-pathname uri)
591 (cxml:xml-parse-error (c)
592 (xslt-error "cannot find imported stylesheet ~A: ~A"
593 uri c)))))
594 (with-open-file
595 (stream pathname
596 :element-type '(unsigned-byte 8)
597 :if-does-not-exist nil)
598 (unless stream
599 (xslt-error "cannot find imported stylesheet ~A at ~A"
600 uri pathname))
601 (when (find str *xsl-import-stack* :test #'equal)
602 (xslt-error "recursive inclusion of ~A" uri))
603 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
604 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
606 (defvar *included-attribute-sets*)
608 (defun parse-stylesheet (designator &key uri-resolver)
609 (with-resignalled-errors ()
610 (xpath:with-namespaces ((nil #.*xsl*))
611 (let* ((*import-priority* 0)
612 (xpath:*allow-variables-in-patterns* nil)
613 (puri:*strict-parse* nil)
614 (stylesheet (make-stylesheet))
615 (env (make-instance 'lexical-xslt-environment))
616 (*excluded-namespaces* *excluded-namespaces*)
617 (*global-variable-declarations* (make-empty-declaration-array))
618 (*included-attribute-sets* nil))
619 (ensure-mode stylesheet nil)
620 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
621 ;; reverse attribute sets:
622 (let ((table (stylesheet-attribute-sets stylesheet)))
623 (maphash (lambda (k v)
624 (setf (gethash k table) (nreverse v)))
625 table))
626 ;; for Errors_err011
627 (dolist (sets *included-attribute-sets*)
628 (loop for (local-name uri nil) in sets do
629 (find-attribute-set local-name uri stylesheet)))
630 ;; add default df
631 (unless (find-decimal-format "" "" stylesheet nil)
632 (setf (find-decimal-format "" "" stylesheet)
633 (make-decimal-format)))
634 ;; compile a template matcher for each mode:
635 (loop
636 for mode being each hash-value in (stylesheet-modes stylesheet)
638 (setf (mode-match-thunk mode)
639 (xpath:make-pattern-matcher
640 (mapcar #'template-compiled-pattern
641 (mode-templates mode)))))
642 ;; and for the strip tests
643 (setf (stylesheet-strip-thunk stylesheet)
644 (let ((patterns (stylesheet-strip-tests stylesheet)))
645 (and patterns
646 (xpath:make-pattern-matcher
647 (mapcar #'strip-test-compiled-pattern patterns)))))
648 stylesheet))))
650 (defun parse-attribute-sets! (stylesheet <transform> env)
651 (do-toplevel (elt "attribute-set" <transform>)
652 (with-import-magic (elt env)
653 (push (let* ((sets
654 (mapcar (lambda (qname)
655 (multiple-value-list (decode-qname qname env nil)))
656 (words
657 (stp:attribute-value elt "use-attribute-sets"))))
658 (instructions
659 (stp:map-children
660 'list
661 (lambda (child)
662 (unless
663 (and (typep child 'stp:element)
664 (or (and (equal (stp:namespace-uri child) *xsl*)
665 (equal (stp:local-name child)
666 "attribute"))
667 (find (stp:namespace-uri child)
668 *extension-namespaces*
669 :test 'equal)))
670 (xslt-error "non-attribute found in attribute set"))
671 (parse-instruction child))
672 elt))
673 (*lexical-variable-declarations*
674 (make-empty-declaration-array))
675 (thunk
676 (compile-instruction `(progn ,@instructions) env))
677 (n-variables (length *lexical-variable-declarations*)))
678 (push sets *included-attribute-sets*)
679 (lambda (ctx)
680 (with-stack-limit ()
681 (loop for (local-name uri nil) in sets do
682 (dolist (thunk (find-attribute-set local-name uri))
683 (funcall thunk ctx)))
684 (let ((*lexical-variable-values*
685 (make-variable-value-array n-variables)))
686 (funcall thunk ctx)))))
687 (gethash (multiple-value-bind (local-name uri)
688 (decode-qname (or (stp:attribute-value elt "name")
689 (xslt-error "missing name"))
691 nil)
692 (cons local-name uri))
693 (stylesheet-attribute-sets stylesheet))))))
695 (defun parse-namespace-aliases! (stylesheet <transform> env)
696 (do-toplevel (elt "namespace-alias" <transform>)
697 (stp:with-attributes (stylesheet-prefix result-prefix) elt
698 (setf (gethash
699 (if (equal stylesheet-prefix "#default")
701 (xpath-sys:environment-find-namespace env stylesheet-prefix))
702 (stylesheet-namespace-aliases stylesheet))
703 (xpath-sys:environment-find-namespace
705 (if (equal result-prefix "#default")
707 result-prefix))))))
709 (defun parse-decimal-formats! (stylesheet <transform> env)
710 (do-toplevel (elt "decimal-format" <transform>)
711 (stp:with-attributes (name
712 ;; strings
713 infinity
714 (nan "NaN")
715 ;; characters:
716 decimal-separator
717 grouping-separator
718 zero-digit
719 percent
720 per-mille
721 digit
722 pattern-separator
723 minus-sign)
725 (multiple-value-bind (local-name uri)
726 (if name
727 (decode-qname name env nil)
728 (values "" ""))
729 (let ((current (find-decimal-format local-name uri stylesheet nil))
730 (new
731 (let ((seen '()))
732 (flet ((chr (key x)
733 (when x
734 (unless (eql (length x) 1)
735 (xslt-error "not a single character: ~A" x))
736 (let ((chr (elt x 0)))
737 (when (find chr seen)
738 (xslt-error
739 "conflicting decimal format characters: ~A"
740 chr))
741 (push chr seen)
742 (list key chr))))
743 (str (key x)
744 (when x
745 (list key x))))
746 (apply #'make-decimal-format
747 (append (str :infinity infinity)
748 (str :nan nan)
749 (chr :decimal-separator decimal-separator)
750 (chr :grouping-separator grouping-separator)
751 (chr :zero-digit zero-digit)
752 (chr :percent percent)
753 (chr :per-mille per-mille)
754 (chr :digit digit)
755 (chr :pattern-separator pattern-separator)
756 (chr :minus-sign minus-sign)))))))
757 (if current
758 (unless (decimal-format= current new)
759 (xslt-error "decimal format mismatch for ~S" local-name))
760 (setf (find-decimal-format local-name uri stylesheet) new)))))))
762 (defun parse-exclude-result-prefixes! (node env)
763 (stp:with-attributes (exclude-result-prefixes)
764 node
765 (dolist (prefix (words (or exclude-result-prefixes "")))
766 (if (equal prefix "#default")
767 (setf prefix nil)
768 (unless (cxml-stp-impl::nc-name-p prefix)
769 (xslt-error "invalid prefix: ~A" prefix)))
770 (push (or (xpath-sys:environment-find-namespace env prefix)
771 (xslt-error "namespace not found: ~A" prefix))
772 *excluded-namespaces*))))
774 (defun parse-extension-element-prefixes! (node env)
775 (stp:with-attributes (extension-element-prefixes)
776 node
777 (dolist (prefix (words (or extension-element-prefixes "")))
778 (if (equal prefix "#default")
779 (setf prefix nil)
780 (unless (cxml-stp-impl::nc-name-p prefix)
781 (xslt-error "invalid prefix: ~A" prefix)))
782 (let ((uri
783 (or (xpath-sys:environment-find-namespace env prefix)
784 (xslt-error "namespace not found: ~A" prefix))))
785 (unless (equal uri *xsl*)
786 (push uri *extension-namespaces*)
787 (push uri *excluded-namespaces*))))))
789 (defun parse-nametest-tokens (str)
790 (labels ((check (boolean)
791 (unless boolean
792 (xslt-error "invalid nametest token")))
793 (check-null (boolean)
794 (check (not boolean))))
795 (cons
796 :patterns
797 (mapcar (lambda (name-test)
798 (destructuring-bind (&optional path &rest junk)
799 (cdr (xpath:parse-pattern-expression name-test))
800 (check-null junk)
801 (check (eq (car path) :path))
802 (destructuring-bind (&optional child &rest junk) (cdr path)
803 (check-null junk)
804 (check (eq (car child) :child))
805 (destructuring-bind (nodetest &rest junk) (cdr child)
806 (check-null junk)
807 (check (or (stringp nodetest)
808 (eq nodetest '*)
809 (and (consp nodetest)
810 (or (eq (car nodetest) :namespace)
811 (eq (car nodetest) :qname)))))))
812 path))
813 (words str)))))
815 (defstruct strip-test
816 compiled-pattern
817 priority
818 position
819 value)
821 (defun parse-strip/preserve-space! (stylesheet <transform> env)
822 (let ((i 0))
823 (do-toplevel (elt "strip-space|preserve-space" <transform>)
824 (let ((*namespaces* (acons-namespaces elt))
825 (value
826 (if (equal (stp:local-name elt) "strip-space")
827 :strip
828 :preserve)))
829 (dolist (expression
830 (cdr (parse-nametest-tokens
831 (stp:attribute-value elt "elements"))))
832 (let* ((compiled-pattern
833 (car (xpath:compute-patterns
834 `(:patterns ,expression)
835 *import-priority*
836 "will set below"
837 env)))
838 (strip-test
839 (make-strip-test :compiled-pattern compiled-pattern
840 :priority (expression-priority expression)
841 :position i
842 :value value)))
843 (setf (xpath:pattern-value compiled-pattern) strip-test)
844 (push strip-test (stylesheet-strip-tests stylesheet)))))
845 (incf i))))
847 (defstruct (output-specification
848 (:conc-name "OUTPUT-"))
849 method
850 indent
851 omit-xml-declaration
852 encoding
853 doctype-system
854 doctype-public)
856 (defun parse-output! (stylesheet <transform>)
857 (dolist (<output> (list-toplevel "output" <transform>))
858 (let ((spec (stylesheet-output-specification stylesheet)))
859 (stp:with-attributes ( ;; version
860 method
861 indent
862 encoding
863 ;;; media-type
864 doctype-system
865 doctype-public
866 omit-xml-declaration
867 ;;; standalone
868 ;;; cdata-section-elements
870 <output>
871 (when method
872 (setf (output-method spec) method))
873 (when indent
874 (setf (output-indent spec) indent))
875 (when encoding
876 (setf (output-encoding spec) encoding))
877 (when doctype-system
878 (setf (output-doctype-system spec) doctype-system))
879 (when doctype-public
880 (setf (output-doctype-public spec) doctype-public))
881 (when omit-xml-declaration
882 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
883 ;;; (when cdata-section-elements
884 ;;; (setf (output-cdata-section-elements spec)
885 ;;; (concatenate 'string
886 ;;; (output-cdata-section-elements spec)
887 ;;; " "
888 ;;; cdata-section-elements)))
889 ))))
891 (defun make-empty-declaration-array ()
892 (make-array 1 :fill-pointer 0 :adjustable t))
894 (defun make-variable-value-array (n-lexical-variables)
895 (make-array n-lexical-variables :initial-element 'unbound))
897 (defun compile-global-variable (<variable> env) ;; also for <param>
898 (stp:with-attributes (name select) <variable>
899 (when (and select (stp:list-children <variable>))
900 (xslt-error "variable with select and body"))
901 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
902 (inner (cond
903 (select
904 (compile-xpath select env))
905 ((stp:list-children <variable>)
906 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
907 (inner-thunk (compile-instruction inner-sexpr env)))
908 (lambda (ctx)
909 (apply-to-result-tree-fragment ctx inner-thunk))))
911 (lambda (ctx)
912 (declare (ignore ctx))
913 ""))))
914 (n-lexical-variables (length *lexical-variable-declarations*)))
915 (xslt-trace-thunk
916 (lambda (ctx)
917 (let* ((*lexical-variable-values*
918 (make-variable-value-array n-lexical-variables)))
919 (funcall inner ctx)))
920 "global ~s (~s) = ~s" name select :result))))
922 (defstruct (variable-chain
923 (:constructor make-variable-chain)
924 (:conc-name "VARIABLE-CHAIN-"))
925 definitions
926 index
927 local-name
928 thunk
929 uri)
931 (defstruct (import-variable
932 (:constructor make-variable)
933 (:conc-name "VARIABLE-"))
934 value-thunk
935 value-thunk-setter
936 param-p)
938 (defun parse-global-variable! (stylesheet <variable> global-env)
939 (let* ((*namespaces* (acons-namespaces <variable>))
940 (instruction-base-uri (stp:base-uri <variable>))
941 (*instruction-base-uri* instruction-base-uri)
942 (*excluded-namespaces* (list *xsl*))
943 (*extension-namespaces* '())
944 (qname (stp:attribute-value <variable> "name")))
945 (with-import-magic (<variable> global-env)
946 (unless qname
947 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
948 (multiple-value-bind (local-name uri)
949 (decode-qname qname global-env nil)
950 ;; For the normal compilation environment of templates, install it
951 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
952 (let ((index (intern-global-variable local-name uri)))
953 ;; For the evaluation of a global variable itself, build a thunk
954 ;; that lazily resolves other variables, stored into
955 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
956 (let* ((value-thunk :unknown)
957 (sgv (stylesheet-global-variables stylesheet))
958 (chain
959 (if (< index (length sgv))
960 (elt sgv index)
961 (make-variable-chain
962 :index index
963 :local-name local-name
964 :uri uri)))
965 (next (car (variable-chain-definitions chain)))
966 (global-variable-thunk
967 (lambda (ctx)
968 (let ((v (global-variable-value index nil)))
969 (cond
970 ((eq v 'seen)
971 (unless next
972 (xslt-error "no next definition for: ~A"
973 local-name))
974 (funcall (variable-value-thunk next) ctx))
975 ((eq v 'unbound)
976 (setf (global-variable-value index) 'seen)
977 (setf (global-variable-value index)
978 (funcall value-thunk ctx)))
980 v)))))
981 (excluded-namespaces *excluded-namespaces*)
982 (extension-namespaces *extension-namespaces*)
983 (variable
984 (make-variable :param-p (namep <variable> "param")))
985 (value-thunk-setter
986 (lambda ()
987 (let* ((*instruction-base-uri* instruction-base-uri)
988 (*excluded-namespaces* excluded-namespaces)
989 (*extension-namespaces* extension-namespaces)
991 (compile-global-variable <variable> global-env)))
992 (setf value-thunk fn)
993 (setf (variable-value-thunk variable) fn)))))
994 (setf (variable-value-thunk-setter variable)
995 value-thunk-setter)
996 (setf (gethash (cons local-name uri)
997 (initial-global-variable-thunks global-env))
998 global-variable-thunk)
999 (setf (variable-chain-thunk chain) global-variable-thunk)
1000 (push variable (variable-chain-definitions chain))
1001 chain))))))
1003 (defun parse-keys! (stylesheet <transform> env)
1004 (xpath:with-namespaces ((nil #.*xsl*))
1005 (do-toplevel (<key> "key" <transform>)
1006 (let ((*instruction-base-uri* (stp:base-uri <key>)))
1007 (stp:with-attributes (name match use) <key>
1008 (unless name (xslt-error "key name attribute not specified"))
1009 (unless match (xslt-error "key match attribute not specified"))
1010 (unless use (xslt-error "key use attribute not specified"))
1011 (multiple-value-bind (local-name uri)
1012 (decode-qname name env nil)
1013 (add-key stylesheet
1014 (cons local-name uri)
1015 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
1016 (compile-xpath use env))))))))
1018 (defun prepare-global-variables (stylesheet <transform>)
1019 (xpath:with-namespaces ((nil #.*xsl*))
1020 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet))
1021 (global-env (make-instance 'global-variable-environment
1022 :initial-global-variable-thunks igvt))
1023 (chains '()))
1024 (do-toplevel (<variable> "variable|param" <transform>)
1025 (let ((chain
1026 (parse-global-variable! stylesheet <variable> global-env)))
1027 (xslt-trace "parsing global variable ~s (uri ~s)"
1028 (variable-chain-local-name chain)
1029 (variable-chain-uri chain))
1030 (when (find chain
1031 chains
1032 :test (lambda (a b)
1033 (and (equal (variable-chain-local-name a)
1034 (variable-chain-local-name b))
1035 (equal (variable-chain-uri a)
1036 (variable-chain-uri b)))))
1037 (xslt-error "duplicate definition for global variable ~A"
1038 (variable-chain-local-name chain)))
1039 (push chain chains)))
1040 (setf chains (nreverse chains))
1041 (let ((table (stylesheet-global-variables stylesheet))
1042 (newlen (length *global-variable-declarations*)))
1043 (adjust-array table newlen :fill-pointer newlen)
1044 (dolist (chain chains)
1045 (setf (elt table (variable-chain-index chain)) chain)))
1046 (lambda ()
1047 ;; now that the global environment knows about all variables, run the
1048 ;; thunk setters to perform their compilation
1049 (mapc (lambda (chain)
1050 (dolist (var (variable-chain-definitions chain))
1051 (funcall (variable-value-thunk-setter var))))
1052 chains)))))
1054 (defun parse-templates! (stylesheet <transform> env)
1055 (let ((i 0))
1056 (do-toplevel (<template> "template" <transform>)
1057 (let ((*namespaces* (acons-namespaces <template>))
1058 (*instruction-base-uri* (stp:base-uri <template>)))
1059 (with-import-magic (<template> env)
1060 (dolist (template (compile-template <template> env i))
1061 (let ((name (template-name template)))
1062 (if name
1063 (let* ((table (stylesheet-named-templates stylesheet))
1064 (head (car (gethash name table))))
1065 (when (and head (eql (template-import-priority head)
1066 (template-import-priority template)))
1067 ;; fixme: is this supposed to be a run-time error?
1068 (xslt-error "conflicting templates for ~A" name))
1069 (push template (gethash name table)))
1070 (let ((mode (ensure-mode/qname stylesheet
1071 (template-mode-qname template)
1072 env)))
1073 (setf (template-mode template) mode)
1074 (push template (mode-templates mode))))))))
1075 (incf i))))
1078 ;;;; APPLY-STYLESHEET
1080 (defvar *stylesheet*)
1082 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
1084 (defun unalias-uri (uri)
1085 (let ((result
1086 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
1087 uri)))
1088 (check-type result string)
1089 result))
1091 (defstruct (parameter
1092 (:constructor make-parameter (value local-name &optional uri)))
1093 (uri "")
1094 local-name
1095 value)
1097 (defun find-parameter-value (local-name uri parameters)
1098 (dolist (p parameters)
1099 (when (and (equal (parameter-local-name p) local-name)
1100 (equal (parameter-uri p) uri))
1101 (return (parameter-value p)))))
1103 (defvar *uri-resolver*)
1105 (defun parse-allowing-microsoft-bom (pathname handler)
1106 (with-open-file (s pathname :element-type '(unsigned-byte 8))
1107 (unless (and (eql (read-byte s nil) #xef)
1108 (eql (read-byte s nil) #xbb)
1109 (eql (read-byte s nil) #xbf))
1110 (file-position s 0))
1111 (cxml:parse s handler)))
1113 (defvar *documents*)
1115 (defun %document (uri-string base-uri)
1116 (let* ((absolute-uri
1117 (puri:merge-uris uri-string (or base-uri "")))
1118 (resolved-uri
1119 (if *uri-resolver*
1120 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
1121 absolute-uri))
1122 (pathname
1123 (handler-case
1124 (uri-to-pathname resolved-uri)
1125 (cxml:xml-parse-error (c)
1126 (xslt-error "cannot find referenced document ~A: ~A"
1127 resolved-uri c))))
1128 (xpath-root-node
1129 (or (gethash pathname *documents*)
1130 (setf (gethash pathname *documents*)
1131 (make-whitespace-stripper
1132 (handler-case
1133 (parse-allowing-microsoft-bom pathname
1134 (stp:make-builder))
1135 ((or file-error cxml:xml-parse-error) (c)
1136 (xslt-error "cannot parse referenced document ~A: ~A"
1137 pathname c)))
1138 (stylesheet-strip-thunk *stylesheet*))))))
1139 (when (puri:uri-fragment absolute-uri)
1140 (xslt-error "use of fragment identifiers in document() not supported"))
1141 xpath-root-node))
1143 (xpath-sys:define-extension xslt *xsl*)
1145 (defun document-base-uri (node)
1146 (xpath-protocol:base-uri
1147 (cond
1148 ((xpath-protocol:node-type-p node :document)
1149 (xpath::find-in-pipe-if
1150 (lambda (x)
1151 (xpath-protocol:node-type-p x :element))
1152 (xpath-protocol:child-pipe node)))
1153 ((xpath-protocol:node-type-p node :element)
1154 node)
1156 (xpath-protocol:parent-node node)))))
1158 (xpath-sys:define-xpath-function/lazy
1159 xslt :document
1160 (object &optional node-set)
1161 (let ((instruction-base-uri *instruction-base-uri*))
1162 (lambda (ctx)
1163 (let* ((object (funcall object ctx))
1164 (node-set (and node-set (funcall node-set ctx)))
1165 (base-uri
1166 (if node-set
1167 (document-base-uri (xpath::textually-first-node node-set))
1168 instruction-base-uri)))
1169 (xpath-sys:make-node-set
1170 (if (xpath:node-set-p object)
1171 (xpath:map-node-set->list
1172 (lambda (node)
1173 (%document (xpath:string-value node)
1174 (if node-set
1175 base-uri
1176 (document-base-uri node))))
1177 object)
1178 (list (%document (xpath:string-value object) base-uri))))))))
1180 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1181 (let ((namespaces *namespaces*))
1182 (lambda (ctx)
1183 (let* ((qname (xpath:string-value (funcall name ctx)))
1184 (object (funcall object ctx))
1185 (expanded-name
1186 (multiple-value-bind (local-name uri)
1187 (decode-qname/runtime qname namespaces nil)
1188 (cons local-name uri)))
1189 (key (find-key expanded-name *stylesheet*)))
1190 (labels ((get-by-key (value)
1191 (let ((value (xpath:string-value value)))
1192 (xpath::filter-pipe
1193 #'(lambda (node)
1194 (let ((uses
1195 (xpath:evaluate-compiled (key-use key) node)))
1196 (if (xpath:node-set-p uses)
1197 (xpath::find-in-pipe
1198 value
1199 (xpath-sys:pipe-of uses)
1200 :key #'xpath:string-value
1201 :test #'equal)
1202 (equal value (xpath:string-value uses)))))
1203 (xpath-sys:pipe-of
1204 (xpath:node-set-value
1205 (xpath:evaluate-compiled (key-match key) ctx)))))))
1206 (xpath-sys:make-node-set
1207 (xpath::sort-pipe
1208 (if (xpath:node-set-p object)
1209 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1210 (get-by-key object)))))))))
1212 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1214 (xpath-sys:define-xpath-function/lazy xslt :current ()
1215 #'(lambda (ctx)
1216 (xpath-sys:make-node-set
1217 (xpath-sys:make-pipe
1218 (xpath:context-starting-node ctx)
1219 nil))))
1221 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1222 #'(lambda (ctx)
1223 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1224 (funcall name ctx))
1225 "")))
1227 (defun %get-node-id (node)
1228 (when (xpath:node-set-p node)
1229 (setf node (xpath::textually-first-node node)))
1230 (when node
1231 (let ((id (xpath-sys:get-node-id node))
1232 (highest-base-uri
1233 (loop
1234 for parent = node then next
1235 for next = (xpath-protocol:parent-node parent)
1236 for this-base-uri = (xpath-protocol:base-uri parent)
1237 for highest-base-uri = (if (plusp (length this-base-uri))
1238 this-base-uri
1239 highest-base-uri)
1240 while next
1241 finally (return highest-base-uri))))
1242 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1243 ;; checked only if everything else matches.
1245 ;; This might be pointless premature optimization, but I like the idea :-)
1246 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1248 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1249 (if node-set-thunk
1250 #'(lambda (ctx)
1251 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1252 #'(lambda (ctx)
1253 (%get-node-id (xpath:context-node ctx)))))
1255 (declaim (special *available-instructions*))
1257 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1258 (let ((namespaces *namespaces*))
1259 #'(lambda (ctx)
1260 (let ((qname (funcall qname ctx)))
1261 (multiple-value-bind (local-name uri)
1262 (decode-qname/runtime qname namespaces nil)
1263 (and (equal uri *xsl*)
1264 (gethash local-name *available-instructions*)
1265 t))))))
1267 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1268 (let ((namespaces *namespaces*))
1269 #'(lambda (ctx)
1270 (let ((qname (funcall qname ctx)))
1271 (multiple-value-bind (local-name uri)
1272 (decode-qname/runtime qname namespaces nil)
1273 (and (zerop (length uri))
1274 (or (xpath-sys:find-xpath-function local-name *xsl*)
1275 (xpath-sys:find-xpath-function local-name uri))
1276 t))))))
1278 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1279 (let ((namespaces *namespaces*))
1280 (lambda (ctx)
1281 (let ((qname (funcall qname ctx)))
1282 (multiple-value-bind (local-name uri)
1283 (decode-qname/runtime qname namespaces nil)
1284 (if (equal uri *xsl*)
1285 (cond
1286 ((equal local-name "version")
1287 "1")
1288 ((equal local-name "vendor")
1289 "Xuriella")
1290 ((equal local-name "vendor-uri")
1291 "http://repo.or.cz/w/xuriella.git")
1293 ""))
1294 ""))))))
1296 (defun apply-stylesheet
1297 (stylesheet source-designator
1298 &key output parameters uri-resolver navigator)
1299 (when (typep stylesheet 'xml-designator)
1300 (setf stylesheet
1301 (handler-bind
1302 ((cxml:xml-parse-error
1303 (lambda (c)
1304 (xslt-error "cannot parse stylesheet: ~A" c))))
1305 (parse-stylesheet stylesheet))))
1306 (with-resignalled-errors ()
1307 (invoke-with-output-sink
1308 (lambda ()
1309 (let* ((*documents* (make-hash-table :test 'equal))
1310 (xpath:*navigator* (or navigator :default-navigator))
1311 (puri:*strict-parse* nil)
1312 (*stylesheet* stylesheet)
1313 (*empty-mode* (make-mode))
1314 (*default-mode* (find-mode stylesheet nil))
1315 (global-variable-chains
1316 (stylesheet-global-variables stylesheet))
1317 (*global-variable-values*
1318 (make-variable-value-array (length global-variable-chains)))
1319 (*uri-resolver* uri-resolver)
1320 (source-document
1321 (if (typep source-designator 'xml-designator)
1322 (cxml:parse source-designator (stp:make-builder))
1323 source-designator))
1324 (xpath-root-node
1325 (make-whitespace-stripper
1326 source-document
1327 (stylesheet-strip-thunk stylesheet)))
1328 (ctx (xpath:make-context xpath-root-node)))
1329 (when (pathnamep source-designator)
1330 (setf (gethash source-designator *documents*) xpath-root-node))
1331 (map nil
1332 (lambda (chain)
1333 (let ((head (car (variable-chain-definitions chain))))
1334 (when (variable-param-p head)
1335 (let ((value
1336 (find-parameter-value
1337 (variable-chain-local-name chain)
1338 (variable-chain-uri chain)
1339 parameters)))
1340 (when value
1341 (setf (global-variable-value
1342 (variable-chain-index chain))
1343 value))))))
1344 global-variable-chains)
1345 (map nil
1346 (lambda (chain)
1347 (funcall (variable-chain-thunk chain) ctx))
1348 global-variable-chains)
1349 ;; zzz we wouldn't have to mask float traps here if we used the
1350 ;; XPath API properly. Unfortunately I've been using FUNCALL
1351 ;; everywhere instead of EVALUATE, so let's paper over that
1352 ;; at a central place to be sure:
1353 (xpath::with-float-traps-masked ()
1354 (apply-templates ctx :mode *default-mode*))))
1355 (stylesheet-output-specification stylesheet)
1356 output)))
1358 (defun find-attribute-set (local-name uri &optional (stylesheet *stylesheet*))
1359 (or (gethash (cons local-name uri) (stylesheet-attribute-sets stylesheet))
1360 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1362 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1363 (when sort-predicate
1364 (setf list
1365 (mapcar #'xpath:context-node
1366 (stable-sort (contextify-node-list list)
1367 sort-predicate))))
1368 (let* ((n (length list))
1369 (s/d (lambda () n)))
1370 (loop
1371 for i from 1
1372 for child in list
1374 (apply-templates (xpath:make-context child s/d i)
1375 :param-bindings param-bindings
1376 :mode mode))))
1378 (defvar *stack-limit* 200)
1380 (defun invoke-with-stack-limit (fn)
1381 (let ((*stack-limit* (1- *stack-limit*)))
1382 (unless (plusp *stack-limit*)
1383 (xslt-error "*stack-limit* reached; stack overflow"))
1384 (funcall fn)))
1386 (defun invoke-template (ctx template param-bindings)
1387 (let ((*lexical-variable-values*
1388 (make-variable-value-array (template-n-variables template))))
1389 (with-stack-limit ()
1390 (loop
1391 for (name-cons value) in param-bindings
1392 for (nil index nil) = (find name-cons
1393 (template-params template)
1394 :test #'equal
1395 :key #'car)
1397 (when index
1398 (setf (lexical-variable-value index) value)))
1399 (funcall (template-body template) ctx))))
1401 (defun apply-default-templates (ctx mode)
1402 (let ((node (xpath:context-node ctx)))
1403 (cond
1404 ((or (xpath-protocol:node-type-p node :processing-instruction)
1405 (xpath-protocol:node-type-p node :comment)))
1406 ((or (xpath-protocol:node-type-p node :text)
1407 (xpath-protocol:node-type-p node :attribute))
1408 (write-text (xpath-protocol:node-text node)))
1410 (apply-templates/list
1411 (xpath::force
1412 (xpath-protocol:child-pipe node))
1413 :mode mode)))))
1415 (defvar *apply-imports*)
1417 (defun apply-applicable-templates (ctx templates param-bindings finally)
1418 (labels ((apply-imports (&optional actual-param-bindings)
1419 (if templates
1420 (let* ((this (pop templates))
1421 (low (template-apply-imports-limit this))
1422 (high (template-import-priority this)))
1423 (setf templates
1424 (remove-if-not
1425 (lambda (x)
1426 (<= low (template-import-priority x) high))
1427 templates))
1428 (invoke-template ctx this actual-param-bindings))
1429 (funcall finally))))
1430 (let ((*apply-imports* #'apply-imports))
1431 (apply-imports param-bindings))))
1433 (defun apply-templates (ctx &key param-bindings mode)
1434 (apply-applicable-templates ctx
1435 (find-templates ctx (or mode *default-mode*))
1436 param-bindings
1437 (lambda ()
1438 (apply-default-templates ctx mode))))
1440 (defun call-template (ctx name &optional param-bindings)
1441 (apply-applicable-templates ctx
1442 (find-named-templates name)
1443 param-bindings
1444 (lambda ()
1445 (error "cannot find named template: ~s"
1446 name))))
1448 (defun find-templates (ctx mode)
1449 (let* ((matching-candidates
1450 (xpath:matching-values (mode-match-thunk mode)
1451 (xpath:context-node ctx)))
1452 (npriorities
1453 (if matching-candidates
1454 (1+ (reduce #'max
1455 matching-candidates
1456 :key #'template-import-priority))
1458 (priority-groups (make-array npriorities :initial-element nil)))
1459 (dolist (template matching-candidates)
1460 (push template
1461 (elt priority-groups (template-import-priority template))))
1462 (loop
1463 for i from (1- npriorities) downto 0
1464 for group = (elt priority-groups i)
1465 for template = (maximize #'template< group)
1466 when template
1467 collect template)))
1469 (defun find-named-templates (name)
1470 (gethash name (stylesheet-named-templates *stylesheet*)))
1472 (defun template< (a b) ;assuming same import priority
1473 (let ((p (template-priority a))
1474 (q (template-priority b)))
1475 (cond
1476 ((< p q) t)
1477 ((> p q) nil)
1479 (xslt-cerror "conflicting templates:~_~A,~_~A"
1480 (template-match-expression a)
1481 (template-match-expression b))
1482 (< (template-position a) (template-position b))))))
1484 (defun maximize (< things)
1485 (when things
1486 (let ((max (car things)))
1487 (dolist (other (cdr things))
1488 (when (funcall < max other)
1489 (setf max other)))
1490 max)))
1492 (defun invoke-with-output-sink (fn output-spec output)
1493 (etypecase output
1494 (pathname
1495 (with-open-file (s output
1496 :direction :output
1497 :element-type '(unsigned-byte 8)
1498 :if-exists :rename-and-delete)
1499 (invoke-with-output-sink fn output-spec s)))
1500 ((or stream null)
1501 (invoke-with-output-sink fn
1502 output-spec
1503 (make-output-sink output-spec output)))
1504 ((or hax:abstract-handler sax:abstract-handler)
1505 (with-xml-output output
1506 (when (typep output '(or combi-sink auto-detect-sink))
1507 (sax:start-dtd output
1508 :autodetect-me-please
1509 (output-doctype-public output-spec)
1510 (output-doctype-system output-spec)))
1511 (funcall fn)))))
1513 (defun make-output-sink (output-spec stream)
1514 (let* ((ystream
1515 (if stream
1516 (let ((et (stream-element-type stream)))
1517 (cond
1518 ((or (null et) (subtypep et '(unsigned-byte 8)))
1519 (runes:make-octet-stream-ystream stream))
1520 ((subtypep et 'character)
1521 (runes:make-character-stream-ystream stream))))
1522 (runes:make-rod-ystream)))
1523 (omit-xml-declaration-p
1524 (equal (output-omit-xml-declaration output-spec) "yes"))
1525 (sink-encoding (or (output-encoding output-spec) "UTF-8"))
1526 (sax-target
1527 (progn
1528 (setf (runes:ystream-encoding ystream)
1529 (cxml::find-output-encoding sink-encoding))
1530 (make-instance 'cxml::sink
1531 :ystream ystream
1532 :omit-xml-declaration-p omit-xml-declaration-p
1533 :encoding sink-encoding))))
1534 (flet ((make-combi-sink ()
1535 (make-instance 'combi-sink
1536 :hax-target (make-instance 'chtml::sink
1537 :ystream ystream)
1538 :sax-target sax-target
1539 :encoding sink-encoding)))
1540 (let ((method-key
1541 (cond
1542 ((equalp (output-method output-spec) "HTML") :html)
1543 ((equalp (output-method output-spec) "TEXT") :text)
1544 ((equalp (output-method output-spec) "XML") :xml)
1545 (t nil))))
1546 (cond
1547 ((and (eq method-key :html)
1548 (null (output-doctype-system output-spec))
1549 (null (output-doctype-public output-spec)))
1550 (make-combi-sink))
1551 ((eq method-key :text)
1552 (make-text-filter sax-target))
1553 ((and (eq method-key :xml)
1554 (null (output-doctype-system output-spec)))
1555 sax-target)
1557 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1559 (defstruct template
1560 match-expression
1561 compiled-pattern
1562 name
1563 import-priority
1564 apply-imports-limit
1565 priority
1566 position
1567 mode
1568 mode-qname
1569 params
1570 body
1571 n-variables)
1573 (defun expression-priority (form)
1574 (let ((step (second form)))
1575 (if (and (null (cddr form))
1576 (listp step)
1577 (member (car step) '(:child :attribute))
1578 (null (cddr step)))
1579 (let ((name (second step)))
1580 (cond
1581 ((or (stringp name)
1582 (and (consp name)
1583 (or (eq (car name) :qname)
1584 (eq (car name) :processing-instruction))))
1585 0.0)
1586 ((and (consp name)
1587 (or (eq (car name) :namespace)
1588 (eq (car name) '*)))
1589 -0.25)
1591 -0.5)))
1592 0.5)))
1594 (defun parse-xpath (str)
1595 (with-resignalled-errors ()
1596 (xpath:parse-xpath str)))
1598 (defun parse-key-pattern (str)
1599 (let ((parsed
1600 (mapcar #'(lambda (item)
1601 `(:path (:root :node)
1602 (:descendant-or-self *)
1603 ,@(cdr item)))
1604 (parse-pattern str))))
1605 (if (null (rest parsed))
1606 (first parsed)
1607 `(:union ,@parsed))))
1609 (defun parse-pattern (str)
1610 (with-resignalled-errors ()
1611 (cdr (xpath::parse-pattern-expression str))))
1613 (defun compile-value-thunk (value env)
1614 (if (and (listp value) (eq (car value) 'progn))
1615 (let ((inner-thunk (compile-instruction value env)))
1616 (lambda (ctx)
1617 (apply-to-result-tree-fragment ctx inner-thunk)))
1618 (compile-xpath value env)))
1620 (defun compile-var-binding (name value env)
1621 (multiple-value-bind (local-name uri)
1622 (decode-qname name env nil)
1623 (let ((thunk (xslt-trace-thunk
1624 (compile-value-thunk value env)
1625 "local variable ~s = ~s" name :result)))
1626 (list (cons local-name uri)
1627 (push-variable local-name
1629 *lexical-variable-declarations*)
1630 thunk))))
1632 (defun compile-var-bindings (forms env)
1633 (loop
1634 for (name value) in forms
1635 collect (compile-var-binding name value env)))
1637 (defun compile-template (<template> env position)
1638 (stp:with-attributes (match name priority mode) <template>
1639 (unless (or name match)
1640 (xslt-error "missing match in template"))
1641 (multiple-value-bind (params body-pos)
1642 (loop
1643 for i from 0
1644 for child in (stp:list-children <template>)
1645 while (namep child "param")
1646 collect (parse-param child) into params
1647 finally (return (values params i)))
1648 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1649 (param-bindings (compile-var-bindings params env))
1650 (body (parse-body <template> body-pos (mapcar #'car params)))
1651 (body-thunk (compile-instruction `(progn ,@body) env))
1652 (outer-body-thunk
1653 (xslt-trace-thunk
1654 #'(lambda (ctx)
1655 (unwind-protect
1656 (progn
1657 ;; set params that weren't initialized by apply-templates
1658 (loop for (name index param-thunk) in param-bindings
1659 when (eq (lexical-variable-value index nil) 'unbound)
1660 do (setf (lexical-variable-value index)
1661 (funcall param-thunk ctx)))
1662 (funcall body-thunk ctx))))
1663 "template: match = ~s name = ~s" match name))
1664 (n-variables (length *lexical-variable-declarations*)))
1665 (append
1666 (when name
1667 (multiple-value-bind (local-name uri)
1668 (decode-qname name env nil)
1669 (list
1670 (make-template :name (cons local-name uri)
1671 :import-priority *import-priority*
1672 :apply-imports-limit *apply-imports-limit*
1673 :params param-bindings
1674 :body outer-body-thunk
1675 :n-variables n-variables))))
1676 (when match
1677 (mapcar (lambda (expression)
1678 (let* ((compiled-pattern
1679 (xslt-trace-thunk
1680 (car (xpath:compute-patterns
1681 `(:patterns ,expression)
1683 :dummy
1684 env))
1685 "match-thunk for template (match ~s): ~s --> ~s"
1686 match expression :result))
1687 (p (if priority
1688 (xpath::parse-xnum priority)
1689 (expression-priority expression)))
1691 (progn
1692 (unless (and (numberp p)
1693 (not (xpath::inf-p p))
1694 (not (xpath::nan-p p)))
1695 (xslt-error "failed to parse priority"))
1696 (float p 1.0d0)))
1697 (template
1698 (make-template :match-expression expression
1699 :compiled-pattern compiled-pattern
1700 :import-priority *import-priority*
1701 :apply-imports-limit *apply-imports-limit*
1702 :priority p
1703 :position position
1704 :mode-qname mode
1705 :params param-bindings
1706 :body outer-body-thunk
1707 :n-variables n-variables)))
1708 (setf (xpath:pattern-value compiled-pattern)
1709 template)
1710 template))
1711 (cdr (xpath:parse-pattern-expression match)))))))))
1712 #+(or)
1713 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")