Check position of import
[xuriella.git] / xslt.lisp
blob7fe2dda6fabd3058f8906240aafe4b32b4630a92
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 (defmacro with-forward-compatible-errors (error-form &body body)
103 `(invoke-with-forward-compatible-errors (lambda () ,@body)
104 (lambda () ,error-form)))
106 (defun invoke-with-forward-compatible-errors (fn error-fn)
107 (let ((result))
108 (tagbody
109 (handler-bind
110 ((xpath:xpath-error
111 (lambda (c)
112 (declare (ignore c))
113 (when *forwards-compatible-p*
114 (go error)))))
115 (setf result (funcall fn)))
116 (go done)
117 error
118 (setf result (funcall error-fn))
119 done)
120 result))
122 (defun compile-xpath (xpath &optional env)
123 (with-resignalled-errors ()
124 (with-forward-compatible-errors
125 (lambda (ctx)
126 (xslt-error "attempt to evaluate an XPath expression with compile-time errors, delayed due to forwards compatible processing: ~A"
127 xpath))
128 (xpath:compile-xpath xpath env))))
130 (defmacro with-stack-limit ((&optional) &body body)
131 `(invoke-with-stack-limit (lambda () ,@body)))
133 (defparameter *without-xslt-current-p* nil)
135 (defmacro without-xslt-current ((&optional) &body body)
136 `(invoke-without-xslt-current (lambda () ,@body)))
138 (defun invoke-without-xslt-current (fn)
139 (let ((*without-xslt-current-p* t))
140 (funcall fn)))
142 ;;; (defun invoke-without-xslt-current (fn)
143 ;;; (let ((non-extensions (gethash "" xpath::*extensions*))
144 ;;; (xpath::*extensions*
145 ;;; ;; hide XSLT extensions
146 ;;; (make-hash-table :test #'equal)))
147 ;;; (setf (gethash "" xpath::*extensions*) non-extensions)
148 ;;; (funcall fn)))
151 ;;;; Helper functions and macros
153 (defun check-for-invalid-attributes (valid-names node)
154 (labels ((check-attribute (a)
155 (unless
156 (let ((uri (stp:namespace-uri a)))
157 (or (and (plusp (length uri)) (not (equal uri *xsl*)))
158 (find (cons (stp:local-name a) uri)
159 valid-names
160 :test #'equal)))
161 (xslt-error "attribute ~A not allowed on ~A"
162 (stp:local-name a)
163 (stp:local-name node)))))
164 (stp:map-attributes nil #'check-attribute node)))
166 (defmacro only-with-attributes ((&rest specs) node &body body)
167 (let ((valid-names
168 (mapcar (lambda (entry)
169 (if (and (listp entry) (cdr entry))
170 (destructuring-bind (name &optional (uri ""))
171 (cdr entry)
172 (cons name uri))
173 (cons (string-downcase
174 (princ-to-string
175 (symbol-name entry)))
176 "")))
177 specs))
178 (%node (gensym)))
179 `(let ((,%NODE ,node))
180 (check-for-invalid-attributes ',valid-names ,%NODE)
181 (stp:with-attributes ,specs ,%NODE
182 ,@body))))
184 (defun map-pipe-eagerly (fn pipe)
185 (xpath::enumerate pipe :key fn :result nil))
187 (defmacro do-pipe ((var pipe &optional result) &body body)
188 `(block nil
189 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
190 ,result))
193 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
195 (defparameter *initial-namespaces*
196 '((nil . "")
197 ("xmlns" . #"http://www.w3.org/2000/xmlns/")
198 ("xml" . #"http://www.w3.org/XML/1998/namespace")))
200 (defparameter *namespaces*
201 *initial-namespaces*)
203 (defvar *global-variable-declarations*)
204 (defvar *lexical-variable-declarations*)
206 (defvar *global-variable-values*)
207 (defvar *lexical-variable-values*)
209 (defclass xslt-environment () ())
211 (defun split-qname (str)
212 (handler-case
213 (multiple-value-bind (prefix local-name)
214 (cxml::split-qname str)
215 (unless
216 ;; FIXME: cxml should really offer a function that does
217 ;; checks for NCName and QName in a sensible way for user code.
218 ;; cxml::split-qname is tailored to the needs of the parser.
220 ;; For now, let's just check the syntax explicitly.
221 (and (or (null prefix) (xpath::nc-name-p prefix))
222 (xpath::nc-name-p local-name))
223 (xslt-error "not a qname: ~A" str))
224 (values prefix local-name))
225 (cxml:well-formedness-violation ()
226 (xslt-error "not a qname: ~A" str))))
228 (defun decode-qname (qname env attributep)
229 (unless qname
230 (xslt-error "missing name"))
231 (multiple-value-bind (prefix local-name)
232 (split-qname qname)
233 (values local-name
234 (if (or prefix (not attributep))
235 (xpath-sys:environment-find-namespace env (or prefix ""))
237 prefix)))
239 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
240 (or (cdr (assoc prefix *namespaces* :test 'equal))
241 ;; zzz gross hack.
242 ;; Change the entire code base to represent "no prefix" as the
243 ;; empty string consistently. unparse.lisp has already been changed.
244 (and (equal prefix "")
245 (cdr (assoc nil *namespaces* :test 'equal)))
246 (and (eql prefix nil)
247 (cdr (assoc "" *namespaces* :test 'equal)))))
249 (defun find-variable-index (local-name uri table)
250 (position (cons local-name uri) table :test 'equal))
252 (defun intern-global-variable (local-name uri)
253 (or (find-variable-index local-name uri *global-variable-declarations*)
254 (push-variable local-name uri *global-variable-declarations*)))
256 (defun push-variable (local-name uri table)
257 (prog1
258 (length table)
259 (vector-push-extend (cons local-name uri) table)))
261 (defun lexical-variable-value (index &optional (errorp t))
262 (let ((result (svref *lexical-variable-values* index)))
263 (when errorp
264 (assert (not (eq result 'unbound))))
265 result))
267 (defun (setf lexical-variable-value) (newval index)
268 (assert (not (eq newval 'unbound)))
269 (setf (svref *lexical-variable-values* index) newval))
271 (defun global-variable-value (index &optional (errorp t))
272 (let ((result (svref *global-variable-values* index)))
273 (when errorp
274 (assert (not (eq result 'unbound))))
275 result))
277 (defun (setf global-variable-value) (newval index)
278 (assert (not (eq newval 'unbound)))
279 (setf (svref *global-variable-values* index) newval))
281 (defmethod xpath-sys:environment-find-function
282 ((env xslt-environment) lname uri)
283 (or (if (string= uri "")
284 (or (xpath-sys:find-xpath-function lname *xsl*)
285 (xpath-sys:find-xpath-function lname uri))
286 (xpath-sys:find-xpath-function lname uri))
287 (when *forwards-compatible-p*
288 (lambda (&rest ignore)
289 (declare (ignore ignore))
290 (xslt-error "attempt to call an unknown XPath function (~A); error delayed until run-time due to forwards compatible processing"
291 lname)))))
293 (defmethod xpath-sys:environment-find-variable
294 ((env xslt-environment) lname uri)
295 (let ((index
296 (find-variable-index lname uri *lexical-variable-declarations*)))
297 (when index
298 (lambda (ctx)
299 (declare (ignore ctx))
300 (svref *lexical-variable-values* index)))))
302 (defclass lexical-xslt-environment (xslt-environment) ())
304 (defmethod xpath-sys:environment-find-variable
305 ((env lexical-xslt-environment) lname uri)
306 (or (call-next-method)
307 (let ((index
308 (find-variable-index lname uri *global-variable-declarations*)))
309 (when index
310 (xslt-trace-thunk
311 (lambda (ctx)
312 (declare (ignore ctx))
313 (svref *global-variable-values* index))
314 "global ~s (uri ~s) = ~s" lname uri :result)))))
316 (defclass key-environment (xslt-environment) ())
318 (defmethod xpath-sys:environment-find-variable
319 ((env key-environment) lname uri)
320 (declare (ignore lname uri))
321 (xslt-error "disallowed variable reference"))
323 (defclass global-variable-environment (xslt-environment)
324 ((initial-global-variable-thunks
325 :initarg :initial-global-variable-thunks
326 :accessor initial-global-variable-thunks)))
328 (defmethod xpath-sys:environment-find-variable
329 ((env global-variable-environment) lname uri)
330 (or (call-next-method)
331 (gethash (cons lname uri) (initial-global-variable-thunks env))))
334 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
335 ;;;;
336 ;;;; A sink that serializes only text not contained in any element.
338 (defmacro with-toplevel-text-output-sink ((var) &body body)
339 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
341 (defclass toplevel-text-output-sink (sax:default-handler)
342 ((target :initarg :target :accessor text-output-sink-target)
343 (depth :initform 0 :accessor textoutput-sink-depth)))
345 (defmethod sax:start-element ((sink toplevel-text-output-sink)
346 namespace-uri local-name qname attributes)
347 (declare (ignore namespace-uri local-name qname attributes))
348 (incf (textoutput-sink-depth sink)))
350 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
351 (when (zerop (textoutput-sink-depth sink))
352 (write-string data (text-output-sink-target sink))))
354 (defmethod sax:unescaped ((sink toplevel-text-output-sink) data)
355 (sax:characters sink data))
357 (defmethod sax:end-element ((sink toplevel-text-output-sink)
358 namespace-uri local-name qname)
359 (declare (ignore namespace-uri local-name qname))
360 (decf (textoutput-sink-depth sink)))
362 (defun invoke-with-toplevel-text-output-sink (fn)
363 (with-output-to-string (s)
364 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
367 ;;;; TEXT-FILTER
368 ;;;;
369 ;;;; A sink that passes through only text (at any level) and turns to
370 ;;;; into unescaped characters.
372 (defclass text-filter (sax:default-handler)
373 ((target :initarg :target :accessor text-filter-target)))
375 (defmethod sax:characters ((sink text-filter) data)
376 (sax:unescaped (text-filter-target sink) data))
378 (defmethod sax:unescaped ((sink text-filter) data)
379 (sax:unescaped (text-filter-target sink) data))
381 (defmethod sax:end-document ((sink text-filter))
382 (sax:end-document (text-filter-target sink)))
384 (defun make-text-filter (target)
385 (make-instance 'text-filter :target target))
388 ;;;; ESCAPER
389 ;;;;
390 ;;;; A sink that recovers from sax:unescaped using sax:characters, as per
391 ;;;; XSLT 16.4.
393 (defclass escaper (cxml:broadcast-handler)
396 (defmethod sax:unescaped ((sink escaper) data)
397 (sax:characters sink data))
399 (defun make-escaper (target)
400 (make-instance 'escaper :handlers (list target)))
403 ;;;; Names
405 (defun of-name (local-name)
406 (stp:of-name local-name *xsl*))
408 (defun namep (node local-name)
409 (and (typep node '(or stp:element stp:attribute))
410 (equal (stp:namespace-uri node) *xsl*)
411 (equal (stp:local-name node) local-name)))
414 ;;;; PARSE-STYLESHEET
416 (defstruct stylesheet
417 (modes (make-hash-table :test 'equal))
418 (global-variables (make-empty-declaration-array))
419 (output-specification (make-output-specification))
420 (strip-tests nil)
421 (strip-thunk nil)
422 (named-templates (make-hash-table :test 'equal))
423 (attribute-sets (make-hash-table :test 'equal))
424 (keys (make-hash-table :test 'equal))
425 (namespace-aliases (make-hash-table :test 'equal))
426 (decimal-formats (make-hash-table :test 'equal))
427 (initial-global-variable-thunks (make-hash-table :test 'equal)))
429 (defstruct mode
430 (templates nil)
431 (match-thunk (lambda (ignore) (declare (ignore ignore)) nil)))
433 (defun find-mode (stylesheet local-name &optional uri)
434 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
436 (defun ensure-mode (stylesheet &optional local-name uri)
437 (or (find-mode stylesheet local-name uri)
438 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
439 (make-mode))))
441 (defun ensure-mode/qname (stylesheet qname env)
442 (if qname
443 (multiple-value-bind (local-name uri)
444 (decode-qname qname env nil)
445 (ensure-mode stylesheet local-name uri))
446 (find-mode stylesheet nil)))
448 (defun acons-namespaces
449 (element &optional (bindings *namespaces*) include-redeclared)
450 (map-namespace-declarations (lambda (prefix uri)
451 (push (cons prefix uri) bindings))
452 element
453 include-redeclared)
454 bindings)
456 (defun find-key (name stylesheet)
457 (or (gethash name (stylesheet-keys stylesheet))
458 (xslt-error "unknown key: ~a" name)))
460 (defun make-key (match use) (cons match use))
462 (defun key-match (key) (car key))
464 (defun key-use (key) (cdr key))
466 (defun add-key (stylesheet name match use)
467 (if (gethash name (stylesheet-keys stylesheet))
468 (xslt-error "duplicate key: ~a" name)
469 (setf (gethash name (stylesheet-keys stylesheet))
470 (make-key match use))))
472 (defvar *excluded-namespaces* (list *xsl*))
473 (defvar *empty-mode*)
474 (defvar *default-mode*)
476 (defvar *xsl-include-stack* nil)
478 (defun uri-to-pathname (uri)
479 (cxml::uri-to-pathname (puri:parse-uri uri)))
481 ;; Why this extra check for literal result element used as stylesheets,
482 ;; instead of a general check for every literal result element? Because
483 ;; Stylesheet__91804 says so.
484 (defun check-Errors_err035 (literal-result-element)
485 (let ((*namespaces* (acons-namespaces literal-result-element))
486 (env (make-instance 'lexical-xslt-environment)))
487 (stp:with-attributes ((extension-element-prefixes
488 "extension-element-prefixes"
489 *xsl*))
490 literal-result-element
491 (dolist (prefix (words (or extension-element-prefixes "")))
492 (if (equal prefix "#default")
493 (setf prefix nil)
494 (unless (cxml-stp-impl::nc-name-p prefix)
495 (xslt-error "invalid prefix: ~A" prefix)))
496 (let ((uri
497 (or (xpath-sys:environment-find-namespace env prefix)
498 (xslt-error "namespace not found: ~A" prefix))))
499 (when (equal uri (stp:namespace-uri literal-result-element))
500 (xslt-error "literal result element used as stylesheet, but is ~
501 declared as an extension element")))))))
503 (defun unwrap-2.3 (document)
504 (let ((literal-result-element (stp:document-element document))
505 (new-template (stp:make-element "template" *xsl*))
506 (new-document-element (stp:make-element "stylesheet" *xsl*)))
507 (check-Errors_err035 literal-result-element)
508 (setf (stp:attribute-value new-document-element "version")
509 (or (stp:attribute-value literal-result-element "version" *xsl*)
510 (xslt-error "not a stylesheet: root element lacks xsl:version")))
511 (setf (stp:attribute-value new-template "match") "/")
512 (setf (stp:document-element document) new-document-element)
513 (stp:append-child new-document-element new-template)
514 (stp:append-child new-template literal-result-element)
515 new-document-element))
517 (defun parse-stylesheet-to-stp (input uri-resolver)
518 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
519 (<transform> (stp:document-element d)))
520 (unless (equal (stp:namespace-uri <transform>) *xsl*)
521 (setf <transform> (unwrap-2.3 d)))
522 (strip-stylesheet <transform>)
523 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
524 (or (equal (stp:local-name <transform>) "transform")
525 (equal (stp:local-name <transform>) "stylesheet")))
526 (xslt-error "not a stylesheet"))
527 (check-for-invalid-attributes
528 '(("version" . "")
529 ("exclude-result-prefixes" . "")
530 ("extension-element-prefixes" . "")
531 ("space" . "http://www.w3.org/XML/1998/namespace")
532 ("id" . ""))
533 <transform>)
534 (let ((invalid
535 (or (stp:find-child-if (of-name "stylesheet") <transform>)
536 (stp:find-child-if (of-name "transform") <transform>))))
537 (when invalid
538 (xslt-error "invalid top-level element ~A" (stp:local-name invalid))))
539 (dolist (include (stp:filter-children (of-name "include") <transform>))
540 (let* ((uri (puri:merge-uris (or (stp:attribute-value include "href")
541 (xslt-error "include without href"))
542 (stp:base-uri include)))
543 (uri (if uri-resolver
544 (funcall uri-resolver uri)
545 uri))
546 (str (puri:render-uri uri nil))
547 (pathname
548 (handler-case
549 (uri-to-pathname uri)
550 (cxml:xml-parse-error (c)
551 (xslt-error "cannot find included stylesheet ~A: ~A"
552 uri c)))))
553 (with-open-file
554 (stream pathname
555 :element-type '(unsigned-byte 8)
556 :if-does-not-exist nil)
557 (unless stream
558 (xslt-error "cannot find included stylesheet ~A at ~A"
559 uri pathname))
560 (when (find str *xsl-include-stack* :test #'equal)
561 (xslt-error "recursive inclusion of ~A" uri))
562 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
563 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
564 (stp:insert-child-after <transform>
565 (stp:copy <transform>2)
566 include)
567 (stp:detach include)))))
568 <transform>))
570 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
571 (defvar *apply-imports-limit*)
572 (defvar *import-priority*)
573 (defvar *extension-namespaces*)
574 (defvar *forwards-compatible-p*)
576 (defmacro do-toplevel ((var xpath <transform>) &body body)
577 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
579 (defun map-toplevel (fn xpath <transform>)
580 (dolist (node (list-toplevel xpath <transform>))
581 (let ((*namespaces* *initial-namespaces*))
582 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
583 (xpath:with-namespaces (("" #.*xsl*))
584 (when (xpath:node-matches-p ancestor "stylesheet|transform")
585 ;; discard namespaces from including stylesheets
586 (setf *namespaces* *initial-namespaces*)))
587 (when (xpath-protocol:node-type-p ancestor :element)
588 (setf *namespaces* (acons-namespaces ancestor *namespaces* t))))
589 (funcall fn node))))
591 (defun list-toplevel (xpath <transform>)
592 (labels ((recurse (sub)
593 (let ((subsubs
594 (xpath-sys:pipe-of
595 (xpath:evaluate "transform|stylesheet" sub))))
596 (xpath::append-pipes
597 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
598 (xpath::mappend-pipe #'recurse subsubs)))))
599 (xpath::sort-nodes (recurse <transform>))))
601 (defmacro with-import-magic ((node env) &body body)
602 `(invoke-with-import-magic (lambda () ,@body) ,node ,env))
604 (defun invoke-with-import-magic (fn node env)
605 (unless (or (namep node "stylesheet") (namep node "transform"))
606 (setf node (stp:parent node)))
607 (let ((*excluded-namespaces* (list *xsl*))
608 (*extension-namespaces* '())
609 (*forwards-compatible-p*
610 (not (equal (stp:attribute-value node "version") "1.0"))))
611 (parse-exclude-result-prefixes! node env)
612 (parse-extension-element-prefixes! node env)
613 (funcall fn)))
615 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
616 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
617 (instruction-base-uri (stp:base-uri <transform>))
618 (namespaces (acons-namespaces <transform>))
619 (apply-imports-limit (1+ *import-priority*))
620 (continuations '()))
621 (let ((*namespaces* namespaces))
622 (invoke-with-import-magic (constantly t) <transform> env))
623 (do-toplevel (elt "node()" <transform>)
624 (let ((version (stp:attribute-value (stp:parent elt) "version")))
625 (cond
626 ((null version)
627 (xslt-error "stylesheet lacks version"))
628 ((equal version "1.0")
629 (if (typep elt 'stp:element)
630 (when (or (equal (stp:namespace-uri elt) "")
631 (and (equal (stp:namespace-uri elt) *xsl*)
632 (not (find (stp:local-name elt)
633 '("key" "template" "output"
634 "strip-space" "preserve-space"
635 "attribute-set" "namespace-alias"
636 "decimal-format" "variable" "param"
637 "import" "include"
638 ;; for include handling:
639 "stylesheet" "transform")
640 :test #'equal))))
641 (xslt-error "unknown top-level element ~A" (stp:local-name elt)))
642 (xslt-error "text at top-level"))))))
643 (macrolet ((with-specials ((&optional) &body body)
644 `(let ((*instruction-base-uri* instruction-base-uri)
645 (*namespaces* namespaces)
646 (*apply-imports-limit* apply-imports-limit))
647 ,@body)))
648 (with-specials ()
649 (do-toplevel (import "import" <transform>)
650 (when (let ((prev (xpath:first-node
651 (xpath:evaluate "preceding-sibling::*"
652 import
653 t))))
654 (and prev (not (namep (stp:local-name prev) "import"))))
655 (xslt-error "import not at beginning of stylesheet"))
656 (let ((uri (puri:merge-uris (or (stp:attribute-value import "href")
657 (xslt-error "import without href"))
658 (stp:base-uri import))))
659 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
660 continuations))))
661 (let ((import-priority
662 (incf *import-priority*))
663 (var-cont (prepare-global-variables stylesheet <transform>)))
664 ;; delay the rest of compilation until we've seen all global
665 ;; variables:
666 (lambda ()
667 (mapc #'funcall (nreverse continuations))
668 (with-specials ()
669 (let ((*import-priority* import-priority))
670 (funcall var-cont)
671 (parse-keys! stylesheet <transform> env)
672 (parse-templates! stylesheet <transform> env)
673 (parse-output! stylesheet <transform> env)
674 (parse-strip/preserve-space! stylesheet <transform> env)
675 (parse-attribute-sets! stylesheet <transform> env)
676 (parse-namespace-aliases! stylesheet <transform> env)
677 (parse-decimal-formats! stylesheet <transform> env))))))))
679 (defvar *xsl-import-stack* nil)
681 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
682 (let* ((uri (if uri-resolver
683 (funcall uri-resolver uri)
684 uri))
685 (str (puri:render-uri uri nil))
686 (pathname
687 (handler-case
688 (uri-to-pathname uri)
689 (cxml:xml-parse-error (c)
690 (xslt-error "cannot find imported stylesheet ~A: ~A"
691 uri c)))))
692 (with-open-file
693 (stream pathname
694 :element-type '(unsigned-byte 8)
695 :if-does-not-exist nil)
696 (unless stream
697 (xslt-error "cannot find imported stylesheet ~A at ~A"
698 uri pathname))
699 (when (find str *xsl-import-stack* :test #'equal)
700 (xslt-error "recursive inclusion of ~A" uri))
701 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
702 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
704 (defvar *included-attribute-sets*)
706 (defun parse-stylesheet (designator &key uri-resolver)
707 (with-resignalled-errors ()
708 (xpath:with-namespaces ((nil #.*xsl*))
709 (let* ((*import-priority* 0)
710 (xpath:*allow-variables-in-patterns* nil)
711 (puri:*strict-parse* nil)
712 (stylesheet (make-stylesheet))
713 (env (make-instance 'lexical-xslt-environment))
714 (*excluded-namespaces* *excluded-namespaces*)
715 (*global-variable-declarations* (make-empty-declaration-array))
716 (*included-attribute-sets* nil))
717 (ensure-mode stylesheet nil)
718 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
719 ;; reverse attribute sets:
720 (let ((table (stylesheet-attribute-sets stylesheet)))
721 (maphash (lambda (k v)
722 (setf (gethash k table) (nreverse v)))
723 table))
724 ;; for Errors_err011
725 (dolist (sets *included-attribute-sets*)
726 (loop for (local-name uri nil) in sets do
727 (find-attribute-set local-name uri stylesheet)))
728 ;; add default df
729 (unless (find-decimal-format "" "" stylesheet nil)
730 (setf (find-decimal-format "" "" stylesheet)
731 (make-decimal-format)))
732 ;; compile a template matcher for each mode:
733 (loop
734 for mode being each hash-value in (stylesheet-modes stylesheet)
736 (setf (mode-match-thunk mode)
737 (xpath:make-pattern-matcher
738 (mapcar #'template-compiled-pattern
739 (mode-templates mode)))))
740 ;; and for the strip tests
741 (setf (stylesheet-strip-thunk stylesheet)
742 (let ((patterns (stylesheet-strip-tests stylesheet)))
743 (and patterns
744 (xpath:make-pattern-matcher
745 (mapcar #'strip-test-compiled-pattern patterns)))))
746 stylesheet))))
748 (defun parse-attribute-sets! (stylesheet <transform> env)
749 (do-toplevel (elt "attribute-set" <transform>)
750 (with-import-magic (elt env)
751 (push (let* ((sets
752 (mapcar (lambda (qname)
753 (multiple-value-list (decode-qname qname env nil)))
754 (words
755 (stp:attribute-value elt "use-attribute-sets"))))
756 (instructions
757 (stp:map-children
758 'list
759 (lambda (child)
760 (unless
761 (and (typep child 'stp:element)
762 (or (and (equal (stp:namespace-uri child) *xsl*)
763 (equal (stp:local-name child)
764 "attribute"))
765 (find (stp:namespace-uri child)
766 *extension-namespaces*
767 :test 'equal)))
768 (xslt-error "non-attribute found in attribute set"))
769 (parse-instruction child))
770 elt))
771 (*lexical-variable-declarations*
772 (make-empty-declaration-array))
773 (thunk
774 (compile-instruction `(progn ,@instructions) env))
775 (n-variables (length *lexical-variable-declarations*)))
776 (push sets *included-attribute-sets*)
777 (lambda (ctx)
778 (with-stack-limit ()
779 (loop for (local-name uri nil) in sets do
780 (dolist (thunk (find-attribute-set local-name uri))
781 (funcall thunk ctx)))
782 (let ((*lexical-variable-values*
783 (make-variable-value-array n-variables)))
784 (funcall thunk ctx)))))
785 (gethash (multiple-value-bind (local-name uri)
786 (decode-qname (or (stp:attribute-value elt "name")
787 (xslt-error "missing name"))
789 nil)
790 (cons local-name uri))
791 (stylesheet-attribute-sets stylesheet))))))
793 (defun parse-namespace-aliases! (stylesheet <transform> env)
794 (do-toplevel (elt "namespace-alias" <transform>)
795 (only-with-attributes (stylesheet-prefix result-prefix) elt
796 (unless stylesheet-prefix
797 (xslt-error "missing stylesheet-prefix in namespace-alias"))
798 (unless result-prefix
799 (xslt-error "missing result-prefix in namespace-alias"))
800 (setf (gethash
801 (if (equal stylesheet-prefix "#default")
803 (xpath-sys:environment-find-namespace env stylesheet-prefix))
804 (stylesheet-namespace-aliases stylesheet))
805 (xpath-sys:environment-find-namespace
807 (if (equal result-prefix "#default")
809 result-prefix))))))
811 (defun parse-decimal-formats! (stylesheet <transform> env)
812 (do-toplevel (elt "decimal-format" <transform>)
813 (stp:with-attributes (name
814 ;; strings
815 infinity
816 (nan "NaN")
817 ;; characters:
818 decimal-separator
819 grouping-separator
820 zero-digit
821 percent
822 per-mille
823 digit
824 pattern-separator
825 minus-sign)
827 (multiple-value-bind (local-name uri)
828 (if name
829 (decode-qname name env nil)
830 (values "" ""))
831 (let ((current (find-decimal-format local-name uri stylesheet nil))
832 (new
833 (let ((seen '()))
834 (flet ((chr (key x)
835 (when x
836 (unless (eql (length x) 1)
837 (xslt-error "not a single character: ~A" x))
838 (let ((chr (elt x 0)))
839 (when (find chr seen)
840 (xslt-error
841 "conflicting decimal format characters: ~A"
842 chr))
843 (push chr seen)
844 (list key chr))))
845 (str (key x)
846 (when x
847 (list key x))))
848 (apply #'make-decimal-format
849 (append (str :infinity infinity)
850 (str :nan nan)
851 (chr :decimal-separator decimal-separator)
852 (chr :grouping-separator grouping-separator)
853 (chr :zero-digit zero-digit)
854 (chr :percent percent)
855 (chr :per-mille per-mille)
856 (chr :digit digit)
857 (chr :pattern-separator pattern-separator)
858 (chr :minus-sign minus-sign)))))))
859 (if current
860 (unless (decimal-format= current new)
861 (xslt-error "decimal format mismatch for ~S" local-name))
862 (setf (find-decimal-format local-name uri stylesheet) new)))))))
864 (defun parse-exclude-result-prefixes! (node env)
865 (stp:with-attributes (exclude-result-prefixes)
866 node
867 (dolist (prefix (words (or exclude-result-prefixes "")))
868 (if (equal prefix "#default")
869 (setf prefix nil)
870 (unless (cxml-stp-impl::nc-name-p prefix)
871 (xslt-error "invalid prefix: ~A" prefix)))
872 (push (or (xpath-sys:environment-find-namespace env prefix)
873 (xslt-error "namespace not found: ~A" prefix))
874 *excluded-namespaces*))))
876 (defun parse-extension-element-prefixes! (node env)
877 (stp:with-attributes (extension-element-prefixes)
878 node
879 (dolist (prefix (words (or extension-element-prefixes "")))
880 (if (equal prefix "#default")
881 (setf prefix nil)
882 (unless (cxml-stp-impl::nc-name-p prefix)
883 (xslt-error "invalid prefix: ~A" prefix)))
884 (let ((uri
885 (or (xpath-sys:environment-find-namespace env prefix)
886 (xslt-error "namespace not found: ~A" prefix))))
887 (unless (equal uri *xsl*)
888 (push uri *extension-namespaces*)
889 (push uri *excluded-namespaces*))))))
891 (defun parse-nametest-tokens (str)
892 (labels ((check (boolean)
893 (unless boolean
894 (xslt-error "invalid nametest token")))
895 (check-null (boolean)
896 (check (not boolean))))
897 (cons
898 :patterns
899 (mapcar (lambda (name-test)
900 (destructuring-bind (&optional path &rest junk)
901 (cdr (xpath:parse-pattern-expression name-test))
902 (check-null junk)
903 (check (eq (car path) :path))
904 (destructuring-bind (&optional child &rest junk) (cdr path)
905 (check-null junk)
906 (check (eq (car child) :child))
907 (destructuring-bind (nodetest &rest junk) (cdr child)
908 (check-null junk)
909 (check (or (stringp nodetest)
910 (eq nodetest '*)
911 (and (consp nodetest)
912 (or (eq (car nodetest) :namespace)
913 (eq (car nodetest) :qname)))))))
914 path))
915 (words str)))))
917 (defstruct strip-test
918 compiled-pattern
919 priority
920 position
921 value)
923 (defun parse-strip/preserve-space! (stylesheet <transform> env)
924 (let ((i 0))
925 (do-toplevel (elt "strip-space|preserve-space" <transform>)
926 (let ((*namespaces* (acons-namespaces elt))
927 (value
928 (if (equal (stp:local-name elt) "strip-space")
929 :strip
930 :preserve)))
931 (dolist (expression
932 (cdr (parse-nametest-tokens
933 (stp:attribute-value elt "elements"))))
934 (let* ((compiled-pattern
935 (car (without-xslt-current ()
936 (xpath:compute-patterns
937 `(:patterns ,expression)
938 *import-priority*
939 "will set below"
940 env))))
941 (strip-test
942 (make-strip-test :compiled-pattern compiled-pattern
943 :priority (expression-priority expression)
944 :position i
945 :value value)))
946 (setf (xpath:pattern-value compiled-pattern) strip-test)
947 (push strip-test (stylesheet-strip-tests stylesheet)))))
948 (incf i))))
950 (defstruct (output-specification
951 (:conc-name "OUTPUT-"))
952 method
953 indent
954 omit-xml-declaration
955 encoding
956 doctype-system
957 doctype-public
958 cdata-section-matchers)
960 (defun parse-output! (stylesheet <transform> env)
961 (dolist (<output> (list-toplevel "output" <transform>))
962 (let ((spec (stylesheet-output-specification stylesheet)))
963 (only-with-attributes (version
964 method
965 indent
966 encoding
967 media-type
968 doctype-system
969 doctype-public
970 omit-xml-declaration
971 standalone
972 cdata-section-elements)
973 <output>
974 (declare (ignore version
975 ;; FIXME:
976 media-type
977 standalone))
978 (when method
979 (setf (output-method spec) method))
980 (when indent
981 (setf (output-indent spec) indent))
982 (when encoding
983 (setf (output-encoding spec) encoding))
984 (when doctype-system
985 (setf (output-doctype-system spec) doctype-system))
986 (when doctype-public
987 (setf (output-doctype-public spec) doctype-public))
988 (when omit-xml-declaration
989 (setf (output-omit-xml-declaration spec) omit-xml-declaration))
990 (when cdata-section-elements
991 (dolist (qname (words cdata-section-elements))
992 (decode-qname qname env nil) ;check the syntax
993 (push (xpath:make-pattern-matcher* qname env)
994 (output-cdata-section-matchers spec))))))))
996 (defun make-empty-declaration-array ()
997 (make-array 1 :fill-pointer 0 :adjustable t))
999 (defun make-variable-value-array (n-lexical-variables)
1000 (make-array n-lexical-variables :initial-element 'unbound))
1002 (defun compile-global-variable (<variable> env) ;; also for <param>
1003 (stp:with-attributes (name select) <variable>
1004 (when (and select (stp:list-children <variable>))
1005 (xslt-error "variable with select and body"))
1006 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1007 (inner (cond
1008 (select
1009 (compile-xpath select env))
1010 ((stp:list-children <variable>)
1011 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
1012 (inner-thunk (compile-instruction inner-sexpr env)))
1013 (lambda (ctx)
1014 (apply-to-result-tree-fragment ctx inner-thunk))))
1016 (lambda (ctx)
1017 (declare (ignore ctx))
1018 ""))))
1019 (n-lexical-variables (length *lexical-variable-declarations*)))
1020 (xslt-trace-thunk
1021 (lambda (ctx)
1022 (let* ((*lexical-variable-values*
1023 (make-variable-value-array n-lexical-variables)))
1024 (funcall inner ctx)))
1025 "global ~s (~s) = ~s" name select :result))))
1027 (defstruct (variable-chain
1028 (:constructor make-variable-chain)
1029 (:conc-name "VARIABLE-CHAIN-"))
1030 definitions
1031 index
1032 local-name
1033 thunk
1034 uri)
1036 (defstruct (import-variable
1037 (:constructor make-variable)
1038 (:conc-name "VARIABLE-"))
1039 value-thunk
1040 value-thunk-setter
1041 param-p)
1043 (defun parse-global-variable! (stylesheet <variable> global-env)
1044 (let* ((*namespaces* (acons-namespaces <variable>))
1045 (instruction-base-uri (stp:base-uri <variable>))
1046 (*instruction-base-uri* instruction-base-uri)
1047 (*excluded-namespaces* (list *xsl*))
1048 (*extension-namespaces* '())
1049 (qname (stp:attribute-value <variable> "name")))
1050 (with-import-magic (<variable> global-env)
1051 (unless qname
1052 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
1053 (multiple-value-bind (local-name uri)
1054 (decode-qname qname global-env nil)
1055 ;; For the normal compilation environment of templates, install it
1056 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
1057 (let ((index (intern-global-variable local-name uri)))
1058 ;; For the evaluation of a global variable itself, build a thunk
1059 ;; that lazily resolves other variables, stored into
1060 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
1061 (let* ((value-thunk :unknown)
1062 (sgv (stylesheet-global-variables stylesheet))
1063 (chain
1064 (if (< index (length sgv))
1065 (elt sgv index)
1066 (make-variable-chain
1067 :index index
1068 :local-name local-name
1069 :uri uri)))
1070 (next (car (variable-chain-definitions chain)))
1071 (global-variable-thunk
1072 (lambda (ctx)
1073 (let ((v (global-variable-value index nil)))
1074 (cond
1075 ((eq v 'seen)
1076 (unless next
1077 (xslt-error "no next definition for: ~A"
1078 local-name))
1079 (funcall (variable-value-thunk next) ctx))
1080 ((eq v 'unbound)
1081 (setf (global-variable-value index) 'seen)
1082 (setf (global-variable-value index)
1083 (funcall value-thunk ctx)))
1085 v)))))
1086 (excluded-namespaces *excluded-namespaces*)
1087 (extension-namespaces *extension-namespaces*)
1088 (variable
1089 (make-variable :param-p (namep <variable> "param")))
1090 (forwards-compatible-p *forwards-compatible-p*)
1091 (value-thunk-setter
1092 (lambda ()
1093 (let* ((*instruction-base-uri* instruction-base-uri)
1094 (*excluded-namespaces* excluded-namespaces)
1095 (*extension-namespaces* extension-namespaces)
1096 (*forwards-compatible-p* forwards-compatible-p)
1098 (compile-global-variable <variable> global-env)))
1099 (setf value-thunk fn)
1100 (setf (variable-value-thunk variable) fn)))))
1101 (setf (variable-value-thunk-setter variable)
1102 value-thunk-setter)
1103 (setf (gethash (cons local-name uri)
1104 (initial-global-variable-thunks global-env))
1105 global-variable-thunk)
1106 (setf (variable-chain-thunk chain) global-variable-thunk)
1107 (push variable (variable-chain-definitions chain))
1108 chain))))))
1110 (defun parse-keys! (stylesheet <transform> env)
1111 (xpath:with-namespaces ((nil #.*xsl*))
1112 (do-toplevel (<key> "key" <transform>)
1113 (with-import-magic (<key> env)
1114 (let ((*instruction-base-uri* (stp:base-uri <key>)))
1115 (stp:with-attributes (name match use) <key>
1116 (unless name (xslt-error "key name attribute not specified"))
1117 (unless match (xslt-error "key match attribute not specified"))
1118 (unless use (xslt-error "key use attribute not specified"))
1119 (multiple-value-bind (local-name uri)
1120 (decode-qname name env nil)
1121 (add-key stylesheet
1122 (cons local-name uri)
1123 (compile-xpath `(xpath:xpath ,(parse-key-pattern match))
1124 env)
1125 (compile-xpath use
1126 (make-instance 'key-environment))))))))))
1128 (defun prepare-global-variables (stylesheet <transform>)
1129 (xpath:with-namespaces ((nil #.*xsl*))
1130 (let* ((igvt (stylesheet-initial-global-variable-thunks stylesheet))
1131 (global-env (make-instance 'global-variable-environment
1132 :initial-global-variable-thunks igvt))
1133 (chains '()))
1134 (do-toplevel (<variable> "variable|param" <transform>)
1135 (let ((chain
1136 (parse-global-variable! stylesheet <variable> global-env)))
1137 (xslt-trace "parsing global variable ~s (uri ~s)"
1138 (variable-chain-local-name chain)
1139 (variable-chain-uri chain))
1140 (when (find chain
1141 chains
1142 :test (lambda (a b)
1143 (and (equal (variable-chain-local-name a)
1144 (variable-chain-local-name b))
1145 (equal (variable-chain-uri a)
1146 (variable-chain-uri b)))))
1147 (xslt-error "duplicate definition for global variable ~A"
1148 (variable-chain-local-name chain)))
1149 (push chain chains)))
1150 (setf chains (nreverse chains))
1151 (let ((table (stylesheet-global-variables stylesheet))
1152 (newlen (length *global-variable-declarations*)))
1153 (adjust-array table newlen :fill-pointer newlen)
1154 (dolist (chain chains)
1155 (setf (elt table (variable-chain-index chain)) chain)))
1156 (lambda ()
1157 ;; now that the global environment knows about all variables, run the
1158 ;; thunk setters to perform their compilation
1159 (mapc (lambda (chain)
1160 (dolist (var (variable-chain-definitions chain))
1161 (funcall (variable-value-thunk-setter var))))
1162 chains)))))
1164 (defun parse-templates! (stylesheet <transform> env)
1165 (let ((i 0))
1166 (do-toplevel (<template> "template" <transform>)
1167 (let ((*namespaces* (acons-namespaces <template>))
1168 (*instruction-base-uri* (stp:base-uri <template>)))
1169 (with-import-magic (<template> env)
1170 (dolist (template (compile-template <template> env i))
1171 (let ((name (template-name template)))
1172 (if name
1173 (let* ((table (stylesheet-named-templates stylesheet))
1174 (head (car (gethash name table))))
1175 (when (and head (eql (template-import-priority head)
1176 (template-import-priority template)))
1177 ;; fixme: is this supposed to be a run-time error?
1178 (xslt-error "conflicting templates for ~A" name))
1179 (push template (gethash name table)))
1180 (let ((mode (ensure-mode/qname stylesheet
1181 (template-mode-qname template)
1182 env)))
1183 (setf (template-mode template) mode)
1184 (push template (mode-templates mode))))))))
1185 (incf i))))
1188 ;;;; APPLY-STYLESHEET
1190 (defvar *stylesheet*)
1192 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
1194 (defun unalias-uri (uri)
1195 (let ((result
1196 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
1197 uri)))
1198 (check-type result string)
1199 result))
1201 (defstruct (parameter
1202 (:constructor make-parameter (value local-name &optional uri)))
1203 (uri "")
1204 local-name
1205 value)
1207 (defun find-parameter-value (local-name uri parameters)
1208 (dolist (p parameters)
1209 (when (and (equal (parameter-local-name p) local-name)
1210 (equal (parameter-uri p) uri))
1211 (return (parameter-value p)))))
1213 (defvar *uri-resolver*)
1215 (defun parse-allowing-microsoft-bom (pathname handler)
1216 (with-open-file (s pathname :element-type '(unsigned-byte 8))
1217 (unless (and (eql (read-byte s nil) #xef)
1218 (eql (read-byte s nil) #xbb)
1219 (eql (read-byte s nil) #xbf))
1220 (file-position s 0))
1221 (cxml:parse s handler)))
1223 (defvar *documents*)
1225 (defun %document (uri-string base-uri)
1226 (let* ((absolute-uri
1227 (puri:merge-uris uri-string (or base-uri "")))
1228 (resolved-uri
1229 (if *uri-resolver*
1230 (funcall *uri-resolver* absolute-uri)
1231 absolute-uri))
1232 (pathname
1233 (handler-case
1234 (uri-to-pathname resolved-uri)
1235 (cxml:xml-parse-error (c)
1236 (xslt-error "cannot find referenced document ~A: ~A"
1237 resolved-uri c))))
1238 (xpath-root-node
1239 (or (gethash pathname *documents*)
1240 (setf (gethash pathname *documents*)
1241 (make-whitespace-stripper
1242 (handler-case
1243 (parse-allowing-microsoft-bom pathname
1244 (stp:make-builder))
1245 ((or file-error cxml:xml-parse-error) (c)
1246 (xslt-error "cannot parse referenced document ~A: ~A"
1247 pathname c)))
1248 (stylesheet-strip-thunk *stylesheet*))))))
1249 (when (puri:uri-fragment absolute-uri)
1250 (xslt-error "use of fragment identifiers in document() not supported"))
1251 xpath-root-node))
1253 (xpath-sys:define-extension xslt *xsl*)
1255 (defun document-base-uri (node)
1256 (xpath-protocol:base-uri
1257 (cond
1258 ((xpath-protocol:node-type-p node :document)
1259 (xpath::find-in-pipe-if
1260 (lambda (x)
1261 (xpath-protocol:node-type-p x :element))
1262 (xpath-protocol:child-pipe node)))
1263 ((xpath-protocol:node-type-p node :element)
1264 node)
1266 (xpath-protocol:parent-node node)))))
1268 (xpath-sys:define-xpath-function/lazy
1269 xslt :document
1270 (object &optional node-set)
1271 (let ((instruction-base-uri *instruction-base-uri*))
1272 (lambda (ctx)
1273 (let* ((object (funcall object ctx))
1274 (node-set (and node-set (funcall node-set ctx)))
1275 (base-uri
1276 (if node-set
1277 (document-base-uri (xpath::textually-first-node node-set))
1278 instruction-base-uri)))
1279 (xpath-sys:make-node-set
1280 (if (xpath:node-set-p object)
1281 (xpath:map-node-set->list
1282 (lambda (node)
1283 (%document (xpath:string-value node)
1284 (if node-set
1285 base-uri
1286 (document-base-uri node))))
1287 object)
1288 (list (%document (xpath:string-value object) base-uri))))))))
1290 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
1291 (let ((namespaces *namespaces*))
1292 (lambda (ctx)
1293 (let* ((qname (xpath:string-value (funcall name ctx)))
1294 (object (funcall object ctx))
1295 (expanded-name
1296 (multiple-value-bind (local-name uri)
1297 (decode-qname/runtime qname namespaces nil)
1298 (cons local-name uri)))
1299 (key (find-key expanded-name *stylesheet*)))
1300 (labels ((get-by-key (value)
1301 (let ((value (xpath:string-value value)))
1302 (xpath::filter-pipe
1303 #'(lambda (node)
1304 (let ((uses
1305 (xpath:evaluate-compiled (key-use key) node)))
1306 (if (xpath:node-set-p uses)
1307 (xpath::find-in-pipe
1308 value
1309 (xpath-sys:pipe-of uses)
1310 :key #'xpath:string-value
1311 :test #'equal)
1312 (equal value (xpath:string-value uses)))))
1313 (xpath-sys:pipe-of
1314 (xpath:node-set-value
1315 (xpath:evaluate-compiled (key-match key) ctx)))))))
1316 (xpath-sys:make-node-set
1317 (xpath::sort-pipe
1318 (if (xpath:node-set-p object)
1319 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
1320 (get-by-key object)))))))))
1322 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
1324 (xpath-sys:define-xpath-function/lazy xslt :current ()
1325 (when *without-xslt-current-p*
1326 (xslt-error "current() not allowed here"))
1327 #'(lambda (ctx)
1328 (xpath-sys:make-node-set
1329 (xpath-sys:make-pipe
1330 (xpath:context-starting-node ctx)
1331 nil))))
1333 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
1334 #'(lambda (ctx)
1335 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
1336 (funcall name ctx))
1337 "")))
1339 (defun %get-node-id (node)
1340 (when (xpath:node-set-p node)
1341 (setf node (xpath::textually-first-node node)))
1342 (when node
1343 (let ((id (xpath-sys:get-node-id node))
1344 (highest-base-uri
1345 (loop
1346 for parent = node then next
1347 for next = (xpath-protocol:parent-node parent)
1348 for this-base-uri = (xpath-protocol:base-uri parent)
1349 for highest-base-uri = (if (plusp (length this-base-uri))
1350 this-base-uri
1351 highest-base-uri)
1352 while next
1353 finally (return highest-base-uri))))
1354 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
1355 ;; checked only if everything else matches.
1357 ;; This might be pointless premature optimization, but I like the idea :-)
1358 (nreverse (concatenate 'string highest-base-uri "//" id)))))
1360 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
1361 (if node-set-thunk
1362 #'(lambda (ctx)
1363 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
1364 #'(lambda (ctx)
1365 (%get-node-id (xpath:context-node ctx)))))
1367 (declaim (special *available-instructions*))
1369 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
1370 (let ((namespaces *namespaces*))
1371 #'(lambda (ctx)
1372 (let ((qname (funcall qname ctx)))
1373 (multiple-value-bind (local-name uri)
1374 (decode-qname/runtime qname namespaces nil)
1375 (and (equal uri *xsl*)
1376 (gethash local-name *available-instructions*)
1377 t))))))
1379 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
1380 (let ((namespaces *namespaces*))
1381 #'(lambda (ctx)
1382 (let ((qname (funcall qname ctx)))
1383 (multiple-value-bind (local-name uri)
1384 (decode-qname/runtime qname namespaces nil)
1385 (and (zerop (length uri))
1386 (or (xpath-sys:find-xpath-function local-name *xsl*)
1387 (xpath-sys:find-xpath-function local-name uri))
1388 t))))))
1390 (xpath-sys:define-xpath-function/lazy xslt :system-property (qname)
1391 (let ((namespaces *namespaces*))
1392 (lambda (ctx)
1393 (let ((qname (xpath:string-value (funcall qname ctx))))
1394 (multiple-value-bind (local-name uri)
1395 (decode-qname/runtime qname namespaces nil)
1396 (if (equal uri *xsl*)
1397 (cond
1398 ((equal local-name "version")
1399 "1")
1400 ((equal local-name "vendor")
1401 "Xuriella")
1402 ((equal local-name "vendor-uri")
1403 "http://repo.or.cz/w/xuriella.git")
1405 ""))
1406 ""))))))
1408 ;; FIXME: should there be separate uri-resolver arguments for stylesheet
1409 ;; and data?
1410 (defun apply-stylesheet
1411 (stylesheet source-designator
1412 &key output parameters uri-resolver navigator)
1413 (when (typep stylesheet 'xml-designator)
1414 (setf stylesheet
1415 (handler-bind
1416 ((cxml:xml-parse-error
1417 (lambda (c)
1418 (xslt-error "cannot parse stylesheet: ~A" c))))
1419 (parse-stylesheet stylesheet :uri-resolver uri-resolver))))
1420 (with-resignalled-errors ()
1421 (invoke-with-output-sink
1422 (lambda ()
1423 (let* ((*documents* (make-hash-table :test 'equal))
1424 (xpath:*navigator* (or navigator :default-navigator))
1425 (puri:*strict-parse* nil)
1426 (*stylesheet* stylesheet)
1427 (*empty-mode* (make-mode))
1428 (*default-mode* (find-mode stylesheet nil))
1429 (global-variable-chains
1430 (stylesheet-global-variables stylesheet))
1431 (*global-variable-values*
1432 (make-variable-value-array (length global-variable-chains)))
1433 (*uri-resolver* uri-resolver)
1434 (source-document
1435 (if (typep source-designator 'xml-designator)
1436 (cxml:parse source-designator (stp:make-builder))
1437 source-designator))
1438 (xpath-root-node
1439 (make-whitespace-stripper
1440 source-document
1441 (stylesheet-strip-thunk stylesheet)))
1442 (ctx (xpath:make-context xpath-root-node)))
1443 (when (pathnamep source-designator)
1444 (setf (gethash source-designator *documents*) xpath-root-node))
1445 (map nil
1446 (lambda (chain)
1447 (let ((head (car (variable-chain-definitions chain))))
1448 (when (variable-param-p head)
1449 (let ((value
1450 (find-parameter-value
1451 (variable-chain-local-name chain)
1452 (variable-chain-uri chain)
1453 parameters)))
1454 (when value
1455 (setf (global-variable-value
1456 (variable-chain-index chain))
1457 value))))))
1458 global-variable-chains)
1459 (map nil
1460 (lambda (chain)
1461 (funcall (variable-chain-thunk chain) ctx))
1462 global-variable-chains)
1463 ;; zzz we wouldn't have to mask float traps here if we used the
1464 ;; XPath API properly. Unfortunately I've been using FUNCALL
1465 ;; everywhere instead of EVALUATE, so let's paper over that
1466 ;; at a central place to be sure:
1467 (xpath::with-float-traps-masked ()
1468 (apply-templates ctx :mode *default-mode*))))
1469 (stylesheet-output-specification stylesheet)
1470 output)))
1472 (defun find-attribute-set (local-name uri &optional (stylesheet *stylesheet*))
1473 (or (gethash (cons local-name uri) (stylesheet-attribute-sets stylesheet))
1474 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1476 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1477 (when sort-predicate
1478 (setf list
1479 (mapcar #'xpath:context-node
1480 (stable-sort (contextify-node-list list)
1481 sort-predicate))))
1482 (let* ((n (length list))
1483 (s/d (lambda () n)))
1484 (loop
1485 for i from 1
1486 for child in list
1488 (apply-templates (xpath:make-context child s/d i)
1489 :param-bindings param-bindings
1490 :mode mode))))
1492 (defvar *stack-limit* 200)
1494 (defun invoke-with-stack-limit (fn)
1495 (let ((*stack-limit* (1- *stack-limit*)))
1496 (unless (plusp *stack-limit*)
1497 (xslt-error "*stack-limit* reached; stack overflow"))
1498 (funcall fn)))
1500 (defun invoke-template (ctx template param-bindings)
1501 (let ((*lexical-variable-values*
1502 (make-variable-value-array (template-n-variables template))))
1503 (with-stack-limit ()
1504 (loop
1505 for (name-cons value) in param-bindings
1506 for (nil index nil) = (find name-cons
1507 (template-params template)
1508 :test #'equal
1509 :key #'car)
1511 (when index
1512 (setf (lexical-variable-value index) value)))
1513 (funcall (template-body template) ctx))))
1515 (defun apply-default-templates (ctx mode)
1516 (let ((node (xpath:context-node ctx)))
1517 (cond
1518 ((or (xpath-protocol:node-type-p node :processing-instruction)
1519 (xpath-protocol:node-type-p node :comment)))
1520 ((or (xpath-protocol:node-type-p node :text)
1521 (xpath-protocol:node-type-p node :attribute))
1522 (write-text (xpath-protocol:node-text node)))
1524 (apply-templates/list
1525 (xpath::force
1526 (xpath-protocol:child-pipe node))
1527 :mode mode)))))
1529 (defvar *apply-imports*)
1531 (defun apply-applicable-templates (ctx templates param-bindings finally)
1532 (labels ((apply-imports (&optional actual-param-bindings)
1533 (if templates
1534 (let* ((this (pop templates))
1535 (low (template-apply-imports-limit this))
1536 (high (template-import-priority this)))
1537 (setf templates
1538 (remove-if-not
1539 (lambda (x)
1540 (<= low (template-import-priority x) high))
1541 templates))
1542 (invoke-template ctx this actual-param-bindings))
1543 (funcall finally))))
1544 (let ((*apply-imports* #'apply-imports))
1545 (apply-imports param-bindings))))
1547 (defun apply-templates (ctx &key param-bindings mode)
1548 (apply-applicable-templates ctx
1549 (find-templates ctx (or mode *default-mode*))
1550 param-bindings
1551 (lambda ()
1552 (apply-default-templates ctx mode))))
1554 (defun call-template (ctx name &optional param-bindings)
1555 (apply-applicable-templates ctx
1556 (find-named-templates name)
1557 param-bindings
1558 (lambda ()
1559 (xslt-error "cannot find named template: ~s"
1560 name))))
1562 (defun find-templates (ctx mode)
1563 (let* ((matching-candidates
1564 (xpath:matching-values (mode-match-thunk mode)
1565 (xpath:context-node ctx)))
1566 (npriorities
1567 (if matching-candidates
1568 (1+ (reduce #'max
1569 matching-candidates
1570 :key #'template-import-priority))
1572 (priority-groups (make-array npriorities :initial-element nil)))
1573 (dolist (template matching-candidates)
1574 (push template
1575 (elt priority-groups (template-import-priority template))))
1576 (loop
1577 for i from (1- npriorities) downto 0
1578 for group = (elt priority-groups i)
1579 for template = (maximize #'template< group)
1580 when template
1581 collect template)))
1583 (defun find-named-templates (name)
1584 (gethash name (stylesheet-named-templates *stylesheet*)))
1586 (defun template< (a b) ;assuming same import priority
1587 (let ((p (template-priority a))
1588 (q (template-priority b)))
1589 (cond
1590 ((< p q) t)
1591 ((> p q) nil)
1593 (xslt-cerror "conflicting templates:~_~A,~_~A"
1594 (template-match-expression a)
1595 (template-match-expression b))
1596 (< (template-position a) (template-position b))))))
1598 (defun maximize (< things)
1599 (when things
1600 (let ((max (car things)))
1601 (dolist (other (cdr things))
1602 (when (funcall < max other)
1603 (setf max other)))
1604 max)))
1606 (defun invoke-with-output-sink (fn output-spec output)
1607 (etypecase output
1608 (pathname
1609 (with-open-file (s output
1610 :direction :output
1611 :element-type '(unsigned-byte 8)
1612 :if-exists :rename-and-delete)
1613 (invoke-with-output-sink fn output-spec s)))
1614 ((or stream null)
1615 (invoke-with-output-sink fn
1616 output-spec
1617 (make-output-sink output-spec output)))
1618 ((or hax:abstract-handler sax:abstract-handler)
1619 (with-xml-output output
1620 (when (typep output '(or combi-sink auto-detect-sink))
1621 (sax:start-dtd output
1622 :autodetect-me-please
1623 (output-doctype-public output-spec)
1624 (output-doctype-system output-spec)))
1625 (funcall fn)))))
1627 (defun make-output-sink (output-spec stream)
1628 (let* ((ystream
1629 (if stream
1630 (let ((et (stream-element-type stream)))
1631 (cond
1632 ((or (null et) (subtypep et '(unsigned-byte 8)))
1633 (runes:make-octet-stream-ystream stream))
1634 ((subtypep et 'character)
1635 (runes:make-character-stream-ystream stream))))
1636 (runes:make-rod-ystream)))
1637 (omit-xml-declaration-p
1638 (boolean-or-error (output-omit-xml-declaration output-spec)))
1639 (sink-encoding (or (output-encoding output-spec) "UTF-8"))
1640 (sax-target
1641 (progn
1642 (setf (runes:ystream-encoding ystream)
1643 (cxml::find-output-encoding sink-encoding))
1644 (make-instance 'cxml::sink
1645 :ystream ystream
1646 :omit-xml-declaration-p omit-xml-declaration-p
1647 :encoding sink-encoding))))
1648 (flet ((make-combi-sink ()
1649 (make-instance 'combi-sink
1650 :hax-target (make-instance 'chtml::sink
1651 :ystream ystream)
1652 :sax-target sax-target
1653 :encoding sink-encoding)))
1654 (let ((method-key
1655 (cond
1656 ((equalp (output-method output-spec) "HTML") :html)
1657 ((equalp (output-method output-spec) "TEXT") :text)
1658 ((equalp (output-method output-spec) "XML") :xml)
1659 (t nil))))
1660 (cond
1661 ((and (eq method-key :html)
1662 (null (output-doctype-system output-spec))
1663 (null (output-doctype-public output-spec)))
1664 (make-combi-sink))
1665 ((eq method-key :text)
1666 (make-text-filter sax-target))
1667 ((and (eq method-key :xml)
1668 (null (output-doctype-system output-spec)))
1669 sax-target)
1671 (make-auto-detect-sink (make-combi-sink) method-key)))))))
1673 (defstruct template
1674 match-expression
1675 compiled-pattern
1676 name
1677 import-priority
1678 apply-imports-limit
1679 priority
1680 position
1681 mode
1682 mode-qname
1683 params
1684 body
1685 n-variables)
1687 (defun expression-priority (form)
1688 (let ((step (second form)))
1689 (if (and (null (cddr form))
1690 (listp step)
1691 (member (car step) '(:child :attribute))
1692 (null (cddr step)))
1693 (let ((name (second step)))
1694 (cond
1695 ((or (stringp name)
1696 (and (consp name)
1697 (or (eq (car name) :qname)
1698 (eq (car name) :processing-instruction))))
1699 0.0)
1700 ((and (consp name)
1701 (or (eq (car name) :namespace)
1702 (eq (car name) '*)))
1703 -0.25)
1705 -0.5)))
1706 0.5)))
1708 (defun parse-key-pattern (str)
1709 (with-resignalled-errors ()
1710 (with-forward-compatible-errors
1711 (xpath:parse-xpath "compile-time-error()") ;hack
1712 (let ((parsed
1713 (mapcar #'(lambda (item)
1714 `(:path (:root :node)
1715 (:descendant-or-self *)
1716 ,@(cdr item)))
1717 (cdr (xpath::parse-pattern-expression str)))))
1718 (if (null (rest parsed))
1719 (first parsed)
1720 `(:union ,@parsed))))))
1722 (defun compile-value-thunk (value env)
1723 (if (and (listp value) (eq (car value) 'progn))
1724 (let ((inner-thunk (compile-instruction value env)))
1725 (lambda (ctx)
1726 (apply-to-result-tree-fragment ctx inner-thunk)))
1727 (compile-xpath value env)))
1729 (defun compile-var-binding (name value env)
1730 (multiple-value-bind (local-name uri)
1731 (decode-qname name env nil)
1732 (let ((thunk (xslt-trace-thunk
1733 (compile-value-thunk value env)
1734 "local variable ~s = ~s" name :result)))
1735 (list (cons local-name uri)
1736 (push-variable local-name
1738 *lexical-variable-declarations*)
1739 thunk))))
1741 (defun compile-var-bindings (forms env)
1742 (loop
1743 for (name value) in forms
1744 collect (compile-var-binding name value env)))
1746 (defun compile-template (<template> env position)
1747 (stp:with-attributes (match name priority mode) <template>
1748 (unless (or name match)
1749 (xslt-error "missing match in template"))
1750 (multiple-value-bind (params body-pos)
1751 (loop
1752 for i from 0
1753 for child in (stp:list-children <template>)
1754 while (namep child "param")
1755 collect (parse-param child) into params
1756 finally (return (values params i)))
1757 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1758 (param-bindings (compile-var-bindings params env))
1759 (body (parse-body <template> body-pos (mapcar #'car params)))
1760 (body-thunk (compile-instruction `(progn ,@body) env))
1761 (outer-body-thunk
1762 (xslt-trace-thunk
1763 #'(lambda (ctx)
1764 (unwind-protect
1765 (progn
1766 ;; set params that weren't initialized by apply-templates
1767 (loop for (name index param-thunk) in param-bindings
1768 when (eq (lexical-variable-value index nil) 'unbound)
1769 do (setf (lexical-variable-value index)
1770 (funcall param-thunk ctx)))
1771 (funcall body-thunk ctx))))
1772 "template: match = ~s name = ~s" match name))
1773 (n-variables (length *lexical-variable-declarations*)))
1774 (append
1775 (when name
1776 (multiple-value-bind (local-name uri)
1777 (decode-qname name env nil)
1778 (list
1779 (make-template :name (cons local-name uri)
1780 :import-priority *import-priority*
1781 :apply-imports-limit *apply-imports-limit*
1782 :params param-bindings
1783 :body outer-body-thunk
1784 :n-variables n-variables))))
1785 (when match
1786 (mapcar (lambda (expression)
1787 (let* ((compiled-pattern
1788 (xslt-trace-thunk
1789 (car (without-xslt-current ()
1790 (xpath:compute-patterns
1791 `(:patterns ,expression)
1793 :dummy
1794 env)))
1795 "match-thunk for template (match ~s): ~s --> ~s"
1796 match expression :result))
1797 (p (if priority
1798 (xpath::parse-xnum priority)
1799 (expression-priority expression)))
1801 (progn
1802 (unless (and (numberp p)
1803 (not (xpath::inf-p p))
1804 (not (xpath::nan-p p)))
1805 (xslt-error "failed to parse priority"))
1806 (float p 1.0d0)))
1807 (template
1808 (make-template :match-expression expression
1809 :compiled-pattern compiled-pattern
1810 :import-priority *import-priority*
1811 :apply-imports-limit *apply-imports-limit*
1812 :priority p
1813 :position position
1814 :mode-qname mode
1815 :params param-bindings
1816 :body outer-body-thunk
1817 :n-variables n-variables)))
1818 (setf (xpath:pattern-value compiled-pattern)
1819 template)
1820 template))
1821 (cdr (xpath:parse-pattern-expression match)))))))))
1822 #+(or)
1823 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")