format-number: Fixed infinity, NaN
[xuriella.git] / xslt.lisp
blobfe236239bf05f9e0860229f44f4a53dd08218042
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 (defun xslt-cerror (fmt &rest args)
56 (with-simple-restart (recover "recover")
57 (error 'recoverable-xslt-error
58 :format-control fmt
59 :format-arguments args)))
61 (defvar *debug* nil)
63 (defmacro handler-case* (form &rest clauses)
64 ;; like HANDLER-CASE if *DEBUG* is off. If it's on, don't establish
65 ;; a handler at all so that we see the real stack traces. (We could use
66 ;; HANDLER-BIND here and check at signalling time, but doesn't seem
67 ;; important.)
68 (let ((doit (gensym)))
69 `(flet ((,doit () ,form))
70 (if *debug*
71 (,doit)
72 (handler-case
73 (,doit)
74 ,@clauses)))))
76 (defun compile-xpath (xpath &optional env)
77 (handler-case*
78 (xpath:compile-xpath xpath env)
79 (xpath:xpath-error (c)
80 (xslt-error "~A" c))))
82 (defmacro with-stack-limit ((&optional) &body body)
83 `(invoke-with-stack-limit (lambda () ,@body)))
86 ;;;; Helper function and macro
88 (defun map-pipe-eagerly (fn pipe)
89 (xpath::enumerate pipe :key fn :result nil))
91 (defmacro do-pipe ((var pipe &optional result) &body body)
92 `(block nil
93 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
94 ,result))
97 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
99 (defparameter *namespaces*
100 '((nil . "")
101 ("xmlns" . #"http://www.w3.org/2000/xmlns/")
102 ("xml" . #"http://www.w3.org/XML/1998/namespace")))
104 (defvar *global-variable-declarations*)
105 (defvar *lexical-variable-declarations*)
107 (defvar *global-variable-values*)
108 (defvar *lexical-variable-values*)
110 (defclass xslt-environment () ())
112 (defun split-qname (str)
113 (handler-case
114 (multiple-value-bind (prefix local-name)
115 (cxml::split-qname str)
116 (unless
117 ;; FIXME: cxml should really offer a function that does
118 ;; checks for NCName and QName in a sensible way for user code.
119 ;; cxml::split-qname is tailored to the needs of the parser.
121 ;; For now, let's just check the syntax explicitly.
122 (and (or (null prefix) (xpath::nc-name-p prefix))
123 (xpath::nc-name-p local-name))
124 (xslt-error "not a qname: ~A" str))
125 (values prefix local-name))
126 (cxml:well-formedness-violation ()
127 (xslt-error "not a qname: ~A" str))))
129 (defun decode-qname (qname env attributep)
130 (multiple-value-bind (prefix local-name)
131 (split-qname qname)
132 (values local-name
133 (if (or prefix (not attributep))
134 (xpath-sys:environment-find-namespace env (or prefix ""))
136 prefix)))
138 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
139 (or (cdr (assoc prefix *namespaces* :test 'equal))
140 ;; zzz gross hack.
141 ;; Change the entire code base to represent "no prefix" as the
142 ;; empty string consistently. unparse.lisp has already been changed.
143 (and (equal prefix "")
144 (cdr (assoc nil *namespaces* :test 'equal)))
145 (and (eql prefix nil)
146 (cdr (assoc "" *namespaces* :test 'equal)))))
148 (defun find-variable-index (local-name uri table)
149 (position (cons local-name uri) table :test 'equal))
151 (defun intern-global-variable (local-name uri)
152 (or (find-variable-index local-name uri *global-variable-declarations*)
153 (push-variable local-name uri *global-variable-declarations*)))
155 (defun push-variable (local-name uri table)
156 (prog1
157 (length table)
158 (vector-push-extend (cons local-name uri) table)))
160 (defun lexical-variable-value (index &optional (errorp t))
161 (let ((result (svref *lexical-variable-values* index)))
162 (when errorp
163 (assert (not (eq result 'unbound))))
164 result))
166 (defun (setf lexical-variable-value) (newval index)
167 (assert (not (eq newval 'unbound)))
168 (setf (svref *lexical-variable-values* index) newval))
170 (defun global-variable-value (index &optional (errorp t))
171 (let ((result (svref *global-variable-values* index)))
172 (when errorp
173 (assert (not (eq result 'unbound))))
174 result))
176 (defun (setf global-variable-value) (newval index)
177 (assert (not (eq newval 'unbound)))
178 (setf (svref *global-variable-values* index) newval))
180 (defmethod xpath-sys:environment-find-function
181 ((env xslt-environment) lname uri)
182 (if (string= uri "")
183 (or (xpath-sys:find-xpath-function lname *xsl*)
184 (xpath-sys:find-xpath-function lname uri))
185 (xpath-sys:find-xpath-function lname uri)))
187 (defmethod xpath-sys:environment-find-variable
188 ((env xslt-environment) lname uri)
189 (let ((index
190 (find-variable-index lname uri *lexical-variable-declarations*)))
191 (when index
192 (lambda (ctx)
193 (declare (ignore ctx))
194 (svref *lexical-variable-values* index)))))
196 (defclass lexical-xslt-environment (xslt-environment) ())
198 (defmethod xpath-sys:environment-find-variable
199 ((env lexical-xslt-environment) lname uri)
200 (or (call-next-method)
201 (let ((index
202 (find-variable-index lname uri *global-variable-declarations*)))
203 (when index
204 (xslt-trace-thunk
205 (lambda (ctx)
206 (declare (ignore ctx))
207 (svref *global-variable-values* index))
208 "global ~s (uri ~s) = ~s" lname uri :result)))))
210 (defclass global-variable-environment (xslt-environment)
211 ((initial-global-variable-thunks
212 :initarg :initial-global-variable-thunks
213 :accessor initial-global-variable-thunks)))
215 (defmethod xpath-sys:environment-find-variable
216 ((env global-variable-environment) lname uri)
217 (or (call-next-method)
218 (gethash (cons lname uri) (initial-global-variable-thunks env))))
221 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
222 ;;;;
223 ;;;; A sink that serializes only text not contained in any element.
225 (defmacro with-toplevel-text-output-sink ((var) &body body)
226 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
228 (defclass toplevel-text-output-sink (sax:default-handler)
229 ((target :initarg :target :accessor text-output-sink-target)
230 (depth :initform 0 :accessor textoutput-sink-depth)))
232 (defmethod sax:start-element ((sink toplevel-text-output-sink)
233 namespace-uri local-name qname attributes)
234 (declare (ignore namespace-uri local-name qname attributes))
235 (incf (textoutput-sink-depth sink)))
237 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
238 (when (zerop (textoutput-sink-depth sink))
239 (write-string data (text-output-sink-target sink))))
241 (defmethod sax:end-element ((sink toplevel-text-output-sink)
242 namespace-uri local-name qname)
243 (declare (ignore namespace-uri local-name qname))
244 (decf (textoutput-sink-depth sink)))
246 (defun invoke-with-toplevel-text-output-sink (fn)
247 (with-output-to-string (s)
248 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
251 ;;;; TEXT-FILTER
252 ;;;;
253 ;;;; A sink that passes through only text (at any level).
255 (defclass text-filter (sax:default-handler)
256 ((target :initarg :target :accessor text-filter-target)))
258 (defmethod sax:characters ((sink text-filter) data)
259 (sax:characters (text-filter-target sink) data))
261 (defmethod sax:end-document ((sink text-filter))
262 (sax:end-document (text-filter-target sink)))
264 (defun make-text-filter (target)
265 (make-instance 'text-filter :target target))
268 ;;;; Names
270 (defun of-name (local-name)
271 (stp:of-name local-name *xsl*))
273 (defun namep (node local-name)
274 (and (typep node '(or stp:element stp:attribute))
275 (equal (stp:namespace-uri node) *xsl*)
276 (equal (stp:local-name node) local-name)))
279 ;;;; PARSE-STYLESHEET
281 (defstruct stylesheet
282 (modes (make-hash-table :test 'equal))
283 (global-variables (make-empty-declaration-array))
284 (output-specification (make-output-specification))
285 (strip-tests nil)
286 (named-templates (make-hash-table :test 'equal))
287 (attribute-sets (make-hash-table :test 'equal))
288 (keys (make-hash-table :test 'equal))
289 (namespace-aliases (make-hash-table :test 'equal))
290 (decimal-formats (make-hash-table :test 'equal)))
292 (defstruct mode (templates nil))
294 (defun find-mode (stylesheet local-name &optional uri)
295 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
297 (defun ensure-mode (stylesheet &optional local-name uri)
298 (or (find-mode stylesheet local-name uri)
299 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
300 (make-mode))))
302 (defun ensure-mode/qname (stylesheet qname env)
303 (if qname
304 (multiple-value-bind (local-name uri)
305 (decode-qname qname env nil)
306 (ensure-mode stylesheet local-name uri))
307 (find-mode stylesheet nil)))
309 (defun acons-namespaces (element &optional (bindings *namespaces*))
310 (map-namespace-declarations (lambda (prefix uri)
311 (push (cons prefix uri) bindings))
312 element)
313 bindings)
315 (defun find-key (name stylesheet)
316 (or (gethash name (stylesheet-keys stylesheet))
317 (xslt-error "unknown key: ~a" name)))
319 (defun make-key (match use) (cons match use))
321 (defun key-match (key) (car key))
323 (defun key-use (key) (cdr key))
325 (defun add-key (stylesheet name match use)
326 (if (gethash name (stylesheet-keys stylesheet))
327 (xslt-error "duplicate key: ~a" name)
328 (setf (gethash name (stylesheet-keys stylesheet))
329 (make-key match use))))
331 (defvar *excluded-namespaces* (list *xsl*))
332 (defvar *empty-mode*)
333 (defvar *default-mode*)
335 (defvar *xsl-include-stack* nil)
337 (defun uri-to-pathname (uri)
338 (cxml::uri-to-pathname (puri:parse-uri uri)))
340 (defun parse-stylesheet-to-stp (input uri-resolver)
341 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
342 (<transform> (stp:document-element d)))
343 (strip-stylesheet <transform>)
344 ;; FIXME: handle embedded stylesheets
345 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
346 (or (equal (stp:local-name <transform>) "transform")
347 (equal (stp:local-name <transform>) "stylesheet")))
348 (xslt-error "not a stylesheet"))
349 (dolist (include (stp:filter-children (of-name "include") <transform>))
350 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
351 (stp:base-uri include)))
352 (uri (if uri-resolver
353 (funcall uri-resolver (puri:render-uri uri nil))
354 uri))
355 (str (puri:render-uri uri nil))
356 (pathname
357 (handler-case
358 (uri-to-pathname uri)
359 (cxml:xml-parse-error (c)
360 (xslt-error "cannot find included stylesheet ~A: ~A"
361 uri c)))))
362 (with-open-file
363 (stream pathname
364 :element-type '(unsigned-byte 8)
365 :if-does-not-exist nil)
366 (unless stream
367 (xslt-error "cannot find included stylesheet ~A at ~A"
368 uri pathname))
369 (when (find str *xsl-include-stack* :test #'equal)
370 (xslt-error "recursive inclusion of ~A" uri))
371 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
372 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
373 (stp:insert-child-after <transform>
374 (stp:copy <transform>2)
375 include)
376 (stp:detach include)))))
377 <transform>))
379 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
380 (defvar *apply-imports-limit*)
381 (defvar *import-priority*)
382 (defvar *extension-namespaces*)
384 (defmacro do-toplevel ((var xpath <transform>) &body body)
385 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
387 (defun map-toplevel (fn xpath <transform>)
388 (dolist (node (list-toplevel xpath <transform>))
389 (let ((*namespaces* *namespaces*))
390 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
391 (when (xpath-protocol:node-type-p ancestor :element)
392 (setf *namespaces* (acons-namespaces ancestor))))
393 (funcall fn node))))
395 (defun list-toplevel (xpath <transform>)
396 (labels ((recurse (sub)
397 (let ((subsubs
398 (xpath-sys:pipe-of
399 (xpath:evaluate "transform|stylesheet" sub))))
400 (xpath::append-pipes
401 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
402 (xpath::mappend-pipe #'recurse subsubs)))))
403 (xpath::sort-nodes (recurse <transform>))))
405 (defmacro with-parsed-prefixes ((node env) &body body)
406 `(invoke-with-parsed-prefixes (lambda () ,@body) ,node ,env))
408 (defun invoke-with-parsed-prefixes (fn node env)
409 (unless (or (namep node "stylesheet") (namep node "transform"))
410 (setf node (stp:parent node)))
411 (let ((*excluded-namespaces* (list *xsl*))
412 (*extension-namespaces* '()))
413 (parse-exclude-result-prefixes! node env)
414 (parse-extension-element-prefixes! node env)
415 (funcall fn)))
417 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
418 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
419 (instruction-base-uri (stp:base-uri <transform>))
420 (namespaces (acons-namespaces <transform>))
421 (apply-imports-limit (1+ *import-priority*))
422 (continuations '()))
423 (let ((*namespaces* namespaces))
424 (invoke-with-parsed-prefixes (constantly t) <transform> env))
425 (macrolet ((with-specials ((&optional) &body body)
426 `(let ((*instruction-base-uri* instruction-base-uri)
427 (*namespaces* namespaces)
428 (*apply-imports-limit* apply-imports-limit))
429 ,@body)))
430 (with-specials ()
431 (do-toplevel (import "import" <transform>)
432 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
433 (stp:base-uri import))))
434 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
435 continuations))))
436 (let ((import-priority
437 (incf *import-priority*))
438 (var-cont (prepare-global-variables stylesheet <transform>)))
439 ;; delay the rest of compilation until we've seen all global
440 ;; variables:
441 (lambda ()
442 (mapc #'funcall (nreverse continuations))
443 (with-specials ()
444 (let ((*import-priority* import-priority))
445 (funcall var-cont)
446 (parse-keys! stylesheet <transform> env)
447 (parse-templates! stylesheet <transform> env)
448 (parse-output! stylesheet <transform>)
449 (parse-strip/preserve-space! stylesheet <transform> env)
450 (parse-attribute-sets! stylesheet <transform> env)
451 (parse-namespace-aliases! stylesheet <transform> env)
452 (parse-decimal-formats! stylesheet <transform> env))))))))
454 (defvar *xsl-import-stack* nil)
456 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
457 (let* ((uri (if uri-resolver
458 (funcall uri-resolver (puri:render-uri uri nil))
459 uri))
460 (str (puri:render-uri uri nil))
461 (pathname
462 (handler-case
463 (uri-to-pathname uri)
464 (cxml:xml-parse-error (c)
465 (xslt-error "cannot find imported stylesheet ~A: ~A"
466 uri c)))))
467 (with-open-file
468 (stream pathname
469 :element-type '(unsigned-byte 8)
470 :if-does-not-exist nil)
471 (unless stream
472 (xslt-error "cannot find imported stylesheet ~A at ~A"
473 uri pathname))
474 (when (find str *xsl-import-stack* :test #'equal)
475 (xslt-error "recursive inclusion of ~A" uri))
476 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
477 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
479 (defun parse-stylesheet (designator &key uri-resolver)
480 (xpath:with-namespaces ((nil #.*xsl*))
481 (let* ((*import-priority* 0)
482 (puri:*strict-parse* nil)
483 (stylesheet (make-stylesheet))
484 (env (make-instance 'lexical-xslt-environment))
485 (*excluded-namespaces* *excluded-namespaces*)
486 (*global-variable-declarations* (make-empty-declaration-array)))
487 (ensure-mode stylesheet nil)
488 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
489 ;; reverse attribute sets:
490 (let ((table (stylesheet-attribute-sets stylesheet)))
491 (maphash (lambda (k v)
492 (setf (gethash k table) (nreverse v)))
493 table))
494 ;; add default df
495 (unless (find-decimal-format "" "" stylesheet nil)
496 (setf (find-decimal-format "" "" stylesheet)
497 (make-decimal-format)))
498 stylesheet)))
500 (defun parse-attribute-sets! (stylesheet <transform> env)
501 (do-toplevel (elt "attribute-set" <transform>)
502 (with-parsed-prefixes (elt env)
503 (push (let* ((sets
504 (mapcar (lambda (qname)
505 (multiple-value-list (decode-qname qname env nil)))
506 (words
507 (stp:attribute-value elt "use-attribute-sets"))))
508 (instructions
509 (stp:map-children
510 'list
511 (lambda (child)
512 (unless (or (not (typep child 'stp:element))
513 (and (equal (stp:namespace-uri child) *xsl*)
514 (equal (stp:local-name child)
515 "attribute"))
516 (find (stp:namespace-uri child)
517 *extension-namespaces*
518 :test 'equal))
519 (xslt-error "non-attribute found in attribute set"))
520 (parse-instruction child))
521 elt))
522 (*lexical-variable-declarations*
523 (make-empty-declaration-array))
524 (thunk
525 (compile-instruction `(progn ,@instructions) env))
526 (n-variables (length *lexical-variable-declarations*)))
527 (lambda (ctx)
528 (with-stack-limit ()
529 (loop for (local-name uri nil) in sets do
530 (dolist (thunk (find-attribute-set local-name uri))
531 (funcall thunk ctx)))
532 (let ((*lexical-variable-values*
533 (make-variable-value-array n-variables)))
534 (funcall thunk ctx)))))
535 (gethash (multiple-value-bind (local-name uri)
536 (decode-qname (stp:attribute-value elt "name") env nil)
537 (cons local-name uri))
538 (stylesheet-attribute-sets stylesheet))))))
540 (defun parse-namespace-aliases! (stylesheet <transform> env)
541 (do-toplevel (elt "namespace-alias" <transform>)
542 (stp:with-attributes (stylesheet-prefix result-prefix) elt
543 (setf (gethash
544 (xpath-sys:environment-find-namespace env stylesheet-prefix)
545 (stylesheet-namespace-aliases stylesheet))
546 (xpath-sys:environment-find-namespace
548 (if (equal result-prefix "#default")
550 result-prefix))))))
552 (defun parse-decimal-formats! (stylesheet <transform> env)
553 (do-toplevel (elt "decimal-format" <transform>)
554 (stp:with-attributes (name
555 ;; strings
556 infinity
558 ;; characters:
559 decimal-separator
560 grouping-separator
561 zero-digit
562 percent
563 per-mille
564 digit
565 pattern-separator
566 minus-sign)
568 (multiple-value-bind (local-name uri)
569 (if name
570 (decode-qname name env nil)
571 (values "" ""))
572 (unless (find-decimal-format local-name uri stylesheet nil)
573 (setf (find-decimal-format local-name uri stylesheet)
574 (flet ((chr (key x)
575 (when x
576 (unless (eql (length x) 1)
577 (xslt-error "not a single character: ~A" x))
578 (list key (elt x 0))))
579 (str (key x)
580 (when x
581 (list key x))))
582 (apply #'make-decimal-format
583 (append (str :infinity infinity)
584 (str :nan nan)
585 (chr :decimal-separator decimal-separator)
586 (chr :grouping-separator grouping-separator)
587 (chr :zero-digit zero-digit)
588 (chr :percent percent)
589 (chr :per-mille per-mille)
590 (chr :digit digit)
591 (chr :pattern-separator pattern-separator)
592 (chr :minus-sign minus-sign))))))))))
594 (defun parse-exclude-result-prefixes! (node env)
595 (stp:with-attributes (exclude-result-prefixes)
596 node
597 (dolist (prefix (words (or exclude-result-prefixes "")))
598 (if (equal prefix "#default")
599 (setf prefix nil)
600 (unless (cxml-stp-impl::nc-name-p prefix)
601 (xslt-error "invalid prefix: ~A" prefix)))
602 (push (or (xpath-sys:environment-find-namespace env prefix)
603 (xslt-error "namespace not found: ~A" prefix))
604 *excluded-namespaces*))))
606 (defun parse-extension-element-prefixes! (node env)
607 (stp:with-attributes (extension-element-prefixes)
608 node
609 (dolist (prefix (words (or extension-element-prefixes "")))
610 (if (equal prefix "#default")
611 (setf prefix nil)
612 (unless (cxml-stp-impl::nc-name-p prefix)
613 (xslt-error "invalid prefix: ~A" prefix)))
614 (let ((uri
615 (or (xpath-sys:environment-find-namespace env prefix)
616 (xslt-error "namespace not found: ~A" prefix))))
617 (unless (equal uri *xsl*)
618 (push uri *extension-namespaces*)
619 (push uri *excluded-namespaces*))))))
621 (defun parse-strip/preserve-space! (stylesheet <transform> env)
622 (xpath:with-namespaces ((nil #.*xsl*))
623 (do-toplevel (elt "strip-space|preserve-space" <transform>)
624 (let ((*namespaces* (acons-namespaces elt))
625 (mode
626 (if (equal (stp:local-name elt) "strip-space")
627 :strip
628 :preserve)))
629 (dolist (name-test (words (stp:attribute-value elt "elements")))
630 (let* ((pos (search ":*" name-test))
631 (test-function
632 (cond
633 ((eql pos (- (length name-test) 2))
634 (let* ((prefix (subseq name-test 0 pos))
635 (name-test-uri
636 (xpath-sys:environment-find-namespace env prefix)))
637 (unless (xpath::nc-name-p prefix)
638 (xslt-error "not an NCName: ~A" prefix))
639 (lambda (local-name uri)
640 (declare (ignore local-name))
641 (if (equal uri name-test-uri)
642 mode
643 nil))))
644 ((equal name-test "*")
645 (lambda (local-name uri)
646 (declare (ignore local-name uri))
647 mode))
649 (multiple-value-bind (name-test-local-name name-test-uri)
650 (decode-qname name-test env nil)
651 (lambda (local-name uri)
652 (if (and (equal local-name name-test-local-name)
653 (equal uri name-test-uri))
654 mode
655 nil)))))))
656 (push test-function (stylesheet-strip-tests stylesheet))))))))
658 (defstruct (output-specification
659 (:conc-name "OUTPUT-"))
660 method
661 indent
662 omit-xml-declaration
663 encoding)
665 (defun parse-output! (stylesheet <transform>)
666 (let ((outputs (list-toplevel "output" <transform>)))
667 (when outputs
668 (when (cdr outputs)
669 ;; FIXME:
670 ;; - concatenate cdata-section-elements
671 ;; - the others must not conflict
672 (error "oops, merging of output elements not supported yet"))
673 (let ((<output> (car outputs))
674 (spec (stylesheet-output-specification stylesheet)))
675 (stp:with-attributes (;; version
676 method
677 indent
678 encoding
679 ;;; media-type
680 ;;; doctype-system
681 ;;; doctype-public
682 omit-xml-declaration
683 ;;; standalone
684 ;;; cdata-section-elements
686 <output>
687 (setf (output-method spec) method)
688 (setf (output-indent spec) indent)
689 (setf (output-encoding spec) encoding)
690 (setf (output-omit-xml-declaration spec) omit-xml-declaration))))))
692 (defun make-empty-declaration-array ()
693 (make-array 1 :fill-pointer 0 :adjustable t))
695 (defun make-variable-value-array (n-lexical-variables)
696 (make-array n-lexical-variables :initial-element 'unbound))
698 (defun compile-global-variable (<variable> env) ;; also for <param>
699 (stp:with-attributes (name select) <variable>
700 (when (and select (stp:list-children <variable>))
701 (xslt-error "variable with select and body"))
702 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
703 (inner (cond
704 (select
705 (compile-xpath select env))
706 ((stp:list-children <variable>)
707 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
708 (inner-thunk (compile-instruction inner-sexpr env)))
709 (lambda (ctx)
710 (apply-to-result-tree-fragment ctx inner-thunk))))
712 (lambda (ctx)
713 (declare (ignore ctx))
714 ""))))
715 (n-lexical-variables (length *lexical-variable-declarations*)))
716 (xslt-trace-thunk
717 (lambda (ctx)
718 (let* ((*lexical-variable-values*
719 (make-variable-value-array n-lexical-variables)))
720 (funcall inner ctx)))
721 "global ~s (~s) = ~s" name select :result))))
723 (defstruct (variable-information
724 (:constructor make-variable)
725 (:conc-name "VARIABLE-"))
726 index
727 thunk
728 local-name
730 param-p
731 thunk-setter)
733 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
734 (let* ((*namespaces* (acons-namespaces <variable>))
735 (instruction-base-uri (stp:base-uri <variable>))
736 (*instruction-base-uri* instruction-base-uri)
737 (*excluded-namespaces* (list *xsl*))
738 (*extension-namespaces* '())
739 (qname (stp:attribute-value <variable> "name")))
740 (with-parsed-prefixes (<variable> global-env)
741 (unless qname
742 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
743 (multiple-value-bind (local-name uri)
744 (decode-qname qname global-env nil)
745 ;; For the normal compilation environment of templates, install it
746 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
747 (let ((index (intern-global-variable local-name uri)))
748 ;; For the evaluation of a global variable itself, build a thunk
749 ;; that lazily resolves other variables, stored into
750 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
751 (let* ((value-thunk :unknown)
752 (global-variable-thunk
753 (lambda (ctx)
754 (let ((v (global-variable-value index nil)))
755 (when (eq v 'seen)
756 (xslt-error "recursive variable definition"))
757 (cond
758 ((eq v 'unbound)
759 (setf (global-variable-value index) 'seen)
760 (setf (global-variable-value index)
761 (funcall value-thunk ctx)))
763 v)))))
764 (excluded-namespaces *excluded-namespaces*)
765 (extension-namespaces *extension-namespaces*)
766 (thunk-setter
767 (lambda ()
768 (let ((*instruction-base-uri* instruction-base-uri)
769 (*excluded-namespaces* excluded-namespaces)
770 (*extension-namespaces* extension-namespaces))
771 (setf value-thunk
772 (compile-global-variable <variable> global-env))))))
773 (setf (gethash (cons local-name uri)
774 (initial-global-variable-thunks global-env))
775 global-variable-thunk)
776 (make-variable :index index
777 :local-name local-name
778 :uri uri
779 :thunk global-variable-thunk
780 :param-p (namep <variable> "param")
781 :thunk-setter thunk-setter)))))))
783 (defun parse-keys! (stylesheet <transform> env)
784 (xpath:with-namespaces ((nil #.*xsl*))
785 (do-toplevel (<key> "key" <transform>)
786 (let ((*instruction-base-uri* (stp:base-uri <key>)))
787 (stp:with-attributes (name match use) <key>
788 (unless name (xslt-error "key name attribute not specified"))
789 (unless match (xslt-error "key match attribute not specified"))
790 (unless use (xslt-error "key use attribute not specified"))
791 (multiple-value-bind (local-name uri)
792 (decode-qname name env nil)
793 (add-key stylesheet
794 (cons local-name uri)
795 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
796 (compile-xpath use env))))))))
798 (defun prepare-global-variables (stylesheet <transform>)
799 (xpath:with-namespaces ((nil #.*xsl*))
800 (let* ((table (make-hash-table :test 'equal))
801 (global-env (make-instance 'global-variable-environment
802 :initial-global-variable-thunks table))
803 (specs '()))
804 (do-toplevel (<variable> "variable|param" <transform>)
805 (let ((var (parse-global-variable! <variable> global-env)))
806 (xslt-trace "parsing global variable ~s (uri ~s)"
807 (variable-local-name var)
808 (variable-uri var))
809 (when (find var
810 specs
811 :test (lambda (a b)
812 (and (equal (variable-local-name a)
813 (variable-local-name b))
814 (equal (variable-uri a)
815 (variable-uri b)))))
816 (xslt-error "duplicate definition for global variable ~A"
817 (variable-local-name var)))
818 (push var specs)))
819 (setf specs (nreverse specs))
820 (lambda ()
821 ;; now that the global environment knows about all variables, run the
822 ;; thunk setters to perform their compilation
823 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
824 (let ((table (stylesheet-global-variables stylesheet))
825 (newlen (length *global-variable-declarations*)))
826 (adjust-array table newlen :fill-pointer newlen)
827 (dolist (spec specs)
828 (setf (elt table (variable-index spec)) spec)))))))
830 (defun parse-templates! (stylesheet <transform> env)
831 (let ((i 0))
832 (do-toplevel (<template> "template" <transform>)
833 (let ((*namespaces* (acons-namespaces <template>))
834 (*instruction-base-uri* (stp:base-uri <template>)))
835 (with-parsed-prefixes (<template> env)
836 (dolist (template (compile-template <template> env i))
837 (let ((name (template-name template)))
838 (if name
839 (let* ((table (stylesheet-named-templates stylesheet))
840 (head (car (gethash name table))))
841 (when (and head (eql (template-import-priority head)
842 (template-import-priority template)))
843 ;; fixme: is this supposed to be a run-time error?
844 (xslt-error "conflicting templates for ~A" name))
845 (push template (gethash name table)))
846 (let ((mode (ensure-mode/qname stylesheet
847 (template-mode-qname template)
848 env)))
849 (setf (template-mode template) mode)
850 (push template (mode-templates mode))))))))
851 (incf i))))
854 ;;;; APPLY-STYLESHEET
856 (defvar *stylesheet*)
858 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
860 (defun unalias-uri (uri)
861 (let ((result
862 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
863 uri)))
864 (check-type result string)
865 result))
867 (defstruct (parameter
868 (:constructor make-parameter (value local-name &optional uri)))
869 (uri "")
870 local-name
871 value)
873 (defun find-parameter-value (local-name uri parameters)
874 (dolist (p parameters)
875 (when (and (equal (parameter-local-name p) local-name)
876 (equal (parameter-uri p) uri))
877 (return (parameter-value p)))))
879 (defvar *uri-resolver*)
881 (defun parse-allowing-microsoft-bom (pathname handler)
882 (with-open-file (s pathname :element-type '(unsigned-byte 8))
883 (unless (and (eql (read-byte s nil) #xef)
884 (eql (read-byte s nil) #xbb)
885 (eql (read-byte s nil) #xbf))
886 (file-position s 0))
887 (cxml:parse s handler)))
889 (defvar *documents*)
891 (defun %document (uri-string base-uri)
892 (let* ((absolute-uri
893 (puri:merge-uris uri-string (or base-uri "")))
894 (resolved-uri
895 (if *uri-resolver*
896 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
897 absolute-uri))
898 (pathname
899 (handler-case
900 (uri-to-pathname resolved-uri)
901 (cxml:xml-parse-error (c)
902 (xslt-error "cannot find referenced document ~A: ~A"
903 resolved-uri c))))
904 (xpath-root-node
905 (or (gethash pathname *documents*)
906 (setf (gethash pathname *documents*)
907 (make-whitespace-stripper
908 (handler-case
909 (parse-allowing-microsoft-bom pathname
910 (stp:make-builder))
911 ((or file-error cxml:xml-parse-error) (c)
912 (xslt-error "cannot parse referenced document ~A: ~A"
913 pathname c)))
914 (stylesheet-strip-tests *stylesheet*))))))
915 (when (puri:uri-fragment absolute-uri)
916 (xslt-error "use of fragment identifiers in document() not supported"))
917 xpath-root-node))
919 (xpath-sys:define-extension xslt *xsl*)
921 (defun document-base-uri (node)
922 (xpath-protocol:base-uri
923 (cond
924 ((xpath-protocol:node-type-p node :document)
925 (xpath::find-in-pipe-if
926 (lambda (x)
927 (xpath-protocol:node-type-p x :element))
928 (xpath-protocol:child-pipe node)))
929 ((xpath-protocol:node-type-p node :element)
930 node)
932 (xpath-protocol:parent-node node)))))
934 (xpath-sys:define-xpath-function/lazy
935 xslt :document
936 (object &optional node-set)
937 (let ((instruction-base-uri *instruction-base-uri*))
938 (lambda (ctx)
939 (let* ((object (funcall object ctx))
940 (node-set (and node-set (funcall node-set ctx)))
941 (base-uri
942 (if node-set
943 (document-base-uri (xpath::textually-first-node node-set))
944 instruction-base-uri)))
945 (xpath-sys:make-node-set
946 (if (xpath:node-set-p object)
947 (xpath:map-node-set->list
948 (lambda (node)
949 (%document (xpath:string-value node)
950 (if node-set
951 base-uri
952 (document-base-uri node))))
953 object)
954 (list (%document (xpath:string-value object) base-uri))))))))
956 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
957 (let ((namespaces *namespaces*))
958 (lambda (ctx)
959 (let* ((qname (xpath:string-value (funcall name ctx)))
960 (object (funcall object ctx))
961 (expanded-name
962 (multiple-value-bind (local-name uri)
963 (decode-qname/runtime qname namespaces nil)
964 (cons local-name uri)))
965 (key (find-key expanded-name *stylesheet*)))
966 (labels ((get-by-key (value)
967 (let ((value (xpath:string-value value)))
968 (xpath::filter-pipe
969 #'(lambda (node)
970 (let ((uses
971 (xpath:evaluate-compiled (key-use key) node)))
972 (if (xpath:node-set-p uses)
973 (xpath::find-in-pipe
974 value
975 (xpath-sys:pipe-of uses)
976 :key #'xpath:string-value
977 :test #'equal)
978 (equal value (xpath:string-value uses)))))
979 (xpath-sys:pipe-of
980 (xpath:node-set-value
981 (xpath:evaluate-compiled (key-match key) ctx)))))))
982 (xpath-sys:make-node-set
983 (xpath::sort-pipe
984 (if (xpath:node-set-p object)
985 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
986 (get-by-key object)))))))))
988 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
990 (xpath-sys:define-xpath-function/lazy xslt :current ()
991 #'(lambda (ctx)
992 (xpath-sys:make-node-set
993 (xpath-sys:make-pipe
994 (xpath:context-starting-node ctx)
995 nil))))
997 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
998 #'(lambda (ctx)
999 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1000 (funcall name ctx))
1001 "")))
1003 (defun %get-node-id (node)
1004 (when (xpath:node-set-p node)
1005 (setf node (xpath::textually-first-node node)))
1006 (when node
1007 (let ((id (xpath-sys:get-node-id node))
1008 (highest-base-uri
1009 (loop
1010 for parent = node then next
1011 for next = (xpath-protocol:parent-node parent)
1012 for this-base-uri = (xpath-protocol:base-uri parent)
1013 for highest-base-uri = (if (plusp (length this-base-uri))
1014 this-base-uri
1015 highest-base-uri)
1016 while next
1017 finally (return highest-base-uri))))
1018 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1019 ;; checked only if everything else matches.
1021 ;; This might be pointless premature optimization, but I like the idea :-)
1022 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1024 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1025 (if node-set-thunk
1026 #'(lambda (ctx)
1027 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1028 #'(lambda (ctx)
1029 (%get-node-id (xpath:context-node ctx)))))
1031 (declaim (special *available-instructions*))
1033 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1034 (let ((namespaces *namespaces*))
1035 #'(lambda (ctx)
1036 (let ((qname (funcall qname ctx)))
1037 (multiple-value-bind (local-name uri)
1038 (decode-qname/runtime qname namespaces nil)
1039 (and (equal uri *xsl*)
1040 (gethash local-name *available-instructions*)
1041 t))))))
1043 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1044 (let ((namespaces *namespaces*))
1045 #'(lambda (ctx)
1046 (let ((qname (funcall qname ctx)))
1047 (multiple-value-bind (local-name uri)
1048 (decode-qname/runtime qname namespaces nil)
1049 (and (zerop (length uri))
1050 (or (xpath-sys:find-xpath-function local-name *xsl*)
1051 (xpath-sys:find-xpath-function local-name uri))
1052 t))))))
1054 (defun apply-stylesheet
1055 (stylesheet source-designator
1056 &key output parameters uri-resolver navigator)
1057 (when (typep stylesheet 'xml-designator)
1058 (setf stylesheet (parse-stylesheet stylesheet)))
1059 (invoke-with-output-sink
1060 (lambda ()
1061 (handler-case*
1062 (let* ((*documents* (make-hash-table :test 'equal))
1063 (xpath:*navigator* (or navigator :default-navigator))
1064 (puri:*strict-parse* nil)
1065 (*stylesheet* stylesheet)
1066 (*empty-mode* (make-mode))
1067 (*default-mode* (find-mode stylesheet nil))
1068 (global-variable-specs
1069 (stylesheet-global-variables stylesheet))
1070 (*global-variable-values*
1071 (make-variable-value-array (length global-variable-specs)))
1072 (*uri-resolver* uri-resolver)
1073 (source-document
1074 (if (typep source-designator 'xml-designator)
1075 (cxml:parse source-designator (stp:make-builder))
1076 source-designator))
1077 (xpath-root-node
1078 (make-whitespace-stripper
1079 source-document
1080 (stylesheet-strip-tests stylesheet)))
1081 (ctx (xpath:make-context xpath-root-node)))
1082 (when (pathnamep source-designator)
1083 (setf (gethash source-designator *documents*) xpath-root-node))
1084 (map nil
1085 (lambda (spec)
1086 (when (variable-param-p spec)
1087 (let ((value
1088 (find-parameter-value (variable-local-name spec)
1089 (variable-uri spec)
1090 parameters)))
1091 (when value
1092 (setf (global-variable-value (variable-index spec))
1093 value)))))
1094 global-variable-specs)
1095 (map nil
1096 (lambda (spec)
1097 (funcall (variable-thunk spec) ctx))
1098 global-variable-specs)
1099 ;; zzz we wouldn't have to mask float traps here if we used the
1100 ;; XPath API properly. Unfortunately I've been using FUNCALL
1101 ;; everywhere instead of EVALUATE, so let's paper over that
1102 ;; at a central place to be sure:
1103 (xpath::with-float-traps-masked ()
1104 (apply-templates ctx :mode *default-mode*)))
1105 (xpath:xpath-error (c)
1106 (xslt-error "~A" c))))
1107 (stylesheet-output-specification stylesheet)
1108 output))
1110 (defun find-attribute-set (local-name uri)
1111 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1112 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1114 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1115 (when sort-predicate
1116 (setf list (sort list sort-predicate)))
1117 (let* ((n (length list))
1118 (s/d (lambda () n)))
1119 (loop
1120 for i from 1
1121 for child in list
1123 (apply-templates (xpath:make-context child s/d i)
1124 :param-bindings param-bindings
1125 :mode mode))))
1127 (defvar *stack-limit* 200)
1129 (defun invoke-with-stack-limit (fn)
1130 (let ((*stack-limit* (1- *stack-limit*)))
1131 (unless (plusp *stack-limit*)
1132 (xslt-error "*stack-limit* reached; stack overflow"))
1133 (funcall fn)))
1135 (defun invoke-template (ctx template param-bindings)
1136 (let ((*lexical-variable-values*
1137 (make-variable-value-array (template-n-variables template))))
1138 (with-stack-limit ()
1139 (loop
1140 for (name-cons value) in param-bindings
1141 for (nil index nil) = (find name-cons
1142 (template-params template)
1143 :test #'equal
1144 :key #'car)
1146 (when index
1147 (setf (lexical-variable-value index) value)))
1148 (funcall (template-body template) ctx))))
1150 (defun apply-default-templates (ctx mode)
1151 (let ((node (xpath:context-node ctx)))
1152 (cond
1153 ((or (xpath-protocol:node-type-p node :processing-instruction)
1154 (xpath-protocol:node-type-p node :comment)))
1155 ((or (xpath-protocol:node-type-p node :text)
1156 (xpath-protocol:node-type-p node :attribute))
1157 (write-text (xpath-protocol:node-text node)))
1159 (apply-templates/list
1160 (xpath::force
1161 (xpath-protocol:child-pipe node))
1162 :mode mode)))))
1164 (defvar *apply-imports*)
1166 (defun apply-applicable-templates (ctx templates param-bindings finally)
1167 (labels ((apply-imports (&optional actual-param-bindings)
1168 (if templates
1169 (let* ((this (pop templates))
1170 (low (template-apply-imports-limit this))
1171 (high (template-import-priority this)))
1172 (setf templates
1173 (remove-if-not
1174 (lambda (x)
1175 (<= low (template-import-priority x) high))
1176 templates))
1177 (invoke-template ctx this actual-param-bindings))
1178 (funcall finally))))
1179 (let ((*apply-imports* #'apply-imports))
1180 (apply-imports param-bindings))))
1182 (defun apply-templates (ctx &key param-bindings mode)
1183 (apply-applicable-templates ctx
1184 (find-templates ctx (or mode *default-mode*))
1185 param-bindings
1186 (lambda ()
1187 (apply-default-templates ctx mode))))
1189 (defun call-template (ctx name &optional param-bindings)
1190 (apply-applicable-templates ctx
1191 (find-named-templates name)
1192 param-bindings
1193 (lambda ()
1194 (error "cannot find named template: ~s"
1195 name))))
1197 (defun find-templates (ctx mode)
1198 (let* ((matching-candidates
1199 (remove-if-not (lambda (template)
1200 (template-matches-p template ctx))
1201 (mode-templates mode)))
1202 (npriorities
1203 (if matching-candidates
1204 (1+ (reduce #'max
1205 matching-candidates
1206 :key #'template-import-priority))
1208 (priority-groups (make-array npriorities :initial-element nil)))
1209 (dolist (template matching-candidates)
1210 (push template
1211 (elt priority-groups (template-import-priority template))))
1212 (loop
1213 for i from (1- npriorities) downto 0
1214 for group = (elt priority-groups i)
1215 for template = (maximize #'template< group)
1216 when template
1217 collect template)))
1219 (defun find-named-templates (name)
1220 (gethash name (stylesheet-named-templates *stylesheet*)))
1222 (defun template< (a b) ;assuming same import priority
1223 (let ((p (template-priority a))
1224 (q (template-priority b)))
1225 (cond
1226 ((< p q) t)
1227 ((> p q) nil)
1229 (xslt-cerror "conflicting templates:~_~A,~_~A"
1230 (template-match-expression a)
1231 (template-match-expression b))
1232 (< (template-position a) (template-position b))))))
1234 (defun maximize (< things)
1235 (when things
1236 (let ((max (car things)))
1237 (dolist (other (cdr things))
1238 (when (funcall < max other)
1239 (setf max other)))
1240 max)))
1242 (defun template-matches-p (template ctx)
1243 (find (xpath:context-node ctx)
1244 (xpath:all-nodes (funcall (template-match-thunk template) ctx))))
1246 (defun invoke-with-output-sink (fn output-spec output)
1247 (etypecase output
1248 (pathname
1249 (with-open-file (s output
1250 :direction :output
1251 :element-type '(unsigned-byte 8)
1252 :if-exists :rename-and-delete)
1253 (invoke-with-output-sink fn output-spec s)))
1254 ((or stream null)
1255 (invoke-with-output-sink fn
1256 output-spec
1257 (make-output-sink output-spec output)))
1258 ((or hax:abstract-handler sax:abstract-handler)
1259 (with-xml-output output
1260 (funcall fn)))))
1262 (defun make-output-sink (output-spec stream)
1263 (let* ((ystream
1264 (if stream
1265 (let ((et (stream-element-type stream)))
1266 (cond
1267 ((or (null et) (subtypep et '(unsigned-byte 8)))
1268 (runes:make-octet-stream-ystream stream))
1269 ((subtypep et 'character)
1270 (runes:make-character-stream-ystream stream))))
1271 (runes:make-rod-ystream)))
1272 (omit-xml-declaration-p
1273 (equal (output-omit-xml-declaration output-spec) "yes"))
1274 (sax-target
1275 (make-instance 'cxml::sink
1276 :ystream ystream
1277 :omit-xml-declaration-p omit-xml-declaration-p)))
1278 (cond
1279 ((equalp (output-method output-spec) "HTML")
1280 (make-instance 'combi-sink
1281 :hax-target (make-instance 'chtml::sink
1282 :ystream ystream)
1283 :sax-target sax-target
1284 :encoding (output-encoding output-spec)))
1285 ((equalp (output-method output-spec) "TEXT")
1286 (make-text-filter sax-target))
1288 sax-target))))
1290 (defstruct template
1291 match-expression
1292 match-thunk
1293 name
1294 import-priority
1295 apply-imports-limit
1296 priority
1297 position
1298 mode
1299 mode-qname
1300 params
1301 body
1302 n-variables)
1304 (defun expression-priority (form)
1305 (let ((step (second form)))
1306 (if (and (null (cddr form))
1307 (listp step)
1308 (member (car step) '(:child :attribute))
1309 (null (cddr step)))
1310 (let ((name (second step)))
1311 (cond
1312 ((or (stringp name)
1313 (and (consp name)
1314 (or (eq (car name) :qname)
1315 (eq (car name) :processing-instruction))))
1316 0.0)
1317 ((and (consp name)
1318 (or (eq (car name) :namespace)
1319 (eq (car name) '*)))
1320 -0.25)
1322 -0.5)))
1323 0.5)))
1325 (defun valid-expression-p (expr)
1326 (cond
1327 ((atom expr) t)
1328 ((eq (first expr) :path)
1329 (every (lambda (x)
1330 (let ((filter (third x)))
1331 (or (null filter) (valid-expression-p filter))))
1332 (cdr expr)))
1333 ((eq (first expr) :variable) ;(!)
1334 nil)
1336 (every #'valid-expression-p (cdr expr)))))
1338 (defun parse-xpath (str)
1339 (handler-case
1340 (xpath:parse-xpath str)
1341 (xpath:xpath-error (c)
1342 (xslt-error "~A" c))))
1344 ;; zzz also use naive-pattern-expression here?
1345 (defun parse-key-pattern (str)
1346 (let ((parsed
1347 (mapcar #'(lambda (item)
1348 `(:path (:root :node)
1349 (:descendant-or-self *)
1350 ,@(cdr item)))
1351 (parse-pattern str))))
1352 (if (null (rest parsed))
1353 (first parsed)
1354 `(:union ,@parsed))))
1356 (defun parse-pattern (str)
1357 ;; zzz check here for anything not allowed as an XSLT pattern
1358 ;; zzz can we hack id() and key() here?
1359 (let ((form (parse-xpath str)))
1360 (unless (consp form)
1361 (xslt-error "not a valid pattern: ~A" str))
1362 (labels ((process-form (form)
1363 (cond ((eq (car form) :union)
1364 (alexandria:mappend #'process-form (rest form)))
1365 ((not (or (eq (car form) :path)
1366 (and (eq (car form) :filter)
1367 (let ((filter (second form)))
1368 (and (consp filter)
1369 (member (car filter)
1370 '(:key :id))))
1371 (equal (third form) '(:true)))
1372 (member (car form) '(:key :id))))
1373 (xslt-error "not a valid pattern: ~A ~A" str form))
1374 ((not (valid-expression-p form))
1375 (xslt-error "invalid filter"))
1376 (t (list form)))))
1377 (process-form form))))
1379 (defun naive-pattern-expression (x)
1380 (ecase (car x)
1381 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1382 ((:filter :key :id) x)))
1384 (defun compile-value-thunk (value env)
1385 (if (and (listp value) (eq (car value) 'progn))
1386 (let ((inner-thunk (compile-instruction value env)))
1387 (lambda (ctx)
1388 (apply-to-result-tree-fragment ctx inner-thunk)))
1389 (compile-xpath value env)))
1391 (defun compile-var-bindings/nointern (forms env)
1392 (loop
1393 for (name value) in forms
1394 collect (multiple-value-bind (local-name uri)
1395 (decode-qname name env nil)
1396 (list (cons local-name uri)
1397 (xslt-trace-thunk
1398 (compile-value-thunk value env)
1399 "local variable ~s = ~s" name :result)))))
1401 (defun compile-var-bindings (forms env)
1402 (loop
1403 for (cons thunk) in (compile-var-bindings/nointern forms env)
1404 for (local-name . uri) = cons
1405 collect (list cons
1406 (push-variable local-name
1408 *lexical-variable-declarations*)
1409 thunk)))
1411 (defun compile-template (<template> env position)
1412 (stp:with-attributes (match name priority mode) <template>
1413 (unless (or name match)
1414 (xslt-error "missing match in template"))
1415 (multiple-value-bind (params body-pos)
1416 (loop
1417 for i from 0
1418 for child in (stp:list-children <template>)
1419 while (namep child "param")
1420 collect (parse-param child) into params
1421 finally (return (values params i)))
1422 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1423 (param-bindings (compile-var-bindings params env))
1424 (body (parse-body <template> body-pos (mapcar #'car params)))
1425 (body-thunk (compile-instruction `(progn ,@body) env))
1426 (outer-body-thunk
1427 (xslt-trace-thunk
1428 #'(lambda (ctx)
1429 (unwind-protect
1430 (progn
1431 ;; set params that weren't initialized by apply-templates
1432 (loop for (name index param-thunk) in param-bindings
1433 when (eq (lexical-variable-value index nil) 'unbound)
1434 do (setf (lexical-variable-value index)
1435 (funcall param-thunk ctx)))
1436 (funcall body-thunk ctx))))
1437 "template: match = ~s name = ~s" match name))
1438 (n-variables (length *lexical-variable-declarations*)))
1439 (append
1440 (when name
1441 (multiple-value-bind (local-name uri)
1442 (decode-qname name env nil)
1443 (list
1444 (make-template :name (cons local-name uri)
1445 :import-priority *import-priority*
1446 :apply-imports-limit *apply-imports-limit*
1447 :params param-bindings
1448 :body outer-body-thunk
1449 :n-variables n-variables))))
1450 (when match
1451 (mapcar (lambda (expression)
1452 (let ((match-thunk
1453 (xslt-trace-thunk
1454 (compile-xpath
1455 `(xpath:xpath
1456 ,(naive-pattern-expression expression))
1457 env)
1458 "match-thunk for template (match ~s): ~s --> ~s"
1459 match expression :result))
1460 (p (if priority
1461 (parse-number:parse-number priority)
1462 (expression-priority expression))))
1463 (make-template :match-expression expression
1464 :match-thunk match-thunk
1465 :import-priority *import-priority*
1466 :apply-imports-limit *apply-imports-limit*
1467 :priority p
1468 :position position
1469 :mode-qname mode
1470 :params param-bindings
1471 :body outer-body-thunk
1472 :n-variables n-variables)))
1473 (parse-pattern match))))))))
1474 #+(or)
1475 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")