Forwards compatible processing: Unknown instruction elements
[xuriella.git] / xslt.lisp
blob2df6990ca4b2ea32cb7e07e0e0f845dc9e688336
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*)
405 (defvar *forwards-compatible-p*)
407 (defmacro do-toplevel ((var xpath <transform>) &body body)
408 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
410 (defun map-toplevel (fn xpath <transform>)
411 (dolist (node (list-toplevel xpath <transform>))
412 (let ((*namespaces* *namespaces*))
413 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
414 (when (xpath-protocol:node-type-p ancestor :element)
415 (setf *namespaces* (acons-namespaces ancestor))))
416 (funcall fn node))))
418 (defun list-toplevel (xpath <transform>)
419 (labels ((recurse (sub)
420 (let ((subsubs
421 (xpath-sys:pipe-of
422 (xpath:evaluate "transform|stylesheet" sub))))
423 (xpath::append-pipes
424 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
425 (xpath::mappend-pipe #'recurse subsubs)))))
426 (xpath::sort-nodes (recurse <transform>))))
428 (defmacro with-import-magic ((node env) &body body)
429 `(invoke-with-import-magic (lambda () ,@body) ,node ,env))
431 (defun invoke-with-import-magic (fn node env)
432 (unless (or (namep node "stylesheet") (namep node "transform"))
433 (setf node (stp:parent node)))
434 (let ((*excluded-namespaces* (list *xsl*))
435 (*extension-namespaces* '())
436 (*forwards-compatible-p*
437 (not (equal (stp:attribute-value node "version") "1.0"))))
438 (parse-exclude-result-prefixes! node env)
439 (parse-extension-element-prefixes! node env)
440 (funcall fn)))
442 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
443 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
444 (instruction-base-uri (stp:base-uri <transform>))
445 (namespaces (acons-namespaces <transform>))
446 (apply-imports-limit (1+ *import-priority*))
447 (continuations '()))
448 (let ((*namespaces* namespaces))
449 (invoke-with-import-magic (constantly t) <transform> env))
450 (macrolet ((with-specials ((&optional) &body body)
451 `(let ((*instruction-base-uri* instruction-base-uri)
452 (*namespaces* namespaces)
453 (*apply-imports-limit* apply-imports-limit))
454 ,@body)))
455 (with-specials ()
456 (do-toplevel (import "import" <transform>)
457 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
458 (stp:base-uri import))))
459 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
460 continuations))))
461 (let ((import-priority
462 (incf *import-priority*))
463 (var-cont (prepare-global-variables stylesheet <transform>)))
464 ;; delay the rest of compilation until we've seen all global
465 ;; variables:
466 (lambda ()
467 (mapc #'funcall (nreverse continuations))
468 (with-specials ()
469 (let ((*import-priority* import-priority))
470 (funcall var-cont)
471 (parse-keys! stylesheet <transform> env)
472 (parse-templates! stylesheet <transform> env)
473 (parse-output! stylesheet <transform>)
474 (parse-strip/preserve-space! stylesheet <transform> env)
475 (parse-attribute-sets! stylesheet <transform> env)
476 (parse-namespace-aliases! stylesheet <transform> env)
477 (parse-decimal-formats! stylesheet <transform> env))))))))
479 (defvar *xsl-import-stack* nil)
481 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
482 (let* ((uri (if uri-resolver
483 (funcall uri-resolver (puri:render-uri uri nil))
484 uri))
485 (str (puri:render-uri uri nil))
486 (pathname
487 (handler-case
488 (uri-to-pathname uri)
489 (cxml:xml-parse-error (c)
490 (xslt-error "cannot find imported stylesheet ~A: ~A"
491 uri c)))))
492 (with-open-file
493 (stream pathname
494 :element-type '(unsigned-byte 8)
495 :if-does-not-exist nil)
496 (unless stream
497 (xslt-error "cannot find imported stylesheet ~A at ~A"
498 uri pathname))
499 (when (find str *xsl-import-stack* :test #'equal)
500 (xslt-error "recursive inclusion of ~A" uri))
501 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
502 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
504 (defun parse-stylesheet (designator &key uri-resolver)
505 (xpath:with-namespaces ((nil #.*xsl*))
506 (let* ((*import-priority* 0)
507 (puri:*strict-parse* nil)
508 (stylesheet (make-stylesheet))
509 (env (make-instance 'lexical-xslt-environment))
510 (*excluded-namespaces* *excluded-namespaces*)
511 (*global-variable-declarations* (make-empty-declaration-array)))
512 (ensure-mode stylesheet nil)
513 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
514 ;; reverse attribute sets:
515 (let ((table (stylesheet-attribute-sets stylesheet)))
516 (maphash (lambda (k v)
517 (setf (gethash k table) (nreverse v)))
518 table))
519 ;; add default df
520 (unless (find-decimal-format "" "" stylesheet nil)
521 (setf (find-decimal-format "" "" stylesheet)
522 (make-decimal-format)))
523 stylesheet)))
525 (defun parse-attribute-sets! (stylesheet <transform> env)
526 (do-toplevel (elt "attribute-set" <transform>)
527 (with-import-magic (elt env)
528 (push (let* ((sets
529 (mapcar (lambda (qname)
530 (multiple-value-list (decode-qname qname env nil)))
531 (words
532 (stp:attribute-value elt "use-attribute-sets"))))
533 (instructions
534 (stp:map-children
535 'list
536 (lambda (child)
537 (unless (or (not (typep child 'stp:element))
538 (and (equal (stp:namespace-uri child) *xsl*)
539 (equal (stp:local-name child)
540 "attribute"))
541 (find (stp:namespace-uri child)
542 *extension-namespaces*
543 :test 'equal))
544 (xslt-error "non-attribute found in attribute set"))
545 (parse-instruction child))
546 elt))
547 (*lexical-variable-declarations*
548 (make-empty-declaration-array))
549 (thunk
550 (compile-instruction `(progn ,@instructions) env))
551 (n-variables (length *lexical-variable-declarations*)))
552 (lambda (ctx)
553 (with-stack-limit ()
554 (loop for (local-name uri nil) in sets do
555 (dolist (thunk (find-attribute-set local-name uri))
556 (funcall thunk ctx)))
557 (let ((*lexical-variable-values*
558 (make-variable-value-array n-variables)))
559 (funcall thunk ctx)))))
560 (gethash (multiple-value-bind (local-name uri)
561 (decode-qname (stp:attribute-value elt "name") env nil)
562 (cons local-name uri))
563 (stylesheet-attribute-sets stylesheet))))))
565 (defun parse-namespace-aliases! (stylesheet <transform> env)
566 (do-toplevel (elt "namespace-alias" <transform>)
567 (stp:with-attributes (stylesheet-prefix result-prefix) elt
568 (setf (gethash
569 (xpath-sys:environment-find-namespace env stylesheet-prefix)
570 (stylesheet-namespace-aliases stylesheet))
571 (xpath-sys:environment-find-namespace
573 (if (equal result-prefix "#default")
575 result-prefix))))))
577 (defun parse-decimal-formats! (stylesheet <transform> env)
578 (do-toplevel (elt "decimal-format" <transform>)
579 (stp:with-attributes (name
580 ;; strings
581 infinity
582 (nan "NaN")
583 ;; characters:
584 decimal-separator
585 grouping-separator
586 zero-digit
587 percent
588 per-mille
589 digit
590 pattern-separator
591 minus-sign)
593 (multiple-value-bind (local-name uri)
594 (if name
595 (decode-qname name env nil)
596 (values "" ""))
597 (unless (find-decimal-format local-name uri stylesheet nil)
598 (setf (find-decimal-format local-name uri stylesheet)
599 (let ((seen '()))
600 (flet ((chr (key x)
601 (when x
602 (unless (eql (length x) 1)
603 (xslt-error "not a single character: ~A" x))
604 (let ((chr (elt x 0)))
605 (when (find chr seen)
606 (xslt-error
607 "conflicting decimal format characters: ~A"
608 chr))
609 (push chr seen)
610 (list key chr))))
611 (str (key x)
612 (when x
613 (list key x))))
614 (apply #'make-decimal-format
615 (append (str :infinity infinity)
616 (str :nan nan)
617 (chr :decimal-separator decimal-separator)
618 (chr :grouping-separator grouping-separator)
619 (chr :zero-digit zero-digit)
620 (chr :percent percent)
621 (chr :per-mille per-mille)
622 (chr :digit digit)
623 (chr :pattern-separator pattern-separator)
624 (chr :minus-sign minus-sign)))))))))))
626 (defun parse-exclude-result-prefixes! (node env)
627 (stp:with-attributes (exclude-result-prefixes)
628 node
629 (dolist (prefix (words (or exclude-result-prefixes "")))
630 (if (equal prefix "#default")
631 (setf prefix nil)
632 (unless (cxml-stp-impl::nc-name-p prefix)
633 (xslt-error "invalid prefix: ~A" prefix)))
634 (push (or (xpath-sys:environment-find-namespace env prefix)
635 (xslt-error "namespace not found: ~A" prefix))
636 *excluded-namespaces*))))
638 (defun parse-extension-element-prefixes! (node env)
639 (stp:with-attributes (extension-element-prefixes)
640 node
641 (dolist (prefix (words (or extension-element-prefixes "")))
642 (if (equal prefix "#default")
643 (setf prefix nil)
644 (unless (cxml-stp-impl::nc-name-p prefix)
645 (xslt-error "invalid prefix: ~A" prefix)))
646 (let ((uri
647 (or (xpath-sys:environment-find-namespace env prefix)
648 (xslt-error "namespace not found: ~A" prefix))))
649 (unless (equal uri *xsl*)
650 (push uri *extension-namespaces*)
651 (push uri *excluded-namespaces*))))))
653 (defun parse-strip/preserve-space! (stylesheet <transform> env)
654 (xpath:with-namespaces ((nil #.*xsl*))
655 (do-toplevel (elt "strip-space|preserve-space" <transform>)
656 (let ((*namespaces* (acons-namespaces elt))
657 (mode
658 (if (equal (stp:local-name elt) "strip-space")
659 :strip
660 :preserve)))
661 (dolist (name-test (words (stp:attribute-value elt "elements")))
662 (let* ((pos (search ":*" name-test))
663 (test-function
664 (cond
665 ((eql pos (- (length name-test) 2))
666 (let* ((prefix (subseq name-test 0 pos))
667 (name-test-uri
668 (xpath-sys:environment-find-namespace env prefix)))
669 (unless (xpath::nc-name-p prefix)
670 (xslt-error "not an NCName: ~A" prefix))
671 (lambda (local-name uri)
672 (declare (ignore local-name))
673 (if (equal uri name-test-uri)
674 mode
675 nil))))
676 ((equal name-test "*")
677 (lambda (local-name uri)
678 (declare (ignore local-name uri))
679 mode))
681 (multiple-value-bind (name-test-local-name name-test-uri)
682 (decode-qname name-test env nil)
683 (lambda (local-name uri)
684 (if (and (equal local-name name-test-local-name)
685 (equal uri name-test-uri))
686 mode
687 nil)))))))
688 (push test-function (stylesheet-strip-tests stylesheet))))))))
690 (defstruct (output-specification
691 (:conc-name "OUTPUT-"))
692 method
693 indent
694 omit-xml-declaration
695 encoding
696 doctype-system
697 doctype-public)
699 (defun parse-output! (stylesheet <transform>)
700 (dolist (<output> (list-toplevel "output" <transform>))
701 (let ((spec (stylesheet-output-specification stylesheet)))
702 (stp:with-attributes ( ;; version
703 method
704 indent
705 encoding
706 ;;; media-type
707 doctype-system
708 doctype-public
709 omit-xml-declaration
710 ;;; standalone
711 ;;; cdata-section-elements
713 <output>
714 (when method
715 (setf (output-method spec) method))
716 (when indent
717 (setf (output-indent spec) indent))
718 (when encoding
719 (setf (output-encoding spec) encoding))
720 (when doctype-system
721 (setf (output-doctype-system spec) doctype-system))
722 (when doctype-public
723 (setf (output-doctype-public spec) doctype-public))
724 (when omit-xml-declaration
725 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
726 ;;; (when cdata-section-elements
727 ;;; (setf (output-cdata-section-elements spec)
728 ;;; (concatenate 'string
729 ;;; (output-cdata-section-elements spec)
730 ;;; " "
731 ;;; cdata-section-elements)))
732 ))))
734 (defun make-empty-declaration-array ()
735 (make-array 1 :fill-pointer 0 :adjustable t))
737 (defun make-variable-value-array (n-lexical-variables)
738 (make-array n-lexical-variables :initial-element 'unbound))
740 (defun compile-global-variable (<variable> env) ;; also for <param>
741 (stp:with-attributes (name select) <variable>
742 (when (and select (stp:list-children <variable>))
743 (xslt-error "variable with select and body"))
744 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
745 (inner (cond
746 (select
747 (compile-xpath select env))
748 ((stp:list-children <variable>)
749 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
750 (inner-thunk (compile-instruction inner-sexpr env)))
751 (lambda (ctx)
752 (apply-to-result-tree-fragment ctx inner-thunk))))
754 (lambda (ctx)
755 (declare (ignore ctx))
756 ""))))
757 (n-lexical-variables (length *lexical-variable-declarations*)))
758 (xslt-trace-thunk
759 (lambda (ctx)
760 (let* ((*lexical-variable-values*
761 (make-variable-value-array n-lexical-variables)))
762 (funcall inner ctx)))
763 "global ~s (~s) = ~s" name select :result))))
765 (defstruct (variable-information
766 (:constructor make-variable)
767 (:conc-name "VARIABLE-"))
768 index
769 thunk
770 local-name
772 param-p
773 thunk-setter)
775 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
776 (let* ((*namespaces* (acons-namespaces <variable>))
777 (instruction-base-uri (stp:base-uri <variable>))
778 (*instruction-base-uri* instruction-base-uri)
779 (*excluded-namespaces* (list *xsl*))
780 (*extension-namespaces* '())
781 (qname (stp:attribute-value <variable> "name")))
782 (with-import-magic (<variable> global-env)
783 (unless qname
784 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
785 (multiple-value-bind (local-name uri)
786 (decode-qname qname global-env nil)
787 ;; For the normal compilation environment of templates, install it
788 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
789 (let ((index (intern-global-variable local-name uri)))
790 ;; For the evaluation of a global variable itself, build a thunk
791 ;; that lazily resolves other variables, stored into
792 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
793 (let* ((value-thunk :unknown)
794 (global-variable-thunk
795 (lambda (ctx)
796 (let ((v (global-variable-value index nil)))
797 (when (eq v 'seen)
798 (xslt-error "recursive variable definition"))
799 (cond
800 ((eq v 'unbound)
801 (setf (global-variable-value index) 'seen)
802 (setf (global-variable-value index)
803 (funcall value-thunk ctx)))
805 v)))))
806 (excluded-namespaces *excluded-namespaces*)
807 (extension-namespaces *extension-namespaces*)
808 (thunk-setter
809 (lambda ()
810 (let ((*instruction-base-uri* instruction-base-uri)
811 (*excluded-namespaces* excluded-namespaces)
812 (*extension-namespaces* extension-namespaces))
813 (setf value-thunk
814 (compile-global-variable <variable> global-env))))))
815 (setf (gethash (cons local-name uri)
816 (initial-global-variable-thunks global-env))
817 global-variable-thunk)
818 (make-variable :index index
819 :local-name local-name
820 :uri uri
821 :thunk global-variable-thunk
822 :param-p (namep <variable> "param")
823 :thunk-setter thunk-setter)))))))
825 (defun parse-keys! (stylesheet <transform> env)
826 (xpath:with-namespaces ((nil #.*xsl*))
827 (do-toplevel (<key> "key" <transform>)
828 (let ((*instruction-base-uri* (stp:base-uri <key>)))
829 (stp:with-attributes (name match use) <key>
830 (unless name (xslt-error "key name attribute not specified"))
831 (unless match (xslt-error "key match attribute not specified"))
832 (unless use (xslt-error "key use attribute not specified"))
833 (multiple-value-bind (local-name uri)
834 (decode-qname name env nil)
835 (add-key stylesheet
836 (cons local-name uri)
837 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
838 (compile-xpath use env))))))))
840 (defun prepare-global-variables (stylesheet <transform>)
841 (xpath:with-namespaces ((nil #.*xsl*))
842 (let* ((table (make-hash-table :test 'equal))
843 (global-env (make-instance 'global-variable-environment
844 :initial-global-variable-thunks table))
845 (specs '()))
846 (do-toplevel (<variable> "variable|param" <transform>)
847 (let ((var (parse-global-variable! <variable> global-env)))
848 (xslt-trace "parsing global variable ~s (uri ~s)"
849 (variable-local-name var)
850 (variable-uri var))
851 (when (find var
852 specs
853 :test (lambda (a b)
854 (and (equal (variable-local-name a)
855 (variable-local-name b))
856 (equal (variable-uri a)
857 (variable-uri b)))))
858 (xslt-error "duplicate definition for global variable ~A"
859 (variable-local-name var)))
860 (push var specs)))
861 (setf specs (nreverse specs))
862 (lambda ()
863 ;; now that the global environment knows about all variables, run the
864 ;; thunk setters to perform their compilation
865 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
866 (let ((table (stylesheet-global-variables stylesheet))
867 (newlen (length *global-variable-declarations*)))
868 (adjust-array table newlen :fill-pointer newlen)
869 (dolist (spec specs)
870 (setf (elt table (variable-index spec)) spec)))))))
872 (defun parse-templates! (stylesheet <transform> env)
873 (let ((i 0))
874 (do-toplevel (<template> "template" <transform>)
875 (let ((*namespaces* (acons-namespaces <template>))
876 (*instruction-base-uri* (stp:base-uri <template>)))
877 (with-import-magic (<template> env)
878 (dolist (template (compile-template <template> env i))
879 (let ((name (template-name template)))
880 (if name
881 (let* ((table (stylesheet-named-templates stylesheet))
882 (head (car (gethash name table))))
883 (when (and head (eql (template-import-priority head)
884 (template-import-priority template)))
885 ;; fixme: is this supposed to be a run-time error?
886 (xslt-error "conflicting templates for ~A" name))
887 (push template (gethash name table)))
888 (let ((mode (ensure-mode/qname stylesheet
889 (template-mode-qname template)
890 env)))
891 (setf (template-mode template) mode)
892 (push template (mode-templates mode))))))))
893 (incf i))))
896 ;;;; APPLY-STYLESHEET
898 (defvar *stylesheet*)
900 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
902 (defun unalias-uri (uri)
903 (let ((result
904 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
905 uri)))
906 (check-type result string)
907 result))
909 (defstruct (parameter
910 (:constructor make-parameter (value local-name &optional uri)))
911 (uri "")
912 local-name
913 value)
915 (defun find-parameter-value (local-name uri parameters)
916 (dolist (p parameters)
917 (when (and (equal (parameter-local-name p) local-name)
918 (equal (parameter-uri p) uri))
919 (return (parameter-value p)))))
921 (defvar *uri-resolver*)
923 (defun parse-allowing-microsoft-bom (pathname handler)
924 (with-open-file (s pathname :element-type '(unsigned-byte 8))
925 (unless (and (eql (read-byte s nil) #xef)
926 (eql (read-byte s nil) #xbb)
927 (eql (read-byte s nil) #xbf))
928 (file-position s 0))
929 (cxml:parse s handler)))
931 (defvar *documents*)
933 (defun %document (uri-string base-uri)
934 (let* ((absolute-uri
935 (puri:merge-uris uri-string (or base-uri "")))
936 (resolved-uri
937 (if *uri-resolver*
938 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
939 absolute-uri))
940 (pathname
941 (handler-case
942 (uri-to-pathname resolved-uri)
943 (cxml:xml-parse-error (c)
944 (xslt-error "cannot find referenced document ~A: ~A"
945 resolved-uri c))))
946 (xpath-root-node
947 (or (gethash pathname *documents*)
948 (setf (gethash pathname *documents*)
949 (make-whitespace-stripper
950 (handler-case
951 (parse-allowing-microsoft-bom pathname
952 (stp:make-builder))
953 ((or file-error cxml:xml-parse-error) (c)
954 (xslt-error "cannot parse referenced document ~A: ~A"
955 pathname c)))
956 (stylesheet-strip-tests *stylesheet*))))))
957 (when (puri:uri-fragment absolute-uri)
958 (xslt-error "use of fragment identifiers in document() not supported"))
959 xpath-root-node))
961 (xpath-sys:define-extension xslt *xsl*)
963 (defun document-base-uri (node)
964 (xpath-protocol:base-uri
965 (cond
966 ((xpath-protocol:node-type-p node :document)
967 (xpath::find-in-pipe-if
968 (lambda (x)
969 (xpath-protocol:node-type-p x :element))
970 (xpath-protocol:child-pipe node)))
971 ((xpath-protocol:node-type-p node :element)
972 node)
974 (xpath-protocol:parent-node node)))))
976 (xpath-sys:define-xpath-function/lazy
977 xslt :document
978 (object &optional node-set)
979 (let ((instruction-base-uri *instruction-base-uri*))
980 (lambda (ctx)
981 (let* ((object (funcall object ctx))
982 (node-set (and node-set (funcall node-set ctx)))
983 (base-uri
984 (if node-set
985 (document-base-uri (xpath::textually-first-node node-set))
986 instruction-base-uri)))
987 (xpath-sys:make-node-set
988 (if (xpath:node-set-p object)
989 (xpath:map-node-set->list
990 (lambda (node)
991 (%document (xpath:string-value node)
992 (if node-set
993 base-uri
994 (document-base-uri node))))
995 object)
996 (list (%document (xpath:string-value object) base-uri))))))))
998 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
999 (let ((namespaces *namespaces*))
1000 (lambda (ctx)
1001 (let* ((qname (xpath:string-value (funcall name ctx)))
1002 (object (funcall object ctx))
1003 (expanded-name
1004 (multiple-value-bind (local-name uri)
1005 (decode-qname/runtime qname namespaces nil)
1006 (cons local-name uri)))
1007 (key (find-key expanded-name *stylesheet*)))
1008 (labels ((get-by-key (value)
1009 (let ((value (xpath:string-value value)))
1010 (xpath::filter-pipe
1011 #'(lambda (node)
1012 (let ((uses
1013 (xpath:evaluate-compiled (key-use key) node)))
1014 (if (xpath:node-set-p uses)
1015 (xpath::find-in-pipe
1016 value
1017 (xpath-sys:pipe-of uses)
1018 :key #'xpath:string-value
1019 :test #'equal)
1020 (equal value (xpath:string-value uses)))))
1021 (xpath-sys:pipe-of
1022 (xpath:node-set-value
1023 (xpath:evaluate-compiled (key-match key) ctx)))))))
1024 (xpath-sys:make-node-set
1025 (xpath::sort-pipe
1026 (if (xpath:node-set-p object)
1027 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1028 (get-by-key object)))))))))
1030 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1032 (xpath-sys:define-xpath-function/lazy xslt :current ()
1033 #'(lambda (ctx)
1034 (xpath-sys:make-node-set
1035 (xpath-sys:make-pipe
1036 (xpath:context-starting-node ctx)
1037 nil))))
1039 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1040 #'(lambda (ctx)
1041 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1042 (funcall name ctx))
1043 "")))
1045 (defun %get-node-id (node)
1046 (when (xpath:node-set-p node)
1047 (setf node (xpath::textually-first-node node)))
1048 (when node
1049 (let ((id (xpath-sys:get-node-id node))
1050 (highest-base-uri
1051 (loop
1052 for parent = node then next
1053 for next = (xpath-protocol:parent-node parent)
1054 for this-base-uri = (xpath-protocol:base-uri parent)
1055 for highest-base-uri = (if (plusp (length this-base-uri))
1056 this-base-uri
1057 highest-base-uri)
1058 while next
1059 finally (return highest-base-uri))))
1060 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1061 ;; checked only if everything else matches.
1063 ;; This might be pointless premature optimization, but I like the idea :-)
1064 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1066 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1067 (if node-set-thunk
1068 #'(lambda (ctx)
1069 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1070 #'(lambda (ctx)
1071 (%get-node-id (xpath:context-node ctx)))))
1073 (declaim (special *available-instructions*))
1075 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1076 (let ((namespaces *namespaces*))
1077 #'(lambda (ctx)
1078 (let ((qname (funcall qname ctx)))
1079 (multiple-value-bind (local-name uri)
1080 (decode-qname/runtime qname namespaces nil)
1081 (and (equal uri *xsl*)
1082 (gethash local-name *available-instructions*)
1083 t))))))
1085 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1086 (let ((namespaces *namespaces*))
1087 #'(lambda (ctx)
1088 (let ((qname (funcall qname ctx)))
1089 (multiple-value-bind (local-name uri)
1090 (decode-qname/runtime qname namespaces nil)
1091 (and (zerop (length uri))
1092 (or (xpath-sys:find-xpath-function local-name *xsl*)
1093 (xpath-sys:find-xpath-function local-name uri))
1094 t))))))
1096 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1097 (let ((namespaces *namespaces*))
1098 (lambda (ctx)
1099 (let ((qname (funcall qname ctx)))
1100 (multiple-value-bind (local-name uri)
1101 (decode-qname/runtime qname namespaces nil)
1102 (if (equal uri *xsl*)
1103 (cond
1104 ((equal local-name "version")
1105 "1")
1106 ((equal local-name "vendor")
1107 "Xuriella")
1108 ((equal local-name "vendor-uri")
1109 "http://repo.or.cz/w/xuriella.git")
1111 ""))
1112 ""))))))
1114 (defun apply-stylesheet
1115 (stylesheet source-designator
1116 &key output parameters uri-resolver navigator)
1117 (when (typep stylesheet 'xml-designator)
1118 (setf stylesheet (parse-stylesheet stylesheet)))
1119 (invoke-with-output-sink
1120 (lambda ()
1121 (handler-case*
1122 (let* ((*documents* (make-hash-table :test 'equal))
1123 (xpath:*navigator* (or navigator :default-navigator))
1124 (puri:*strict-parse* nil)
1125 (*stylesheet* stylesheet)
1126 (*empty-mode* (make-mode))
1127 (*default-mode* (find-mode stylesheet nil))
1128 (global-variable-specs
1129 (stylesheet-global-variables stylesheet))
1130 (*global-variable-values*
1131 (make-variable-value-array (length global-variable-specs)))
1132 (*uri-resolver* uri-resolver)
1133 (source-document
1134 (if (typep source-designator 'xml-designator)
1135 (cxml:parse source-designator (stp:make-builder))
1136 source-designator))
1137 (xpath-root-node
1138 (make-whitespace-stripper
1139 source-document
1140 (stylesheet-strip-tests stylesheet)))
1141 (ctx (xpath:make-context xpath-root-node)))
1142 (when (pathnamep source-designator)
1143 (setf (gethash source-designator *documents*) xpath-root-node))
1144 (map nil
1145 (lambda (spec)
1146 (when (variable-param-p spec)
1147 (let ((value
1148 (find-parameter-value (variable-local-name spec)
1149 (variable-uri spec)
1150 parameters)))
1151 (when value
1152 (setf (global-variable-value (variable-index spec))
1153 value)))))
1154 global-variable-specs)
1155 (map nil
1156 (lambda (spec)
1157 (funcall (variable-thunk spec) ctx))
1158 global-variable-specs)
1159 ;; zzz we wouldn't have to mask float traps here if we used the
1160 ;; XPath API properly. Unfortunately I've been using FUNCALL
1161 ;; everywhere instead of EVALUATE, so let's paper over that
1162 ;; at a central place to be sure:
1163 (xpath::with-float-traps-masked ()
1164 (apply-templates ctx :mode *default-mode*)))
1165 (xpath:xpath-error (c)
1166 (xslt-error "~A" c))))
1167 (stylesheet-output-specification stylesheet)
1168 output))
1170 (defun find-attribute-set (local-name uri)
1171 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1172 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1174 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1175 (when sort-predicate
1176 (setf list
1177 (mapcar #'xpath:context-node
1178 (stable-sort (contextify-node-list list)
1179 sort-predicate))))
1180 (let* ((n (length list))
1181 (s/d (lambda () n)))
1182 (loop
1183 for i from 1
1184 for child in list
1186 (apply-templates (xpath:make-context child s/d i)
1187 :param-bindings param-bindings
1188 :mode mode))))
1190 (defvar *stack-limit* 200)
1192 (defun invoke-with-stack-limit (fn)
1193 (let ((*stack-limit* (1- *stack-limit*)))
1194 (unless (plusp *stack-limit*)
1195 (xslt-error "*stack-limit* reached; stack overflow"))
1196 (funcall fn)))
1198 (defun invoke-template (ctx template param-bindings)
1199 (let ((*lexical-variable-values*
1200 (make-variable-value-array (template-n-variables template))))
1201 (with-stack-limit ()
1202 (loop
1203 for (name-cons value) in param-bindings
1204 for (nil index nil) = (find name-cons
1205 (template-params template)
1206 :test #'equal
1207 :key #'car)
1209 (when index
1210 (setf (lexical-variable-value index) value)))
1211 (funcall (template-body template) ctx))))
1213 (defun apply-default-templates (ctx mode)
1214 (let ((node (xpath:context-node ctx)))
1215 (cond
1216 ((or (xpath-protocol:node-type-p node :processing-instruction)
1217 (xpath-protocol:node-type-p node :comment)))
1218 ((or (xpath-protocol:node-type-p node :text)
1219 (xpath-protocol:node-type-p node :attribute))
1220 (write-text (xpath-protocol:node-text node)))
1222 (apply-templates/list
1223 (xpath::force
1224 (xpath-protocol:child-pipe node))
1225 :mode mode)))))
1227 (defvar *apply-imports*)
1229 (defun apply-applicable-templates (ctx templates param-bindings finally)
1230 (labels ((apply-imports (&optional actual-param-bindings)
1231 (if templates
1232 (let* ((this (pop templates))
1233 (low (template-apply-imports-limit this))
1234 (high (template-import-priority this)))
1235 (setf templates
1236 (remove-if-not
1237 (lambda (x)
1238 (<= low (template-import-priority x) high))
1239 templates))
1240 (invoke-template ctx this actual-param-bindings))
1241 (funcall finally))))
1242 (let ((*apply-imports* #'apply-imports))
1243 (apply-imports param-bindings))))
1245 (defun apply-templates (ctx &key param-bindings mode)
1246 (apply-applicable-templates ctx
1247 (find-templates ctx (or mode *default-mode*))
1248 param-bindings
1249 (lambda ()
1250 (apply-default-templates ctx mode))))
1252 (defun call-template (ctx name &optional param-bindings)
1253 (apply-applicable-templates ctx
1254 (find-named-templates name)
1255 param-bindings
1256 (lambda ()
1257 (error "cannot find named template: ~s"
1258 name))))
1260 (defun find-templates (ctx mode)
1261 (let* ((matching-candidates
1262 (remove-if-not (lambda (template)
1263 (template-matches-p template ctx))
1264 (mode-templates mode)))
1265 (npriorities
1266 (if matching-candidates
1267 (1+ (reduce #'max
1268 matching-candidates
1269 :key #'template-import-priority))
1271 (priority-groups (make-array npriorities :initial-element nil)))
1272 (dolist (template matching-candidates)
1273 (push template
1274 (elt priority-groups (template-import-priority template))))
1275 (loop
1276 for i from (1- npriorities) downto 0
1277 for group = (elt priority-groups i)
1278 for template = (maximize #'template< group)
1279 when template
1280 collect template)))
1282 (defun find-named-templates (name)
1283 (gethash name (stylesheet-named-templates *stylesheet*)))
1285 (defun template< (a b) ;assuming same import priority
1286 (let ((p (template-priority a))
1287 (q (template-priority b)))
1288 (cond
1289 ((< p q) t)
1290 ((> p q) nil)
1292 (xslt-cerror "conflicting templates:~_~A,~_~A"
1293 (template-match-expression a)
1294 (template-match-expression b))
1295 (< (template-position a) (template-position b))))))
1297 (defun maximize (< things)
1298 (when things
1299 (let ((max (car things)))
1300 (dolist (other (cdr things))
1301 (when (funcall < max other)
1302 (setf max other)))
1303 max)))
1305 (defun template-matches-p (template ctx)
1306 (find (xpath:context-node ctx)
1307 (xpath:all-nodes (funcall (template-match-thunk template) ctx))
1308 :test #'xpath-protocol:node-equal))
1310 (defun invoke-with-output-sink (fn output-spec output)
1311 (etypecase output
1312 (pathname
1313 (with-open-file (s output
1314 :direction :output
1315 :element-type '(unsigned-byte 8)
1316 :if-exists :rename-and-delete)
1317 (invoke-with-output-sink fn output-spec s)))
1318 ((or stream null)
1319 (invoke-with-output-sink fn
1320 output-spec
1321 (make-output-sink output-spec output)))
1322 ((or hax:abstract-handler sax:abstract-handler)
1323 (with-xml-output output
1324 (when (typep output '(or combi-sink auto-detect-sink))
1325 (sax:start-dtd output
1326 :autodetect-me-please
1327 (output-doctype-public output-spec)
1328 (output-doctype-system output-spec)))
1329 (funcall fn)))))
1331 (defun make-output-sink (output-spec stream)
1332 (let* ((ystream
1333 (if stream
1334 (let ((et (stream-element-type stream)))
1335 (cond
1336 ((or (null et) (subtypep et '(unsigned-byte 8)))
1337 (runes:make-octet-stream-ystream stream))
1338 ((subtypep et 'character)
1339 (runes:make-character-stream-ystream stream))))
1340 (runes:make-rod-ystream)))
1341 (omit-xml-declaration-p
1342 (equal (output-omit-xml-declaration output-spec) "yes"))
1343 (sax-target
1344 (make-instance 'cxml::sink
1345 :ystream ystream
1346 :omit-xml-declaration-p omit-xml-declaration-p)))
1347 (flet ((make-combi-sink ()
1348 (make-instance 'combi-sink
1349 :hax-target (make-instance 'chtml::sink
1350 :ystream ystream)
1351 :sax-target sax-target
1352 :encoding (output-encoding output-spec))))
1353 (let ((method-key
1354 (cond
1355 ((equalp (output-method output-spec) "HTML") :html)
1356 ((equalp (output-method output-spec) "TEXT") :text)
1357 ((equalp (output-method output-spec) "XML") :xml)
1358 (t nil))))
1359 (cond
1360 ((and (eq method-key :html)
1361 (null (output-doctype-system output-spec))
1362 (null (output-doctype-public output-spec)))
1363 (make-combi-sink))
1364 ((eq method-key :text)
1365 (make-text-filter sax-target))
1366 ((and (eq method-key :xml)
1367 (null (output-doctype-system output-spec)))
1368 sax-target)
1370 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1372 (defstruct template
1373 match-expression
1374 match-thunk
1375 name
1376 import-priority
1377 apply-imports-limit
1378 priority
1379 position
1380 mode
1381 mode-qname
1382 params
1383 body
1384 n-variables)
1386 (defun expression-priority (form)
1387 (let ((step (second form)))
1388 (if (and (null (cddr form))
1389 (listp step)
1390 (member (car step) '(:child :attribute))
1391 (null (cddr step)))
1392 (let ((name (second step)))
1393 (cond
1394 ((or (stringp name)
1395 (and (consp name)
1396 (or (eq (car name) :qname)
1397 (eq (car name) :processing-instruction))))
1398 0.0)
1399 ((and (consp name)
1400 (or (eq (car name) :namespace)
1401 (eq (car name) '*)))
1402 -0.25)
1404 -0.5)))
1405 0.5)))
1407 (defun valid-expression-p (expr)
1408 (cond
1409 ((atom expr) t)
1410 ((eq (first expr) :path)
1411 (every (lambda (x)
1412 (let ((filter (third x)))
1413 (or (null filter) (valid-expression-p filter))))
1414 (cdr expr)))
1415 ((eq (first expr) :variable) ;(!)
1416 nil)
1418 (every #'valid-expression-p (cdr expr)))))
1420 (defun parse-xpath (str)
1421 (handler-case
1422 (xpath:parse-xpath str)
1423 (xpath:xpath-error (c)
1424 (xslt-error "~A" c))))
1426 ;; zzz also use naive-pattern-expression here?
1427 (defun parse-key-pattern (str)
1428 (let ((parsed
1429 (mapcar #'(lambda (item)
1430 `(:path (:root :node)
1431 (:descendant-or-self *)
1432 ,@(cdr item)))
1433 (parse-pattern str))))
1434 (if (null (rest parsed))
1435 (first parsed)
1436 `(:union ,@parsed))))
1438 (defun parse-pattern (str)
1439 ;; zzz check here for anything not allowed as an XSLT pattern
1440 ;; zzz can we hack id() and key() here?
1441 (let ((form (parse-xpath str)))
1442 (unless (consp form)
1443 (xslt-error "not a valid pattern: ~A" str))
1444 (labels ((process-form (form)
1445 (cond ((eq (car form) :union)
1446 (alexandria:mappend #'process-form (rest form)))
1447 ((not (or (eq (car form) :path)
1448 (and (eq (car form) :filter)
1449 (let ((filter (second form)))
1450 (and (consp filter)
1451 (member (car filter)
1452 '(:key :id))))
1453 (equal (third form) '(:true)))
1454 (member (car form) '(:key :id))))
1455 (xslt-error "not a valid pattern: ~A ~A" str form))
1456 ((not (valid-expression-p form))
1457 (xslt-error "invalid filter"))
1458 (t (list form)))))
1459 (process-form form))))
1461 (defun naive-pattern-expression (x)
1462 (ecase (car x)
1463 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1464 ((:filter :key :id) x)))
1466 (defun compile-value-thunk (value env)
1467 (if (and (listp value) (eq (car value) 'progn))
1468 (let ((inner-thunk (compile-instruction value env)))
1469 (lambda (ctx)
1470 (apply-to-result-tree-fragment ctx inner-thunk)))
1471 (compile-xpath value env)))
1473 (defun compile-var-binding (name value env)
1474 (multiple-value-bind (local-name uri)
1475 (decode-qname name env nil)
1476 (let ((thunk (xslt-trace-thunk
1477 (compile-value-thunk value env)
1478 "local variable ~s = ~s" name :result)))
1479 (list (cons local-name uri)
1480 (push-variable local-name
1482 *lexical-variable-declarations*)
1483 thunk))))
1485 (defun compile-var-bindings (forms env)
1486 (loop
1487 for (name value) in forms
1488 collect (compile-var-binding name value env)))
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")