Check for attribute set names
[xuriella.git] / xslt.lisp
bloba3dbd99ede11cb2decebb890ca55a569ae07e86a
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 (multiple-value-bind (prefix local-name)
186 (split-qname qname)
187 (values local-name
188 (if (or prefix (not attributep))
189 (xpath-sys:environment-find-namespace env (or prefix ""))
191 prefix)))
193 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
194 (or (cdr (assoc prefix *namespaces* :test 'equal))
195 ;; zzz gross hack.
196 ;; Change the entire code base to represent "no prefix" as the
197 ;; empty string consistently. unparse.lisp has already been changed.
198 (and (equal prefix "")
199 (cdr (assoc nil *namespaces* :test 'equal)))
200 (and (eql prefix nil)
201 (cdr (assoc "" *namespaces* :test 'equal)))))
203 (defun find-variable-index (local-name uri table)
204 (position (cons local-name uri) table :test 'equal))
206 (defun intern-global-variable (local-name uri)
207 (or (find-variable-index local-name uri *global-variable-declarations*)
208 (push-variable local-name uri *global-variable-declarations*)))
210 (defun push-variable (local-name uri table)
211 (prog1
212 (length table)
213 (vector-push-extend (cons local-name uri) table)))
215 (defun lexical-variable-value (index &optional (errorp t))
216 (let ((result (svref *lexical-variable-values* index)))
217 (when errorp
218 (assert (not (eq result 'unbound))))
219 result))
221 (defun (setf lexical-variable-value) (newval index)
222 (assert (not (eq newval 'unbound)))
223 (setf (svref *lexical-variable-values* index) newval))
225 (defun global-variable-value (index &optional (errorp t))
226 (let ((result (svref *global-variable-values* index)))
227 (when errorp
228 (assert (not (eq result 'unbound))))
229 result))
231 (defun (setf global-variable-value) (newval index)
232 (assert (not (eq newval 'unbound)))
233 (setf (svref *global-variable-values* index) newval))
235 (defmethod xpath-sys:environment-find-function
236 ((env xslt-environment) lname uri)
237 (if (string= uri "")
238 (or (xpath-sys:find-xpath-function lname *xsl*)
239 (xpath-sys:find-xpath-function lname uri))
240 (xpath-sys:find-xpath-function lname uri)))
242 (defmethod xpath-sys:environment-find-variable
243 ((env xslt-environment) lname uri)
244 (let ((index
245 (find-variable-index lname uri *lexical-variable-declarations*)))
246 (when index
247 (lambda (ctx)
248 (declare (ignore ctx))
249 (svref *lexical-variable-values* index)))))
251 (defclass lexical-xslt-environment (xslt-environment) ())
253 (defmethod xpath-sys:environment-find-variable
254 ((env lexical-xslt-environment) lname uri)
255 (or (call-next-method)
256 (let ((index
257 (find-variable-index lname uri *global-variable-declarations*)))
258 (when index
259 (xslt-trace-thunk
260 (lambda (ctx)
261 (declare (ignore ctx))
262 (svref *global-variable-values* index))
263 "global ~s (uri ~s) = ~s" lname uri :result)))))
265 (defclass global-variable-environment (xslt-environment)
266 ((initial-global-variable-thunks
267 :initarg :initial-global-variable-thunks
268 :accessor initial-global-variable-thunks)))
270 (defmethod xpath-sys:environment-find-variable
271 ((env global-variable-environment) lname uri)
272 (or (call-next-method)
273 (gethash (cons lname uri) (initial-global-variable-thunks env))))
276 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
277 ;;;;
278 ;;;; A sink that serializes only text not contained in any element.
280 (defmacro with-toplevel-text-output-sink ((var) &body body)
281 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
283 (defclass toplevel-text-output-sink (sax:default-handler)
284 ((target :initarg :target :accessor text-output-sink-target)
285 (depth :initform 0 :accessor textoutput-sink-depth)))
287 (defmethod sax:start-element ((sink toplevel-text-output-sink)
288 namespace-uri local-name qname attributes)
289 (declare (ignore namespace-uri local-name qname attributes))
290 (incf (textoutput-sink-depth sink)))
292 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
293 (when (zerop (textoutput-sink-depth sink))
294 (write-string data (text-output-sink-target sink))))
296 (defmethod sax:unescaped ((sink toplevel-text-output-sink) data)
297 (sax:characters sink data))
299 (defmethod sax:end-element ((sink toplevel-text-output-sink)
300 namespace-uri local-name qname)
301 (declare (ignore namespace-uri local-name qname))
302 (decf (textoutput-sink-depth sink)))
304 (defun invoke-with-toplevel-text-output-sink (fn)
305 (with-output-to-string (s)
306 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
309 ;;;; TEXT-FILTER
310 ;;;;
311 ;;;; A sink that passes through only text (at any level) and turns to
312 ;;;; into unescaped characters.
314 (defclass text-filter (sax:default-handler)
315 ((target :initarg :target :accessor text-filter-target)))
317 (defmethod sax:characters ((sink text-filter) data)
318 (sax:unescaped (text-filter-target sink) data))
320 (defmethod sax:unescaped ((sink text-filter) data)
321 (sax:unescaped (text-filter-target sink) data))
323 (defmethod sax:end-document ((sink text-filter))
324 (sax:end-document (text-filter-target sink)))
326 (defun make-text-filter (target)
327 (make-instance 'text-filter :target target))
330 ;;;; ESCAPER
331 ;;;;
332 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
333 ;;;; XSLT 16.4.
335 (defclass escaper (cxml:broadcast-handler)
338 (defmethod sax:unescaped ((sink escaper) data)
339 (sax:characters sink data))
341 (defun make-escaper (target)
342 (make-instance 'escaper :handlers (list target)))
345 ;;;; Names
347 (defun of-name (local-name)
348 (stp:of-name local-name *xsl*))
350 (defun namep (node local-name)
351 (and (typep node '(or stp:element stp:attribute))
352 (equal (stp:namespace-uri node) *xsl*)
353 (equal (stp:local-name node) local-name)))
356 ;;;; PARSE-STYLESHEET
358 (defstruct stylesheet
359 (modes (make-hash-table :test 'equal))
360 (global-variables (make-empty-declaration-array))
361 (output-specification (make-output-specification))
362 (strip-tests nil)
363 (strip-thunk nil)
364 (named-templates (make-hash-table :test 'equal))
365 (attribute-sets (make-hash-table :test 'equal))
366 (keys (make-hash-table :test 'equal))
367 (namespace-aliases (make-hash-table :test 'equal))
368 (decimal-formats (make-hash-table :test 'equal))
369 (initial-global-variable-thunks (make-hash-table :test 'equal)))
371 (defstruct mode
372 (templates nil)
373 (match-thunk (lambda (ignore) (declare (ignore ignore)) nil)))
375 (defun find-mode (stylesheet local-name &optional uri)
376 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
378 (defun ensure-mode (stylesheet &optional local-name uri)
379 (or (find-mode stylesheet local-name uri)
380 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
381 (make-mode))))
383 (defun ensure-mode/qname (stylesheet qname env)
384 (if qname
385 (multiple-value-bind (local-name uri)
386 (decode-qname qname env nil)
387 (ensure-mode stylesheet local-name uri))
388 (find-mode stylesheet nil)))
390 (defun acons-namespaces (element &optional (bindings *namespaces*))
391 (map-namespace-declarations (lambda (prefix uri)
392 (push (cons prefix uri) bindings))
393 element)
394 bindings)
396 (defun find-key (name stylesheet)
397 (or (gethash name (stylesheet-keys stylesheet))
398 (xslt-error "unknown key: ~a" name)))
400 (defun make-key (match use) (cons match use))
402 (defun key-match (key) (car key))
404 (defun key-use (key) (cdr key))
406 (defun add-key (stylesheet name match use)
407 (if (gethash name (stylesheet-keys stylesheet))
408 (xslt-error "duplicate key: ~a" name)
409 (setf (gethash name (stylesheet-keys stylesheet))
410 (make-key match use))))
412 (defvar *excluded-namespaces* (list *xsl*))
413 (defvar *empty-mode*)
414 (defvar *default-mode*)
416 (defvar *xsl-include-stack* nil)
418 (defun uri-to-pathname (uri)
419 (cxml::uri-to-pathname (puri:parse-uri uri)))
421 (defun unwrap-2.3 (document)
422 (let ((literal-result-element (stp:document-element document))
423 (new-template (stp:make-element "template" *xsl*))
424 (new-document-element (stp:make-element "stylesheet" *xsl*)))
425 (setf (stp:attribute-value new-document-element "version")
426 (or (stp:attribute-value literal-result-element "version" *xsl*)
427 (xslt-error "not a stylesheet: root element lacks xsl:version")))
428 (setf (stp:attribute-value new-template "match") "/")
429 (setf (stp:document-element document) new-document-element)
430 (stp:append-child new-document-element new-template)
431 (stp:append-child new-template literal-result-element)
432 new-document-element))
434 (defun parse-stylesheet-to-stp (input uri-resolver)
435 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
436 (<transform> (stp:document-element d)))
437 (unless (equal (stp:namespace-uri <transform>) *xsl*)
438 (setf <transform> (unwrap-2.3 d)))
439 (strip-stylesheet <transform>)
440 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
441 (or (equal (stp:local-name <transform>) "transform")
442 (equal (stp:local-name <transform>) "stylesheet")))
443 (xslt-error "not a stylesheet"))
444 (check-for-invalid-attributes '(("version" . "")
445 ("exclude-result-prefixes" . "")
446 ("extension-element-prefixes" . ""))
447 <transform>)
448 (let ((invalid
449 (or (stp:find-child-if (of-name "stylesheet") <transform>)
450 (stp:find-child-if (of-name "transform") <transform>))))
451 (when invalid
452 (xslt-error "invalid top-level element ~A" (stp:local-name invalid))))
453 (dolist (include (stp:filter-children (of-name "include") <transform>))
454 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
455 (stp:base-uri include)))
456 (uri (if uri-resolver
457 (funcall uri-resolver (puri:render-uri uri nil))
458 uri))
459 (str (puri:render-uri uri nil))
460 (pathname
461 (handler-case
462 (uri-to-pathname uri)
463 (cxml:xml-parse-error (c)
464 (xslt-error "cannot find included stylesheet ~A: ~A"
465 uri c)))))
466 (with-open-file
467 (stream pathname
468 :element-type '(unsigned-byte 8)
469 :if-does-not-exist nil)
470 (unless stream
471 (xslt-error "cannot find included stylesheet ~A at ~A"
472 uri pathname))
473 (when (find str *xsl-include-stack* :test #'equal)
474 (xslt-error "recursive inclusion of ~A" uri))
475 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
476 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
477 (stp:insert-child-after <transform>
478 (stp:copy <transform>2)
479 include)
480 (stp:detach include)))))
481 <transform>))
483 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
484 (defvar *apply-imports-limit*)
485 (defvar *import-priority*)
486 (defvar *extension-namespaces*)
487 (defvar *forwards-compatible-p*)
489 (defmacro do-toplevel ((var xpath <transform>) &body body)
490 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
492 (defun map-toplevel (fn xpath <transform>)
493 (dolist (node (list-toplevel xpath <transform>))
494 (let ((*namespaces* *namespaces*))
495 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
496 (when (xpath-protocol:node-type-p ancestor :element)
497 (setf *namespaces* (acons-namespaces ancestor))))
498 (funcall fn node))))
500 (defun list-toplevel (xpath <transform>)
501 (labels ((recurse (sub)
502 (let ((subsubs
503 (xpath-sys:pipe-of
504 (xpath:evaluate "transform|stylesheet" sub))))
505 (xpath::append-pipes
506 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
507 (xpath::mappend-pipe #'recurse subsubs)))))
508 (xpath::sort-nodes (recurse <transform>))))
510 (defmacro with-import-magic ((node env) &body body)
511 `(invoke-with-import-magic (lambda () ,@body) ,node ,env))
513 (defun invoke-with-import-magic (fn node env)
514 (unless (or (namep node "stylesheet") (namep node "transform"))
515 (setf node (stp:parent node)))
516 (let ((*excluded-namespaces* (list *xsl*))
517 (*extension-namespaces* '())
518 (*forwards-compatible-p*
519 (not (equal (stp:attribute-value node "version") "1.0"))))
520 (parse-exclude-result-prefixes! node env)
521 (parse-extension-element-prefixes! node env)
522 (funcall fn)))
524 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
525 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
526 (instruction-base-uri (stp:base-uri <transform>))
527 (namespaces (acons-namespaces <transform>))
528 (apply-imports-limit (1+ *import-priority*))
529 (continuations '()))
530 (let ((*namespaces* namespaces))
531 (invoke-with-import-magic (constantly t) <transform> env))
532 (do-toplevel (elt "node()" <transform>)
533 (let ((version (stp:attribute-value (stp:parent elt) "version")))
534 (cond
535 ((null version)
536 (xslt-error "stylesheet lacks version"))
537 ((equal version "1.0")
538 (if (typep elt 'stp:element)
539 (when (or (equal (stp:namespace-uri elt) "")
540 (and (equal (stp:namespace-uri elt) *xsl*)
541 (not (find (stp:local-name elt)
542 '("key" "template" "output"
543 "strip-space" "preserve-space"
544 "attribute-set" "namespace-alias"
545 "decimal-format" "variable" "param"
546 "import" "include"
547 ;; for include handling:
548 "stylesheet" "transform")
549 :test #'equal))))
550 (xslt-error "unknown top-level element ~A" (stp:local-name elt)))
551 (xslt-error "text at top-level"))))))
552 (macrolet ((with-specials ((&optional) &body body)
553 `(let ((*instruction-base-uri* instruction-base-uri)
554 (*namespaces* namespaces)
555 (*apply-imports-limit* apply-imports-limit))
556 ,@body)))
557 (with-specials ()
558 (do-toplevel (import "import" <transform>)
559 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
560 (stp:base-uri import))))
561 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
562 continuations))))
563 (let ((import-priority
564 (incf *import-priority*))
565 (var-cont (prepare-global-variables stylesheet <transform>)))
566 ;; delay the rest of compilation until we've seen all global
567 ;; variables:
568 (lambda ()
569 (mapc #'funcall (nreverse continuations))
570 (with-specials ()
571 (let ((*import-priority* import-priority))
572 (funcall var-cont)
573 (parse-keys! stylesheet <transform> env)
574 (parse-templates! stylesheet <transform> env)
575 (parse-output! stylesheet <transform>)
576 (parse-strip/preserve-space! stylesheet <transform> env)
577 (parse-attribute-sets! stylesheet <transform> env)
578 (parse-namespace-aliases! stylesheet <transform> env)
579 (parse-decimal-formats! stylesheet <transform> env))))))))
581 (defvar *xsl-import-stack* nil)
583 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
584 (let* ((uri (if uri-resolver
585 (funcall uri-resolver (puri:render-uri uri nil))
586 uri))
587 (str (puri:render-uri uri nil))
588 (pathname
589 (handler-case
590 (uri-to-pathname uri)
591 (cxml:xml-parse-error (c)
592 (xslt-error "cannot find imported stylesheet ~A: ~A"
593 uri c)))))
594 (with-open-file
595 (stream pathname
596 :element-type '(unsigned-byte 8)
597 :if-does-not-exist nil)
598 (unless stream
599 (xslt-error "cannot find imported stylesheet ~A at ~A"
600 uri pathname))
601 (when (find str *xsl-import-stack* :test #'equal)
602 (xslt-error "recursive inclusion of ~A" uri))
603 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
604 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
606 (defun parse-stylesheet (designator &key uri-resolver)
607 (with-resignalled-errors ()
608 (xpath:with-namespaces ((nil #.*xsl*))
609 (let* ((*import-priority* 0)
610 (xpath:*allow-variables-in-patterns* nil)
611 (puri:*strict-parse* nil)
612 (stylesheet (make-stylesheet))
613 (env (make-instance 'lexical-xslt-environment))
614 (*excluded-namespaces* *excluded-namespaces*)
615 (*global-variable-declarations* (make-empty-declaration-array)))
616 (ensure-mode stylesheet nil)
617 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
618 ;; reverse attribute sets:
619 (let ((table (stylesheet-attribute-sets stylesheet)))
620 (maphash (lambda (k v)
621 (setf (gethash k table) (nreverse v)))
622 table))
623 ;; add default df
624 (unless (find-decimal-format "" "" stylesheet nil)
625 (setf (find-decimal-format "" "" stylesheet)
626 (make-decimal-format)))
627 ;; compile a template matcher for each mode:
628 (loop
629 for mode being each hash-value in (stylesheet-modes stylesheet)
631 (setf (mode-match-thunk mode)
632 (xpath:make-pattern-matcher
633 (mapcar #'template-compiled-pattern
634 (mode-templates mode)))))
635 ;; and for the strip tests
636 (setf (stylesheet-strip-thunk stylesheet)
637 (let ((patterns (stylesheet-strip-tests stylesheet)))
638 (and patterns
639 (xpath:make-pattern-matcher
640 (mapcar #'strip-test-compiled-pattern patterns)))))
641 stylesheet))))
643 (defun parse-attribute-sets! (stylesheet <transform> env)
644 (do-toplevel (elt "attribute-set" <transform>)
645 (with-import-magic (elt env)
646 (push (let* ((sets
647 (mapcar (lambda (qname)
648 (multiple-value-list (decode-qname qname env nil)))
649 (words
650 (stp:attribute-value elt "use-attribute-sets"))))
651 (instructions
652 (stp:map-children
653 'list
654 (lambda (child)
655 (unless
656 (and (typep child 'stp:element)
657 (or (and (equal (stp:namespace-uri child) *xsl*)
658 (equal (stp:local-name child)
659 "attribute"))
660 (find (stp:namespace-uri child)
661 *extension-namespaces*
662 :test 'equal)))
663 (xslt-error "non-attribute found in attribute set"))
664 (parse-instruction child))
665 elt))
666 (*lexical-variable-declarations*
667 (make-empty-declaration-array))
668 (thunk
669 (compile-instruction `(progn ,@instructions) env))
670 (n-variables (length *lexical-variable-declarations*)))
671 (lambda (ctx)
672 (with-stack-limit ()
673 (loop for (local-name uri nil) in sets do
674 (dolist (thunk (find-attribute-set local-name uri))
675 (funcall thunk ctx)))
676 (let ((*lexical-variable-values*
677 (make-variable-value-array n-variables)))
678 (funcall thunk ctx)))))
679 (gethash (multiple-value-bind (local-name uri)
680 (decode-qname (or (stp:attribute-value elt "name")
681 (xslt-error "missing name"))
683 nil)
684 (cons local-name uri))
685 (stylesheet-attribute-sets stylesheet))))))
687 (defun parse-namespace-aliases! (stylesheet <transform> env)
688 (do-toplevel (elt "namespace-alias" <transform>)
689 (stp:with-attributes (stylesheet-prefix result-prefix) elt
690 (setf (gethash
691 (if (equal stylesheet-prefix "#default")
693 (xpath-sys:environment-find-namespace env stylesheet-prefix))
694 (stylesheet-namespace-aliases stylesheet))
695 (xpath-sys:environment-find-namespace
697 (if (equal result-prefix "#default")
699 result-prefix))))))
701 (defun parse-decimal-formats! (stylesheet <transform> env)
702 (do-toplevel (elt "decimal-format" <transform>)
703 (stp:with-attributes (name
704 ;; strings
705 infinity
706 (nan "NaN")
707 ;; characters:
708 decimal-separator
709 grouping-separator
710 zero-digit
711 percent
712 per-mille
713 digit
714 pattern-separator
715 minus-sign)
717 (multiple-value-bind (local-name uri)
718 (if name
719 (decode-qname name env nil)
720 (values "" ""))
721 (let ((current (find-decimal-format local-name uri stylesheet nil))
722 (new
723 (let ((seen '()))
724 (flet ((chr (key x)
725 (when x
726 (unless (eql (length x) 1)
727 (xslt-error "not a single character: ~A" x))
728 (let ((chr (elt x 0)))
729 (when (find chr seen)
730 (xslt-error
731 "conflicting decimal format characters: ~A"
732 chr))
733 (push chr seen)
734 (list key chr))))
735 (str (key x)
736 (when x
737 (list key x))))
738 (apply #'make-decimal-format
739 (append (str :infinity infinity)
740 (str :nan nan)
741 (chr :decimal-separator decimal-separator)
742 (chr :grouping-separator grouping-separator)
743 (chr :zero-digit zero-digit)
744 (chr :percent percent)
745 (chr :per-mille per-mille)
746 (chr :digit digit)
747 (chr :pattern-separator pattern-separator)
748 (chr :minus-sign minus-sign)))))))
749 (if current
750 (unless (decimal-format= current new)
751 (xslt-error "decimal format mismatch for ~S" local-name))
752 (setf (find-decimal-format local-name uri stylesheet) new)))))))
754 (defun parse-exclude-result-prefixes! (node env)
755 (stp:with-attributes (exclude-result-prefixes)
756 node
757 (dolist (prefix (words (or exclude-result-prefixes "")))
758 (if (equal prefix "#default")
759 (setf prefix nil)
760 (unless (cxml-stp-impl::nc-name-p prefix)
761 (xslt-error "invalid prefix: ~A" prefix)))
762 (push (or (xpath-sys:environment-find-namespace env prefix)
763 (xslt-error "namespace not found: ~A" prefix))
764 *excluded-namespaces*))))
766 (defun parse-extension-element-prefixes! (node env)
767 (stp:with-attributes (extension-element-prefixes)
768 node
769 (dolist (prefix (words (or extension-element-prefixes "")))
770 (if (equal prefix "#default")
771 (setf prefix nil)
772 (unless (cxml-stp-impl::nc-name-p prefix)
773 (xslt-error "invalid prefix: ~A" prefix)))
774 (let ((uri
775 (or (xpath-sys:environment-find-namespace env prefix)
776 (xslt-error "namespace not found: ~A" prefix))))
777 (unless (equal uri *xsl*)
778 (push uri *extension-namespaces*)
779 (push uri *excluded-namespaces*))))))
781 (defun parse-nametest-tokens (str)
782 (labels ((check (boolean)
783 (unless boolean
784 (xslt-error "invalid nametest token")))
785 (check-null (boolean)
786 (check (not boolean))))
787 (cons
788 :patterns
789 (mapcar (lambda (name-test)
790 (destructuring-bind (&optional path &rest junk)
791 (cdr (xpath:parse-pattern-expression name-test))
792 (check-null junk)
793 (check (eq (car path) :path))
794 (destructuring-bind (&optional child &rest junk) (cdr path)
795 (check-null junk)
796 (check (eq (car child) :child))
797 (destructuring-bind (nodetest &rest junk) (cdr child)
798 (check-null junk)
799 (check (or (stringp nodetest)
800 (eq nodetest '*)
801 (and (consp nodetest)
802 (or (eq (car nodetest) :namespace)
803 (eq (car nodetest) :qname)))))))
804 path))
805 (words str)))))
807 (defstruct strip-test
808 compiled-pattern
809 priority
810 position
811 value)
813 (defun parse-strip/preserve-space! (stylesheet <transform> env)
814 (let ((i 0))
815 (do-toplevel (elt "strip-space|preserve-space" <transform>)
816 (let ((*namespaces* (acons-namespaces elt))
817 (value
818 (if (equal (stp:local-name elt) "strip-space")
819 :strip
820 :preserve)))
821 (dolist (expression
822 (cdr (parse-nametest-tokens
823 (stp:attribute-value elt "elements"))))
824 (let* ((compiled-pattern
825 (car (xpath:compute-patterns
826 `(:patterns ,expression)
827 *import-priority*
828 "will set below"
829 env)))
830 (strip-test
831 (make-strip-test :compiled-pattern compiled-pattern
832 :priority (expression-priority expression)
833 :position i
834 :value value)))
835 (setf (xpath:pattern-value compiled-pattern) strip-test)
836 (push strip-test (stylesheet-strip-tests stylesheet)))))
837 (incf i))))
839 (defstruct (output-specification
840 (:conc-name "OUTPUT-"))
841 method
842 indent
843 omit-xml-declaration
844 encoding
845 doctype-system
846 doctype-public)
848 (defun parse-output! (stylesheet <transform>)
849 (dolist (<output> (list-toplevel "output" <transform>))
850 (let ((spec (stylesheet-output-specification stylesheet)))
851 (stp:with-attributes ( ;; version
852 method
853 indent
854 encoding
855 ;;; media-type
856 doctype-system
857 doctype-public
858 omit-xml-declaration
859 ;;; standalone
860 ;;; cdata-section-elements
862 <output>
863 (when method
864 (setf (output-method spec) method))
865 (when indent
866 (setf (output-indent spec) indent))
867 (when encoding
868 (setf (output-encoding spec) encoding))
869 (when doctype-system
870 (setf (output-doctype-system spec) doctype-system))
871 (when doctype-public
872 (setf (output-doctype-public spec) doctype-public))
873 (when omit-xml-declaration
874 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
875 ;;; (when cdata-section-elements
876 ;;; (setf (output-cdata-section-elements spec)
877 ;;; (concatenate 'string
878 ;;; (output-cdata-section-elements spec)
879 ;;; " "
880 ;;; cdata-section-elements)))
881 ))))
883 (defun make-empty-declaration-array ()
884 (make-array 1 :fill-pointer 0 :adjustable t))
886 (defun make-variable-value-array (n-lexical-variables)
887 (make-array n-lexical-variables :initial-element 'unbound))
889 (defun compile-global-variable (<variable> env) ;; also for <param>
890 (stp:with-attributes (name select) <variable>
891 (when (and select (stp:list-children <variable>))
892 (xslt-error "variable with select and body"))
893 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
894 (inner (cond
895 (select
896 (compile-xpath select env))
897 ((stp:list-children <variable>)
898 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
899 (inner-thunk (compile-instruction inner-sexpr env)))
900 (lambda (ctx)
901 (apply-to-result-tree-fragment ctx inner-thunk))))
903 (lambda (ctx)
904 (declare (ignore ctx))
905 ""))))
906 (n-lexical-variables (length *lexical-variable-declarations*)))
907 (xslt-trace-thunk
908 (lambda (ctx)
909 (let* ((*lexical-variable-values*
910 (make-variable-value-array n-lexical-variables)))
911 (funcall inner ctx)))
912 "global ~s (~s) = ~s" name select :result))))
914 (defstruct (variable-chain
915 (:constructor make-variable-chain)
916 (:conc-name "VARIABLE-CHAIN-"))
917 definitions
918 index
919 local-name
920 thunk
921 uri)
923 (defstruct (import-variable
924 (:constructor make-variable)
925 (:conc-name "VARIABLE-"))
926 value-thunk
927 value-thunk-setter
928 param-p)
930 (defun parse-global-variable! (stylesheet <variable> global-env)
931 (let* ((*namespaces* (acons-namespaces <variable>))
932 (instruction-base-uri (stp:base-uri <variable>))
933 (*instruction-base-uri* instruction-base-uri)
934 (*excluded-namespaces* (list *xsl*))
935 (*extension-namespaces* '())
936 (qname (stp:attribute-value <variable> "name")))
937 (with-import-magic (<variable> global-env)
938 (unless qname
939 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
940 (multiple-value-bind (local-name uri)
941 (decode-qname qname global-env nil)
942 ;; For the normal compilation environment of templates, install it
943 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
944 (let ((index (intern-global-variable local-name uri)))
945 ;; For the evaluation of a global variable itself, build a thunk
946 ;; that lazily resolves other variables, stored into
947 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
948 (let* ((value-thunk :unknown)
949 (sgv (stylesheet-global-variables stylesheet))
950 (chain
951 (if (< index (length sgv))
952 (elt sgv index)
953 (make-variable-chain
954 :index index
955 :local-name local-name
956 :uri uri)))
957 (next (car (variable-chain-definitions chain)))
958 (global-variable-thunk
959 (lambda (ctx)
960 (let ((v (global-variable-value index nil)))
961 (cond
962 ((eq v 'seen)
963 (unless next
964 (xslt-error "no next definition for: ~A"
965 local-name))
966 (funcall (variable-value-thunk next) ctx))
967 ((eq v 'unbound)
968 (setf (global-variable-value index) 'seen)
969 (setf (global-variable-value index)
970 (funcall value-thunk ctx)))
972 v)))))
973 (excluded-namespaces *excluded-namespaces*)
974 (extension-namespaces *extension-namespaces*)
975 (variable
976 (make-variable :param-p (namep <variable> "param")))
977 (value-thunk-setter
978 (lambda ()
979 (let* ((*instruction-base-uri* instruction-base-uri)
980 (*excluded-namespaces* excluded-namespaces)
981 (*extension-namespaces* extension-namespaces)
983 (compile-global-variable <variable> global-env)))
984 (setf value-thunk fn)
985 (setf (variable-value-thunk variable) fn)))))
986 (setf (variable-value-thunk-setter variable)
987 value-thunk-setter)
988 (setf (gethash (cons local-name uri)
989 (initial-global-variable-thunks global-env))
990 global-variable-thunk)
991 (setf (variable-chain-thunk chain) global-variable-thunk)
992 (push variable (variable-chain-definitions chain))
993 chain))))))
995 (defun parse-keys! (stylesheet <transform> env)
996 (xpath:with-namespaces ((nil #.*xsl*))
997 (do-toplevel (<key> "key" <transform>)
998 (let ((*instruction-base-uri* (stp:base-uri <key>)))
999 (stp:with-attributes (name match use) <key>
1000 (unless name (xslt-error "key name attribute not specified"))
1001 (unless match (xslt-error "key match attribute not specified"))
1002 (unless use (xslt-error "key use attribute not specified"))
1003 (multiple-value-bind (local-name uri)
1004 (decode-qname name env nil)
1005 (add-key stylesheet
1006 (cons local-name uri)
1007 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
1008 (compile-xpath use env))))))))
1010 (defun prepare-global-variables (stylesheet <transform>)
1011 (xpath:with-namespaces ((nil #.*xsl*))
1012 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet))
1013 (global-env (make-instance 'global-variable-environment
1014 :initial-global-variable-thunks igvt))
1015 (chains '()))
1016 (do-toplevel (<variable> "variable|param" <transform>)
1017 (let ((chain
1018 (parse-global-variable! stylesheet <variable> global-env)))
1019 (xslt-trace "parsing global variable ~s (uri ~s)"
1020 (variable-chain-local-name chain)
1021 (variable-chain-uri chain))
1022 (when (find chain
1023 chains
1024 :test (lambda (a b)
1025 (and (equal (variable-chain-local-name a)
1026 (variable-chain-local-name b))
1027 (equal (variable-chain-uri a)
1028 (variable-chain-uri b)))))
1029 (xslt-error "duplicate definition for global variable ~A"
1030 (variable-chain-local-name chain)))
1031 (push chain chains)))
1032 (setf chains (nreverse chains))
1033 (let ((table (stylesheet-global-variables stylesheet))
1034 (newlen (length *global-variable-declarations*)))
1035 (adjust-array table newlen :fill-pointer newlen)
1036 (dolist (chain chains)
1037 (setf (elt table (variable-chain-index chain)) chain)))
1038 (lambda ()
1039 ;; now that the global environment knows about all variables, run the
1040 ;; thunk setters to perform their compilation
1041 (mapc (lambda (chain)
1042 (dolist (var (variable-chain-definitions chain))
1043 (funcall (variable-value-thunk-setter var))))
1044 chains)))))
1046 (defun parse-templates! (stylesheet <transform> env)
1047 (let ((i 0))
1048 (do-toplevel (<template> "template" <transform>)
1049 (let ((*namespaces* (acons-namespaces <template>))
1050 (*instruction-base-uri* (stp:base-uri <template>)))
1051 (with-import-magic (<template> env)
1052 (dolist (template (compile-template <template> env i))
1053 (let ((name (template-name template)))
1054 (if name
1055 (let* ((table (stylesheet-named-templates stylesheet))
1056 (head (car (gethash name table))))
1057 (when (and head (eql (template-import-priority head)
1058 (template-import-priority template)))
1059 ;; fixme: is this supposed to be a run-time error?
1060 (xslt-error "conflicting templates for ~A" name))
1061 (push template (gethash name table)))
1062 (let ((mode (ensure-mode/qname stylesheet
1063 (template-mode-qname template)
1064 env)))
1065 (setf (template-mode template) mode)
1066 (push template (mode-templates mode))))))))
1067 (incf i))))
1070 ;;;; APPLY-STYLESHEET
1072 (defvar *stylesheet*)
1074 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
1076 (defun unalias-uri (uri)
1077 (let ((result
1078 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
1079 uri)))
1080 (check-type result string)
1081 result))
1083 (defstruct (parameter
1084 (:constructor make-parameter (value local-name &optional uri)))
1085 (uri "")
1086 local-name
1087 value)
1089 (defun find-parameter-value (local-name uri parameters)
1090 (dolist (p parameters)
1091 (when (and (equal (parameter-local-name p) local-name)
1092 (equal (parameter-uri p) uri))
1093 (return (parameter-value p)))))
1095 (defvar *uri-resolver*)
1097 (defun parse-allowing-microsoft-bom (pathname handler)
1098 (with-open-file (s pathname :element-type '(unsigned-byte 8))
1099 (unless (and (eql (read-byte s nil) #xef)
1100 (eql (read-byte s nil) #xbb)
1101 (eql (read-byte s nil) #xbf))
1102 (file-position s 0))
1103 (cxml:parse s handler)))
1105 (defvar *documents*)
1107 (defun %document (uri-string base-uri)
1108 (let* ((absolute-uri
1109 (puri:merge-uris uri-string (or base-uri "")))
1110 (resolved-uri
1111 (if *uri-resolver*
1112 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
1113 absolute-uri))
1114 (pathname
1115 (handler-case
1116 (uri-to-pathname resolved-uri)
1117 (cxml:xml-parse-error (c)
1118 (xslt-error "cannot find referenced document ~A: ~A"
1119 resolved-uri c))))
1120 (xpath-root-node
1121 (or (gethash pathname *documents*)
1122 (setf (gethash pathname *documents*)
1123 (make-whitespace-stripper
1124 (handler-case
1125 (parse-allowing-microsoft-bom pathname
1126 (stp:make-builder))
1127 ((or file-error cxml:xml-parse-error) (c)
1128 (xslt-error "cannot parse referenced document ~A: ~A"
1129 pathname c)))
1130 (stylesheet-strip-thunk *stylesheet*))))))
1131 (when (puri:uri-fragment absolute-uri)
1132 (xslt-error "use of fragment identifiers in document() not supported"))
1133 xpath-root-node))
1135 (xpath-sys:define-extension xslt *xsl*)
1137 (defun document-base-uri (node)
1138 (xpath-protocol:base-uri
1139 (cond
1140 ((xpath-protocol:node-type-p node :document)
1141 (xpath::find-in-pipe-if
1142 (lambda (x)
1143 (xpath-protocol:node-type-p x :element))
1144 (xpath-protocol:child-pipe node)))
1145 ((xpath-protocol:node-type-p node :element)
1146 node)
1148 (xpath-protocol:parent-node node)))))
1150 (xpath-sys:define-xpath-function/lazy
1151 xslt :document
1152 (object &optional node-set)
1153 (let ((instruction-base-uri *instruction-base-uri*))
1154 (lambda (ctx)
1155 (let* ((object (funcall object ctx))
1156 (node-set (and node-set (funcall node-set ctx)))
1157 (base-uri
1158 (if node-set
1159 (document-base-uri (xpath::textually-first-node node-set))
1160 instruction-base-uri)))
1161 (xpath-sys:make-node-set
1162 (if (xpath:node-set-p object)
1163 (xpath:map-node-set->list
1164 (lambda (node)
1165 (%document (xpath:string-value node)
1166 (if node-set
1167 base-uri
1168 (document-base-uri node))))
1169 object)
1170 (list (%document (xpath:string-value object) base-uri))))))))
1172 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1173 (let ((namespaces *namespaces*))
1174 (lambda (ctx)
1175 (let* ((qname (xpath:string-value (funcall name ctx)))
1176 (object (funcall object ctx))
1177 (expanded-name
1178 (multiple-value-bind (local-name uri)
1179 (decode-qname/runtime qname namespaces nil)
1180 (cons local-name uri)))
1181 (key (find-key expanded-name *stylesheet*)))
1182 (labels ((get-by-key (value)
1183 (let ((value (xpath:string-value value)))
1184 (xpath::filter-pipe
1185 #'(lambda (node)
1186 (let ((uses
1187 (xpath:evaluate-compiled (key-use key) node)))
1188 (if (xpath:node-set-p uses)
1189 (xpath::find-in-pipe
1190 value
1191 (xpath-sys:pipe-of uses)
1192 :key #'xpath:string-value
1193 :test #'equal)
1194 (equal value (xpath:string-value uses)))))
1195 (xpath-sys:pipe-of
1196 (xpath:node-set-value
1197 (xpath:evaluate-compiled (key-match key) ctx)))))))
1198 (xpath-sys:make-node-set
1199 (xpath::sort-pipe
1200 (if (xpath:node-set-p object)
1201 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1202 (get-by-key object)))))))))
1204 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1206 (xpath-sys:define-xpath-function/lazy xslt :current ()
1207 #'(lambda (ctx)
1208 (xpath-sys:make-node-set
1209 (xpath-sys:make-pipe
1210 (xpath:context-starting-node ctx)
1211 nil))))
1213 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1214 #'(lambda (ctx)
1215 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1216 (funcall name ctx))
1217 "")))
1219 (defun %get-node-id (node)
1220 (when (xpath:node-set-p node)
1221 (setf node (xpath::textually-first-node node)))
1222 (when node
1223 (let ((id (xpath-sys:get-node-id node))
1224 (highest-base-uri
1225 (loop
1226 for parent = node then next
1227 for next = (xpath-protocol:parent-node parent)
1228 for this-base-uri = (xpath-protocol:base-uri parent)
1229 for highest-base-uri = (if (plusp (length this-base-uri))
1230 this-base-uri
1231 highest-base-uri)
1232 while next
1233 finally (return highest-base-uri))))
1234 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1235 ;; checked only if everything else matches.
1237 ;; This might be pointless premature optimization, but I like the idea :-)
1238 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1240 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1241 (if node-set-thunk
1242 #'(lambda (ctx)
1243 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1244 #'(lambda (ctx)
1245 (%get-node-id (xpath:context-node ctx)))))
1247 (declaim (special *available-instructions*))
1249 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1250 (let ((namespaces *namespaces*))
1251 #'(lambda (ctx)
1252 (let ((qname (funcall qname ctx)))
1253 (multiple-value-bind (local-name uri)
1254 (decode-qname/runtime qname namespaces nil)
1255 (and (equal uri *xsl*)
1256 (gethash local-name *available-instructions*)
1257 t))))))
1259 (xpath-sys:define-xpath-function/lazy xslt :function-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 (zerop (length uri))
1266 (or (xpath-sys:find-xpath-function local-name *xsl*)
1267 (xpath-sys:find-xpath-function local-name uri))
1268 t))))))
1270 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1271 (let ((namespaces *namespaces*))
1272 (lambda (ctx)
1273 (let ((qname (funcall qname ctx)))
1274 (multiple-value-bind (local-name uri)
1275 (decode-qname/runtime qname namespaces nil)
1276 (if (equal uri *xsl*)
1277 (cond
1278 ((equal local-name "version")
1279 "1")
1280 ((equal local-name "vendor")
1281 "Xuriella")
1282 ((equal local-name "vendor-uri")
1283 "http://repo.or.cz/w/xuriella.git")
1285 ""))
1286 ""))))))
1288 (defun apply-stylesheet
1289 (stylesheet source-designator
1290 &key output parameters uri-resolver navigator)
1291 (when (typep stylesheet 'xml-designator)
1292 (setf stylesheet
1293 (handler-bind
1294 ((cxml:xml-parse-error
1295 (lambda (c)
1296 (xslt-error "cannot parse stylesheet: ~A" c))))
1297 (parse-stylesheet stylesheet))))
1298 (with-resignalled-errors ()
1299 (invoke-with-output-sink
1300 (lambda ()
1301 (let* ((*documents* (make-hash-table :test 'equal))
1302 (xpath:*navigator* (or navigator :default-navigator))
1303 (puri:*strict-parse* nil)
1304 (*stylesheet* stylesheet)
1305 (*empty-mode* (make-mode))
1306 (*default-mode* (find-mode stylesheet nil))
1307 (global-variable-chains
1308 (stylesheet-global-variables stylesheet))
1309 (*global-variable-values*
1310 (make-variable-value-array (length global-variable-chains)))
1311 (*uri-resolver* uri-resolver)
1312 (source-document
1313 (if (typep source-designator 'xml-designator)
1314 (cxml:parse source-designator (stp:make-builder))
1315 source-designator))
1316 (xpath-root-node
1317 (make-whitespace-stripper
1318 source-document
1319 (stylesheet-strip-thunk stylesheet)))
1320 (ctx (xpath:make-context xpath-root-node)))
1321 (when (pathnamep source-designator)
1322 (setf (gethash source-designator *documents*) xpath-root-node))
1323 (map nil
1324 (lambda (chain)
1325 (let ((head (car (variable-chain-definitions chain))))
1326 (when (variable-param-p head)
1327 (let ((value
1328 (find-parameter-value
1329 (variable-chain-local-name chain)
1330 (variable-chain-uri chain)
1331 parameters)))
1332 (when value
1333 (setf (global-variable-value
1334 (variable-chain-index chain))
1335 value))))))
1336 global-variable-chains)
1337 (map nil
1338 (lambda (chain)
1339 (funcall (variable-chain-thunk chain) ctx))
1340 global-variable-chains)
1341 ;; zzz we wouldn't have to mask float traps here if we used the
1342 ;; XPath API properly. Unfortunately I've been using FUNCALL
1343 ;; everywhere instead of EVALUATE, so let's paper over that
1344 ;; at a central place to be sure:
1345 (xpath::with-float-traps-masked ()
1346 (apply-templates ctx :mode *default-mode*))))
1347 (stylesheet-output-specification stylesheet)
1348 output)))
1350 (defun find-attribute-set (local-name uri)
1351 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1352 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1354 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1355 (when sort-predicate
1356 (setf list
1357 (mapcar #'xpath:context-node
1358 (stable-sort (contextify-node-list list)
1359 sort-predicate))))
1360 (let* ((n (length list))
1361 (s/d (lambda () n)))
1362 (loop
1363 for i from 1
1364 for child in list
1366 (apply-templates (xpath:make-context child s/d i)
1367 :param-bindings param-bindings
1368 :mode mode))))
1370 (defvar *stack-limit* 200)
1372 (defun invoke-with-stack-limit (fn)
1373 (let ((*stack-limit* (1- *stack-limit*)))
1374 (unless (plusp *stack-limit*)
1375 (xslt-error "*stack-limit* reached; stack overflow"))
1376 (funcall fn)))
1378 (defun invoke-template (ctx template param-bindings)
1379 (let ((*lexical-variable-values*
1380 (make-variable-value-array (template-n-variables template))))
1381 (with-stack-limit ()
1382 (loop
1383 for (name-cons value) in param-bindings
1384 for (nil index nil) = (find name-cons
1385 (template-params template)
1386 :test #'equal
1387 :key #'car)
1389 (when index
1390 (setf (lexical-variable-value index) value)))
1391 (funcall (template-body template) ctx))))
1393 (defun apply-default-templates (ctx mode)
1394 (let ((node (xpath:context-node ctx)))
1395 (cond
1396 ((or (xpath-protocol:node-type-p node :processing-instruction)
1397 (xpath-protocol:node-type-p node :comment)))
1398 ((or (xpath-protocol:node-type-p node :text)
1399 (xpath-protocol:node-type-p node :attribute))
1400 (write-text (xpath-protocol:node-text node)))
1402 (apply-templates/list
1403 (xpath::force
1404 (xpath-protocol:child-pipe node))
1405 :mode mode)))))
1407 (defvar *apply-imports*)
1409 (defun apply-applicable-templates (ctx templates param-bindings finally)
1410 (labels ((apply-imports (&optional actual-param-bindings)
1411 (if templates
1412 (let* ((this (pop templates))
1413 (low (template-apply-imports-limit this))
1414 (high (template-import-priority this)))
1415 (setf templates
1416 (remove-if-not
1417 (lambda (x)
1418 (<= low (template-import-priority x) high))
1419 templates))
1420 (invoke-template ctx this actual-param-bindings))
1421 (funcall finally))))
1422 (let ((*apply-imports* #'apply-imports))
1423 (apply-imports param-bindings))))
1425 (defun apply-templates (ctx &key param-bindings mode)
1426 (apply-applicable-templates ctx
1427 (find-templates ctx (or mode *default-mode*))
1428 param-bindings
1429 (lambda ()
1430 (apply-default-templates ctx mode))))
1432 (defun call-template (ctx name &optional param-bindings)
1433 (apply-applicable-templates ctx
1434 (find-named-templates name)
1435 param-bindings
1436 (lambda ()
1437 (error "cannot find named template: ~s"
1438 name))))
1440 (defun find-templates (ctx mode)
1441 (let* ((matching-candidates
1442 (xpath:matching-values (mode-match-thunk mode)
1443 (xpath:context-node ctx)))
1444 (npriorities
1445 (if matching-candidates
1446 (1+ (reduce #'max
1447 matching-candidates
1448 :key #'template-import-priority))
1450 (priority-groups (make-array npriorities :initial-element nil)))
1451 (dolist (template matching-candidates)
1452 (push template
1453 (elt priority-groups (template-import-priority template))))
1454 (loop
1455 for i from (1- npriorities) downto 0
1456 for group = (elt priority-groups i)
1457 for template = (maximize #'template< group)
1458 when template
1459 collect template)))
1461 (defun find-named-templates (name)
1462 (gethash name (stylesheet-named-templates *stylesheet*)))
1464 (defun template< (a b) ;assuming same import priority
1465 (let ((p (template-priority a))
1466 (q (template-priority b)))
1467 (cond
1468 ((< p q) t)
1469 ((> p q) nil)
1471 (xslt-cerror "conflicting templates:~_~A,~_~A"
1472 (template-match-expression a)
1473 (template-match-expression b))
1474 (< (template-position a) (template-position b))))))
1476 (defun maximize (< things)
1477 (when things
1478 (let ((max (car things)))
1479 (dolist (other (cdr things))
1480 (when (funcall < max other)
1481 (setf max other)))
1482 max)))
1484 (defun invoke-with-output-sink (fn output-spec output)
1485 (etypecase output
1486 (pathname
1487 (with-open-file (s output
1488 :direction :output
1489 :element-type '(unsigned-byte 8)
1490 :if-exists :rename-and-delete)
1491 (invoke-with-output-sink fn output-spec s)))
1492 ((or stream null)
1493 (invoke-with-output-sink fn
1494 output-spec
1495 (make-output-sink output-spec output)))
1496 ((or hax:abstract-handler sax:abstract-handler)
1497 (with-xml-output output
1498 (when (typep output '(or combi-sink auto-detect-sink))
1499 (sax:start-dtd output
1500 :autodetect-me-please
1501 (output-doctype-public output-spec)
1502 (output-doctype-system output-spec)))
1503 (funcall fn)))))
1505 (defun make-output-sink (output-spec stream)
1506 (let* ((ystream
1507 (if stream
1508 (let ((et (stream-element-type stream)))
1509 (cond
1510 ((or (null et) (subtypep et '(unsigned-byte 8)))
1511 (runes:make-octet-stream-ystream stream))
1512 ((subtypep et 'character)
1513 (runes:make-character-stream-ystream stream))))
1514 (runes:make-rod-ystream)))
1515 (omit-xml-declaration-p
1516 (equal (output-omit-xml-declaration output-spec) "yes"))
1517 (sink-encoding (or (output-encoding output-spec) "UTF-8"))
1518 (sax-target
1519 (progn
1520 (setf (runes:ystream-encoding ystream)
1521 (cxml::find-output-encoding sink-encoding))
1522 (make-instance 'cxml::sink
1523 :ystream ystream
1524 :omit-xml-declaration-p omit-xml-declaration-p
1525 :encoding sink-encoding))))
1526 (flet ((make-combi-sink ()
1527 (make-instance 'combi-sink
1528 :hax-target (make-instance 'chtml::sink
1529 :ystream ystream)
1530 :sax-target sax-target
1531 :encoding sink-encoding)))
1532 (let ((method-key
1533 (cond
1534 ((equalp (output-method output-spec) "HTML") :html)
1535 ((equalp (output-method output-spec) "TEXT") :text)
1536 ((equalp (output-method output-spec) "XML") :xml)
1537 (t nil))))
1538 (cond
1539 ((and (eq method-key :html)
1540 (null (output-doctype-system output-spec))
1541 (null (output-doctype-public output-spec)))
1542 (make-combi-sink))
1543 ((eq method-key :text)
1544 (make-text-filter sax-target))
1545 ((and (eq method-key :xml)
1546 (null (output-doctype-system output-spec)))
1547 sax-target)
1549 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1551 (defstruct template
1552 match-expression
1553 compiled-pattern
1554 name
1555 import-priority
1556 apply-imports-limit
1557 priority
1558 position
1559 mode
1560 mode-qname
1561 params
1562 body
1563 n-variables)
1565 (defun expression-priority (form)
1566 (let ((step (second form)))
1567 (if (and (null (cddr form))
1568 (listp step)
1569 (member (car step) '(:child :attribute))
1570 (null (cddr step)))
1571 (let ((name (second step)))
1572 (cond
1573 ((or (stringp name)
1574 (and (consp name)
1575 (or (eq (car name) :qname)
1576 (eq (car name) :processing-instruction))))
1577 0.0)
1578 ((and (consp name)
1579 (or (eq (car name) :namespace)
1580 (eq (car name) '*)))
1581 -0.25)
1583 -0.5)))
1584 0.5)))
1586 (defun parse-xpath (str)
1587 (with-resignalled-errors ()
1588 (xpath:parse-xpath str)))
1590 (defun parse-key-pattern (str)
1591 (let ((parsed
1592 (mapcar #'(lambda (item)
1593 `(:path (:root :node)
1594 (:descendant-or-self *)
1595 ,@(cdr item)))
1596 (parse-pattern str))))
1597 (if (null (rest parsed))
1598 (first parsed)
1599 `(:union ,@parsed))))
1601 (defun parse-pattern (str)
1602 (with-resignalled-errors ()
1603 (cdr (xpath::parse-pattern-expression str))))
1605 (defun compile-value-thunk (value env)
1606 (if (and (listp value) (eq (car value) 'progn))
1607 (let ((inner-thunk (compile-instruction value env)))
1608 (lambda (ctx)
1609 (apply-to-result-tree-fragment ctx inner-thunk)))
1610 (compile-xpath value env)))
1612 (defun compile-var-binding (name value env)
1613 (multiple-value-bind (local-name uri)
1614 (decode-qname name env nil)
1615 (let ((thunk (xslt-trace-thunk
1616 (compile-value-thunk value env)
1617 "local variable ~s = ~s" name :result)))
1618 (list (cons local-name uri)
1619 (push-variable local-name
1621 *lexical-variable-declarations*)
1622 thunk))))
1624 (defun compile-var-bindings (forms env)
1625 (loop
1626 for (name value) in forms
1627 collect (compile-var-binding name value env)))
1629 (defun compile-template (<template> env position)
1630 (stp:with-attributes (match name priority mode) <template>
1631 (unless (or name match)
1632 (xslt-error "missing match in template"))
1633 (multiple-value-bind (params body-pos)
1634 (loop
1635 for i from 0
1636 for child in (stp:list-children <template>)
1637 while (namep child "param")
1638 collect (parse-param child) into params
1639 finally (return (values params i)))
1640 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1641 (param-bindings (compile-var-bindings params env))
1642 (body (parse-body <template> body-pos (mapcar #'car params)))
1643 (body-thunk (compile-instruction `(progn ,@body) env))
1644 (outer-body-thunk
1645 (xslt-trace-thunk
1646 #'(lambda (ctx)
1647 (unwind-protect
1648 (progn
1649 ;; set params that weren't initialized by apply-templates
1650 (loop for (name index param-thunk) in param-bindings
1651 when (eq (lexical-variable-value index nil) 'unbound)
1652 do (setf (lexical-variable-value index)
1653 (funcall param-thunk ctx)))
1654 (funcall body-thunk ctx))))
1655 "template: match = ~s name = ~s" match name))
1656 (n-variables (length *lexical-variable-declarations*)))
1657 (append
1658 (when name
1659 (multiple-value-bind (local-name uri)
1660 (decode-qname name env nil)
1661 (list
1662 (make-template :name (cons local-name uri)
1663 :import-priority *import-priority*
1664 :apply-imports-limit *apply-imports-limit*
1665 :params param-bindings
1666 :body outer-body-thunk
1667 :n-variables n-variables))))
1668 (when match
1669 (mapcar (lambda (expression)
1670 (let* ((compiled-pattern
1671 (xslt-trace-thunk
1672 (car (xpath:compute-patterns
1673 `(:patterns ,expression)
1675 :dummy
1676 env))
1677 "match-thunk for template (match ~s): ~s --> ~s"
1678 match expression :result))
1679 (p (if priority
1680 (xpath::parse-xnum priority)
1681 (expression-priority expression)))
1683 (progn
1684 (unless (and (numberp p)
1685 (not (xpath::inf-p p))
1686 (not (xpath::nan-p p)))
1687 (xslt-error "failed to parse priority"))
1688 (float p 1.0d0)))
1689 (template
1690 (make-template :match-expression expression
1691 :compiled-pattern compiled-pattern
1692 :import-priority *import-priority*
1693 :apply-imports-limit *apply-imports-limit*
1694 :priority p
1695 :position position
1696 :mode-qname mode
1697 :params param-bindings
1698 :body outer-body-thunk
1699 :n-variables n-variables)))
1700 (setf (xpath:pattern-value compiled-pattern)
1701 template)
1702 template))
1703 (cdr (xpath:parse-pattern-expression match)))))))))
1704 #+(or)
1705 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")