xsl:number fixes: format tokenization
[xuriella.git] / xslt.lisp
blobd9d99d0ef00e3668aae7fa49154008f974e1f83b
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
557 (nan "NaN")
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 (let ((seen '()))
575 (flet ((chr (key x)
576 (when x
577 (unless (eql (length x) 1)
578 (xslt-error "not a single character: ~A" x))
579 (let ((chr (elt x 0)))
580 (when (find chr seen)
581 (xslt-error
582 "conflicting decimal format characters: ~A"
583 chr))
584 (push chr seen)
585 (list key chr))))
586 (str (key x)
587 (when x
588 (list key x))))
589 (apply #'make-decimal-format
590 (append (str :infinity infinity)
591 (str :nan nan)
592 (chr :decimal-separator decimal-separator)
593 (chr :grouping-separator grouping-separator)
594 (chr :zero-digit zero-digit)
595 (chr :percent percent)
596 (chr :per-mille per-mille)
597 (chr :digit digit)
598 (chr :pattern-separator pattern-separator)
599 (chr :minus-sign minus-sign)))))))))))
601 (defun parse-exclude-result-prefixes! (node env)
602 (stp:with-attributes (exclude-result-prefixes)
603 node
604 (dolist (prefix (words (or exclude-result-prefixes "")))
605 (if (equal prefix "#default")
606 (setf prefix nil)
607 (unless (cxml-stp-impl::nc-name-p prefix)
608 (xslt-error "invalid prefix: ~A" prefix)))
609 (push (or (xpath-sys:environment-find-namespace env prefix)
610 (xslt-error "namespace not found: ~A" prefix))
611 *excluded-namespaces*))))
613 (defun parse-extension-element-prefixes! (node env)
614 (stp:with-attributes (extension-element-prefixes)
615 node
616 (dolist (prefix (words (or extension-element-prefixes "")))
617 (if (equal prefix "#default")
618 (setf prefix nil)
619 (unless (cxml-stp-impl::nc-name-p prefix)
620 (xslt-error "invalid prefix: ~A" prefix)))
621 (let ((uri
622 (or (xpath-sys:environment-find-namespace env prefix)
623 (xslt-error "namespace not found: ~A" prefix))))
624 (unless (equal uri *xsl*)
625 (push uri *extension-namespaces*)
626 (push uri *excluded-namespaces*))))))
628 (defun parse-strip/preserve-space! (stylesheet <transform> env)
629 (xpath:with-namespaces ((nil #.*xsl*))
630 (do-toplevel (elt "strip-space|preserve-space" <transform>)
631 (let ((*namespaces* (acons-namespaces elt))
632 (mode
633 (if (equal (stp:local-name elt) "strip-space")
634 :strip
635 :preserve)))
636 (dolist (name-test (words (stp:attribute-value elt "elements")))
637 (let* ((pos (search ":*" name-test))
638 (test-function
639 (cond
640 ((eql pos (- (length name-test) 2))
641 (let* ((prefix (subseq name-test 0 pos))
642 (name-test-uri
643 (xpath-sys:environment-find-namespace env prefix)))
644 (unless (xpath::nc-name-p prefix)
645 (xslt-error "not an NCName: ~A" prefix))
646 (lambda (local-name uri)
647 (declare (ignore local-name))
648 (if (equal uri name-test-uri)
649 mode
650 nil))))
651 ((equal name-test "*")
652 (lambda (local-name uri)
653 (declare (ignore local-name uri))
654 mode))
656 (multiple-value-bind (name-test-local-name name-test-uri)
657 (decode-qname name-test env nil)
658 (lambda (local-name uri)
659 (if (and (equal local-name name-test-local-name)
660 (equal uri name-test-uri))
661 mode
662 nil)))))))
663 (push test-function (stylesheet-strip-tests stylesheet))))))))
665 (defstruct (output-specification
666 (:conc-name "OUTPUT-"))
667 method
668 indent
669 omit-xml-declaration
670 encoding)
672 (defun parse-output! (stylesheet <transform>)
673 (let ((outputs (list-toplevel "output" <transform>)))
674 (when outputs
675 (when (cdr outputs)
676 ;; FIXME:
677 ;; - concatenate cdata-section-elements
678 ;; - the others must not conflict
679 (error "oops, merging of output elements not supported yet"))
680 (let ((<output> (car outputs))
681 (spec (stylesheet-output-specification stylesheet)))
682 (stp:with-attributes (;; version
683 method
684 indent
685 encoding
686 ;;; media-type
687 ;;; doctype-system
688 ;;; doctype-public
689 omit-xml-declaration
690 ;;; standalone
691 ;;; cdata-section-elements
693 <output>
694 (setf (output-method spec) method)
695 (setf (output-indent spec) indent)
696 (setf (output-encoding spec) encoding)
697 (setf (output-omit-xml-declaration spec) omit-xml-declaration))))))
699 (defun make-empty-declaration-array ()
700 (make-array 1 :fill-pointer 0 :adjustable t))
702 (defun make-variable-value-array (n-lexical-variables)
703 (make-array n-lexical-variables :initial-element 'unbound))
705 (defun compile-global-variable (<variable> env) ;; also for <param>
706 (stp:with-attributes (name select) <variable>
707 (when (and select (stp:list-children <variable>))
708 (xslt-error "variable with select and body"))
709 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
710 (inner (cond
711 (select
712 (compile-xpath select env))
713 ((stp:list-children <variable>)
714 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
715 (inner-thunk (compile-instruction inner-sexpr env)))
716 (lambda (ctx)
717 (apply-to-result-tree-fragment ctx inner-thunk))))
719 (lambda (ctx)
720 (declare (ignore ctx))
721 ""))))
722 (n-lexical-variables (length *lexical-variable-declarations*)))
723 (xslt-trace-thunk
724 (lambda (ctx)
725 (let* ((*lexical-variable-values*
726 (make-variable-value-array n-lexical-variables)))
727 (funcall inner ctx)))
728 "global ~s (~s) = ~s" name select :result))))
730 (defstruct (variable-information
731 (:constructor make-variable)
732 (:conc-name "VARIABLE-"))
733 index
734 thunk
735 local-name
737 param-p
738 thunk-setter)
740 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
741 (let* ((*namespaces* (acons-namespaces <variable>))
742 (instruction-base-uri (stp:base-uri <variable>))
743 (*instruction-base-uri* instruction-base-uri)
744 (*excluded-namespaces* (list *xsl*))
745 (*extension-namespaces* '())
746 (qname (stp:attribute-value <variable> "name")))
747 (with-parsed-prefixes (<variable> global-env)
748 (unless qname
749 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
750 (multiple-value-bind (local-name uri)
751 (decode-qname qname global-env nil)
752 ;; For the normal compilation environment of templates, install it
753 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
754 (let ((index (intern-global-variable local-name uri)))
755 ;; For the evaluation of a global variable itself, build a thunk
756 ;; that lazily resolves other variables, stored into
757 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
758 (let* ((value-thunk :unknown)
759 (global-variable-thunk
760 (lambda (ctx)
761 (let ((v (global-variable-value index nil)))
762 (when (eq v 'seen)
763 (xslt-error "recursive variable definition"))
764 (cond
765 ((eq v 'unbound)
766 (setf (global-variable-value index) 'seen)
767 (setf (global-variable-value index)
768 (funcall value-thunk ctx)))
770 v)))))
771 (excluded-namespaces *excluded-namespaces*)
772 (extension-namespaces *extension-namespaces*)
773 (thunk-setter
774 (lambda ()
775 (let ((*instruction-base-uri* instruction-base-uri)
776 (*excluded-namespaces* excluded-namespaces)
777 (*extension-namespaces* extension-namespaces))
778 (setf value-thunk
779 (compile-global-variable <variable> global-env))))))
780 (setf (gethash (cons local-name uri)
781 (initial-global-variable-thunks global-env))
782 global-variable-thunk)
783 (make-variable :index index
784 :local-name local-name
785 :uri uri
786 :thunk global-variable-thunk
787 :param-p (namep <variable> "param")
788 :thunk-setter thunk-setter)))))))
790 (defun parse-keys! (stylesheet <transform> env)
791 (xpath:with-namespaces ((nil #.*xsl*))
792 (do-toplevel (<key> "key" <transform>)
793 (let ((*instruction-base-uri* (stp:base-uri <key>)))
794 (stp:with-attributes (name match use) <key>
795 (unless name (xslt-error "key name attribute not specified"))
796 (unless match (xslt-error "key match attribute not specified"))
797 (unless use (xslt-error "key use attribute not specified"))
798 (multiple-value-bind (local-name uri)
799 (decode-qname name env nil)
800 (add-key stylesheet
801 (cons local-name uri)
802 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
803 (compile-xpath use env))))))))
805 (defun prepare-global-variables (stylesheet <transform>)
806 (xpath:with-namespaces ((nil #.*xsl*))
807 (let* ((table (make-hash-table :test 'equal))
808 (global-env (make-instance 'global-variable-environment
809 :initial-global-variable-thunks table))
810 (specs '()))
811 (do-toplevel (<variable> "variable|param" <transform>)
812 (let ((var (parse-global-variable! <variable> global-env)))
813 (xslt-trace "parsing global variable ~s (uri ~s)"
814 (variable-local-name var)
815 (variable-uri var))
816 (when (find var
817 specs
818 :test (lambda (a b)
819 (and (equal (variable-local-name a)
820 (variable-local-name b))
821 (equal (variable-uri a)
822 (variable-uri b)))))
823 (xslt-error "duplicate definition for global variable ~A"
824 (variable-local-name var)))
825 (push var specs)))
826 (setf specs (nreverse specs))
827 (lambda ()
828 ;; now that the global environment knows about all variables, run the
829 ;; thunk setters to perform their compilation
830 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
831 (let ((table (stylesheet-global-variables stylesheet))
832 (newlen (length *global-variable-declarations*)))
833 (adjust-array table newlen :fill-pointer newlen)
834 (dolist (spec specs)
835 (setf (elt table (variable-index spec)) spec)))))))
837 (defun parse-templates! (stylesheet <transform> env)
838 (let ((i 0))
839 (do-toplevel (<template> "template" <transform>)
840 (let ((*namespaces* (acons-namespaces <template>))
841 (*instruction-base-uri* (stp:base-uri <template>)))
842 (with-parsed-prefixes (<template> env)
843 (dolist (template (compile-template <template> env i))
844 (let ((name (template-name template)))
845 (if name
846 (let* ((table (stylesheet-named-templates stylesheet))
847 (head (car (gethash name table))))
848 (when (and head (eql (template-import-priority head)
849 (template-import-priority template)))
850 ;; fixme: is this supposed to be a run-time error?
851 (xslt-error "conflicting templates for ~A" name))
852 (push template (gethash name table)))
853 (let ((mode (ensure-mode/qname stylesheet
854 (template-mode-qname template)
855 env)))
856 (setf (template-mode template) mode)
857 (push template (mode-templates mode))))))))
858 (incf i))))
861 ;;;; APPLY-STYLESHEET
863 (defvar *stylesheet*)
865 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
867 (defun unalias-uri (uri)
868 (let ((result
869 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
870 uri)))
871 (check-type result string)
872 result))
874 (defstruct (parameter
875 (:constructor make-parameter (value local-name &optional uri)))
876 (uri "")
877 local-name
878 value)
880 (defun find-parameter-value (local-name uri parameters)
881 (dolist (p parameters)
882 (when (and (equal (parameter-local-name p) local-name)
883 (equal (parameter-uri p) uri))
884 (return (parameter-value p)))))
886 (defvar *uri-resolver*)
888 (defun parse-allowing-microsoft-bom (pathname handler)
889 (with-open-file (s pathname :element-type '(unsigned-byte 8))
890 (unless (and (eql (read-byte s nil) #xef)
891 (eql (read-byte s nil) #xbb)
892 (eql (read-byte s nil) #xbf))
893 (file-position s 0))
894 (cxml:parse s handler)))
896 (defvar *documents*)
898 (defun %document (uri-string base-uri)
899 (let* ((absolute-uri
900 (puri:merge-uris uri-string (or base-uri "")))
901 (resolved-uri
902 (if *uri-resolver*
903 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
904 absolute-uri))
905 (pathname
906 (handler-case
907 (uri-to-pathname resolved-uri)
908 (cxml:xml-parse-error (c)
909 (xslt-error "cannot find referenced document ~A: ~A"
910 resolved-uri c))))
911 (xpath-root-node
912 (or (gethash pathname *documents*)
913 (setf (gethash pathname *documents*)
914 (make-whitespace-stripper
915 (handler-case
916 (parse-allowing-microsoft-bom pathname
917 (stp:make-builder))
918 ((or file-error cxml:xml-parse-error) (c)
919 (xslt-error "cannot parse referenced document ~A: ~A"
920 pathname c)))
921 (stylesheet-strip-tests *stylesheet*))))))
922 (when (puri:uri-fragment absolute-uri)
923 (xslt-error "use of fragment identifiers in document() not supported"))
924 xpath-root-node))
926 (xpath-sys:define-extension xslt *xsl*)
928 (defun document-base-uri (node)
929 (xpath-protocol:base-uri
930 (cond
931 ((xpath-protocol:node-type-p node :document)
932 (xpath::find-in-pipe-if
933 (lambda (x)
934 (xpath-protocol:node-type-p x :element))
935 (xpath-protocol:child-pipe node)))
936 ((xpath-protocol:node-type-p node :element)
937 node)
939 (xpath-protocol:parent-node node)))))
941 (xpath-sys:define-xpath-function/lazy
942 xslt :document
943 (object &optional node-set)
944 (let ((instruction-base-uri *instruction-base-uri*))
945 (lambda (ctx)
946 (let* ((object (funcall object ctx))
947 (node-set (and node-set (funcall node-set ctx)))
948 (base-uri
949 (if node-set
950 (document-base-uri (xpath::textually-first-node node-set))
951 instruction-base-uri)))
952 (xpath-sys:make-node-set
953 (if (xpath:node-set-p object)
954 (xpath:map-node-set->list
955 (lambda (node)
956 (%document (xpath:string-value node)
957 (if node-set
958 base-uri
959 (document-base-uri node))))
960 object)
961 (list (%document (xpath:string-value object) base-uri))))))))
963 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
964 (let ((namespaces *namespaces*))
965 (lambda (ctx)
966 (let* ((qname (xpath:string-value (funcall name ctx)))
967 (object (funcall object ctx))
968 (expanded-name
969 (multiple-value-bind (local-name uri)
970 (decode-qname/runtime qname namespaces nil)
971 (cons local-name uri)))
972 (key (find-key expanded-name *stylesheet*)))
973 (labels ((get-by-key (value)
974 (let ((value (xpath:string-value value)))
975 (xpath::filter-pipe
976 #'(lambda (node)
977 (let ((uses
978 (xpath:evaluate-compiled (key-use key) node)))
979 (if (xpath:node-set-p uses)
980 (xpath::find-in-pipe
981 value
982 (xpath-sys:pipe-of uses)
983 :key #'xpath:string-value
984 :test #'equal)
985 (equal value (xpath:string-value uses)))))
986 (xpath-sys:pipe-of
987 (xpath:node-set-value
988 (xpath:evaluate-compiled (key-match key) ctx)))))))
989 (xpath-sys:make-node-set
990 (xpath::sort-pipe
991 (if (xpath:node-set-p object)
992 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
993 (get-by-key object)))))))))
995 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
997 (xpath-sys:define-xpath-function/lazy xslt :current ()
998 #'(lambda (ctx)
999 (xpath-sys:make-node-set
1000 (xpath-sys:make-pipe
1001 (xpath:context-starting-node ctx)
1002 nil))))
1004 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1005 #'(lambda (ctx)
1006 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1007 (funcall name ctx))
1008 "")))
1010 (defun %get-node-id (node)
1011 (when (xpath:node-set-p node)
1012 (setf node (xpath::textually-first-node node)))
1013 (when node
1014 (let ((id (xpath-sys:get-node-id node))
1015 (highest-base-uri
1016 (loop
1017 for parent = node then next
1018 for next = (xpath-protocol:parent-node parent)
1019 for this-base-uri = (xpath-protocol:base-uri parent)
1020 for highest-base-uri = (if (plusp (length this-base-uri))
1021 this-base-uri
1022 highest-base-uri)
1023 while next
1024 finally (return highest-base-uri))))
1025 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1026 ;; checked only if everything else matches.
1028 ;; This might be pointless premature optimization, but I like the idea :-)
1029 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1031 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1032 (if node-set-thunk
1033 #'(lambda (ctx)
1034 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1035 #'(lambda (ctx)
1036 (%get-node-id (xpath:context-node ctx)))))
1038 (declaim (special *available-instructions*))
1040 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1041 (let ((namespaces *namespaces*))
1042 #'(lambda (ctx)
1043 (let ((qname (funcall qname ctx)))
1044 (multiple-value-bind (local-name uri)
1045 (decode-qname/runtime qname namespaces nil)
1046 (and (equal uri *xsl*)
1047 (gethash local-name *available-instructions*)
1048 t))))))
1050 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1051 (let ((namespaces *namespaces*))
1052 #'(lambda (ctx)
1053 (let ((qname (funcall qname ctx)))
1054 (multiple-value-bind (local-name uri)
1055 (decode-qname/runtime qname namespaces nil)
1056 (and (zerop (length uri))
1057 (or (xpath-sys:find-xpath-function local-name *xsl*)
1058 (xpath-sys:find-xpath-function local-name uri))
1059 t))))))
1061 (defun apply-stylesheet
1062 (stylesheet source-designator
1063 &key output parameters uri-resolver navigator)
1064 (when (typep stylesheet 'xml-designator)
1065 (setf stylesheet (parse-stylesheet stylesheet)))
1066 (invoke-with-output-sink
1067 (lambda ()
1068 (handler-case*
1069 (let* ((*documents* (make-hash-table :test 'equal))
1070 (xpath:*navigator* (or navigator :default-navigator))
1071 (puri:*strict-parse* nil)
1072 (*stylesheet* stylesheet)
1073 (*empty-mode* (make-mode))
1074 (*default-mode* (find-mode stylesheet nil))
1075 (global-variable-specs
1076 (stylesheet-global-variables stylesheet))
1077 (*global-variable-values*
1078 (make-variable-value-array (length global-variable-specs)))
1079 (*uri-resolver* uri-resolver)
1080 (source-document
1081 (if (typep source-designator 'xml-designator)
1082 (cxml:parse source-designator (stp:make-builder))
1083 source-designator))
1084 (xpath-root-node
1085 (make-whitespace-stripper
1086 source-document
1087 (stylesheet-strip-tests stylesheet)))
1088 (ctx (xpath:make-context xpath-root-node)))
1089 (when (pathnamep source-designator)
1090 (setf (gethash source-designator *documents*) xpath-root-node))
1091 (map nil
1092 (lambda (spec)
1093 (when (variable-param-p spec)
1094 (let ((value
1095 (find-parameter-value (variable-local-name spec)
1096 (variable-uri spec)
1097 parameters)))
1098 (when value
1099 (setf (global-variable-value (variable-index spec))
1100 value)))))
1101 global-variable-specs)
1102 (map nil
1103 (lambda (spec)
1104 (funcall (variable-thunk spec) ctx))
1105 global-variable-specs)
1106 ;; zzz we wouldn't have to mask float traps here if we used the
1107 ;; XPath API properly. Unfortunately I've been using FUNCALL
1108 ;; everywhere instead of EVALUATE, so let's paper over that
1109 ;; at a central place to be sure:
1110 (xpath::with-float-traps-masked ()
1111 (apply-templates ctx :mode *default-mode*)))
1112 (xpath:xpath-error (c)
1113 (xslt-error "~A" c))))
1114 (stylesheet-output-specification stylesheet)
1115 output))
1117 (defun find-attribute-set (local-name uri)
1118 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1119 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1121 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1122 (when sort-predicate
1123 (setf list (sort list sort-predicate)))
1124 (let* ((n (length list))
1125 (s/d (lambda () n)))
1126 (loop
1127 for i from 1
1128 for child in list
1130 (apply-templates (xpath:make-context child s/d i)
1131 :param-bindings param-bindings
1132 :mode mode))))
1134 (defvar *stack-limit* 200)
1136 (defun invoke-with-stack-limit (fn)
1137 (let ((*stack-limit* (1- *stack-limit*)))
1138 (unless (plusp *stack-limit*)
1139 (xslt-error "*stack-limit* reached; stack overflow"))
1140 (funcall fn)))
1142 (defun invoke-template (ctx template param-bindings)
1143 (let ((*lexical-variable-values*
1144 (make-variable-value-array (template-n-variables template))))
1145 (with-stack-limit ()
1146 (loop
1147 for (name-cons value) in param-bindings
1148 for (nil index nil) = (find name-cons
1149 (template-params template)
1150 :test #'equal
1151 :key #'car)
1153 (when index
1154 (setf (lexical-variable-value index) value)))
1155 (funcall (template-body template) ctx))))
1157 (defun apply-default-templates (ctx mode)
1158 (let ((node (xpath:context-node ctx)))
1159 (cond
1160 ((or (xpath-protocol:node-type-p node :processing-instruction)
1161 (xpath-protocol:node-type-p node :comment)))
1162 ((or (xpath-protocol:node-type-p node :text)
1163 (xpath-protocol:node-type-p node :attribute))
1164 (write-text (xpath-protocol:node-text node)))
1166 (apply-templates/list
1167 (xpath::force
1168 (xpath-protocol:child-pipe node))
1169 :mode mode)))))
1171 (defvar *apply-imports*)
1173 (defun apply-applicable-templates (ctx templates param-bindings finally)
1174 (labels ((apply-imports (&optional actual-param-bindings)
1175 (if templates
1176 (let* ((this (pop templates))
1177 (low (template-apply-imports-limit this))
1178 (high (template-import-priority this)))
1179 (setf templates
1180 (remove-if-not
1181 (lambda (x)
1182 (<= low (template-import-priority x) high))
1183 templates))
1184 (invoke-template ctx this actual-param-bindings))
1185 (funcall finally))))
1186 (let ((*apply-imports* #'apply-imports))
1187 (apply-imports param-bindings))))
1189 (defun apply-templates (ctx &key param-bindings mode)
1190 (apply-applicable-templates ctx
1191 (find-templates ctx (or mode *default-mode*))
1192 param-bindings
1193 (lambda ()
1194 (apply-default-templates ctx mode))))
1196 (defun call-template (ctx name &optional param-bindings)
1197 (apply-applicable-templates ctx
1198 (find-named-templates name)
1199 param-bindings
1200 (lambda ()
1201 (error "cannot find named template: ~s"
1202 name))))
1204 (defun find-templates (ctx mode)
1205 (let* ((matching-candidates
1206 (remove-if-not (lambda (template)
1207 (template-matches-p template ctx))
1208 (mode-templates mode)))
1209 (npriorities
1210 (if matching-candidates
1211 (1+ (reduce #'max
1212 matching-candidates
1213 :key #'template-import-priority))
1215 (priority-groups (make-array npriorities :initial-element nil)))
1216 (dolist (template matching-candidates)
1217 (push template
1218 (elt priority-groups (template-import-priority template))))
1219 (loop
1220 for i from (1- npriorities) downto 0
1221 for group = (elt priority-groups i)
1222 for template = (maximize #'template< group)
1223 when template
1224 collect template)))
1226 (defun find-named-templates (name)
1227 (gethash name (stylesheet-named-templates *stylesheet*)))
1229 (defun template< (a b) ;assuming same import priority
1230 (let ((p (template-priority a))
1231 (q (template-priority b)))
1232 (cond
1233 ((< p q) t)
1234 ((> p q) nil)
1236 (xslt-cerror "conflicting templates:~_~A,~_~A"
1237 (template-match-expression a)
1238 (template-match-expression b))
1239 (< (template-position a) (template-position b))))))
1241 (defun maximize (< things)
1242 (when things
1243 (let ((max (car things)))
1244 (dolist (other (cdr things))
1245 (when (funcall < max other)
1246 (setf max other)))
1247 max)))
1249 (defun template-matches-p (template ctx)
1250 (find (xpath:context-node ctx)
1251 (xpath:all-nodes (funcall (template-match-thunk template) ctx))))
1253 (defun invoke-with-output-sink (fn output-spec output)
1254 (etypecase output
1255 (pathname
1256 (with-open-file (s output
1257 :direction :output
1258 :element-type '(unsigned-byte 8)
1259 :if-exists :rename-and-delete)
1260 (invoke-with-output-sink fn output-spec s)))
1261 ((or stream null)
1262 (invoke-with-output-sink fn
1263 output-spec
1264 (make-output-sink output-spec output)))
1265 ((or hax:abstract-handler sax:abstract-handler)
1266 (with-xml-output output
1267 (funcall fn)))))
1269 (defun make-output-sink (output-spec stream)
1270 (let* ((ystream
1271 (if stream
1272 (let ((et (stream-element-type stream)))
1273 (cond
1274 ((or (null et) (subtypep et '(unsigned-byte 8)))
1275 (runes:make-octet-stream-ystream stream))
1276 ((subtypep et 'character)
1277 (runes:make-character-stream-ystream stream))))
1278 (runes:make-rod-ystream)))
1279 (omit-xml-declaration-p
1280 (equal (output-omit-xml-declaration output-spec) "yes"))
1281 (sax-target
1282 (make-instance 'cxml::sink
1283 :ystream ystream
1284 :omit-xml-declaration-p omit-xml-declaration-p)))
1285 (cond
1286 ((equalp (output-method output-spec) "HTML")
1287 (make-instance 'combi-sink
1288 :hax-target (make-instance 'chtml::sink
1289 :ystream ystream)
1290 :sax-target sax-target
1291 :encoding (output-encoding output-spec)))
1292 ((equalp (output-method output-spec) "TEXT")
1293 (make-text-filter sax-target))
1295 sax-target))))
1297 (defstruct template
1298 match-expression
1299 match-thunk
1300 name
1301 import-priority
1302 apply-imports-limit
1303 priority
1304 position
1305 mode
1306 mode-qname
1307 params
1308 body
1309 n-variables)
1311 (defun expression-priority (form)
1312 (let ((step (second form)))
1313 (if (and (null (cddr form))
1314 (listp step)
1315 (member (car step) '(:child :attribute))
1316 (null (cddr step)))
1317 (let ((name (second step)))
1318 (cond
1319 ((or (stringp name)
1320 (and (consp name)
1321 (or (eq (car name) :qname)
1322 (eq (car name) :processing-instruction))))
1323 0.0)
1324 ((and (consp name)
1325 (or (eq (car name) :namespace)
1326 (eq (car name) '*)))
1327 -0.25)
1329 -0.5)))
1330 0.5)))
1332 (defun valid-expression-p (expr)
1333 (cond
1334 ((atom expr) t)
1335 ((eq (first expr) :path)
1336 (every (lambda (x)
1337 (let ((filter (third x)))
1338 (or (null filter) (valid-expression-p filter))))
1339 (cdr expr)))
1340 ((eq (first expr) :variable) ;(!)
1341 nil)
1343 (every #'valid-expression-p (cdr expr)))))
1345 (defun parse-xpath (str)
1346 (handler-case
1347 (xpath:parse-xpath str)
1348 (xpath:xpath-error (c)
1349 (xslt-error "~A" c))))
1351 ;; zzz also use naive-pattern-expression here?
1352 (defun parse-key-pattern (str)
1353 (let ((parsed
1354 (mapcar #'(lambda (item)
1355 `(:path (:root :node)
1356 (:descendant-or-self *)
1357 ,@(cdr item)))
1358 (parse-pattern str))))
1359 (if (null (rest parsed))
1360 (first parsed)
1361 `(:union ,@parsed))))
1363 (defun parse-pattern (str)
1364 ;; zzz check here for anything not allowed as an XSLT pattern
1365 ;; zzz can we hack id() and key() here?
1366 (let ((form (parse-xpath str)))
1367 (unless (consp form)
1368 (xslt-error "not a valid pattern: ~A" str))
1369 (labels ((process-form (form)
1370 (cond ((eq (car form) :union)
1371 (alexandria:mappend #'process-form (rest form)))
1372 ((not (or (eq (car form) :path)
1373 (and (eq (car form) :filter)
1374 (let ((filter (second form)))
1375 (and (consp filter)
1376 (member (car filter)
1377 '(:key :id))))
1378 (equal (third form) '(:true)))
1379 (member (car form) '(:key :id))))
1380 (xslt-error "not a valid pattern: ~A ~A" str form))
1381 ((not (valid-expression-p form))
1382 (xslt-error "invalid filter"))
1383 (t (list form)))))
1384 (process-form form))))
1386 (defun naive-pattern-expression (x)
1387 (ecase (car x)
1388 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1389 ((:filter :key :id) x)))
1391 (defun compile-value-thunk (value env)
1392 (if (and (listp value) (eq (car value) 'progn))
1393 (let ((inner-thunk (compile-instruction value env)))
1394 (lambda (ctx)
1395 (apply-to-result-tree-fragment ctx inner-thunk)))
1396 (compile-xpath value env)))
1398 (defun compile-var-bindings/nointern (forms env)
1399 (loop
1400 for (name value) in forms
1401 collect (multiple-value-bind (local-name uri)
1402 (decode-qname name env nil)
1403 (list (cons local-name uri)
1404 (xslt-trace-thunk
1405 (compile-value-thunk value env)
1406 "local variable ~s = ~s" name :result)))))
1408 (defun compile-var-bindings (forms env)
1409 (loop
1410 for (cons thunk) in (compile-var-bindings/nointern forms env)
1411 for (local-name . uri) = cons
1412 collect (list cons
1413 (push-variable local-name
1415 *lexical-variable-declarations*)
1416 thunk)))
1418 (defun compile-template (<template> env position)
1419 (stp:with-attributes (match name priority mode) <template>
1420 (unless (or name match)
1421 (xslt-error "missing match in template"))
1422 (multiple-value-bind (params body-pos)
1423 (loop
1424 for i from 0
1425 for child in (stp:list-children <template>)
1426 while (namep child "param")
1427 collect (parse-param child) into params
1428 finally (return (values params i)))
1429 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1430 (param-bindings (compile-var-bindings params env))
1431 (body (parse-body <template> body-pos (mapcar #'car params)))
1432 (body-thunk (compile-instruction `(progn ,@body) env))
1433 (outer-body-thunk
1434 (xslt-trace-thunk
1435 #'(lambda (ctx)
1436 (unwind-protect
1437 (progn
1438 ;; set params that weren't initialized by apply-templates
1439 (loop for (name index param-thunk) in param-bindings
1440 when (eq (lexical-variable-value index nil) 'unbound)
1441 do (setf (lexical-variable-value index)
1442 (funcall param-thunk ctx)))
1443 (funcall body-thunk ctx))))
1444 "template: match = ~s name = ~s" match name))
1445 (n-variables (length *lexical-variable-declarations*)))
1446 (append
1447 (when name
1448 (multiple-value-bind (local-name uri)
1449 (decode-qname name env nil)
1450 (list
1451 (make-template :name (cons local-name uri)
1452 :import-priority *import-priority*
1453 :apply-imports-limit *apply-imports-limit*
1454 :params param-bindings
1455 :body outer-body-thunk
1456 :n-variables n-variables))))
1457 (when match
1458 (mapcar (lambda (expression)
1459 (let ((match-thunk
1460 (xslt-trace-thunk
1461 (compile-xpath
1462 `(xpath:xpath
1463 ,(naive-pattern-expression expression))
1464 env)
1465 "match-thunk for template (match ~s): ~s --> ~s"
1466 match expression :result))
1467 (p (if priority
1468 (parse-number:parse-number priority)
1469 (expression-priority expression))))
1470 (make-template :match-expression expression
1471 :match-thunk match-thunk
1472 :import-priority *import-priority*
1473 :apply-imports-limit *apply-imports-limit*
1474 :priority p
1475 :position position
1476 :mode-qname mode
1477 :params param-bindings
1478 :body outer-body-thunk
1479 :n-variables n-variables)))
1480 (parse-pattern match))))))))
1481 #+(or)
1482 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")