Comment recovery
[xuriella.git] / xslt.lisp
blobbbf81c35b7d8731869a104b8a83bd87b2d2d8003
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 (defun apply-stylesheet
1094 (stylesheet source-designator
1095 &key output parameters uri-resolver navigator)
1096 (when (typep stylesheet 'xml-designator)
1097 (setf stylesheet (parse-stylesheet stylesheet)))
1098 (invoke-with-output-sink
1099 (lambda ()
1100 (handler-case*
1101 (let* ((*documents* (make-hash-table :test 'equal))
1102 (xpath:*navigator* (or navigator :default-navigator))
1103 (puri:*strict-parse* nil)
1104 (*stylesheet* stylesheet)
1105 (*empty-mode* (make-mode))
1106 (*default-mode* (find-mode stylesheet nil))
1107 (global-variable-specs
1108 (stylesheet-global-variables stylesheet))
1109 (*global-variable-values*
1110 (make-variable-value-array (length global-variable-specs)))
1111 (*uri-resolver* uri-resolver)
1112 (source-document
1113 (if (typep source-designator 'xml-designator)
1114 (cxml:parse source-designator (stp:make-builder))
1115 source-designator))
1116 (xpath-root-node
1117 (make-whitespace-stripper
1118 source-document
1119 (stylesheet-strip-tests stylesheet)))
1120 (ctx (xpath:make-context xpath-root-node)))
1121 (when (pathnamep source-designator)
1122 (setf (gethash source-designator *documents*) xpath-root-node))
1123 (map nil
1124 (lambda (spec)
1125 (when (variable-param-p spec)
1126 (let ((value
1127 (find-parameter-value (variable-local-name spec)
1128 (variable-uri spec)
1129 parameters)))
1130 (when value
1131 (setf (global-variable-value (variable-index spec))
1132 value)))))
1133 global-variable-specs)
1134 (map nil
1135 (lambda (spec)
1136 (funcall (variable-thunk spec) ctx))
1137 global-variable-specs)
1138 ;; zzz we wouldn't have to mask float traps here if we used the
1139 ;; XPath API properly. Unfortunately I've been using FUNCALL
1140 ;; everywhere instead of EVALUATE, so let's paper over that
1141 ;; at a central place to be sure:
1142 (xpath::with-float-traps-masked ()
1143 (apply-templates ctx :mode *default-mode*)))
1144 (xpath:xpath-error (c)
1145 (xslt-error "~A" c))))
1146 (stylesheet-output-specification stylesheet)
1147 output))
1149 (defun find-attribute-set (local-name uri)
1150 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1151 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1153 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1154 (when sort-predicate
1155 (setf list (sort list sort-predicate)))
1156 (let* ((n (length list))
1157 (s/d (lambda () n)))
1158 (loop
1159 for i from 1
1160 for child in list
1162 (apply-templates (xpath:make-context child s/d i)
1163 :param-bindings param-bindings
1164 :mode mode))))
1166 (defvar *stack-limit* 200)
1168 (defun invoke-with-stack-limit (fn)
1169 (let ((*stack-limit* (1- *stack-limit*)))
1170 (unless (plusp *stack-limit*)
1171 (xslt-error "*stack-limit* reached; stack overflow"))
1172 (funcall fn)))
1174 (defun invoke-template (ctx template param-bindings)
1175 (let ((*lexical-variable-values*
1176 (make-variable-value-array (template-n-variables template))))
1177 (with-stack-limit ()
1178 (loop
1179 for (name-cons value) in param-bindings
1180 for (nil index nil) = (find name-cons
1181 (template-params template)
1182 :test #'equal
1183 :key #'car)
1185 (when index
1186 (setf (lexical-variable-value index) value)))
1187 (funcall (template-body template) ctx))))
1189 (defun apply-default-templates (ctx mode)
1190 (let ((node (xpath:context-node ctx)))
1191 (cond
1192 ((or (xpath-protocol:node-type-p node :processing-instruction)
1193 (xpath-protocol:node-type-p node :comment)))
1194 ((or (xpath-protocol:node-type-p node :text)
1195 (xpath-protocol:node-type-p node :attribute))
1196 (write-text (xpath-protocol:node-text node)))
1198 (apply-templates/list
1199 (xpath::force
1200 (xpath-protocol:child-pipe node))
1201 :mode mode)))))
1203 (defvar *apply-imports*)
1205 (defun apply-applicable-templates (ctx templates param-bindings finally)
1206 (labels ((apply-imports (&optional actual-param-bindings)
1207 (if templates
1208 (let* ((this (pop templates))
1209 (low (template-apply-imports-limit this))
1210 (high (template-import-priority this)))
1211 (setf templates
1212 (remove-if-not
1213 (lambda (x)
1214 (<= low (template-import-priority x) high))
1215 templates))
1216 (invoke-template ctx this actual-param-bindings))
1217 (funcall finally))))
1218 (let ((*apply-imports* #'apply-imports))
1219 (apply-imports param-bindings))))
1221 (defun apply-templates (ctx &key param-bindings mode)
1222 (apply-applicable-templates ctx
1223 (find-templates ctx (or mode *default-mode*))
1224 param-bindings
1225 (lambda ()
1226 (apply-default-templates ctx mode))))
1228 (defun call-template (ctx name &optional param-bindings)
1229 (apply-applicable-templates ctx
1230 (find-named-templates name)
1231 param-bindings
1232 (lambda ()
1233 (error "cannot find named template: ~s"
1234 name))))
1236 (defun find-templates (ctx mode)
1237 (let* ((matching-candidates
1238 (remove-if-not (lambda (template)
1239 (template-matches-p template ctx))
1240 (mode-templates mode)))
1241 (npriorities
1242 (if matching-candidates
1243 (1+ (reduce #'max
1244 matching-candidates
1245 :key #'template-import-priority))
1247 (priority-groups (make-array npriorities :initial-element nil)))
1248 (dolist (template matching-candidates)
1249 (push template
1250 (elt priority-groups (template-import-priority template))))
1251 (loop
1252 for i from (1- npriorities) downto 0
1253 for group = (elt priority-groups i)
1254 for template = (maximize #'template< group)
1255 when template
1256 collect template)))
1258 (defun find-named-templates (name)
1259 (gethash name (stylesheet-named-templates *stylesheet*)))
1261 (defun template< (a b) ;assuming same import priority
1262 (let ((p (template-priority a))
1263 (q (template-priority b)))
1264 (cond
1265 ((< p q) t)
1266 ((> p q) nil)
1268 (xslt-cerror "conflicting templates:~_~A,~_~A"
1269 (template-match-expression a)
1270 (template-match-expression b))
1271 (< (template-position a) (template-position b))))))
1273 (defun maximize (< things)
1274 (when things
1275 (let ((max (car things)))
1276 (dolist (other (cdr things))
1277 (when (funcall < max other)
1278 (setf max other)))
1279 max)))
1281 (defun template-matches-p (template ctx)
1282 (find (xpath:context-node ctx)
1283 (xpath:all-nodes (funcall (template-match-thunk template) ctx))))
1285 (defun invoke-with-output-sink (fn output-spec output)
1286 (etypecase output
1287 (pathname
1288 (with-open-file (s output
1289 :direction :output
1290 :element-type '(unsigned-byte 8)
1291 :if-exists :rename-and-delete)
1292 (invoke-with-output-sink fn output-spec s)))
1293 ((or stream null)
1294 (invoke-with-output-sink fn
1295 output-spec
1296 (make-output-sink output-spec output)))
1297 ((or hax:abstract-handler sax:abstract-handler)
1298 (with-xml-output output
1299 (when (typep output '(or combi-sink auto-detect-sink))
1300 (sax:start-dtd output
1301 :autodetect-me-please
1302 (output-doctype-public output-spec)
1303 (output-doctype-system output-spec)))
1304 (funcall fn)))))
1306 (defun make-output-sink (output-spec stream)
1307 (let* ((ystream
1308 (if stream
1309 (let ((et (stream-element-type stream)))
1310 (cond
1311 ((or (null et) (subtypep et '(unsigned-byte 8)))
1312 (runes:make-octet-stream-ystream stream))
1313 ((subtypep et 'character)
1314 (runes:make-character-stream-ystream stream))))
1315 (runes:make-rod-ystream)))
1316 (omit-xml-declaration-p
1317 (equal (output-omit-xml-declaration output-spec) "yes"))
1318 (sax-target
1319 (make-instance 'cxml::sink
1320 :ystream ystream
1321 :omit-xml-declaration-p omit-xml-declaration-p)))
1322 (flet ((make-combi-sink ()
1323 (make-instance 'combi-sink
1324 :hax-target (make-instance 'chtml::sink
1325 :ystream ystream)
1326 :sax-target sax-target
1327 :encoding (output-encoding output-spec))))
1328 (let ((method-key
1329 (cond
1330 ((equalp (output-method output-spec) "HTML") :html)
1331 ((equalp (output-method output-spec) "TEXT") :text)
1332 ((equalp (output-method output-spec) "XML") :xml)
1333 (t nil))))
1334 (cond
1335 ((and (eq method-key :html)
1336 (null (output-doctype-system output-spec))
1337 (null (output-doctype-public output-spec)))
1338 (make-combi-sink))
1339 ((eq method-key :text)
1340 (make-text-filter sax-target))
1341 ((and (eq method-key :xml)
1342 (null (output-doctype-system output-spec)))
1343 sax-target)
1345 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1347 (defstruct template
1348 match-expression
1349 match-thunk
1350 name
1351 import-priority
1352 apply-imports-limit
1353 priority
1354 position
1355 mode
1356 mode-qname
1357 params
1358 body
1359 n-variables)
1361 (defun expression-priority (form)
1362 (let ((step (second form)))
1363 (if (and (null (cddr form))
1364 (listp step)
1365 (member (car step) '(:child :attribute))
1366 (null (cddr step)))
1367 (let ((name (second step)))
1368 (cond
1369 ((or (stringp name)
1370 (and (consp name)
1371 (or (eq (car name) :qname)
1372 (eq (car name) :processing-instruction))))
1373 0.0)
1374 ((and (consp name)
1375 (or (eq (car name) :namespace)
1376 (eq (car name) '*)))
1377 -0.25)
1379 -0.5)))
1380 0.5)))
1382 (defun valid-expression-p (expr)
1383 (cond
1384 ((atom expr) t)
1385 ((eq (first expr) :path)
1386 (every (lambda (x)
1387 (let ((filter (third x)))
1388 (or (null filter) (valid-expression-p filter))))
1389 (cdr expr)))
1390 ((eq (first expr) :variable) ;(!)
1391 nil)
1393 (every #'valid-expression-p (cdr expr)))))
1395 (defun parse-xpath (str)
1396 (handler-case
1397 (xpath:parse-xpath str)
1398 (xpath:xpath-error (c)
1399 (xslt-error "~A" c))))
1401 ;; zzz also use naive-pattern-expression here?
1402 (defun parse-key-pattern (str)
1403 (let ((parsed
1404 (mapcar #'(lambda (item)
1405 `(:path (:root :node)
1406 (:descendant-or-self *)
1407 ,@(cdr item)))
1408 (parse-pattern str))))
1409 (if (null (rest parsed))
1410 (first parsed)
1411 `(:union ,@parsed))))
1413 (defun parse-pattern (str)
1414 ;; zzz check here for anything not allowed as an XSLT pattern
1415 ;; zzz can we hack id() and key() here?
1416 (let ((form (parse-xpath str)))
1417 (unless (consp form)
1418 (xslt-error "not a valid pattern: ~A" str))
1419 (labels ((process-form (form)
1420 (cond ((eq (car form) :union)
1421 (alexandria:mappend #'process-form (rest form)))
1422 ((not (or (eq (car form) :path)
1423 (and (eq (car form) :filter)
1424 (let ((filter (second form)))
1425 (and (consp filter)
1426 (member (car filter)
1427 '(:key :id))))
1428 (equal (third form) '(:true)))
1429 (member (car form) '(:key :id))))
1430 (xslt-error "not a valid pattern: ~A ~A" str form))
1431 ((not (valid-expression-p form))
1432 (xslt-error "invalid filter"))
1433 (t (list form)))))
1434 (process-form form))))
1436 (defun naive-pattern-expression (x)
1437 (ecase (car x)
1438 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1439 ((:filter :key :id) x)))
1441 (defun compile-value-thunk (value env)
1442 (if (and (listp value) (eq (car value) 'progn))
1443 (let ((inner-thunk (compile-instruction value env)))
1444 (lambda (ctx)
1445 (apply-to-result-tree-fragment ctx inner-thunk)))
1446 (compile-xpath value env)))
1448 (defun compile-var-bindings/nointern (forms env)
1449 (loop
1450 for (name value) in forms
1451 collect (multiple-value-bind (local-name uri)
1452 (decode-qname name env nil)
1453 (list (cons local-name uri)
1454 (xslt-trace-thunk
1455 (compile-value-thunk value env)
1456 "local variable ~s = ~s" name :result)))))
1458 (defun compile-var-bindings (forms env)
1459 (loop
1460 for (cons thunk) in (compile-var-bindings/nointern forms env)
1461 for (local-name . uri) = cons
1462 collect (list cons
1463 (push-variable local-name
1465 *lexical-variable-declarations*)
1466 thunk)))
1468 (defun compile-template (<template> env position)
1469 (stp:with-attributes (match name priority mode) <template>
1470 (unless (or name match)
1471 (xslt-error "missing match in template"))
1472 (multiple-value-bind (params body-pos)
1473 (loop
1474 for i from 0
1475 for child in (stp:list-children <template>)
1476 while (namep child "param")
1477 collect (parse-param child) into params
1478 finally (return (values params i)))
1479 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1480 (param-bindings (compile-var-bindings params env))
1481 (body (parse-body <template> body-pos (mapcar #'car params)))
1482 (body-thunk (compile-instruction `(progn ,@body) env))
1483 (outer-body-thunk
1484 (xslt-trace-thunk
1485 #'(lambda (ctx)
1486 (unwind-protect
1487 (progn
1488 ;; set params that weren't initialized by apply-templates
1489 (loop for (name index param-thunk) in param-bindings
1490 when (eq (lexical-variable-value index nil) 'unbound)
1491 do (setf (lexical-variable-value index)
1492 (funcall param-thunk ctx)))
1493 (funcall body-thunk ctx))))
1494 "template: match = ~s name = ~s" match name))
1495 (n-variables (length *lexical-variable-declarations*)))
1496 (append
1497 (when name
1498 (multiple-value-bind (local-name uri)
1499 (decode-qname name env nil)
1500 (list
1501 (make-template :name (cons local-name uri)
1502 :import-priority *import-priority*
1503 :apply-imports-limit *apply-imports-limit*
1504 :params param-bindings
1505 :body outer-body-thunk
1506 :n-variables n-variables))))
1507 (when match
1508 (mapcar (lambda (expression)
1509 (let ((match-thunk
1510 (xslt-trace-thunk
1511 (compile-xpath
1512 `(xpath:xpath
1513 ,(naive-pattern-expression expression))
1514 env)
1515 "match-thunk for template (match ~s): ~s --> ~s"
1516 match expression :result))
1517 (p (if priority
1518 (parse-number:parse-number priority)
1519 (expression-priority expression))))
1520 (make-template :match-expression expression
1521 :match-thunk match-thunk
1522 :import-priority *import-priority*
1523 :apply-imports-limit *apply-imports-limit*
1524 :priority p
1525 :position position
1526 :mode-qname mode
1527 :params param-bindings
1528 :body outer-body-thunk
1529 :n-variables n-variables)))
1530 (parse-pattern match))))))))
1531 #+(or)
1532 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")