xsl:sort parameters are AVTs
[xuriella.git] / xslt.lisp
bloba43607edd3ab9afeb9457f25c604dc700984cc86
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:unescaped ((sink toplevel-text-output-sink) data)
242 (sax:characters sink data))
244 (defmethod sax:end-element ((sink toplevel-text-output-sink)
245 namespace-uri local-name qname)
246 (declare (ignore namespace-uri local-name qname))
247 (decf (textoutput-sink-depth sink)))
249 (defun invoke-with-toplevel-text-output-sink (fn)
250 (with-output-to-string (s)
251 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
254 ;;;; TEXT-FILTER
255 ;;;;
256 ;;;; A sink that passes through only text (at any level) and turns to
257 ;;;; into unescaped characters.
259 (defclass text-filter (sax:default-handler)
260 ((target :initarg :target :accessor text-filter-target)))
262 (defmethod sax:characters ((sink text-filter) data)
263 (sax:unescaped (text-filter-target sink) data))
265 (defmethod sax:unescaped ((sink text-filter) data)
266 (sax:unescaped (text-filter-target sink) data))
268 (defmethod sax:end-document ((sink text-filter))
269 (sax:end-document (text-filter-target sink)))
271 (defun make-text-filter (target)
272 (make-instance 'text-filter :target target))
275 ;;;; ESCAPER
276 ;;;;
277 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
278 ;;;; XSLT 16.4.
280 (defclass escaper (cxml:broadcast-handler)
283 (defmethod sax:unescaped ((sink escaper) data)
284 (sax:characters sink data))
286 (defun make-escaper (target)
287 (make-instance 'escaper :handlers (list target)))
290 ;;;; Names
292 (defun of-name (local-name)
293 (stp:of-name local-name *xsl*))
295 (defun namep (node local-name)
296 (and (typep node '(or stp:element stp:attribute))
297 (equal (stp:namespace-uri node) *xsl*)
298 (equal (stp:local-name node) local-name)))
301 ;;;; PARSE-STYLESHEET
303 (defstruct stylesheet
304 (modes (make-hash-table :test 'equal))
305 (global-variables (make-empty-declaration-array))
306 (output-specification (make-output-specification))
307 (strip-tests nil)
308 (named-templates (make-hash-table :test 'equal))
309 (attribute-sets (make-hash-table :test 'equal))
310 (keys (make-hash-table :test 'equal))
311 (namespace-aliases (make-hash-table :test 'equal))
312 (decimal-formats (make-hash-table :test 'equal)))
314 (defstruct mode (templates nil))
316 (defun find-mode (stylesheet local-name &optional uri)
317 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
319 (defun ensure-mode (stylesheet &optional local-name uri)
320 (or (find-mode stylesheet local-name uri)
321 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
322 (make-mode))))
324 (defun ensure-mode/qname (stylesheet qname env)
325 (if qname
326 (multiple-value-bind (local-name uri)
327 (decode-qname qname env nil)
328 (ensure-mode stylesheet local-name uri))
329 (find-mode stylesheet nil)))
331 (defun acons-namespaces (element &optional (bindings *namespaces*))
332 (map-namespace-declarations (lambda (prefix uri)
333 (push (cons prefix uri) bindings))
334 element)
335 bindings)
337 (defun find-key (name stylesheet)
338 (or (gethash name (stylesheet-keys stylesheet))
339 (xslt-error "unknown key: ~a" name)))
341 (defun make-key (match use) (cons match use))
343 (defun key-match (key) (car key))
345 (defun key-use (key) (cdr key))
347 (defun add-key (stylesheet name match use)
348 (if (gethash name (stylesheet-keys stylesheet))
349 (xslt-error "duplicate key: ~a" name)
350 (setf (gethash name (stylesheet-keys stylesheet))
351 (make-key match use))))
353 (defvar *excluded-namespaces* (list *xsl*))
354 (defvar *empty-mode*)
355 (defvar *default-mode*)
357 (defvar *xsl-include-stack* nil)
359 (defun uri-to-pathname (uri)
360 (cxml::uri-to-pathname (puri:parse-uri uri)))
362 (defun parse-stylesheet-to-stp (input uri-resolver)
363 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
364 (<transform> (stp:document-element d)))
365 (strip-stylesheet <transform>)
366 ;; FIXME: handle embedded stylesheets
367 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
368 (or (equal (stp:local-name <transform>) "transform")
369 (equal (stp:local-name <transform>) "stylesheet")))
370 (xslt-error "not a stylesheet"))
371 (dolist (include (stp:filter-children (of-name "include") <transform>))
372 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
373 (stp:base-uri include)))
374 (uri (if uri-resolver
375 (funcall uri-resolver (puri:render-uri uri nil))
376 uri))
377 (str (puri:render-uri uri nil))
378 (pathname
379 (handler-case
380 (uri-to-pathname uri)
381 (cxml:xml-parse-error (c)
382 (xslt-error "cannot find included stylesheet ~A: ~A"
383 uri c)))))
384 (with-open-file
385 (stream pathname
386 :element-type '(unsigned-byte 8)
387 :if-does-not-exist nil)
388 (unless stream
389 (xslt-error "cannot find included stylesheet ~A at ~A"
390 uri pathname))
391 (when (find str *xsl-include-stack* :test #'equal)
392 (xslt-error "recursive inclusion of ~A" uri))
393 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
394 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
395 (stp:insert-child-after <transform>
396 (stp:copy <transform>2)
397 include)
398 (stp:detach include)))))
399 <transform>))
401 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
402 (defvar *apply-imports-limit*)
403 (defvar *import-priority*)
404 (defvar *extension-namespaces*)
406 (defmacro do-toplevel ((var xpath <transform>) &body body)
407 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
409 (defun map-toplevel (fn xpath <transform>)
410 (dolist (node (list-toplevel xpath <transform>))
411 (let ((*namespaces* *namespaces*))
412 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
413 (when (xpath-protocol:node-type-p ancestor :element)
414 (setf *namespaces* (acons-namespaces ancestor))))
415 (funcall fn node))))
417 (defun list-toplevel (xpath <transform>)
418 (labels ((recurse (sub)
419 (let ((subsubs
420 (xpath-sys:pipe-of
421 (xpath:evaluate "transform|stylesheet" sub))))
422 (xpath::append-pipes
423 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
424 (xpath::mappend-pipe #'recurse subsubs)))))
425 (xpath::sort-nodes (recurse <transform>))))
427 (defmacro with-parsed-prefixes ((node env) &body body)
428 `(invoke-with-parsed-prefixes (lambda () ,@body) ,node ,env))
430 (defun invoke-with-parsed-prefixes (fn node env)
431 (unless (or (namep node "stylesheet") (namep node "transform"))
432 (setf node (stp:parent node)))
433 (let ((*excluded-namespaces* (list *xsl*))
434 (*extension-namespaces* '()))
435 (parse-exclude-result-prefixes! node env)
436 (parse-extension-element-prefixes! node env)
437 (funcall fn)))
439 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
440 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
441 (instruction-base-uri (stp:base-uri <transform>))
442 (namespaces (acons-namespaces <transform>))
443 (apply-imports-limit (1+ *import-priority*))
444 (continuations '()))
445 (let ((*namespaces* namespaces))
446 (invoke-with-parsed-prefixes (constantly t) <transform> env))
447 (macrolet ((with-specials ((&optional) &body body)
448 `(let ((*instruction-base-uri* instruction-base-uri)
449 (*namespaces* namespaces)
450 (*apply-imports-limit* apply-imports-limit))
451 ,@body)))
452 (with-specials ()
453 (do-toplevel (import "import" <transform>)
454 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
455 (stp:base-uri import))))
456 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
457 continuations))))
458 (let ((import-priority
459 (incf *import-priority*))
460 (var-cont (prepare-global-variables stylesheet <transform>)))
461 ;; delay the rest of compilation until we've seen all global
462 ;; variables:
463 (lambda ()
464 (mapc #'funcall (nreverse continuations))
465 (with-specials ()
466 (let ((*import-priority* import-priority))
467 (funcall var-cont)
468 (parse-keys! stylesheet <transform> env)
469 (parse-templates! stylesheet <transform> env)
470 (parse-output! stylesheet <transform>)
471 (parse-strip/preserve-space! stylesheet <transform> env)
472 (parse-attribute-sets! stylesheet <transform> env)
473 (parse-namespace-aliases! stylesheet <transform> env)
474 (parse-decimal-formats! stylesheet <transform> env))))))))
476 (defvar *xsl-import-stack* nil)
478 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
479 (let* ((uri (if uri-resolver
480 (funcall uri-resolver (puri:render-uri uri nil))
481 uri))
482 (str (puri:render-uri uri nil))
483 (pathname
484 (handler-case
485 (uri-to-pathname uri)
486 (cxml:xml-parse-error (c)
487 (xslt-error "cannot find imported stylesheet ~A: ~A"
488 uri c)))))
489 (with-open-file
490 (stream pathname
491 :element-type '(unsigned-byte 8)
492 :if-does-not-exist nil)
493 (unless stream
494 (xslt-error "cannot find imported stylesheet ~A at ~A"
495 uri pathname))
496 (when (find str *xsl-import-stack* :test #'equal)
497 (xslt-error "recursive inclusion of ~A" uri))
498 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
499 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
501 (defun parse-stylesheet (designator &key uri-resolver)
502 (xpath:with-namespaces ((nil #.*xsl*))
503 (let* ((*import-priority* 0)
504 (puri:*strict-parse* nil)
505 (stylesheet (make-stylesheet))
506 (env (make-instance 'lexical-xslt-environment))
507 (*excluded-namespaces* *excluded-namespaces*)
508 (*global-variable-declarations* (make-empty-declaration-array)))
509 (ensure-mode stylesheet nil)
510 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
511 ;; reverse attribute sets:
512 (let ((table (stylesheet-attribute-sets stylesheet)))
513 (maphash (lambda (k v)
514 (setf (gethash k table) (nreverse v)))
515 table))
516 ;; add default df
517 (unless (find-decimal-format "" "" stylesheet nil)
518 (setf (find-decimal-format "" "" stylesheet)
519 (make-decimal-format)))
520 stylesheet)))
522 (defun parse-attribute-sets! (stylesheet <transform> env)
523 (do-toplevel (elt "attribute-set" <transform>)
524 (with-parsed-prefixes (elt env)
525 (push (let* ((sets
526 (mapcar (lambda (qname)
527 (multiple-value-list (decode-qname qname env nil)))
528 (words
529 (stp:attribute-value elt "use-attribute-sets"))))
530 (instructions
531 (stp:map-children
532 'list
533 (lambda (child)
534 (unless (or (not (typep child 'stp:element))
535 (and (equal (stp:namespace-uri child) *xsl*)
536 (equal (stp:local-name child)
537 "attribute"))
538 (find (stp:namespace-uri child)
539 *extension-namespaces*
540 :test 'equal))
541 (xslt-error "non-attribute found in attribute set"))
542 (parse-instruction child))
543 elt))
544 (*lexical-variable-declarations*
545 (make-empty-declaration-array))
546 (thunk
547 (compile-instruction `(progn ,@instructions) env))
548 (n-variables (length *lexical-variable-declarations*)))
549 (lambda (ctx)
550 (with-stack-limit ()
551 (loop for (local-name uri nil) in sets do
552 (dolist (thunk (find-attribute-set local-name uri))
553 (funcall thunk ctx)))
554 (let ((*lexical-variable-values*
555 (make-variable-value-array n-variables)))
556 (funcall thunk ctx)))))
557 (gethash (multiple-value-bind (local-name uri)
558 (decode-qname (stp:attribute-value elt "name") env nil)
559 (cons local-name uri))
560 (stylesheet-attribute-sets stylesheet))))))
562 (defun parse-namespace-aliases! (stylesheet <transform> env)
563 (do-toplevel (elt "namespace-alias" <transform>)
564 (stp:with-attributes (stylesheet-prefix result-prefix) elt
565 (setf (gethash
566 (xpath-sys:environment-find-namespace env stylesheet-prefix)
567 (stylesheet-namespace-aliases stylesheet))
568 (xpath-sys:environment-find-namespace
570 (if (equal result-prefix "#default")
572 result-prefix))))))
574 (defun parse-decimal-formats! (stylesheet <transform> env)
575 (do-toplevel (elt "decimal-format" <transform>)
576 (stp:with-attributes (name
577 ;; strings
578 infinity
579 (nan "NaN")
580 ;; characters:
581 decimal-separator
582 grouping-separator
583 zero-digit
584 percent
585 per-mille
586 digit
587 pattern-separator
588 minus-sign)
590 (multiple-value-bind (local-name uri)
591 (if name
592 (decode-qname name env nil)
593 (values "" ""))
594 (unless (find-decimal-format local-name uri stylesheet nil)
595 (setf (find-decimal-format local-name uri stylesheet)
596 (let ((seen '()))
597 (flet ((chr (key x)
598 (when x
599 (unless (eql (length x) 1)
600 (xslt-error "not a single character: ~A" x))
601 (let ((chr (elt x 0)))
602 (when (find chr seen)
603 (xslt-error
604 "conflicting decimal format characters: ~A"
605 chr))
606 (push chr seen)
607 (list key chr))))
608 (str (key x)
609 (when x
610 (list key x))))
611 (apply #'make-decimal-format
612 (append (str :infinity infinity)
613 (str :nan nan)
614 (chr :decimal-separator decimal-separator)
615 (chr :grouping-separator grouping-separator)
616 (chr :zero-digit zero-digit)
617 (chr :percent percent)
618 (chr :per-mille per-mille)
619 (chr :digit digit)
620 (chr :pattern-separator pattern-separator)
621 (chr :minus-sign minus-sign)))))))))))
623 (defun parse-exclude-result-prefixes! (node env)
624 (stp:with-attributes (exclude-result-prefixes)
625 node
626 (dolist (prefix (words (or exclude-result-prefixes "")))
627 (if (equal prefix "#default")
628 (setf prefix nil)
629 (unless (cxml-stp-impl::nc-name-p prefix)
630 (xslt-error "invalid prefix: ~A" prefix)))
631 (push (or (xpath-sys:environment-find-namespace env prefix)
632 (xslt-error "namespace not found: ~A" prefix))
633 *excluded-namespaces*))))
635 (defun parse-extension-element-prefixes! (node env)
636 (stp:with-attributes (extension-element-prefixes)
637 node
638 (dolist (prefix (words (or extension-element-prefixes "")))
639 (if (equal prefix "#default")
640 (setf prefix nil)
641 (unless (cxml-stp-impl::nc-name-p prefix)
642 (xslt-error "invalid prefix: ~A" prefix)))
643 (let ((uri
644 (or (xpath-sys:environment-find-namespace env prefix)
645 (xslt-error "namespace not found: ~A" prefix))))
646 (unless (equal uri *xsl*)
647 (push uri *extension-namespaces*)
648 (push uri *excluded-namespaces*))))))
650 (defun parse-strip/preserve-space! (stylesheet <transform> env)
651 (xpath:with-namespaces ((nil #.*xsl*))
652 (do-toplevel (elt "strip-space|preserve-space" <transform>)
653 (let ((*namespaces* (acons-namespaces elt))
654 (mode
655 (if (equal (stp:local-name elt) "strip-space")
656 :strip
657 :preserve)))
658 (dolist (name-test (words (stp:attribute-value elt "elements")))
659 (let* ((pos (search ":*" name-test))
660 (test-function
661 (cond
662 ((eql pos (- (length name-test) 2))
663 (let* ((prefix (subseq name-test 0 pos))
664 (name-test-uri
665 (xpath-sys:environment-find-namespace env prefix)))
666 (unless (xpath::nc-name-p prefix)
667 (xslt-error "not an NCName: ~A" prefix))
668 (lambda (local-name uri)
669 (declare (ignore local-name))
670 (if (equal uri name-test-uri)
671 mode
672 nil))))
673 ((equal name-test "*")
674 (lambda (local-name uri)
675 (declare (ignore local-name uri))
676 mode))
678 (multiple-value-bind (name-test-local-name name-test-uri)
679 (decode-qname name-test env nil)
680 (lambda (local-name uri)
681 (if (and (equal local-name name-test-local-name)
682 (equal uri name-test-uri))
683 mode
684 nil)))))))
685 (push test-function (stylesheet-strip-tests stylesheet))))))))
687 (defstruct (output-specification
688 (:conc-name "OUTPUT-"))
689 method
690 indent
691 omit-xml-declaration
692 encoding
693 doctype-system
694 doctype-public)
696 (defun parse-output! (stylesheet <transform>)
697 (dolist (<output> (list-toplevel "output" <transform>))
698 (let ((spec (stylesheet-output-specification stylesheet)))
699 (stp:with-attributes ( ;; version
700 method
701 indent
702 encoding
703 ;;; media-type
704 doctype-system
705 doctype-public
706 omit-xml-declaration
707 ;;; standalone
708 ;;; cdata-section-elements
710 <output>
711 (when method
712 (setf (output-method spec) method))
713 (when indent
714 (setf (output-indent spec) indent))
715 (when encoding
716 (setf (output-encoding spec) encoding))
717 (when doctype-system
718 (setf (output-doctype-system spec) doctype-system))
719 (when doctype-public
720 (setf (output-doctype-public spec) doctype-public))
721 (when omit-xml-declaration
722 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
723 ;;; (when cdata-section-elements
724 ;;; (setf (output-cdata-section-elements spec)
725 ;;; (concatenate 'string
726 ;;; (output-cdata-section-elements spec)
727 ;;; " "
728 ;;; cdata-section-elements)))
729 ))))
731 (defun make-empty-declaration-array ()
732 (make-array 1 :fill-pointer 0 :adjustable t))
734 (defun make-variable-value-array (n-lexical-variables)
735 (make-array n-lexical-variables :initial-element 'unbound))
737 (defun compile-global-variable (<variable> env) ;; also for <param>
738 (stp:with-attributes (name select) <variable>
739 (when (and select (stp:list-children <variable>))
740 (xslt-error "variable with select and body"))
741 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
742 (inner (cond
743 (select
744 (compile-xpath select env))
745 ((stp:list-children <variable>)
746 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
747 (inner-thunk (compile-instruction inner-sexpr env)))
748 (lambda (ctx)
749 (apply-to-result-tree-fragment ctx inner-thunk))))
751 (lambda (ctx)
752 (declare (ignore ctx))
753 ""))))
754 (n-lexical-variables (length *lexical-variable-declarations*)))
755 (xslt-trace-thunk
756 (lambda (ctx)
757 (let* ((*lexical-variable-values*
758 (make-variable-value-array n-lexical-variables)))
759 (funcall inner ctx)))
760 "global ~s (~s) = ~s" name select :result))))
762 (defstruct (variable-information
763 (:constructor make-variable)
764 (:conc-name "VARIABLE-"))
765 index
766 thunk
767 local-name
769 param-p
770 thunk-setter)
772 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
773 (let* ((*namespaces* (acons-namespaces <variable>))
774 (instruction-base-uri (stp:base-uri <variable>))
775 (*instruction-base-uri* instruction-base-uri)
776 (*excluded-namespaces* (list *xsl*))
777 (*extension-namespaces* '())
778 (qname (stp:attribute-value <variable> "name")))
779 (with-parsed-prefixes (<variable> global-env)
780 (unless qname
781 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
782 (multiple-value-bind (local-name uri)
783 (decode-qname qname global-env nil)
784 ;; For the normal compilation environment of templates, install it
785 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
786 (let ((index (intern-global-variable local-name uri)))
787 ;; For the evaluation of a global variable itself, build a thunk
788 ;; that lazily resolves other variables, stored into
789 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
790 (let* ((value-thunk :unknown)
791 (global-variable-thunk
792 (lambda (ctx)
793 (let ((v (global-variable-value index nil)))
794 (when (eq v 'seen)
795 (xslt-error "recursive variable definition"))
796 (cond
797 ((eq v 'unbound)
798 (setf (global-variable-value index) 'seen)
799 (setf (global-variable-value index)
800 (funcall value-thunk ctx)))
802 v)))))
803 (excluded-namespaces *excluded-namespaces*)
804 (extension-namespaces *extension-namespaces*)
805 (thunk-setter
806 (lambda ()
807 (let ((*instruction-base-uri* instruction-base-uri)
808 (*excluded-namespaces* excluded-namespaces)
809 (*extension-namespaces* extension-namespaces))
810 (setf value-thunk
811 (compile-global-variable <variable> global-env))))))
812 (setf (gethash (cons local-name uri)
813 (initial-global-variable-thunks global-env))
814 global-variable-thunk)
815 (make-variable :index index
816 :local-name local-name
817 :uri uri
818 :thunk global-variable-thunk
819 :param-p (namep <variable> "param")
820 :thunk-setter thunk-setter)))))))
822 (defun parse-keys! (stylesheet <transform> env)
823 (xpath:with-namespaces ((nil #.*xsl*))
824 (do-toplevel (<key> "key" <transform>)
825 (let ((*instruction-base-uri* (stp:base-uri <key>)))
826 (stp:with-attributes (name match use) <key>
827 (unless name (xslt-error "key name attribute not specified"))
828 (unless match (xslt-error "key match attribute not specified"))
829 (unless use (xslt-error "key use attribute not specified"))
830 (multiple-value-bind (local-name uri)
831 (decode-qname name env nil)
832 (add-key stylesheet
833 (cons local-name uri)
834 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
835 (compile-xpath use env))))))))
837 (defun prepare-global-variables (stylesheet <transform>)
838 (xpath:with-namespaces ((nil #.*xsl*))
839 (let* ((table (make-hash-table :test 'equal))
840 (global-env (make-instance 'global-variable-environment
841 :initial-global-variable-thunks table))
842 (specs '()))
843 (do-toplevel (<variable> "variable|param" <transform>)
844 (let ((var (parse-global-variable! <variable> global-env)))
845 (xslt-trace "parsing global variable ~s (uri ~s)"
846 (variable-local-name var)
847 (variable-uri var))
848 (when (find var
849 specs
850 :test (lambda (a b)
851 (and (equal (variable-local-name a)
852 (variable-local-name b))
853 (equal (variable-uri a)
854 (variable-uri b)))))
855 (xslt-error "duplicate definition for global variable ~A"
856 (variable-local-name var)))
857 (push var specs)))
858 (setf specs (nreverse specs))
859 (lambda ()
860 ;; now that the global environment knows about all variables, run the
861 ;; thunk setters to perform their compilation
862 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
863 (let ((table (stylesheet-global-variables stylesheet))
864 (newlen (length *global-variable-declarations*)))
865 (adjust-array table newlen :fill-pointer newlen)
866 (dolist (spec specs)
867 (setf (elt table (variable-index spec)) spec)))))))
869 (defun parse-templates! (stylesheet <transform> env)
870 (let ((i 0))
871 (do-toplevel (<template> "template" <transform>)
872 (let ((*namespaces* (acons-namespaces <template>))
873 (*instruction-base-uri* (stp:base-uri <template>)))
874 (with-parsed-prefixes (<template> env)
875 (dolist (template (compile-template <template> env i))
876 (let ((name (template-name template)))
877 (if name
878 (let* ((table (stylesheet-named-templates stylesheet))
879 (head (car (gethash name table))))
880 (when (and head (eql (template-import-priority head)
881 (template-import-priority template)))
882 ;; fixme: is this supposed to be a run-time error?
883 (xslt-error "conflicting templates for ~A" name))
884 (push template (gethash name table)))
885 (let ((mode (ensure-mode/qname stylesheet
886 (template-mode-qname template)
887 env)))
888 (setf (template-mode template) mode)
889 (push template (mode-templates mode))))))))
890 (incf i))))
893 ;;;; APPLY-STYLESHEET
895 (defvar *stylesheet*)
897 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
899 (defun unalias-uri (uri)
900 (let ((result
901 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
902 uri)))
903 (check-type result string)
904 result))
906 (defstruct (parameter
907 (:constructor make-parameter (value local-name &optional uri)))
908 (uri "")
909 local-name
910 value)
912 (defun find-parameter-value (local-name uri parameters)
913 (dolist (p parameters)
914 (when (and (equal (parameter-local-name p) local-name)
915 (equal (parameter-uri p) uri))
916 (return (parameter-value p)))))
918 (defvar *uri-resolver*)
920 (defun parse-allowing-microsoft-bom (pathname handler)
921 (with-open-file (s pathname :element-type '(unsigned-byte 8))
922 (unless (and (eql (read-byte s nil) #xef)
923 (eql (read-byte s nil) #xbb)
924 (eql (read-byte s nil) #xbf))
925 (file-position s 0))
926 (cxml:parse s handler)))
928 (defvar *documents*)
930 (defun %document (uri-string base-uri)
931 (let* ((absolute-uri
932 (puri:merge-uris uri-string (or base-uri "")))
933 (resolved-uri
934 (if *uri-resolver*
935 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
936 absolute-uri))
937 (pathname
938 (handler-case
939 (uri-to-pathname resolved-uri)
940 (cxml:xml-parse-error (c)
941 (xslt-error "cannot find referenced document ~A: ~A"
942 resolved-uri c))))
943 (xpath-root-node
944 (or (gethash pathname *documents*)
945 (setf (gethash pathname *documents*)
946 (make-whitespace-stripper
947 (handler-case
948 (parse-allowing-microsoft-bom pathname
949 (stp:make-builder))
950 ((or file-error cxml:xml-parse-error) (c)
951 (xslt-error "cannot parse referenced document ~A: ~A"
952 pathname c)))
953 (stylesheet-strip-tests *stylesheet*))))))
954 (when (puri:uri-fragment absolute-uri)
955 (xslt-error "use of fragment identifiers in document() not supported"))
956 xpath-root-node))
958 (xpath-sys:define-extension xslt *xsl*)
960 (defun document-base-uri (node)
961 (xpath-protocol:base-uri
962 (cond
963 ((xpath-protocol:node-type-p node :document)
964 (xpath::find-in-pipe-if
965 (lambda (x)
966 (xpath-protocol:node-type-p x :element))
967 (xpath-protocol:child-pipe node)))
968 ((xpath-protocol:node-type-p node :element)
969 node)
971 (xpath-protocol:parent-node node)))))
973 (xpath-sys:define-xpath-function/lazy
974 xslt :document
975 (object &optional node-set)
976 (let ((instruction-base-uri *instruction-base-uri*))
977 (lambda (ctx)
978 (let* ((object (funcall object ctx))
979 (node-set (and node-set (funcall node-set ctx)))
980 (base-uri
981 (if node-set
982 (document-base-uri (xpath::textually-first-node node-set))
983 instruction-base-uri)))
984 (xpath-sys:make-node-set
985 (if (xpath:node-set-p object)
986 (xpath:map-node-set->list
987 (lambda (node)
988 (%document (xpath:string-value node)
989 (if node-set
990 base-uri
991 (document-base-uri node))))
992 object)
993 (list (%document (xpath:string-value object) base-uri))))))))
995 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
996 (let ((namespaces *namespaces*))
997 (lambda (ctx)
998 (let* ((qname (xpath:string-value (funcall name ctx)))
999 (object (funcall object ctx))
1000 (expanded-name
1001 (multiple-value-bind (local-name uri)
1002 (decode-qname/runtime qname namespaces nil)
1003 (cons local-name uri)))
1004 (key (find-key expanded-name *stylesheet*)))
1005 (labels ((get-by-key (value)
1006 (let ((value (xpath:string-value value)))
1007 (xpath::filter-pipe
1008 #'(lambda (node)
1009 (let ((uses
1010 (xpath:evaluate-compiled (key-use key) node)))
1011 (if (xpath:node-set-p uses)
1012 (xpath::find-in-pipe
1013 value
1014 (xpath-sys:pipe-of uses)
1015 :key #'xpath:string-value
1016 :test #'equal)
1017 (equal value (xpath:string-value uses)))))
1018 (xpath-sys:pipe-of
1019 (xpath:node-set-value
1020 (xpath:evaluate-compiled (key-match key) ctx)))))))
1021 (xpath-sys:make-node-set
1022 (xpath::sort-pipe
1023 (if (xpath:node-set-p object)
1024 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1025 (get-by-key object)))))))))
1027 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1029 (xpath-sys:define-xpath-function/lazy xslt :current ()
1030 #'(lambda (ctx)
1031 (xpath-sys:make-node-set
1032 (xpath-sys:make-pipe
1033 (xpath:context-starting-node ctx)
1034 nil))))
1036 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1037 #'(lambda (ctx)
1038 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1039 (funcall name ctx))
1040 "")))
1042 (defun %get-node-id (node)
1043 (when (xpath:node-set-p node)
1044 (setf node (xpath::textually-first-node node)))
1045 (when node
1046 (let ((id (xpath-sys:get-node-id node))
1047 (highest-base-uri
1048 (loop
1049 for parent = node then next
1050 for next = (xpath-protocol:parent-node parent)
1051 for this-base-uri = (xpath-protocol:base-uri parent)
1052 for highest-base-uri = (if (plusp (length this-base-uri))
1053 this-base-uri
1054 highest-base-uri)
1055 while next
1056 finally (return highest-base-uri))))
1057 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1058 ;; checked only if everything else matches.
1060 ;; This might be pointless premature optimization, but I like the idea :-)
1061 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1063 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1064 (if node-set-thunk
1065 #'(lambda (ctx)
1066 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1067 #'(lambda (ctx)
1068 (%get-node-id (xpath:context-node ctx)))))
1070 (declaim (special *available-instructions*))
1072 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1073 (let ((namespaces *namespaces*))
1074 #'(lambda (ctx)
1075 (let ((qname (funcall qname ctx)))
1076 (multiple-value-bind (local-name uri)
1077 (decode-qname/runtime qname namespaces nil)
1078 (and (equal uri *xsl*)
1079 (gethash local-name *available-instructions*)
1080 t))))))
1082 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1083 (let ((namespaces *namespaces*))
1084 #'(lambda (ctx)
1085 (let ((qname (funcall qname ctx)))
1086 (multiple-value-bind (local-name uri)
1087 (decode-qname/runtime qname namespaces nil)
1088 (and (zerop (length uri))
1089 (or (xpath-sys:find-xpath-function local-name *xsl*)
1090 (xpath-sys:find-xpath-function local-name uri))
1091 t))))))
1093 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1094 (let ((namespaces *namespaces*))
1095 (lambda (ctx)
1096 (let ((qname (funcall qname ctx)))
1097 (multiple-value-bind (local-name uri)
1098 (decode-qname/runtime qname namespaces nil)
1099 (if (equal uri *xsl*)
1100 (cond
1101 ((equal local-name "version")
1102 "1")
1103 ((equal local-name "vendor")
1104 "Xuriella")
1105 ((equal local-name "vendor-uri")
1106 "http://repo.or.cz/w/xuriella.git")
1108 ""))
1109 ""))))))
1111 (defun apply-stylesheet
1112 (stylesheet source-designator
1113 &key output parameters uri-resolver navigator)
1114 (when (typep stylesheet 'xml-designator)
1115 (setf stylesheet (parse-stylesheet stylesheet)))
1116 (invoke-with-output-sink
1117 (lambda ()
1118 (handler-case*
1119 (let* ((*documents* (make-hash-table :test 'equal))
1120 (xpath:*navigator* (or navigator :default-navigator))
1121 (puri:*strict-parse* nil)
1122 (*stylesheet* stylesheet)
1123 (*empty-mode* (make-mode))
1124 (*default-mode* (find-mode stylesheet nil))
1125 (global-variable-specs
1126 (stylesheet-global-variables stylesheet))
1127 (*global-variable-values*
1128 (make-variable-value-array (length global-variable-specs)))
1129 (*uri-resolver* uri-resolver)
1130 (source-document
1131 (if (typep source-designator 'xml-designator)
1132 (cxml:parse source-designator (stp:make-builder))
1133 source-designator))
1134 (xpath-root-node
1135 (make-whitespace-stripper
1136 source-document
1137 (stylesheet-strip-tests stylesheet)))
1138 (ctx (xpath:make-context xpath-root-node)))
1139 (when (pathnamep source-designator)
1140 (setf (gethash source-designator *documents*) xpath-root-node))
1141 (map nil
1142 (lambda (spec)
1143 (when (variable-param-p spec)
1144 (let ((value
1145 (find-parameter-value (variable-local-name spec)
1146 (variable-uri spec)
1147 parameters)))
1148 (when value
1149 (setf (global-variable-value (variable-index spec))
1150 value)))))
1151 global-variable-specs)
1152 (map nil
1153 (lambda (spec)
1154 (funcall (variable-thunk spec) ctx))
1155 global-variable-specs)
1156 ;; zzz we wouldn't have to mask float traps here if we used the
1157 ;; XPath API properly. Unfortunately I've been using FUNCALL
1158 ;; everywhere instead of EVALUATE, so let's paper over that
1159 ;; at a central place to be sure:
1160 (xpath::with-float-traps-masked ()
1161 (apply-templates ctx :mode *default-mode*)))
1162 (xpath:xpath-error (c)
1163 (xslt-error "~A" c))))
1164 (stylesheet-output-specification stylesheet)
1165 output))
1167 (defun find-attribute-set (local-name uri)
1168 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1169 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1171 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1172 (when sort-predicate
1173 (setf list
1174 (mapcar #'xpath:context-node
1175 (stable-sort (contextify-node-list list)
1176 sort-predicate))))
1177 (let* ((n (length list))
1178 (s/d (lambda () n)))
1179 (loop
1180 for i from 1
1181 for child in list
1183 (apply-templates (xpath:make-context child s/d i)
1184 :param-bindings param-bindings
1185 :mode mode))))
1187 (defvar *stack-limit* 200)
1189 (defun invoke-with-stack-limit (fn)
1190 (let ((*stack-limit* (1- *stack-limit*)))
1191 (unless (plusp *stack-limit*)
1192 (xslt-error "*stack-limit* reached; stack overflow"))
1193 (funcall fn)))
1195 (defun invoke-template (ctx template param-bindings)
1196 (let ((*lexical-variable-values*
1197 (make-variable-value-array (template-n-variables template))))
1198 (with-stack-limit ()
1199 (loop
1200 for (name-cons value) in param-bindings
1201 for (nil index nil) = (find name-cons
1202 (template-params template)
1203 :test #'equal
1204 :key #'car)
1206 (when index
1207 (setf (lexical-variable-value index) value)))
1208 (funcall (template-body template) ctx))))
1210 (defun apply-default-templates (ctx mode)
1211 (let ((node (xpath:context-node ctx)))
1212 (cond
1213 ((or (xpath-protocol:node-type-p node :processing-instruction)
1214 (xpath-protocol:node-type-p node :comment)))
1215 ((or (xpath-protocol:node-type-p node :text)
1216 (xpath-protocol:node-type-p node :attribute))
1217 (write-text (xpath-protocol:node-text node)))
1219 (apply-templates/list
1220 (xpath::force
1221 (xpath-protocol:child-pipe node))
1222 :mode mode)))))
1224 (defvar *apply-imports*)
1226 (defun apply-applicable-templates (ctx templates param-bindings finally)
1227 (labels ((apply-imports (&optional actual-param-bindings)
1228 (if templates
1229 (let* ((this (pop templates))
1230 (low (template-apply-imports-limit this))
1231 (high (template-import-priority this)))
1232 (setf templates
1233 (remove-if-not
1234 (lambda (x)
1235 (<= low (template-import-priority x) high))
1236 templates))
1237 (invoke-template ctx this actual-param-bindings))
1238 (funcall finally))))
1239 (let ((*apply-imports* #'apply-imports))
1240 (apply-imports param-bindings))))
1242 (defun apply-templates (ctx &key param-bindings mode)
1243 (apply-applicable-templates ctx
1244 (find-templates ctx (or mode *default-mode*))
1245 param-bindings
1246 (lambda ()
1247 (apply-default-templates ctx mode))))
1249 (defun call-template (ctx name &optional param-bindings)
1250 (apply-applicable-templates ctx
1251 (find-named-templates name)
1252 param-bindings
1253 (lambda ()
1254 (error "cannot find named template: ~s"
1255 name))))
1257 (defun find-templates (ctx mode)
1258 (let* ((matching-candidates
1259 (remove-if-not (lambda (template)
1260 (template-matches-p template ctx))
1261 (mode-templates mode)))
1262 (npriorities
1263 (if matching-candidates
1264 (1+ (reduce #'max
1265 matching-candidates
1266 :key #'template-import-priority))
1268 (priority-groups (make-array npriorities :initial-element nil)))
1269 (dolist (template matching-candidates)
1270 (push template
1271 (elt priority-groups (template-import-priority template))))
1272 (loop
1273 for i from (1- npriorities) downto 0
1274 for group = (elt priority-groups i)
1275 for template = (maximize #'template< group)
1276 when template
1277 collect template)))
1279 (defun find-named-templates (name)
1280 (gethash name (stylesheet-named-templates *stylesheet*)))
1282 (defun template< (a b) ;assuming same import priority
1283 (let ((p (template-priority a))
1284 (q (template-priority b)))
1285 (cond
1286 ((< p q) t)
1287 ((> p q) nil)
1289 (xslt-cerror "conflicting templates:~_~A,~_~A"
1290 (template-match-expression a)
1291 (template-match-expression b))
1292 (< (template-position a) (template-position b))))))
1294 (defun maximize (< things)
1295 (when things
1296 (let ((max (car things)))
1297 (dolist (other (cdr things))
1298 (when (funcall < max other)
1299 (setf max other)))
1300 max)))
1302 (defun template-matches-p (template ctx)
1303 (find (xpath:context-node ctx)
1304 (xpath:all-nodes (funcall (template-match-thunk template) ctx))
1305 :test #'xpath-protocol:node-equal))
1307 (defun invoke-with-output-sink (fn output-spec output)
1308 (etypecase output
1309 (pathname
1310 (with-open-file (s output
1311 :direction :output
1312 :element-type '(unsigned-byte 8)
1313 :if-exists :rename-and-delete)
1314 (invoke-with-output-sink fn output-spec s)))
1315 ((or stream null)
1316 (invoke-with-output-sink fn
1317 output-spec
1318 (make-output-sink output-spec output)))
1319 ((or hax:abstract-handler sax:abstract-handler)
1320 (with-xml-output output
1321 (when (typep output '(or combi-sink auto-detect-sink))
1322 (sax:start-dtd output
1323 :autodetect-me-please
1324 (output-doctype-public output-spec)
1325 (output-doctype-system output-spec)))
1326 (funcall fn)))))
1328 (defun make-output-sink (output-spec stream)
1329 (let* ((ystream
1330 (if stream
1331 (let ((et (stream-element-type stream)))
1332 (cond
1333 ((or (null et) (subtypep et '(unsigned-byte 8)))
1334 (runes:make-octet-stream-ystream stream))
1335 ((subtypep et 'character)
1336 (runes:make-character-stream-ystream stream))))
1337 (runes:make-rod-ystream)))
1338 (omit-xml-declaration-p
1339 (equal (output-omit-xml-declaration output-spec) "yes"))
1340 (sax-target
1341 (make-instance 'cxml::sink
1342 :ystream ystream
1343 :omit-xml-declaration-p omit-xml-declaration-p)))
1344 (flet ((make-combi-sink ()
1345 (make-instance 'combi-sink
1346 :hax-target (make-instance 'chtml::sink
1347 :ystream ystream)
1348 :sax-target sax-target
1349 :encoding (output-encoding output-spec))))
1350 (let ((method-key
1351 (cond
1352 ((equalp (output-method output-spec) "HTML") :html)
1353 ((equalp (output-method output-spec) "TEXT") :text)
1354 ((equalp (output-method output-spec) "XML") :xml)
1355 (t nil))))
1356 (cond
1357 ((and (eq method-key :html)
1358 (null (output-doctype-system output-spec))
1359 (null (output-doctype-public output-spec)))
1360 (make-combi-sink))
1361 ((eq method-key :text)
1362 (make-text-filter sax-target))
1363 ((and (eq method-key :xml)
1364 (null (output-doctype-system output-spec)))
1365 sax-target)
1367 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1369 (defstruct template
1370 match-expression
1371 match-thunk
1372 name
1373 import-priority
1374 apply-imports-limit
1375 priority
1376 position
1377 mode
1378 mode-qname
1379 params
1380 body
1381 n-variables)
1383 (defun expression-priority (form)
1384 (let ((step (second form)))
1385 (if (and (null (cddr form))
1386 (listp step)
1387 (member (car step) '(:child :attribute))
1388 (null (cddr step)))
1389 (let ((name (second step)))
1390 (cond
1391 ((or (stringp name)
1392 (and (consp name)
1393 (or (eq (car name) :qname)
1394 (eq (car name) :processing-instruction))))
1395 0.0)
1396 ((and (consp name)
1397 (or (eq (car name) :namespace)
1398 (eq (car name) '*)))
1399 -0.25)
1401 -0.5)))
1402 0.5)))
1404 (defun valid-expression-p (expr)
1405 (cond
1406 ((atom expr) t)
1407 ((eq (first expr) :path)
1408 (every (lambda (x)
1409 (let ((filter (third x)))
1410 (or (null filter) (valid-expression-p filter))))
1411 (cdr expr)))
1412 ((eq (first expr) :variable) ;(!)
1413 nil)
1415 (every #'valid-expression-p (cdr expr)))))
1417 (defun parse-xpath (str)
1418 (handler-case
1419 (xpath:parse-xpath str)
1420 (xpath:xpath-error (c)
1421 (xslt-error "~A" c))))
1423 ;; zzz also use naive-pattern-expression here?
1424 (defun parse-key-pattern (str)
1425 (let ((parsed
1426 (mapcar #'(lambda (item)
1427 `(:path (:root :node)
1428 (:descendant-or-self *)
1429 ,@(cdr item)))
1430 (parse-pattern str))))
1431 (if (null (rest parsed))
1432 (first parsed)
1433 `(:union ,@parsed))))
1435 (defun parse-pattern (str)
1436 ;; zzz check here for anything not allowed as an XSLT pattern
1437 ;; zzz can we hack id() and key() here?
1438 (let ((form (parse-xpath str)))
1439 (unless (consp form)
1440 (xslt-error "not a valid pattern: ~A" str))
1441 (labels ((process-form (form)
1442 (cond ((eq (car form) :union)
1443 (alexandria:mappend #'process-form (rest form)))
1444 ((not (or (eq (car form) :path)
1445 (and (eq (car form) :filter)
1446 (let ((filter (second form)))
1447 (and (consp filter)
1448 (member (car filter)
1449 '(:key :id))))
1450 (equal (third form) '(:true)))
1451 (member (car form) '(:key :id))))
1452 (xslt-error "not a valid pattern: ~A ~A" str form))
1453 ((not (valid-expression-p form))
1454 (xslt-error "invalid filter"))
1455 (t (list form)))))
1456 (process-form form))))
1458 (defun naive-pattern-expression (x)
1459 (ecase (car x)
1460 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1461 ((:filter :key :id) x)))
1463 (defun compile-value-thunk (value env)
1464 (if (and (listp value) (eq (car value) 'progn))
1465 (let ((inner-thunk (compile-instruction value env)))
1466 (lambda (ctx)
1467 (apply-to-result-tree-fragment ctx inner-thunk)))
1468 (compile-xpath value env)))
1470 (defun compile-var-bindings/nointern (forms env)
1471 (loop
1472 for (name value) in forms
1473 collect (multiple-value-bind (local-name uri)
1474 (decode-qname name env nil)
1475 (list (cons local-name uri)
1476 (xslt-trace-thunk
1477 (compile-value-thunk value env)
1478 "local variable ~s = ~s" name :result)))))
1480 (defun compile-var-bindings (forms env)
1481 (loop
1482 for (cons thunk) in (compile-var-bindings/nointern forms env)
1483 for (local-name . uri) = cons
1484 collect (list cons
1485 (push-variable local-name
1487 *lexical-variable-declarations*)
1488 thunk)))
1490 (defun compile-template (<template> env position)
1491 (stp:with-attributes (match name priority mode) <template>
1492 (unless (or name match)
1493 (xslt-error "missing match in template"))
1494 (multiple-value-bind (params body-pos)
1495 (loop
1496 for i from 0
1497 for child in (stp:list-children <template>)
1498 while (namep child "param")
1499 collect (parse-param child) into params
1500 finally (return (values params i)))
1501 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1502 (param-bindings (compile-var-bindings params env))
1503 (body (parse-body <template> body-pos (mapcar #'car params)))
1504 (body-thunk (compile-instruction `(progn ,@body) env))
1505 (outer-body-thunk
1506 (xslt-trace-thunk
1507 #'(lambda (ctx)
1508 (unwind-protect
1509 (progn
1510 ;; set params that weren't initialized by apply-templates
1511 (loop for (name index param-thunk) in param-bindings
1512 when (eq (lexical-variable-value index nil) 'unbound)
1513 do (setf (lexical-variable-value index)
1514 (funcall param-thunk ctx)))
1515 (funcall body-thunk ctx))))
1516 "template: match = ~s name = ~s" match name))
1517 (n-variables (length *lexical-variable-declarations*)))
1518 (append
1519 (when name
1520 (multiple-value-bind (local-name uri)
1521 (decode-qname name env nil)
1522 (list
1523 (make-template :name (cons local-name uri)
1524 :import-priority *import-priority*
1525 :apply-imports-limit *apply-imports-limit*
1526 :params param-bindings
1527 :body outer-body-thunk
1528 :n-variables n-variables))))
1529 (when match
1530 (mapcar (lambda (expression)
1531 (let ((match-thunk
1532 (xslt-trace-thunk
1533 (compile-xpath
1534 `(xpath:xpath
1535 ,(naive-pattern-expression expression))
1536 env)
1537 "match-thunk for template (match ~s): ~s --> ~s"
1538 match expression :result))
1539 (p (if priority
1540 (parse-number:parse-number priority)
1541 (expression-priority expression))))
1542 (make-template :match-expression expression
1543 :match-thunk match-thunk
1544 :import-priority *import-priority*
1545 :apply-imports-limit *apply-imports-limit*
1546 :priority p
1547 :position position
1548 :mode-qname mode
1549 :params param-bindings
1550 :body outer-body-thunk
1551 :n-variables n-variables)))
1552 (parse-pattern match))))))))
1553 #+(or)
1554 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")