Check the name in call-template
[xuriella.git] / xslt.lisp
blob8decee138f156b552169f2ca0310170334a45b00
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 ;; Many errors in XSLT are "recoverable", with a specified action that must
56 ;; be taken if the error isn't raised. My original plan was to implement
57 ;; such issues as continuable conditions, so that users are alerted about
58 ;; portability issues with their stylesheet, but can contiue anyway.
60 ;; However, our current test suite driver compares against Saxon results,
61 ;; and Saxon recovers (nearly) always. So our coverage of these errors
62 ;; is very incomplete.
64 ;; Re-enable this code once we can check that it's actually being used
65 ;; everywhere.
66 (defun xslt-cerror (fmt &rest args)
67 (declare (ignore fmt args))
68 #+(or)
69 (with-simple-restart (recover "recover")
70 (error 'recoverable-xslt-error
71 :format-control fmt
72 :format-arguments args)))
74 (defvar *debug* nil)
76 (defmacro handler-case* (form &rest clauses)
77 ;; like HANDLER-CASE if *DEBUG* is off. If it's on, don't establish
78 ;; a handler at all so that we see the real stack traces. (We could use
79 ;; HANDLER-BIND here and check at signalling time, but doesn't seem
80 ;; important.)
81 (let ((doit (gensym)))
82 `(flet ((,doit () ,form))
83 (if *debug*
84 (,doit)
85 (handler-case
86 (,doit)
87 ,@clauses)))))
89 (defmacro with-resignalled-errors ((&optional) &body body)
90 `(invoke-with-resignalled-errors (lambda () ,@body)))
92 (defun invoke-with-resignalled-errors (fn)
93 (handler-bind
94 ((xpath:xpath-error
95 (lambda (c)
96 (xslt-error "~A" c)))
97 (babel-encodings:character-encoding-error
98 (lambda (c)
99 (xslt-error "~A" c))))
100 (funcall fn)))
102 (defun compile-xpath (xpath &optional env)
103 (with-resignalled-errors ()
104 (xpath:compile-xpath xpath env)))
106 (defmacro with-stack-limit ((&optional) &body body)
107 `(invoke-with-stack-limit (lambda () ,@body)))
110 ;;;; Helper functions and macros
112 (defun check-for-invalid-attributes (valid-names node)
113 (labels ((check-attribute (a)
114 (unless
115 (let ((uri (stp:namespace-uri a)))
116 (or (and (plusp (length uri)) (not (equal uri *xsl*)))
117 (find (cons (stp:local-name a) uri)
118 valid-names
119 :test #'equal)))
120 (xslt-error "attribute ~A not allowed on ~A"
121 (stp:local-name a)
122 (stp:local-name node)))))
123 (stp:map-attributes nil #'check-attribute node)))
125 (defmacro only-with-attributes ((&rest specs) node &body body)
126 (let ((valid-names
127 (mapcar (lambda (entry)
128 (if (and (listp entry) (cdr entry))
129 (destructuring-bind (name &optional (uri ""))
130 (cdr entry)
131 (cons name uri))
132 (cons (string-downcase
133 (princ-to-string
134 (symbol-name entry)))
135 "")))
136 specs))
137 (%node (gensym)))
138 `(let ((,%NODE ,node))
139 (check-for-invalid-attributes ',valid-names ,%NODE)
140 (stp:with-attributes ,specs ,%NODE
141 ,@body))))
143 (defun map-pipe-eagerly (fn pipe)
144 (xpath::enumerate pipe :key fn :result nil))
146 (defmacro do-pipe ((var pipe &optional result) &body body)
147 `(block nil
148 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
149 ,result))
152 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
154 (defparameter *namespaces*
155 '((nil . "")
156 ("xmlns" . #"http://www.w3.org/2000/xmlns/")
157 ("xml" . #"http://www.w3.org/XML/1998/namespace")))
159 (defvar *global-variable-declarations*)
160 (defvar *lexical-variable-declarations*)
162 (defvar *global-variable-values*)
163 (defvar *lexical-variable-values*)
165 (defclass xslt-environment () ())
167 (defun split-qname (str)
168 (handler-case
169 (multiple-value-bind (prefix local-name)
170 (cxml::split-qname str)
171 (unless
172 ;; FIXME: cxml should really offer a function that does
173 ;; checks for NCName and QName in a sensible way for user code.
174 ;; cxml::split-qname is tailored to the needs of the parser.
176 ;; For now, let's just check the syntax explicitly.
177 (and (or (null prefix) (xpath::nc-name-p prefix))
178 (xpath::nc-name-p local-name))
179 (xslt-error "not a qname: ~A" str))
180 (values prefix local-name))
181 (cxml:well-formedness-violation ()
182 (xslt-error "not a qname: ~A" str))))
184 (defun decode-qname (qname env attributep)
185 (unless qname
186 (xslt-error "missing name"))
187 (multiple-value-bind (prefix local-name)
188 (split-qname qname)
189 (values local-name
190 (if (or prefix (not attributep))
191 (xpath-sys:environment-find-namespace env (or prefix ""))
193 prefix)))
195 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
196 (or (cdr (assoc prefix *namespaces* :test 'equal))
197 ;; zzz gross hack.
198 ;; Change the entire code base to represent "no prefix" as the
199 ;; empty string consistently. unparse.lisp has already been changed.
200 (and (equal prefix "")
201 (cdr (assoc nil *namespaces* :test 'equal)))
202 (and (eql prefix nil)
203 (cdr (assoc "" *namespaces* :test 'equal)))))
205 (defun find-variable-index (local-name uri table)
206 (position (cons local-name uri) table :test 'equal))
208 (defun intern-global-variable (local-name uri)
209 (or (find-variable-index local-name uri *global-variable-declarations*)
210 (push-variable local-name uri *global-variable-declarations*)))
212 (defun push-variable (local-name uri table)
213 (prog1
214 (length table)
215 (vector-push-extend (cons local-name uri) table)))
217 (defun lexical-variable-value (index &optional (errorp t))
218 (let ((result (svref *lexical-variable-values* index)))
219 (when errorp
220 (assert (not (eq result 'unbound))))
221 result))
223 (defun (setf lexical-variable-value) (newval index)
224 (assert (not (eq newval 'unbound)))
225 (setf (svref *lexical-variable-values* index) newval))
227 (defun global-variable-value (index &optional (errorp t))
228 (let ((result (svref *global-variable-values* index)))
229 (when errorp
230 (assert (not (eq result 'unbound))))
231 result))
233 (defun (setf global-variable-value) (newval index)
234 (assert (not (eq newval 'unbound)))
235 (setf (svref *global-variable-values* index) newval))
237 (defmethod xpath-sys:environment-find-function
238 ((env xslt-environment) lname uri)
239 (if (string= uri "")
240 (or (xpath-sys:find-xpath-function lname *xsl*)
241 (xpath-sys:find-xpath-function lname uri))
242 (xpath-sys:find-xpath-function lname uri)))
244 (defmethod xpath-sys:environment-find-variable
245 ((env xslt-environment) lname uri)
246 (let ((index
247 (find-variable-index lname uri *lexical-variable-declarations*)))
248 (when index
249 (lambda (ctx)
250 (declare (ignore ctx))
251 (svref *lexical-variable-values* index)))))
253 (defclass lexical-xslt-environment (xslt-environment) ())
255 (defmethod xpath-sys:environment-find-variable
256 ((env lexical-xslt-environment) lname uri)
257 (or (call-next-method)
258 (let ((index
259 (find-variable-index lname uri *global-variable-declarations*)))
260 (when index
261 (xslt-trace-thunk
262 (lambda (ctx)
263 (declare (ignore ctx))
264 (svref *global-variable-values* index))
265 "global ~s (uri ~s) = ~s" lname uri :result)))))
267 (defclass global-variable-environment (xslt-environment)
268 ((initial-global-variable-thunks
269 :initarg :initial-global-variable-thunks
270 :accessor initial-global-variable-thunks)))
272 (defmethod xpath-sys:environment-find-variable
273 ((env global-variable-environment) lname uri)
274 (or (call-next-method)
275 (gethash (cons lname uri) (initial-global-variable-thunks env))))
278 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
279 ;;;;
280 ;;;; A sink that serializes only text not contained in any element.
282 (defmacro with-toplevel-text-output-sink ((var) &body body)
283 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
285 (defclass toplevel-text-output-sink (sax:default-handler)
286 ((target :initarg :target :accessor text-output-sink-target)
287 (depth :initform 0 :accessor textoutput-sink-depth)))
289 (defmethod sax:start-element ((sink toplevel-text-output-sink)
290 namespace-uri local-name qname attributes)
291 (declare (ignore namespace-uri local-name qname attributes))
292 (incf (textoutput-sink-depth sink)))
294 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
295 (when (zerop (textoutput-sink-depth sink))
296 (write-string data (text-output-sink-target sink))))
298 (defmethod sax:unescaped ((sink toplevel-text-output-sink) data)
299 (sax:characters sink data))
301 (defmethod sax:end-element ((sink toplevel-text-output-sink)
302 namespace-uri local-name qname)
303 (declare (ignore namespace-uri local-name qname))
304 (decf (textoutput-sink-depth sink)))
306 (defun invoke-with-toplevel-text-output-sink (fn)
307 (with-output-to-string (s)
308 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
311 ;;;; TEXT-FILTER
312 ;;;;
313 ;;;; A sink that passes through only text (at any level) and turns to
314 ;;;; into unescaped characters.
316 (defclass text-filter (sax:default-handler)
317 ((target :initarg :target :accessor text-filter-target)))
319 (defmethod sax:characters ((sink text-filter) data)
320 (sax:unescaped (text-filter-target sink) data))
322 (defmethod sax:unescaped ((sink text-filter) data)
323 (sax:unescaped (text-filter-target sink) data))
325 (defmethod sax:end-document ((sink text-filter))
326 (sax:end-document (text-filter-target sink)))
328 (defun make-text-filter (target)
329 (make-instance 'text-filter :target target))
332 ;;;; ESCAPER
333 ;;;;
334 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
335 ;;;; XSLT 16.4.
337 (defclass escaper (cxml:broadcast-handler)
340 (defmethod sax:unescaped ((sink escaper) data)
341 (sax:characters sink data))
343 (defun make-escaper (target)
344 (make-instance 'escaper :handlers (list target)))
347 ;;;; Names
349 (defun of-name (local-name)
350 (stp:of-name local-name *xsl*))
352 (defun namep (node local-name)
353 (and (typep node '(or stp:element stp:attribute))
354 (equal (stp:namespace-uri node) *xsl*)
355 (equal (stp:local-name node) local-name)))
358 ;;;; PARSE-STYLESHEET
360 (defstruct stylesheet
361 (modes (make-hash-table :test 'equal))
362 (global-variables (make-empty-declaration-array))
363 (output-specification (make-output-specification))
364 (strip-tests nil)
365 (strip-thunk nil)
366 (named-templates (make-hash-table :test 'equal))
367 (attribute-sets (make-hash-table :test 'equal))
368 (keys (make-hash-table :test 'equal))
369 (namespace-aliases (make-hash-table :test 'equal))
370 (decimal-formats (make-hash-table :test 'equal))
371 (initial-global-variable-thunks (make-hash-table :test 'equal)))
373 (defstruct mode
374 (templates nil)
375 (match-thunk (lambda (ignore) (declare (ignore ignore)) nil)))
377 (defun find-mode (stylesheet local-name &optional uri)
378 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
380 (defun ensure-mode (stylesheet &optional local-name uri)
381 (or (find-mode stylesheet local-name uri)
382 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
383 (make-mode))))
385 (defun ensure-mode/qname (stylesheet qname env)
386 (if qname
387 (multiple-value-bind (local-name uri)
388 (decode-qname qname env nil)
389 (ensure-mode stylesheet local-name uri))
390 (find-mode stylesheet nil)))
392 (defun acons-namespaces (element &optional (bindings *namespaces*))
393 (map-namespace-declarations (lambda (prefix uri)
394 (push (cons prefix uri) bindings))
395 element)
396 bindings)
398 (defun find-key (name stylesheet)
399 (or (gethash name (stylesheet-keys stylesheet))
400 (xslt-error "unknown key: ~a" name)))
402 (defun make-key (match use) (cons match use))
404 (defun key-match (key) (car key))
406 (defun key-use (key) (cdr key))
408 (defun add-key (stylesheet name match use)
409 (if (gethash name (stylesheet-keys stylesheet))
410 (xslt-error "duplicate key: ~a" name)
411 (setf (gethash name (stylesheet-keys stylesheet))
412 (make-key match use))))
414 (defvar *excluded-namespaces* (list *xsl*))
415 (defvar *empty-mode*)
416 (defvar *default-mode*)
418 (defvar *xsl-include-stack* nil)
420 (defun uri-to-pathname (uri)
421 (cxml::uri-to-pathname (puri:parse-uri uri)))
423 (defun unwrap-2.3 (document)
424 (let ((literal-result-element (stp:document-element document))
425 (new-template (stp:make-element "template" *xsl*))
426 (new-document-element (stp:make-element "stylesheet" *xsl*)))
427 (setf (stp:attribute-value new-document-element "version")
428 (or (stp:attribute-value literal-result-element "version" *xsl*)
429 (xslt-error "not a stylesheet: root element lacks xsl:version")))
430 (setf (stp:attribute-value new-template "match") "/")
431 (setf (stp:document-element document) new-document-element)
432 (stp:append-child new-document-element new-template)
433 (stp:append-child new-template literal-result-element)
434 new-document-element))
436 (defun parse-stylesheet-to-stp (input uri-resolver)
437 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
438 (<transform> (stp:document-element d)))
439 (unless (equal (stp:namespace-uri <transform>) *xsl*)
440 (setf <transform> (unwrap-2.3 d)))
441 (strip-stylesheet <transform>)
442 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
443 (or (equal (stp:local-name <transform>) "transform")
444 (equal (stp:local-name <transform>) "stylesheet")))
445 (xslt-error "not a stylesheet"))
446 (check-for-invalid-attributes '(("version" . "")
447 ("exclude-result-prefixes" . "")
448 ("extension-element-prefixes" . ""))
449 <transform>)
450 (let ((invalid
451 (or (stp:find-child-if (of-name "stylesheet") <transform>)
452 (stp:find-child-if (of-name "transform") <transform>))))
453 (when invalid
454 (xslt-error "invalid top-level element ~A" (stp:local-name invalid))))
455 (dolist (include (stp:filter-children (of-name "include") <transform>))
456 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
457 (stp:base-uri include)))
458 (uri (if uri-resolver
459 (funcall uri-resolver (puri:render-uri uri nil))
460 uri))
461 (str (puri:render-uri uri nil))
462 (pathname
463 (handler-case
464 (uri-to-pathname uri)
465 (cxml:xml-parse-error (c)
466 (xslt-error "cannot find included stylesheet ~A: ~A"
467 uri c)))))
468 (with-open-file
469 (stream pathname
470 :element-type '(unsigned-byte 8)
471 :if-does-not-exist nil)
472 (unless stream
473 (xslt-error "cannot find included stylesheet ~A at ~A"
474 uri pathname))
475 (when (find str *xsl-include-stack* :test #'equal)
476 (xslt-error "recursive inclusion of ~A" uri))
477 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
478 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
479 (stp:insert-child-after <transform>
480 (stp:copy <transform>2)
481 include)
482 (stp:detach include)))))
483 <transform>))
485 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
486 (defvar *apply-imports-limit*)
487 (defvar *import-priority*)
488 (defvar *extension-namespaces*)
489 (defvar *forwards-compatible-p*)
491 (defmacro do-toplevel ((var xpath <transform>) &body body)
492 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
494 (defun map-toplevel (fn xpath <transform>)
495 (dolist (node (list-toplevel xpath <transform>))
496 (let ((*namespaces* *namespaces*))
497 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
498 (when (xpath-protocol:node-type-p ancestor :element)
499 (setf *namespaces* (acons-namespaces ancestor))))
500 (funcall fn node))))
502 (defun list-toplevel (xpath <transform>)
503 (labels ((recurse (sub)
504 (let ((subsubs
505 (xpath-sys:pipe-of
506 (xpath:evaluate "transform|stylesheet" sub))))
507 (xpath::append-pipes
508 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
509 (xpath::mappend-pipe #'recurse subsubs)))))
510 (xpath::sort-nodes (recurse <transform>))))
512 (defmacro with-import-magic ((node env) &body body)
513 `(invoke-with-import-magic (lambda () ,@body) ,node ,env))
515 (defun invoke-with-import-magic (fn node env)
516 (unless (or (namep node "stylesheet") (namep node "transform"))
517 (setf node (stp:parent node)))
518 (let ((*excluded-namespaces* (list *xsl*))
519 (*extension-namespaces* '())
520 (*forwards-compatible-p*
521 (not (equal (stp:attribute-value node "version") "1.0"))))
522 (parse-exclude-result-prefixes! node env)
523 (parse-extension-element-prefixes! node env)
524 (funcall fn)))
526 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
527 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
528 (instruction-base-uri (stp:base-uri <transform>))
529 (namespaces (acons-namespaces <transform>))
530 (apply-imports-limit (1+ *import-priority*))
531 (continuations '()))
532 (let ((*namespaces* namespaces))
533 (invoke-with-import-magic (constantly t) <transform> env))
534 (do-toplevel (elt "node()" <transform>)
535 (let ((version (stp:attribute-value (stp:parent elt) "version")))
536 (cond
537 ((null version)
538 (xslt-error "stylesheet lacks version"))
539 ((equal version "1.0")
540 (if (typep elt 'stp:element)
541 (when (or (equal (stp:namespace-uri elt) "")
542 (and (equal (stp:namespace-uri elt) *xsl*)
543 (not (find (stp:local-name elt)
544 '("key" "template" "output"
545 "strip-space" "preserve-space"
546 "attribute-set" "namespace-alias"
547 "decimal-format" "variable" "param"
548 "import" "include"
549 ;; for include handling:
550 "stylesheet" "transform")
551 :test #'equal))))
552 (xslt-error "unknown top-level element ~A" (stp:local-name elt)))
553 (xslt-error "text at top-level"))))))
554 (macrolet ((with-specials ((&optional) &body body)
555 `(let ((*instruction-base-uri* instruction-base-uri)
556 (*namespaces* namespaces)
557 (*apply-imports-limit* apply-imports-limit))
558 ,@body)))
559 (with-specials ()
560 (do-toplevel (import "import" <transform>)
561 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
562 (stp:base-uri import))))
563 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
564 continuations))))
565 (let ((import-priority
566 (incf *import-priority*))
567 (var-cont (prepare-global-variables stylesheet <transform>)))
568 ;; delay the rest of compilation until we've seen all global
569 ;; variables:
570 (lambda ()
571 (mapc #'funcall (nreverse continuations))
572 (with-specials ()
573 (let ((*import-priority* import-priority))
574 (funcall var-cont)
575 (parse-keys! stylesheet <transform> env)
576 (parse-templates! stylesheet <transform> env)
577 (parse-output! stylesheet <transform>)
578 (parse-strip/preserve-space! stylesheet <transform> env)
579 (parse-attribute-sets! stylesheet <transform> env)
580 (parse-namespace-aliases! stylesheet <transform> env)
581 (parse-decimal-formats! stylesheet <transform> env))))))))
583 (defvar *xsl-import-stack* nil)
585 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
586 (let* ((uri (if uri-resolver
587 (funcall uri-resolver (puri:render-uri uri nil))
588 uri))
589 (str (puri:render-uri uri nil))
590 (pathname
591 (handler-case
592 (uri-to-pathname uri)
593 (cxml:xml-parse-error (c)
594 (xslt-error "cannot find imported stylesheet ~A: ~A"
595 uri c)))))
596 (with-open-file
597 (stream pathname
598 :element-type '(unsigned-byte 8)
599 :if-does-not-exist nil)
600 (unless stream
601 (xslt-error "cannot find imported stylesheet ~A at ~A"
602 uri pathname))
603 (when (find str *xsl-import-stack* :test #'equal)
604 (xslt-error "recursive inclusion of ~A" uri))
605 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
606 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
608 (defvar *included-attribute-sets*)
610 (defun parse-stylesheet (designator &key uri-resolver)
611 (with-resignalled-errors ()
612 (xpath:with-namespaces ((nil #.*xsl*))
613 (let* ((*import-priority* 0)
614 (xpath:*allow-variables-in-patterns* nil)
615 (puri:*strict-parse* nil)
616 (stylesheet (make-stylesheet))
617 (env (make-instance 'lexical-xslt-environment))
618 (*excluded-namespaces* *excluded-namespaces*)
619 (*global-variable-declarations* (make-empty-declaration-array))
620 (*included-attribute-sets* nil))
621 (ensure-mode stylesheet nil)
622 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
623 ;; reverse attribute sets:
624 (let ((table (stylesheet-attribute-sets stylesheet)))
625 (maphash (lambda (k v)
626 (setf (gethash k table) (nreverse v)))
627 table))
628 ;; for Errors_err011
629 (dolist (sets *included-attribute-sets*)
630 (loop for (local-name uri nil) in sets do
631 (find-attribute-set local-name uri stylesheet)))
632 ;; add default df
633 (unless (find-decimal-format "" "" stylesheet nil)
634 (setf (find-decimal-format "" "" stylesheet)
635 (make-decimal-format)))
636 ;; compile a template matcher for each mode:
637 (loop
638 for mode being each hash-value in (stylesheet-modes stylesheet)
640 (setf (mode-match-thunk mode)
641 (xpath:make-pattern-matcher
642 (mapcar #'template-compiled-pattern
643 (mode-templates mode)))))
644 ;; and for the strip tests
645 (setf (stylesheet-strip-thunk stylesheet)
646 (let ((patterns (stylesheet-strip-tests stylesheet)))
647 (and patterns
648 (xpath:make-pattern-matcher
649 (mapcar #'strip-test-compiled-pattern patterns)))))
650 stylesheet))))
652 (defun parse-attribute-sets! (stylesheet <transform> env)
653 (do-toplevel (elt "attribute-set" <transform>)
654 (with-import-magic (elt env)
655 (push (let* ((sets
656 (mapcar (lambda (qname)
657 (multiple-value-list (decode-qname qname env nil)))
658 (words
659 (stp:attribute-value elt "use-attribute-sets"))))
660 (instructions
661 (stp:map-children
662 'list
663 (lambda (child)
664 (unless
665 (and (typep child 'stp:element)
666 (or (and (equal (stp:namespace-uri child) *xsl*)
667 (equal (stp:local-name child)
668 "attribute"))
669 (find (stp:namespace-uri child)
670 *extension-namespaces*
671 :test 'equal)))
672 (xslt-error "non-attribute found in attribute set"))
673 (parse-instruction child))
674 elt))
675 (*lexical-variable-declarations*
676 (make-empty-declaration-array))
677 (thunk
678 (compile-instruction `(progn ,@instructions) env))
679 (n-variables (length *lexical-variable-declarations*)))
680 (push sets *included-attribute-sets*)
681 (lambda (ctx)
682 (with-stack-limit ()
683 (loop for (local-name uri nil) in sets do
684 (dolist (thunk (find-attribute-set local-name uri))
685 (funcall thunk ctx)))
686 (let ((*lexical-variable-values*
687 (make-variable-value-array n-variables)))
688 (funcall thunk ctx)))))
689 (gethash (multiple-value-bind (local-name uri)
690 (decode-qname (or (stp:attribute-value elt "name")
691 (xslt-error "missing name"))
693 nil)
694 (cons local-name uri))
695 (stylesheet-attribute-sets stylesheet))))))
697 (defun parse-namespace-aliases! (stylesheet <transform> env)
698 (do-toplevel (elt "namespace-alias" <transform>)
699 (stp:with-attributes (stylesheet-prefix result-prefix) elt
700 (setf (gethash
701 (if (equal stylesheet-prefix "#default")
703 (xpath-sys:environment-find-namespace env stylesheet-prefix))
704 (stylesheet-namespace-aliases stylesheet))
705 (xpath-sys:environment-find-namespace
707 (if (equal result-prefix "#default")
709 result-prefix))))))
711 (defun parse-decimal-formats! (stylesheet <transform> env)
712 (do-toplevel (elt "decimal-format" <transform>)
713 (stp:with-attributes (name
714 ;; strings
715 infinity
716 (nan "NaN")
717 ;; characters:
718 decimal-separator
719 grouping-separator
720 zero-digit
721 percent
722 per-mille
723 digit
724 pattern-separator
725 minus-sign)
727 (multiple-value-bind (local-name uri)
728 (if name
729 (decode-qname name env nil)
730 (values "" ""))
731 (let ((current (find-decimal-format local-name uri stylesheet nil))
732 (new
733 (let ((seen '()))
734 (flet ((chr (key x)
735 (when x
736 (unless (eql (length x) 1)
737 (xslt-error "not a single character: ~A" x))
738 (let ((chr (elt x 0)))
739 (when (find chr seen)
740 (xslt-error
741 "conflicting decimal format characters: ~A"
742 chr))
743 (push chr seen)
744 (list key chr))))
745 (str (key x)
746 (when x
747 (list key x))))
748 (apply #'make-decimal-format
749 (append (str :infinity infinity)
750 (str :nan nan)
751 (chr :decimal-separator decimal-separator)
752 (chr :grouping-separator grouping-separator)
753 (chr :zero-digit zero-digit)
754 (chr :percent percent)
755 (chr :per-mille per-mille)
756 (chr :digit digit)
757 (chr :pattern-separator pattern-separator)
758 (chr :minus-sign minus-sign)))))))
759 (if current
760 (unless (decimal-format= current new)
761 (xslt-error "decimal format mismatch for ~S" local-name))
762 (setf (find-decimal-format local-name uri stylesheet) new)))))))
764 (defun parse-exclude-result-prefixes! (node env)
765 (stp:with-attributes (exclude-result-prefixes)
766 node
767 (dolist (prefix (words (or exclude-result-prefixes "")))
768 (if (equal prefix "#default")
769 (setf prefix nil)
770 (unless (cxml-stp-impl::nc-name-p prefix)
771 (xslt-error "invalid prefix: ~A" prefix)))
772 (push (or (xpath-sys:environment-find-namespace env prefix)
773 (xslt-error "namespace not found: ~A" prefix))
774 *excluded-namespaces*))))
776 (defun parse-extension-element-prefixes! (node env)
777 (stp:with-attributes (extension-element-prefixes)
778 node
779 (dolist (prefix (words (or extension-element-prefixes "")))
780 (if (equal prefix "#default")
781 (setf prefix nil)
782 (unless (cxml-stp-impl::nc-name-p prefix)
783 (xslt-error "invalid prefix: ~A" prefix)))
784 (let ((uri
785 (or (xpath-sys:environment-find-namespace env prefix)
786 (xslt-error "namespace not found: ~A" prefix))))
787 (unless (equal uri *xsl*)
788 (push uri *extension-namespaces*)
789 (push uri *excluded-namespaces*))))))
791 (defun parse-nametest-tokens (str)
792 (labels ((check (boolean)
793 (unless boolean
794 (xslt-error "invalid nametest token")))
795 (check-null (boolean)
796 (check (not boolean))))
797 (cons
798 :patterns
799 (mapcar (lambda (name-test)
800 (destructuring-bind (&optional path &rest junk)
801 (cdr (xpath:parse-pattern-expression name-test))
802 (check-null junk)
803 (check (eq (car path) :path))
804 (destructuring-bind (&optional child &rest junk) (cdr path)
805 (check-null junk)
806 (check (eq (car child) :child))
807 (destructuring-bind (nodetest &rest junk) (cdr child)
808 (check-null junk)
809 (check (or (stringp nodetest)
810 (eq nodetest '*)
811 (and (consp nodetest)
812 (or (eq (car nodetest) :namespace)
813 (eq (car nodetest) :qname)))))))
814 path))
815 (words str)))))
817 (defstruct strip-test
818 compiled-pattern
819 priority
820 position
821 value)
823 (defun parse-strip/preserve-space! (stylesheet <transform> env)
824 (let ((i 0))
825 (do-toplevel (elt "strip-space|preserve-space" <transform>)
826 (let ((*namespaces* (acons-namespaces elt))
827 (value
828 (if (equal (stp:local-name elt) "strip-space")
829 :strip
830 :preserve)))
831 (dolist (expression
832 (cdr (parse-nametest-tokens
833 (stp:attribute-value elt "elements"))))
834 (let* ((compiled-pattern
835 (car (xpath:compute-patterns
836 `(:patterns ,expression)
837 *import-priority*
838 "will set below"
839 env)))
840 (strip-test
841 (make-strip-test :compiled-pattern compiled-pattern
842 :priority (expression-priority expression)
843 :position i
844 :value value)))
845 (setf (xpath:pattern-value compiled-pattern) strip-test)
846 (push strip-test (stylesheet-strip-tests stylesheet)))))
847 (incf i))))
849 (defstruct (output-specification
850 (:conc-name "OUTPUT-"))
851 method
852 indent
853 omit-xml-declaration
854 encoding
855 doctype-system
856 doctype-public)
858 (defun parse-output! (stylesheet <transform>)
859 (dolist (<output> (list-toplevel "output" <transform>))
860 (let ((spec (stylesheet-output-specification stylesheet)))
861 (stp:with-attributes ( ;; version
862 method
863 indent
864 encoding
865 ;;; media-type
866 doctype-system
867 doctype-public
868 omit-xml-declaration
869 ;;; standalone
870 ;;; cdata-section-elements
872 <output>
873 (when method
874 (setf (output-method spec) method))
875 (when indent
876 (setf (output-indent spec) indent))
877 (when encoding
878 (setf (output-encoding spec) encoding))
879 (when doctype-system
880 (setf (output-doctype-system spec) doctype-system))
881 (when doctype-public
882 (setf (output-doctype-public spec) doctype-public))
883 (when omit-xml-declaration
884 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
885 ;;; (when cdata-section-elements
886 ;;; (setf (output-cdata-section-elements spec)
887 ;;; (concatenate 'string
888 ;;; (output-cdata-section-elements spec)
889 ;;; " "
890 ;;; cdata-section-elements)))
891 ))))
893 (defun make-empty-declaration-array ()
894 (make-array 1 :fill-pointer 0 :adjustable t))
896 (defun make-variable-value-array (n-lexical-variables)
897 (make-array n-lexical-variables :initial-element 'unbound))
899 (defun compile-global-variable (<variable> env) ;; also for <param>
900 (stp:with-attributes (name select) <variable>
901 (when (and select (stp:list-children <variable>))
902 (xslt-error "variable with select and body"))
903 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
904 (inner (cond
905 (select
906 (compile-xpath select env))
907 ((stp:list-children <variable>)
908 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
909 (inner-thunk (compile-instruction inner-sexpr env)))
910 (lambda (ctx)
911 (apply-to-result-tree-fragment ctx inner-thunk))))
913 (lambda (ctx)
914 (declare (ignore ctx))
915 ""))))
916 (n-lexical-variables (length *lexical-variable-declarations*)))
917 (xslt-trace-thunk
918 (lambda (ctx)
919 (let* ((*lexical-variable-values*
920 (make-variable-value-array n-lexical-variables)))
921 (funcall inner ctx)))
922 "global ~s (~s) = ~s" name select :result))))
924 (defstruct (variable-chain
925 (:constructor make-variable-chain)
926 (:conc-name "VARIABLE-CHAIN-"))
927 definitions
928 index
929 local-name
930 thunk
931 uri)
933 (defstruct (import-variable
934 (:constructor make-variable)
935 (:conc-name "VARIABLE-"))
936 value-thunk
937 value-thunk-setter
938 param-p)
940 (defun parse-global-variable! (stylesheet <variable> global-env)
941 (let* ((*namespaces* (acons-namespaces <variable>))
942 (instruction-base-uri (stp:base-uri <variable>))
943 (*instruction-base-uri* instruction-base-uri)
944 (*excluded-namespaces* (list *xsl*))
945 (*extension-namespaces* '())
946 (qname (stp:attribute-value <variable> "name")))
947 (with-import-magic (<variable> global-env)
948 (unless qname
949 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
950 (multiple-value-bind (local-name uri)
951 (decode-qname qname global-env nil)
952 ;; For the normal compilation environment of templates, install it
953 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
954 (let ((index (intern-global-variable local-name uri)))
955 ;; For the evaluation of a global variable itself, build a thunk
956 ;; that lazily resolves other variables, stored into
957 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
958 (let* ((value-thunk :unknown)
959 (sgv (stylesheet-global-variables stylesheet))
960 (chain
961 (if (< index (length sgv))
962 (elt sgv index)
963 (make-variable-chain
964 :index index
965 :local-name local-name
966 :uri uri)))
967 (next (car (variable-chain-definitions chain)))
968 (global-variable-thunk
969 (lambda (ctx)
970 (let ((v (global-variable-value index nil)))
971 (cond
972 ((eq v 'seen)
973 (unless next
974 (xslt-error "no next definition for: ~A"
975 local-name))
976 (funcall (variable-value-thunk next) ctx))
977 ((eq v 'unbound)
978 (setf (global-variable-value index) 'seen)
979 (setf (global-variable-value index)
980 (funcall value-thunk ctx)))
982 v)))))
983 (excluded-namespaces *excluded-namespaces*)
984 (extension-namespaces *extension-namespaces*)
985 (variable
986 (make-variable :param-p (namep <variable> "param")))
987 (value-thunk-setter
988 (lambda ()
989 (let* ((*instruction-base-uri* instruction-base-uri)
990 (*excluded-namespaces* excluded-namespaces)
991 (*extension-namespaces* extension-namespaces)
993 (compile-global-variable <variable> global-env)))
994 (setf value-thunk fn)
995 (setf (variable-value-thunk variable) fn)))))
996 (setf (variable-value-thunk-setter variable)
997 value-thunk-setter)
998 (setf (gethash (cons local-name uri)
999 (initial-global-variable-thunks global-env))
1000 global-variable-thunk)
1001 (setf (variable-chain-thunk chain) global-variable-thunk)
1002 (push variable (variable-chain-definitions chain))
1003 chain))))))
1005 (defun parse-keys! (stylesheet <transform> env)
1006 (xpath:with-namespaces ((nil #.*xsl*))
1007 (do-toplevel (<key> "key" <transform>)
1008 (let ((*instruction-base-uri* (stp:base-uri <key>)))
1009 (stp:with-attributes (name match use) <key>
1010 (unless name (xslt-error "key name attribute not specified"))
1011 (unless match (xslt-error "key match attribute not specified"))
1012 (unless use (xslt-error "key use attribute not specified"))
1013 (multiple-value-bind (local-name uri)
1014 (decode-qname name env nil)
1015 (add-key stylesheet
1016 (cons local-name uri)
1017 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
1018 (compile-xpath use env))))))))
1020 (defun prepare-global-variables (stylesheet <transform>)
1021 (xpath:with-namespaces ((nil #.*xsl*))
1022 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet))
1023 (global-env (make-instance 'global-variable-environment
1024 :initial-global-variable-thunks igvt))
1025 (chains '()))
1026 (do-toplevel (<variable> "variable|param" <transform>)
1027 (let ((chain
1028 (parse-global-variable! stylesheet <variable> global-env)))
1029 (xslt-trace "parsing global variable ~s (uri ~s)"
1030 (variable-chain-local-name chain)
1031 (variable-chain-uri chain))
1032 (when (find chain
1033 chains
1034 :test (lambda (a b)
1035 (and (equal (variable-chain-local-name a)
1036 (variable-chain-local-name b))
1037 (equal (variable-chain-uri a)
1038 (variable-chain-uri b)))))
1039 (xslt-error "duplicate definition for global variable ~A"
1040 (variable-chain-local-name chain)))
1041 (push chain chains)))
1042 (setf chains (nreverse chains))
1043 (let ((table (stylesheet-global-variables stylesheet))
1044 (newlen (length *global-variable-declarations*)))
1045 (adjust-array table newlen :fill-pointer newlen)
1046 (dolist (chain chains)
1047 (setf (elt table (variable-chain-index chain)) chain)))
1048 (lambda ()
1049 ;; now that the global environment knows about all variables, run the
1050 ;; thunk setters to perform their compilation
1051 (mapc (lambda (chain)
1052 (dolist (var (variable-chain-definitions chain))
1053 (funcall (variable-value-thunk-setter var))))
1054 chains)))))
1056 (defun parse-templates! (stylesheet <transform> env)
1057 (let ((i 0))
1058 (do-toplevel (<template> "template" <transform>)
1059 (let ((*namespaces* (acons-namespaces <template>))
1060 (*instruction-base-uri* (stp:base-uri <template>)))
1061 (with-import-magic (<template> env)
1062 (dolist (template (compile-template <template> env i))
1063 (let ((name (template-name template)))
1064 (if name
1065 (let* ((table (stylesheet-named-templates stylesheet))
1066 (head (car (gethash name table))))
1067 (when (and head (eql (template-import-priority head)
1068 (template-import-priority template)))
1069 ;; fixme: is this supposed to be a run-time error?
1070 (xslt-error "conflicting templates for ~A" name))
1071 (push template (gethash name table)))
1072 (let ((mode (ensure-mode/qname stylesheet
1073 (template-mode-qname template)
1074 env)))
1075 (setf (template-mode template) mode)
1076 (push template (mode-templates mode))))))))
1077 (incf i))))
1080 ;;;; APPLY-STYLESHEET
1082 (defvar *stylesheet*)
1084 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
1086 (defun unalias-uri (uri)
1087 (let ((result
1088 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
1089 uri)))
1090 (check-type result string)
1091 result))
1093 (defstruct (parameter
1094 (:constructor make-parameter (value local-name &optional uri)))
1095 (uri "")
1096 local-name
1097 value)
1099 (defun find-parameter-value (local-name uri parameters)
1100 (dolist (p parameters)
1101 (when (and (equal (parameter-local-name p) local-name)
1102 (equal (parameter-uri p) uri))
1103 (return (parameter-value p)))))
1105 (defvar *uri-resolver*)
1107 (defun parse-allowing-microsoft-bom (pathname handler)
1108 (with-open-file (s pathname :element-type '(unsigned-byte 8))
1109 (unless (and (eql (read-byte s nil) #xef)
1110 (eql (read-byte s nil) #xbb)
1111 (eql (read-byte s nil) #xbf))
1112 (file-position s 0))
1113 (cxml:parse s handler)))
1115 (defvar *documents*)
1117 (defun %document (uri-string base-uri)
1118 (let* ((absolute-uri
1119 (puri:merge-uris uri-string (or base-uri "")))
1120 (resolved-uri
1121 (if *uri-resolver*
1122 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
1123 absolute-uri))
1124 (pathname
1125 (handler-case
1126 (uri-to-pathname resolved-uri)
1127 (cxml:xml-parse-error (c)
1128 (xslt-error "cannot find referenced document ~A: ~A"
1129 resolved-uri c))))
1130 (xpath-root-node
1131 (or (gethash pathname *documents*)
1132 (setf (gethash pathname *documents*)
1133 (make-whitespace-stripper
1134 (handler-case
1135 (parse-allowing-microsoft-bom pathname
1136 (stp:make-builder))
1137 ((or file-error cxml:xml-parse-error) (c)
1138 (xslt-error "cannot parse referenced document ~A: ~A"
1139 pathname c)))
1140 (stylesheet-strip-thunk *stylesheet*))))))
1141 (when (puri:uri-fragment absolute-uri)
1142 (xslt-error "use of fragment identifiers in document() not supported"))
1143 xpath-root-node))
1145 (xpath-sys:define-extension xslt *xsl*)
1147 (defun document-base-uri (node)
1148 (xpath-protocol:base-uri
1149 (cond
1150 ((xpath-protocol:node-type-p node :document)
1151 (xpath::find-in-pipe-if
1152 (lambda (x)
1153 (xpath-protocol:node-type-p x :element))
1154 (xpath-protocol:child-pipe node)))
1155 ((xpath-protocol:node-type-p node :element)
1156 node)
1158 (xpath-protocol:parent-node node)))))
1160 (xpath-sys:define-xpath-function/lazy
1161 xslt :document
1162 (object &optional node-set)
1163 (let ((instruction-base-uri *instruction-base-uri*))
1164 (lambda (ctx)
1165 (let* ((object (funcall object ctx))
1166 (node-set (and node-set (funcall node-set ctx)))
1167 (base-uri
1168 (if node-set
1169 (document-base-uri (xpath::textually-first-node node-set))
1170 instruction-base-uri)))
1171 (xpath-sys:make-node-set
1172 (if (xpath:node-set-p object)
1173 (xpath:map-node-set->list
1174 (lambda (node)
1175 (%document (xpath:string-value node)
1176 (if node-set
1177 base-uri
1178 (document-base-uri node))))
1179 object)
1180 (list (%document (xpath:string-value object) base-uri))))))))
1182 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1183 (let ((namespaces *namespaces*))
1184 (lambda (ctx)
1185 (let* ((qname (xpath:string-value (funcall name ctx)))
1186 (object (funcall object ctx))
1187 (expanded-name
1188 (multiple-value-bind (local-name uri)
1189 (decode-qname/runtime qname namespaces nil)
1190 (cons local-name uri)))
1191 (key (find-key expanded-name *stylesheet*)))
1192 (labels ((get-by-key (value)
1193 (let ((value (xpath:string-value value)))
1194 (xpath::filter-pipe
1195 #'(lambda (node)
1196 (let ((uses
1197 (xpath:evaluate-compiled (key-use key) node)))
1198 (if (xpath:node-set-p uses)
1199 (xpath::find-in-pipe
1200 value
1201 (xpath-sys:pipe-of uses)
1202 :key #'xpath:string-value
1203 :test #'equal)
1204 (equal value (xpath:string-value uses)))))
1205 (xpath-sys:pipe-of
1206 (xpath:node-set-value
1207 (xpath:evaluate-compiled (key-match key) ctx)))))))
1208 (xpath-sys:make-node-set
1209 (xpath::sort-pipe
1210 (if (xpath:node-set-p object)
1211 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1212 (get-by-key object)))))))))
1214 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1216 (xpath-sys:define-xpath-function/lazy xslt :current ()
1217 #'(lambda (ctx)
1218 (xpath-sys:make-node-set
1219 (xpath-sys:make-pipe
1220 (xpath:context-starting-node ctx)
1221 nil))))
1223 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1224 #'(lambda (ctx)
1225 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1226 (funcall name ctx))
1227 "")))
1229 (defun %get-node-id (node)
1230 (when (xpath:node-set-p node)
1231 (setf node (xpath::textually-first-node node)))
1232 (when node
1233 (let ((id (xpath-sys:get-node-id node))
1234 (highest-base-uri
1235 (loop
1236 for parent = node then next
1237 for next = (xpath-protocol:parent-node parent)
1238 for this-base-uri = (xpath-protocol:base-uri parent)
1239 for highest-base-uri = (if (plusp (length this-base-uri))
1240 this-base-uri
1241 highest-base-uri)
1242 while next
1243 finally (return highest-base-uri))))
1244 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1245 ;; checked only if everything else matches.
1247 ;; This might be pointless premature optimization, but I like the idea :-)
1248 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1250 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1251 (if node-set-thunk
1252 #'(lambda (ctx)
1253 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1254 #'(lambda (ctx)
1255 (%get-node-id (xpath:context-node ctx)))))
1257 (declaim (special *available-instructions*))
1259 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1260 (let ((namespaces *namespaces*))
1261 #'(lambda (ctx)
1262 (let ((qname (funcall qname ctx)))
1263 (multiple-value-bind (local-name uri)
1264 (decode-qname/runtime qname namespaces nil)
1265 (and (equal uri *xsl*)
1266 (gethash local-name *available-instructions*)
1267 t))))))
1269 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1270 (let ((namespaces *namespaces*))
1271 #'(lambda (ctx)
1272 (let ((qname (funcall qname ctx)))
1273 (multiple-value-bind (local-name uri)
1274 (decode-qname/runtime qname namespaces nil)
1275 (and (zerop (length uri))
1276 (or (xpath-sys:find-xpath-function local-name *xsl*)
1277 (xpath-sys:find-xpath-function local-name uri))
1278 t))))))
1280 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1281 (let ((namespaces *namespaces*))
1282 (lambda (ctx)
1283 (let ((qname (funcall qname ctx)))
1284 (multiple-value-bind (local-name uri)
1285 (decode-qname/runtime qname namespaces nil)
1286 (if (equal uri *xsl*)
1287 (cond
1288 ((equal local-name "version")
1289 "1")
1290 ((equal local-name "vendor")
1291 "Xuriella")
1292 ((equal local-name "vendor-uri")
1293 "http://repo.or.cz/w/xuriella.git")
1295 ""))
1296 ""))))))
1298 (defun apply-stylesheet
1299 (stylesheet source-designator
1300 &key output parameters uri-resolver navigator)
1301 (when (typep stylesheet 'xml-designator)
1302 (setf stylesheet
1303 (handler-bind
1304 ((cxml:xml-parse-error
1305 (lambda (c)
1306 (xslt-error "cannot parse stylesheet: ~A" c))))
1307 (parse-stylesheet stylesheet))))
1308 (with-resignalled-errors ()
1309 (invoke-with-output-sink
1310 (lambda ()
1311 (let* ((*documents* (make-hash-table :test 'equal))
1312 (xpath:*navigator* (or navigator :default-navigator))
1313 (puri:*strict-parse* nil)
1314 (*stylesheet* stylesheet)
1315 (*empty-mode* (make-mode))
1316 (*default-mode* (find-mode stylesheet nil))
1317 (global-variable-chains
1318 (stylesheet-global-variables stylesheet))
1319 (*global-variable-values*
1320 (make-variable-value-array (length global-variable-chains)))
1321 (*uri-resolver* uri-resolver)
1322 (source-document
1323 (if (typep source-designator 'xml-designator)
1324 (cxml:parse source-designator (stp:make-builder))
1325 source-designator))
1326 (xpath-root-node
1327 (make-whitespace-stripper
1328 source-document
1329 (stylesheet-strip-thunk stylesheet)))
1330 (ctx (xpath:make-context xpath-root-node)))
1331 (when (pathnamep source-designator)
1332 (setf (gethash source-designator *documents*) xpath-root-node))
1333 (map nil
1334 (lambda (chain)
1335 (let ((head (car (variable-chain-definitions chain))))
1336 (when (variable-param-p head)
1337 (let ((value
1338 (find-parameter-value
1339 (variable-chain-local-name chain)
1340 (variable-chain-uri chain)
1341 parameters)))
1342 (when value
1343 (setf (global-variable-value
1344 (variable-chain-index chain))
1345 value))))))
1346 global-variable-chains)
1347 (map nil
1348 (lambda (chain)
1349 (funcall (variable-chain-thunk chain) ctx))
1350 global-variable-chains)
1351 ;; zzz we wouldn't have to mask float traps here if we used the
1352 ;; XPath API properly. Unfortunately I've been using FUNCALL
1353 ;; everywhere instead of EVALUATE, so let's paper over that
1354 ;; at a central place to be sure:
1355 (xpath::with-float-traps-masked ()
1356 (apply-templates ctx :mode *default-mode*))))
1357 (stylesheet-output-specification stylesheet)
1358 output)))
1360 (defun find-attribute-set (local-name uri &optional (stylesheet *stylesheet*))
1361 (or (gethash (cons local-name uri) (stylesheet-attribute-sets stylesheet))
1362 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1364 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1365 (when sort-predicate
1366 (setf list
1367 (mapcar #'xpath:context-node
1368 (stable-sort (contextify-node-list list)
1369 sort-predicate))))
1370 (let* ((n (length list))
1371 (s/d (lambda () n)))
1372 (loop
1373 for i from 1
1374 for child in list
1376 (apply-templates (xpath:make-context child s/d i)
1377 :param-bindings param-bindings
1378 :mode mode))))
1380 (defvar *stack-limit* 200)
1382 (defun invoke-with-stack-limit (fn)
1383 (let ((*stack-limit* (1- *stack-limit*)))
1384 (unless (plusp *stack-limit*)
1385 (xslt-error "*stack-limit* reached; stack overflow"))
1386 (funcall fn)))
1388 (defun invoke-template (ctx template param-bindings)
1389 (let ((*lexical-variable-values*
1390 (make-variable-value-array (template-n-variables template))))
1391 (with-stack-limit ()
1392 (loop
1393 for (name-cons value) in param-bindings
1394 for (nil index nil) = (find name-cons
1395 (template-params template)
1396 :test #'equal
1397 :key #'car)
1399 (when index
1400 (setf (lexical-variable-value index) value)))
1401 (funcall (template-body template) ctx))))
1403 (defun apply-default-templates (ctx mode)
1404 (let ((node (xpath:context-node ctx)))
1405 (cond
1406 ((or (xpath-protocol:node-type-p node :processing-instruction)
1407 (xpath-protocol:node-type-p node :comment)))
1408 ((or (xpath-protocol:node-type-p node :text)
1409 (xpath-protocol:node-type-p node :attribute))
1410 (write-text (xpath-protocol:node-text node)))
1412 (apply-templates/list
1413 (xpath::force
1414 (xpath-protocol:child-pipe node))
1415 :mode mode)))))
1417 (defvar *apply-imports*)
1419 (defun apply-applicable-templates (ctx templates param-bindings finally)
1420 (labels ((apply-imports (&optional actual-param-bindings)
1421 (if templates
1422 (let* ((this (pop templates))
1423 (low (template-apply-imports-limit this))
1424 (high (template-import-priority this)))
1425 (setf templates
1426 (remove-if-not
1427 (lambda (x)
1428 (<= low (template-import-priority x) high))
1429 templates))
1430 (invoke-template ctx this actual-param-bindings))
1431 (funcall finally))))
1432 (let ((*apply-imports* #'apply-imports))
1433 (apply-imports param-bindings))))
1435 (defun apply-templates (ctx &key param-bindings mode)
1436 (apply-applicable-templates ctx
1437 (find-templates ctx (or mode *default-mode*))
1438 param-bindings
1439 (lambda ()
1440 (apply-default-templates ctx mode))))
1442 (defun call-template (ctx name &optional param-bindings)
1443 (apply-applicable-templates ctx
1444 (find-named-templates name)
1445 param-bindings
1446 (lambda ()
1447 (error "cannot find named template: ~s"
1448 name))))
1450 (defun find-templates (ctx mode)
1451 (let* ((matching-candidates
1452 (xpath:matching-values (mode-match-thunk mode)
1453 (xpath:context-node ctx)))
1454 (npriorities
1455 (if matching-candidates
1456 (1+ (reduce #'max
1457 matching-candidates
1458 :key #'template-import-priority))
1460 (priority-groups (make-array npriorities :initial-element nil)))
1461 (dolist (template matching-candidates)
1462 (push template
1463 (elt priority-groups (template-import-priority template))))
1464 (loop
1465 for i from (1- npriorities) downto 0
1466 for group = (elt priority-groups i)
1467 for template = (maximize #'template< group)
1468 when template
1469 collect template)))
1471 (defun find-named-templates (name)
1472 (gethash name (stylesheet-named-templates *stylesheet*)))
1474 (defun template< (a b) ;assuming same import priority
1475 (let ((p (template-priority a))
1476 (q (template-priority b)))
1477 (cond
1478 ((< p q) t)
1479 ((> p q) nil)
1481 (xslt-cerror "conflicting templates:~_~A,~_~A"
1482 (template-match-expression a)
1483 (template-match-expression b))
1484 (< (template-position a) (template-position b))))))
1486 (defun maximize (< things)
1487 (when things
1488 (let ((max (car things)))
1489 (dolist (other (cdr things))
1490 (when (funcall < max other)
1491 (setf max other)))
1492 max)))
1494 (defun invoke-with-output-sink (fn output-spec output)
1495 (etypecase output
1496 (pathname
1497 (with-open-file (s output
1498 :direction :output
1499 :element-type '(unsigned-byte 8)
1500 :if-exists :rename-and-delete)
1501 (invoke-with-output-sink fn output-spec s)))
1502 ((or stream null)
1503 (invoke-with-output-sink fn
1504 output-spec
1505 (make-output-sink output-spec output)))
1506 ((or hax:abstract-handler sax:abstract-handler)
1507 (with-xml-output output
1508 (when (typep output '(or combi-sink auto-detect-sink))
1509 (sax:start-dtd output
1510 :autodetect-me-please
1511 (output-doctype-public output-spec)
1512 (output-doctype-system output-spec)))
1513 (funcall fn)))))
1515 (defun make-output-sink (output-spec stream)
1516 (let* ((ystream
1517 (if stream
1518 (let ((et (stream-element-type stream)))
1519 (cond
1520 ((or (null et) (subtypep et '(unsigned-byte 8)))
1521 (runes:make-octet-stream-ystream stream))
1522 ((subtypep et 'character)
1523 (runes:make-character-stream-ystream stream))))
1524 (runes:make-rod-ystream)))
1525 (omit-xml-declaration-p
1526 (equal (output-omit-xml-declaration output-spec) "yes"))
1527 (sink-encoding (or (output-encoding output-spec) "UTF-8"))
1528 (sax-target
1529 (progn
1530 (setf (runes:ystream-encoding ystream)
1531 (cxml::find-output-encoding sink-encoding))
1532 (make-instance 'cxml::sink
1533 :ystream ystream
1534 :omit-xml-declaration-p omit-xml-declaration-p
1535 :encoding sink-encoding))))
1536 (flet ((make-combi-sink ()
1537 (make-instance 'combi-sink
1538 :hax-target (make-instance 'chtml::sink
1539 :ystream ystream)
1540 :sax-target sax-target
1541 :encoding sink-encoding)))
1542 (let ((method-key
1543 (cond
1544 ((equalp (output-method output-spec) "HTML") :html)
1545 ((equalp (output-method output-spec) "TEXT") :text)
1546 ((equalp (output-method output-spec) "XML") :xml)
1547 (t nil))))
1548 (cond
1549 ((and (eq method-key :html)
1550 (null (output-doctype-system output-spec))
1551 (null (output-doctype-public output-spec)))
1552 (make-combi-sink))
1553 ((eq method-key :text)
1554 (make-text-filter sax-target))
1555 ((and (eq method-key :xml)
1556 (null (output-doctype-system output-spec)))
1557 sax-target)
1559 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1561 (defstruct template
1562 match-expression
1563 compiled-pattern
1564 name
1565 import-priority
1566 apply-imports-limit
1567 priority
1568 position
1569 mode
1570 mode-qname
1571 params
1572 body
1573 n-variables)
1575 (defun expression-priority (form)
1576 (let ((step (second form)))
1577 (if (and (null (cddr form))
1578 (listp step)
1579 (member (car step) '(:child :attribute))
1580 (null (cddr step)))
1581 (let ((name (second step)))
1582 (cond
1583 ((or (stringp name)
1584 (and (consp name)
1585 (or (eq (car name) :qname)
1586 (eq (car name) :processing-instruction))))
1587 0.0)
1588 ((and (consp name)
1589 (or (eq (car name) :namespace)
1590 (eq (car name) '*)))
1591 -0.25)
1593 -0.5)))
1594 0.5)))
1596 (defun parse-xpath (str)
1597 (with-resignalled-errors ()
1598 (xpath:parse-xpath str)))
1600 (defun parse-key-pattern (str)
1601 (let ((parsed
1602 (mapcar #'(lambda (item)
1603 `(:path (:root :node)
1604 (:descendant-or-self *)
1605 ,@(cdr item)))
1606 (parse-pattern str))))
1607 (if (null (rest parsed))
1608 (first parsed)
1609 `(:union ,@parsed))))
1611 (defun parse-pattern (str)
1612 (with-resignalled-errors ()
1613 (cdr (xpath::parse-pattern-expression str))))
1615 (defun compile-value-thunk (value env)
1616 (if (and (listp value) (eq (car value) 'progn))
1617 (let ((inner-thunk (compile-instruction value env)))
1618 (lambda (ctx)
1619 (apply-to-result-tree-fragment ctx inner-thunk)))
1620 (compile-xpath value env)))
1622 (defun compile-var-binding (name value env)
1623 (multiple-value-bind (local-name uri)
1624 (decode-qname name env nil)
1625 (let ((thunk (xslt-trace-thunk
1626 (compile-value-thunk value env)
1627 "local variable ~s = ~s" name :result)))
1628 (list (cons local-name uri)
1629 (push-variable local-name
1631 *lexical-variable-declarations*)
1632 thunk))))
1634 (defun compile-var-bindings (forms env)
1635 (loop
1636 for (name value) in forms
1637 collect (compile-var-binding name value env)))
1639 (defun compile-template (<template> env position)
1640 (stp:with-attributes (match name priority mode) <template>
1641 (unless (or name match)
1642 (xslt-error "missing match in template"))
1643 (multiple-value-bind (params body-pos)
1644 (loop
1645 for i from 0
1646 for child in (stp:list-children <template>)
1647 while (namep child "param")
1648 collect (parse-param child) into params
1649 finally (return (values params i)))
1650 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1651 (param-bindings (compile-var-bindings params env))
1652 (body (parse-body <template> body-pos (mapcar #'car params)))
1653 (body-thunk (compile-instruction `(progn ,@body) env))
1654 (outer-body-thunk
1655 (xslt-trace-thunk
1656 #'(lambda (ctx)
1657 (unwind-protect
1658 (progn
1659 ;; set params that weren't initialized by apply-templates
1660 (loop for (name index param-thunk) in param-bindings
1661 when (eq (lexical-variable-value index nil) 'unbound)
1662 do (setf (lexical-variable-value index)
1663 (funcall param-thunk ctx)))
1664 (funcall body-thunk ctx))))
1665 "template: match = ~s name = ~s" match name))
1666 (n-variables (length *lexical-variable-declarations*)))
1667 (append
1668 (when name
1669 (multiple-value-bind (local-name uri)
1670 (decode-qname name env nil)
1671 (list
1672 (make-template :name (cons local-name uri)
1673 :import-priority *import-priority*
1674 :apply-imports-limit *apply-imports-limit*
1675 :params param-bindings
1676 :body outer-body-thunk
1677 :n-variables n-variables))))
1678 (when match
1679 (mapcar (lambda (expression)
1680 (let* ((compiled-pattern
1681 (xslt-trace-thunk
1682 (car (xpath:compute-patterns
1683 `(:patterns ,expression)
1685 :dummy
1686 env))
1687 "match-thunk for template (match ~s): ~s --> ~s"
1688 match expression :result))
1689 (p (if priority
1690 (xpath::parse-xnum priority)
1691 (expression-priority expression)))
1693 (progn
1694 (unless (and (numberp p)
1695 (not (xpath::inf-p p))
1696 (not (xpath::nan-p p)))
1697 (xslt-error "failed to parse priority"))
1698 (float p 1.0d0)))
1699 (template
1700 (make-template :match-expression expression
1701 :compiled-pattern compiled-pattern
1702 :import-priority *import-priority*
1703 :apply-imports-limit *apply-imports-limit*
1704 :priority p
1705 :position position
1706 :mode-qname mode
1707 :params param-bindings
1708 :body outer-body-thunk
1709 :n-variables n-variables)))
1710 (setf (xpath:pattern-value compiled-pattern)
1711 template)
1712 template))
1713 (cdr (xpath:parse-pattern-expression match)))))))))
1714 #+(or)
1715 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")