format-number: Fixed left side
[xuriella.git] / xslt.lisp
blob007b17fc73c0744c13783bc34eadb92630160906
1 ;;; -*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
3 ;;; Copyright (c) 2007,2008 David Lichteblau, Ivan Shvedunov.
4 ;;; All rights reserved.
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; * Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; * Redistributions in binary form must reproduce the above
14 ;;; copyright notice, this list of conditions and the following
15 ;;; disclaimer in the documentation and/or other materials
16 ;;; provided with the distribution.
17 ;;;
18 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
19 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
22 ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
24 ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 (in-package :xuriella)
32 #+sbcl
33 (declaim (optimize (debug 2)))
36 (eval-when (:compile-toplevel :load-toplevel :execute)
37 (defvar *xsl* "http://www.w3.org/1999/XSL/Transform")
38 (defvar *xml* "http://www.w3.org/XML/1998/namespace")
39 (defvar *html* "http://www.w3.org/1999/xhtml"))
42 ;;;; XSLT-ERROR
44 (define-condition xslt-error (simple-error)
46 (:documentation "The class of all XSLT errors."))
48 (define-condition recoverable-xslt-error (xslt-error)
50 (:documentation "The class of recoverable XSLT errors."))
52 (defun xslt-error (fmt &rest args)
53 (error 'xslt-error :format-control fmt :format-arguments args))
55 (defun xslt-cerror (fmt &rest args)
56 (with-simple-restart (recover "recover")
57 (error 'recoverable-xslt-error
58 :format-control fmt
59 :format-arguments args)))
61 (defvar *debug* nil)
63 (defmacro handler-case* (form &rest clauses)
64 ;; like HANDLER-CASE if *DEBUG* is off. If it's on, don't establish
65 ;; a handler at all so that we see the real stack traces. (We could use
66 ;; HANDLER-BIND here and check at signalling time, but doesn't seem
67 ;; important.)
68 (let ((doit (gensym)))
69 `(flet ((,doit () ,form))
70 (if *debug*
71 (,doit)
72 (handler-case
73 (,doit)
74 ,@clauses)))))
76 (defun compile-xpath (xpath &optional env)
77 (handler-case*
78 (xpath:compile-xpath xpath env)
79 (xpath:xpath-error (c)
80 (xslt-error "~A" c))))
82 (defmacro with-stack-limit ((&optional) &body body)
83 `(invoke-with-stack-limit (lambda () ,@body)))
86 ;;;; Helper function and macro
88 (defun map-pipe-eagerly (fn pipe)
89 (xpath::enumerate pipe :key fn :result nil))
91 (defmacro do-pipe ((var pipe &optional result) &body body)
92 `(block nil
93 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
94 ,result))
97 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
99 (defparameter *namespaces*
100 '((nil . "")
101 ("xmlns" . #"http://www.w3.org/2000/xmlns/")
102 ("xml" . #"http://www.w3.org/XML/1998/namespace")))
104 (defvar *global-variable-declarations*)
105 (defvar *lexical-variable-declarations*)
107 (defvar *global-variable-values*)
108 (defvar *lexical-variable-values*)
110 (defclass xslt-environment () ())
112 (defun split-qname (str)
113 (handler-case
114 (multiple-value-bind (prefix local-name)
115 (cxml::split-qname str)
116 (unless
117 ;; FIXME: cxml should really offer a function that does
118 ;; checks for NCName and QName in a sensible way for user code.
119 ;; cxml::split-qname is tailored to the needs of the parser.
121 ;; For now, let's just check the syntax explicitly.
122 (and (or (null prefix) (xpath::nc-name-p prefix))
123 (xpath::nc-name-p local-name))
124 (xslt-error "not a qname: ~A" str))
125 (values prefix local-name))
126 (cxml:well-formedness-violation ()
127 (xslt-error "not a qname: ~A" str))))
129 (defun decode-qname (qname env attributep)
130 (multiple-value-bind (prefix local-name)
131 (split-qname qname)
132 (values local-name
133 (if (or prefix (not attributep))
134 (xpath-sys:environment-find-namespace env (or prefix ""))
136 prefix)))
138 (defmethod xpath-sys:environment-find-namespace ((env xslt-environment) prefix)
139 (or (cdr (assoc prefix *namespaces* :test 'equal))
140 ;; zzz gross hack.
141 ;; Change the entire code base to represent "no prefix" as the
142 ;; empty string consistently. unparse.lisp has already been changed.
143 (and (equal prefix "")
144 (cdr (assoc nil *namespaces* :test 'equal)))
145 (and (eql prefix nil)
146 (cdr (assoc "" *namespaces* :test 'equal)))))
148 (defun find-variable-index (local-name uri table)
149 (position (cons local-name uri) table :test 'equal))
151 (defun intern-global-variable (local-name uri)
152 (or (find-variable-index local-name uri *global-variable-declarations*)
153 (push-variable local-name uri *global-variable-declarations*)))
155 (defun push-variable (local-name uri table)
156 (prog1
157 (length table)
158 (vector-push-extend (cons local-name uri) table)))
160 (defun lexical-variable-value (index &optional (errorp t))
161 (let ((result (svref *lexical-variable-values* index)))
162 (when errorp
163 (assert (not (eq result 'unbound))))
164 result))
166 (defun (setf lexical-variable-value) (newval index)
167 (assert (not (eq newval 'unbound)))
168 (setf (svref *lexical-variable-values* index) newval))
170 (defun global-variable-value (index &optional (errorp t))
171 (let ((result (svref *global-variable-values* index)))
172 (when errorp
173 (assert (not (eq result 'unbound))))
174 result))
176 (defun (setf global-variable-value) (newval index)
177 (assert (not (eq newval 'unbound)))
178 (setf (svref *global-variable-values* index) newval))
180 (defmethod xpath-sys:environment-find-function
181 ((env xslt-environment) lname uri)
182 (if (string= uri "")
183 (or (xpath-sys:find-xpath-function lname *xsl*)
184 (xpath-sys:find-xpath-function lname uri))
185 (xpath-sys:find-xpath-function lname uri)))
187 (defmethod xpath-sys:environment-find-variable
188 ((env xslt-environment) lname uri)
189 (let ((index
190 (find-variable-index lname uri *lexical-variable-declarations*)))
191 (when index
192 (lambda (ctx)
193 (declare (ignore ctx))
194 (svref *lexical-variable-values* index)))))
196 (defclass lexical-xslt-environment (xslt-environment) ())
198 (defmethod xpath-sys:environment-find-variable
199 ((env lexical-xslt-environment) lname uri)
200 (or (call-next-method)
201 (let ((index
202 (find-variable-index lname uri *global-variable-declarations*)))
203 (when index
204 (xslt-trace-thunk
205 (lambda (ctx)
206 (declare (ignore ctx))
207 (svref *global-variable-values* index))
208 "global ~s (uri ~s) = ~s" lname uri :result)))))
210 (defclass global-variable-environment (xslt-environment)
211 ((initial-global-variable-thunks
212 :initarg :initial-global-variable-thunks
213 :accessor initial-global-variable-thunks)))
215 (defmethod xpath-sys:environment-find-variable
216 ((env global-variable-environment) lname uri)
217 (or (call-next-method)
218 (gethash (cons lname uri) (initial-global-variable-thunks env))))
221 ;;;; TOPLEVEL-TEXT-OUTPUT-SINK
222 ;;;;
223 ;;;; A sink that serializes only text not contained in any element.
225 (defmacro with-toplevel-text-output-sink ((var) &body body)
226 `(invoke-with-toplevel-text-output-sink (lambda (,var) ,@body)))
228 (defclass toplevel-text-output-sink (sax:default-handler)
229 ((target :initarg :target :accessor text-output-sink-target)
230 (depth :initform 0 :accessor textoutput-sink-depth)))
232 (defmethod sax:start-element ((sink toplevel-text-output-sink)
233 namespace-uri local-name qname attributes)
234 (declare (ignore namespace-uri local-name qname attributes))
235 (incf (textoutput-sink-depth sink)))
237 (defmethod sax:characters ((sink toplevel-text-output-sink) data)
238 (when (zerop (textoutput-sink-depth sink))
239 (write-string data (text-output-sink-target sink))))
241 (defmethod sax:end-element ((sink toplevel-text-output-sink)
242 namespace-uri local-name qname)
243 (declare (ignore namespace-uri local-name qname))
244 (decf (textoutput-sink-depth sink)))
246 (defun invoke-with-toplevel-text-output-sink (fn)
247 (with-output-to-string (s)
248 (funcall fn (make-instance 'toplevel-text-output-sink :target s))))
251 ;;;; TEXT-FILTER
252 ;;;;
253 ;;;; A sink that passes through only text (at any level).
255 (defclass text-filter (sax:default-handler)
256 ((target :initarg :target :accessor text-filter-target)))
258 (defmethod sax:characters ((sink text-filter) data)
259 (sax:characters (text-filter-target sink) data))
261 (defmethod sax:end-document ((sink text-filter))
262 (sax:end-document (text-filter-target sink)))
264 (defun make-text-filter (target)
265 (make-instance 'text-filter :target target))
268 ;;;; Names
270 (defun of-name (local-name)
271 (stp:of-name local-name *xsl*))
273 (defun namep (node local-name)
274 (and (typep node '(or stp:element stp:attribute))
275 (equal (stp:namespace-uri node) *xsl*)
276 (equal (stp:local-name node) local-name)))
279 ;;;; PARSE-STYLESHEET
281 (defstruct stylesheet
282 (modes (make-hash-table :test 'equal))
283 (global-variables (make-empty-declaration-array))
284 (output-specification (make-output-specification))
285 (strip-tests nil)
286 (named-templates (make-hash-table :test 'equal))
287 (attribute-sets (make-hash-table :test 'equal))
288 (keys (make-hash-table :test 'equal))
289 (namespace-aliases (make-hash-table :test 'equal)))
291 (defstruct mode (templates nil))
293 (defun find-mode (stylesheet local-name &optional uri)
294 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
296 (defun ensure-mode (stylesheet &optional local-name uri)
297 (or (find-mode stylesheet local-name uri)
298 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
299 (make-mode))))
301 (defun ensure-mode/qname (stylesheet qname env)
302 (if qname
303 (multiple-value-bind (local-name uri)
304 (decode-qname qname env nil)
305 (ensure-mode stylesheet local-name uri))
306 (find-mode stylesheet nil)))
308 (defun acons-namespaces (element &optional (bindings *namespaces*))
309 (map-namespace-declarations (lambda (prefix uri)
310 (push (cons prefix uri) bindings))
311 element)
312 bindings)
314 (defun find-key (name stylesheet)
315 (or (gethash name (stylesheet-keys stylesheet))
316 (xslt-error "unknown key: ~a" name)))
318 (defun make-key (match use) (cons match use))
320 (defun key-match (key) (car key))
322 (defun key-use (key) (cdr key))
324 (defun add-key (stylesheet name match use)
325 (if (gethash name (stylesheet-keys stylesheet))
326 (xslt-error "duplicate key: ~a" name)
327 (setf (gethash name (stylesheet-keys stylesheet))
328 (make-key match use))))
330 (defvar *excluded-namespaces* (list *xsl*))
331 (defvar *empty-mode*)
332 (defvar *default-mode*)
334 (defvar *xsl-include-stack* nil)
336 (defun uri-to-pathname (uri)
337 (cxml::uri-to-pathname (puri:parse-uri uri)))
339 (defun parse-stylesheet-to-stp (input uri-resolver)
340 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
341 (<transform> (stp:document-element d)))
342 (strip-stylesheet <transform>)
343 ;; FIXME: handle embedded stylesheets
344 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
345 (or (equal (stp:local-name <transform>) "transform")
346 (equal (stp:local-name <transform>) "stylesheet")))
347 (xslt-error "not a stylesheet"))
348 (dolist (include (stp:filter-children (of-name "include") <transform>))
349 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
350 (stp:base-uri include)))
351 (uri (if uri-resolver
352 (funcall uri-resolver (puri:render-uri uri nil))
353 uri))
354 (str (puri:render-uri uri nil))
355 (pathname
356 (handler-case
357 (uri-to-pathname uri)
358 (cxml:xml-parse-error (c)
359 (xslt-error "cannot find included stylesheet ~A: ~A"
360 uri c)))))
361 (with-open-file
362 (stream pathname
363 :element-type '(unsigned-byte 8)
364 :if-does-not-exist nil)
365 (unless stream
366 (xslt-error "cannot find included stylesheet ~A at ~A"
367 uri pathname))
368 (when (find str *xsl-include-stack* :test #'equal)
369 (xslt-error "recursive inclusion of ~A" uri))
370 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
371 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
372 (stp:insert-child-after <transform>
373 (stp:copy <transform>2)
374 include)
375 (stp:detach include)))))
376 <transform>))
378 (defvar *instruction-base-uri*) ;misnamed, is also used in other attributes
379 (defvar *apply-imports-limit*)
380 (defvar *import-priority*)
381 (defvar *extension-namespaces*)
383 (defmacro do-toplevel ((var xpath <transform>) &body body)
384 `(map-toplevel (lambda (,var) ,@body) ,xpath ,<transform>))
386 (defun map-toplevel (fn xpath <transform>)
387 (dolist (node (list-toplevel xpath <transform>))
388 (let ((*namespaces* *namespaces*))
389 (xpath:do-node-set (ancestor (xpath:evaluate "ancestor::node()" node))
390 (when (xpath-protocol:node-type-p ancestor :element)
391 (setf *namespaces* (acons-namespaces ancestor))))
392 (funcall fn node))))
394 (defun list-toplevel (xpath <transform>)
395 (labels ((recurse (sub)
396 (let ((subsubs
397 (xpath-sys:pipe-of
398 (xpath:evaluate "transform|stylesheet" sub))))
399 (xpath::append-pipes
400 (xpath-sys:pipe-of (xpath:evaluate xpath sub))
401 (xpath::mappend-pipe #'recurse subsubs)))))
402 (xpath::sort-nodes (recurse <transform>))))
404 (defmacro with-parsed-prefixes ((node env) &body body)
405 `(invoke-with-parsed-prefixes (lambda () ,@body) ,node ,env))
407 (defun invoke-with-parsed-prefixes (fn node env)
408 (unless (or (namep node "stylesheet") (namep node "transform"))
409 (setf node (stp:parent node)))
410 (let ((*excluded-namespaces* (list *xsl*))
411 (*extension-namespaces* '()))
412 (parse-exclude-result-prefixes! node env)
413 (parse-extension-element-prefixes! node env)
414 (funcall fn)))
416 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
417 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
418 (instruction-base-uri (stp:base-uri <transform>))
419 (namespaces (acons-namespaces <transform>))
420 (apply-imports-limit (1+ *import-priority*))
421 (continuations '()))
422 (let ((*namespaces* namespaces))
423 (invoke-with-parsed-prefixes (constantly t) <transform> env))
424 (macrolet ((with-specials ((&optional) &body body)
425 `(let ((*instruction-base-uri* instruction-base-uri)
426 (*namespaces* namespaces)
427 (*apply-imports-limit* apply-imports-limit))
428 ,@body)))
429 (with-specials ()
430 (do-toplevel (import "import" <transform>)
431 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
432 (stp:base-uri import))))
433 (push (parse-imported-stylesheet env stylesheet uri uri-resolver)
434 continuations))))
435 (let ((import-priority
436 (incf *import-priority*))
437 (var-cont (prepare-global-variables stylesheet <transform>)))
438 ;; delay the rest of compilation until we've seen all global
439 ;; variables:
440 (lambda ()
441 (mapc #'funcall (nreverse continuations))
442 (with-specials ()
443 (let ((*import-priority* import-priority))
444 (funcall var-cont)
445 (parse-keys! stylesheet <transform> env)
446 (parse-templates! stylesheet <transform> env)
447 (parse-output! stylesheet <transform>)
448 (parse-strip/preserve-space! stylesheet <transform> env)
449 (parse-attribute-sets! stylesheet <transform> env)
450 (parse-namespace-aliases! stylesheet <transform> env))))))))
452 (defvar *xsl-import-stack* nil)
454 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
455 (let* ((uri (if uri-resolver
456 (funcall uri-resolver (puri:render-uri uri nil))
457 uri))
458 (str (puri:render-uri uri nil))
459 (pathname
460 (handler-case
461 (uri-to-pathname uri)
462 (cxml:xml-parse-error (c)
463 (xslt-error "cannot find imported stylesheet ~A: ~A"
464 uri c)))))
465 (with-open-file
466 (stream pathname
467 :element-type '(unsigned-byte 8)
468 :if-does-not-exist nil)
469 (unless stream
470 (xslt-error "cannot find imported stylesheet ~A at ~A"
471 uri pathname))
472 (when (find str *xsl-import-stack* :test #'equal)
473 (xslt-error "recursive inclusion of ~A" uri))
474 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
475 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
477 (defun parse-stylesheet (designator &key uri-resolver)
478 (xpath:with-namespaces ((nil #.*xsl*))
479 (let* ((*import-priority* 0)
480 (puri:*strict-parse* nil)
481 (stylesheet (make-stylesheet))
482 (env (make-instance 'lexical-xslt-environment))
483 (*excluded-namespaces* *excluded-namespaces*)
484 (*global-variable-declarations* (make-empty-declaration-array)))
485 (ensure-mode stylesheet nil)
486 (funcall (parse-1-stylesheet env stylesheet designator uri-resolver))
487 ;; reverse attribute sets:
488 (let ((table (stylesheet-attribute-sets stylesheet)))
489 (maphash (lambda (k v)
490 (setf (gethash k table) (nreverse v)))
491 table))
492 stylesheet)))
494 (defun parse-attribute-sets! (stylesheet <transform> env)
495 (do-toplevel (elt "attribute-set" <transform>)
496 (with-parsed-prefixes (elt env)
497 (push (let* ((sets
498 (mapcar (lambda (qname)
499 (multiple-value-list (decode-qname qname env nil)))
500 (words
501 (stp:attribute-value elt "use-attribute-sets"))))
502 (instructions
503 (stp:map-children
504 'list
505 (lambda (child)
506 (unless (or (not (typep child 'stp:element))
507 (and (equal (stp:namespace-uri child) *xsl*)
508 (equal (stp:local-name child)
509 "attribute"))
510 (find (stp:namespace-uri child)
511 *extension-namespaces*
512 :test 'equal))
513 (xslt-error "non-attribute found in attribute set"))
514 (parse-instruction child))
515 elt))
516 (*lexical-variable-declarations*
517 (make-empty-declaration-array))
518 (thunk
519 (compile-instruction `(progn ,@instructions) env))
520 (n-variables (length *lexical-variable-declarations*)))
521 (lambda (ctx)
522 (with-stack-limit ()
523 (loop for (local-name uri nil) in sets do
524 (dolist (thunk (find-attribute-set local-name uri))
525 (funcall thunk ctx)))
526 (let ((*lexical-variable-values*
527 (make-variable-value-array n-variables)))
528 (funcall thunk ctx)))))
529 (gethash (multiple-value-bind (local-name uri)
530 (decode-qname (stp:attribute-value elt "name") env nil)
531 (cons local-name uri))
532 (stylesheet-attribute-sets stylesheet))))))
534 (defun parse-namespace-aliases! (stylesheet <transform> env)
535 (do-toplevel (elt "namespace-alias" <transform>)
536 (stp:with-attributes (stylesheet-prefix result-prefix) elt
537 (setf (gethash
538 (xpath-sys:environment-find-namespace env stylesheet-prefix)
539 (stylesheet-namespace-aliases stylesheet))
540 (xpath-sys:environment-find-namespace
542 (if (equal result-prefix "#default")
544 result-prefix))))))
546 (defun parse-exclude-result-prefixes! (node env)
547 (stp:with-attributes (exclude-result-prefixes)
548 node
549 (dolist (prefix (words (or exclude-result-prefixes "")))
550 (if (equal prefix "#default")
551 (setf prefix nil)
552 (unless (cxml-stp-impl::nc-name-p prefix)
553 (xslt-error "invalid prefix: ~A" prefix)))
554 (push (or (xpath-sys:environment-find-namespace env prefix)
555 (xslt-error "namespace not found: ~A" prefix))
556 *excluded-namespaces*))))
558 (defun parse-extension-element-prefixes! (node env)
559 (stp:with-attributes (extension-element-prefixes)
560 node
561 (dolist (prefix (words (or extension-element-prefixes "")))
562 (if (equal prefix "#default")
563 (setf prefix nil)
564 (unless (cxml-stp-impl::nc-name-p prefix)
565 (xslt-error "invalid prefix: ~A" prefix)))
566 (let ((uri
567 (or (xpath-sys:environment-find-namespace env prefix)
568 (xslt-error "namespace not found: ~A" prefix))))
569 (unless (equal uri *xsl*)
570 (push uri *extension-namespaces*)
571 (push uri *excluded-namespaces*))))))
573 (defun parse-strip/preserve-space! (stylesheet <transform> env)
574 (xpath:with-namespaces ((nil #.*xsl*))
575 (do-toplevel (elt "strip-space|preserve-space" <transform>)
576 (let ((*namespaces* (acons-namespaces elt))
577 (mode
578 (if (equal (stp:local-name elt) "strip-space")
579 :strip
580 :preserve)))
581 (dolist (name-test (words (stp:attribute-value elt "elements")))
582 (let* ((pos (search ":*" name-test))
583 (test-function
584 (cond
585 ((eql pos (- (length name-test) 2))
586 (let* ((prefix (subseq name-test 0 pos))
587 (name-test-uri
588 (xpath-sys:environment-find-namespace env prefix)))
589 (unless (xpath::nc-name-p prefix)
590 (xslt-error "not an NCName: ~A" prefix))
591 (lambda (local-name uri)
592 (declare (ignore local-name))
593 (if (equal uri name-test-uri)
594 mode
595 nil))))
596 ((equal name-test "*")
597 (lambda (local-name uri)
598 (declare (ignore local-name uri))
599 mode))
601 (multiple-value-bind (name-test-local-name name-test-uri)
602 (decode-qname name-test env nil)
603 (lambda (local-name uri)
604 (if (and (equal local-name name-test-local-name)
605 (equal uri name-test-uri))
606 mode
607 nil)))))))
608 (push test-function (stylesheet-strip-tests stylesheet))))))))
610 (defstruct (output-specification
611 (:conc-name "OUTPUT-"))
612 method
613 indent
614 omit-xml-declaration
615 encoding)
617 (defun parse-output! (stylesheet <transform>)
618 (let ((outputs (list-toplevel "output" <transform>)))
619 (when outputs
620 (when (cdr outputs)
621 ;; FIXME:
622 ;; - concatenate cdata-section-elements
623 ;; - the others must not conflict
624 (error "oops, merging of output elements not supported yet"))
625 (let ((<output> (car outputs))
626 (spec (stylesheet-output-specification stylesheet)))
627 (stp:with-attributes (;; version
628 method
629 indent
630 encoding
631 ;;; media-type
632 ;;; doctype-system
633 ;;; doctype-public
634 omit-xml-declaration
635 ;;; standalone
636 ;;; cdata-section-elements
638 <output>
639 (setf (output-method spec) method)
640 (setf (output-indent spec) indent)
641 (setf (output-encoding spec) encoding)
642 (setf (output-omit-xml-declaration spec) omit-xml-declaration))))))
644 (defun make-empty-declaration-array ()
645 (make-array 1 :fill-pointer 0 :adjustable t))
647 (defun make-variable-value-array (n-lexical-variables)
648 (make-array n-lexical-variables :initial-element 'unbound))
650 (defun compile-global-variable (<variable> env) ;; also for <param>
651 (stp:with-attributes (name select) <variable>
652 (when (and select (stp:list-children <variable>))
653 (xslt-error "variable with select and body"))
654 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
655 (inner (cond
656 (select
657 (compile-xpath select env))
658 ((stp:list-children <variable>)
659 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
660 (inner-thunk (compile-instruction inner-sexpr env)))
661 (lambda (ctx)
662 (apply-to-result-tree-fragment ctx inner-thunk))))
664 (lambda (ctx)
665 (declare (ignore ctx))
666 ""))))
667 (n-lexical-variables (length *lexical-variable-declarations*)))
668 (xslt-trace-thunk
669 (lambda (ctx)
670 (let* ((*lexical-variable-values*
671 (make-variable-value-array n-lexical-variables)))
672 (funcall inner ctx)))
673 "global ~s (~s) = ~s" name select :result))))
675 (defstruct (variable-information
676 (:constructor make-variable)
677 (:conc-name "VARIABLE-"))
678 index
679 thunk
680 local-name
682 param-p
683 thunk-setter)
685 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
686 (let* ((*namespaces* (acons-namespaces <variable>))
687 (instruction-base-uri (stp:base-uri <variable>))
688 (*instruction-base-uri* instruction-base-uri)
689 (*excluded-namespaces* (list *xsl*))
690 (*extension-namespaces* '())
691 (qname (stp:attribute-value <variable> "name")))
692 (with-parsed-prefixes (<variable> global-env)
693 (unless qname
694 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
695 (multiple-value-bind (local-name uri)
696 (decode-qname qname global-env nil)
697 ;; For the normal compilation environment of templates, install it
698 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
699 (let ((index (intern-global-variable local-name uri)))
700 ;; For the evaluation of a global variable itself, build a thunk
701 ;; that lazily resolves other variables, stored into
702 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
703 (let* ((value-thunk :unknown)
704 (global-variable-thunk
705 (lambda (ctx)
706 (let ((v (global-variable-value index nil)))
707 (when (eq v 'seen)
708 (xslt-error "recursive variable definition"))
709 (cond
710 ((eq v 'unbound)
711 (setf (global-variable-value index) 'seen)
712 (setf (global-variable-value index)
713 (funcall value-thunk ctx)))
715 v)))))
716 (excluded-namespaces *excluded-namespaces*)
717 (extension-namespaces *extension-namespaces*)
718 (thunk-setter
719 (lambda ()
720 (let ((*instruction-base-uri* instruction-base-uri)
721 (*excluded-namespaces* excluded-namespaces)
722 (*extension-namespaces* extension-namespaces))
723 (setf value-thunk
724 (compile-global-variable <variable> global-env))))))
725 (setf (gethash (cons local-name uri)
726 (initial-global-variable-thunks global-env))
727 global-variable-thunk)
728 (make-variable :index index
729 :local-name local-name
730 :uri uri
731 :thunk global-variable-thunk
732 :param-p (namep <variable> "param")
733 :thunk-setter thunk-setter)))))))
735 (defun parse-keys! (stylesheet <transform> env)
736 (xpath:with-namespaces ((nil #.*xsl*))
737 (do-toplevel (<key> "key" <transform>)
738 (let ((*instruction-base-uri* (stp:base-uri <key>)))
739 (stp:with-attributes (name match use) <key>
740 (unless name (xslt-error "key name attribute not specified"))
741 (unless match (xslt-error "key match attribute not specified"))
742 (unless use (xslt-error "key use attribute not specified"))
743 (multiple-value-bind (local-name uri)
744 (decode-qname name env nil)
745 (add-key stylesheet
746 (cons local-name uri)
747 (compile-xpath `(xpath:xpath ,(parse-key-pattern match)) env)
748 (compile-xpath use env))))))))
750 (defun prepare-global-variables (stylesheet <transform>)
751 (xpath:with-namespaces ((nil #.*xsl*))
752 (let* ((table (make-hash-table :test 'equal))
753 (global-env (make-instance 'global-variable-environment
754 :initial-global-variable-thunks table))
755 (specs '()))
756 (do-toplevel (<variable> "variable|param" <transform>)
757 (let ((var (parse-global-variable! <variable> global-env)))
758 (xslt-trace "parsing global variable ~s (uri ~s)"
759 (variable-local-name var)
760 (variable-uri var))
761 (when (find var
762 specs
763 :test (lambda (a b)
764 (and (equal (variable-local-name a)
765 (variable-local-name b))
766 (equal (variable-uri a)
767 (variable-uri b)))))
768 (xslt-error "duplicate definition for global variable ~A"
769 (variable-local-name var)))
770 (push var specs)))
771 (setf specs (nreverse specs))
772 (lambda ()
773 ;; now that the global environment knows about all variables, run the
774 ;; thunk setters to perform their compilation
775 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
776 (let ((table (stylesheet-global-variables stylesheet))
777 (newlen (length *global-variable-declarations*)))
778 (adjust-array table newlen :fill-pointer newlen)
779 (dolist (spec specs)
780 (setf (elt table (variable-index spec)) spec)))))))
782 (defun parse-templates! (stylesheet <transform> env)
783 (let ((i 0))
784 (do-toplevel (<template> "template" <transform>)
785 (let ((*namespaces* (acons-namespaces <template>))
786 (*instruction-base-uri* (stp:base-uri <template>)))
787 (with-parsed-prefixes (<template> env)
788 (dolist (template (compile-template <template> env i))
789 (let ((name (template-name template)))
790 (if name
791 (let* ((table (stylesheet-named-templates stylesheet))
792 (head (car (gethash name table))))
793 (when (and head (eql (template-import-priority head)
794 (template-import-priority template)))
795 ;; fixme: is this supposed to be a run-time error?
796 (xslt-error "conflicting templates for ~A" name))
797 (push template (gethash name table)))
798 (let ((mode (ensure-mode/qname stylesheet
799 (template-mode-qname template)
800 env)))
801 (setf (template-mode template) mode)
802 (push template (mode-templates mode))))))))
803 (incf i))))
806 ;;;; APPLY-STYLESHEET
808 (defvar *stylesheet*)
810 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
812 (defun unalias-uri (uri)
813 (let ((result
814 (gethash uri (stylesheet-namespace-aliases *stylesheet*)
815 uri)))
816 (check-type result string)
817 result))
819 (defstruct (parameter
820 (:constructor make-parameter (value local-name &optional uri)))
821 (uri "")
822 local-name
823 value)
825 (defun find-parameter-value (local-name uri parameters)
826 (dolist (p parameters)
827 (when (and (equal (parameter-local-name p) local-name)
828 (equal (parameter-uri p) uri))
829 (return (parameter-value p)))))
831 (defvar *uri-resolver*)
833 (defun parse-allowing-microsoft-bom (pathname handler)
834 (with-open-file (s pathname :element-type '(unsigned-byte 8))
835 (unless (and (eql (read-byte s nil) #xef)
836 (eql (read-byte s nil) #xbb)
837 (eql (read-byte s nil) #xbf))
838 (file-position s 0))
839 (cxml:parse s handler)))
841 (defvar *documents*)
843 (defun %document (uri-string base-uri)
844 (let* ((absolute-uri
845 (puri:merge-uris uri-string (or base-uri "")))
846 (resolved-uri
847 (if *uri-resolver*
848 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
849 absolute-uri))
850 (pathname
851 (handler-case
852 (uri-to-pathname resolved-uri)
853 (cxml:xml-parse-error (c)
854 (xslt-error "cannot find referenced document ~A: ~A"
855 resolved-uri c))))
856 (xpath-root-node
857 (or (gethash pathname *documents*)
858 (setf (gethash pathname *documents*)
859 (make-whitespace-stripper
860 (handler-case
861 (parse-allowing-microsoft-bom pathname
862 (stp:make-builder))
863 ((or file-error cxml:xml-parse-error) (c)
864 (xslt-error "cannot parse referenced document ~A: ~A"
865 pathname c)))
866 (stylesheet-strip-tests *stylesheet*))))))
867 (when (puri:uri-fragment absolute-uri)
868 (xslt-error "use of fragment identifiers in document() not supported"))
869 xpath-root-node))
871 (xpath-sys:define-extension xslt *xsl*)
873 (defun document-base-uri (node)
874 (xpath-protocol:base-uri
875 (cond
876 ((xpath-protocol:node-type-p node :document)
877 (xpath::find-in-pipe-if
878 (lambda (x)
879 (xpath-protocol:node-type-p x :element))
880 (xpath-protocol:child-pipe node)))
881 ((xpath-protocol:node-type-p node :element)
882 node)
884 (xpath-protocol:parent-node node)))))
886 (xpath-sys:define-xpath-function/lazy
887 xslt :document
888 (object &optional node-set)
889 (let ((instruction-base-uri *instruction-base-uri*))
890 (lambda (ctx)
891 (let* ((object (funcall object ctx))
892 (node-set (and node-set (funcall node-set ctx)))
893 (base-uri
894 (if node-set
895 (document-base-uri (xpath::textually-first-node node-set))
896 instruction-base-uri)))
897 (xpath-sys:make-node-set
898 (if (xpath:node-set-p object)
899 (xpath:map-node-set->list
900 (lambda (node)
901 (%document (xpath:string-value node)
902 (if node-set
903 base-uri
904 (document-base-uri node))))
905 object)
906 (list (%document (xpath:string-value object) base-uri))))))))
908 (xpath-sys:define-xpath-function/lazy xslt :key (name object)
909 (let ((namespaces *namespaces*))
910 (lambda (ctx)
911 (let* ((qname (xpath:string-value (funcall name ctx)))
912 (object (funcall object ctx))
913 (expanded-name
914 (multiple-value-bind (local-name uri)
915 (decode-qname/runtime qname namespaces nil)
916 (cons local-name uri)))
917 (key (find-key expanded-name *stylesheet*)))
918 (labels ((get-by-key (value)
919 (let ((value (xpath:string-value value)))
920 (xpath::filter-pipe
921 #'(lambda (node)
922 (let ((uses
923 (xpath:evaluate-compiled (key-use key) node)))
924 (if (xpath:node-set-p uses)
925 (xpath::find-in-pipe
926 value
927 (xpath-sys:pipe-of uses)
928 :key #'xpath:string-value
929 :test #'equal)
930 (equal value (xpath:string-value uses)))))
931 (xpath-sys:pipe-of
932 (xpath:node-set-value
933 (xpath:evaluate-compiled (key-match key) ctx)))))))
934 (xpath-sys:make-node-set
935 (xpath::sort-pipe
936 (if (xpath:node-set-p object)
937 (xpath::mappend-pipe #'get-by-key (xpath-sys:pipe-of object))
938 (get-by-key object)))))))))
940 ;; FIXME: add alias mechanism for XPath extensions in order to avoid duplication
942 (xpath-sys:define-xpath-function/lazy xslt :current ()
943 #'(lambda (ctx)
944 (xpath-sys:make-node-set
945 (xpath-sys:make-pipe
946 (xpath:context-starting-node ctx)
947 nil))))
949 (xpath-sys:define-xpath-function/lazy xslt :unparsed-entity-uri (name)
950 #'(lambda (ctx)
951 (or (xpath-protocol:unparsed-entity-uri (xpath:context-node ctx)
952 (funcall name ctx))
953 "")))
955 (defun %get-node-id (node)
956 (when (xpath:node-set-p node)
957 (setf node (xpath::textually-first-node node)))
958 (when node
959 (let ((id (xpath-sys:get-node-id node))
960 (highest-base-uri
961 (loop
962 for parent = node then next
963 for next = (xpath-protocol:parent-node parent)
964 for this-base-uri = (xpath-protocol:base-uri parent)
965 for highest-base-uri = (if (plusp (length this-base-uri))
966 this-base-uri
967 highest-base-uri)
968 while next
969 finally (return highest-base-uri))))
970 ;; Heuristic: Reverse it so that the /home/david/alwaysthesame prefix is
971 ;; checked only if everything else matches.
973 ;; This might be pointless premature optimization, but I like the idea :-)
974 (nreverse (concatenate 'string highest-base-uri "//" id)))))
976 (xpath-sys:define-xpath-function/lazy xslt :generate-id (&optional node-set-thunk)
977 (if node-set-thunk
978 #'(lambda (ctx)
979 (%get-node-id (xpath:node-set-value (funcall node-set-thunk ctx))))
980 #'(lambda (ctx)
981 (%get-node-id (xpath:context-node ctx)))))
983 (declaim (special *available-instructions*))
985 (xpath-sys:define-xpath-function/lazy xslt :element-available (qname)
986 (let ((namespaces *namespaces*))
987 #'(lambda (ctx)
988 (let ((qname (funcall qname ctx)))
989 (multiple-value-bind (local-name uri)
990 (decode-qname/runtime qname namespaces nil)
991 (and (equal uri *xsl*)
992 (gethash local-name *available-instructions*)
993 t))))))
995 (xpath-sys:define-xpath-function/lazy xslt :function-available (qname)
996 (let ((namespaces *namespaces*))
997 #'(lambda (ctx)
998 (let ((qname (funcall qname ctx)))
999 (multiple-value-bind (local-name uri)
1000 (decode-qname/runtime qname namespaces nil)
1001 (and (zerop (length uri))
1002 (or (xpath-sys:find-xpath-function local-name *xsl*)
1003 (xpath-sys:find-xpath-function local-name uri))
1004 t))))))
1006 (defun apply-stylesheet
1007 (stylesheet source-designator
1008 &key output parameters uri-resolver navigator)
1009 (when (typep stylesheet 'xml-designator)
1010 (setf stylesheet (parse-stylesheet stylesheet)))
1011 (invoke-with-output-sink
1012 (lambda ()
1013 (handler-case*
1014 (let* ((*documents* (make-hash-table :test 'equal))
1015 (xpath:*navigator* (or navigator :default-navigator))
1016 (puri:*strict-parse* nil)
1017 (*stylesheet* stylesheet)
1018 (*empty-mode* (make-mode))
1019 (*default-mode* (find-mode stylesheet nil))
1020 (global-variable-specs
1021 (stylesheet-global-variables stylesheet))
1022 (*global-variable-values*
1023 (make-variable-value-array (length global-variable-specs)))
1024 (*uri-resolver* uri-resolver)
1025 (source-document
1026 (if (typep source-designator 'xml-designator)
1027 (cxml:parse source-designator (stp:make-builder))
1028 source-designator))
1029 (xpath-root-node
1030 (make-whitespace-stripper
1031 source-document
1032 (stylesheet-strip-tests stylesheet)))
1033 (ctx (xpath:make-context xpath-root-node)))
1034 (when (pathnamep source-designator)
1035 (setf (gethash source-designator *documents*) xpath-root-node))
1036 (map nil
1037 (lambda (spec)
1038 (when (variable-param-p spec)
1039 (let ((value
1040 (find-parameter-value (variable-local-name spec)
1041 (variable-uri spec)
1042 parameters)))
1043 (when value
1044 (setf (global-variable-value (variable-index spec))
1045 value)))))
1046 global-variable-specs)
1047 (map nil
1048 (lambda (spec)
1049 (funcall (variable-thunk spec) ctx))
1050 global-variable-specs)
1051 ;; zzz we wouldn't have to mask float traps here if we used the
1052 ;; XPath API properly. Unfortunately I've been using FUNCALL
1053 ;; everywhere instead of EVALUATE, so let's paper over that
1054 ;; at a central place to be sure:
1055 (xpath::with-float-traps-masked ()
1056 (apply-templates ctx :mode *default-mode*)))
1057 (xpath:xpath-error (c)
1058 (xslt-error "~A" c))))
1059 (stylesheet-output-specification stylesheet)
1060 output))
1062 (defun find-attribute-set (local-name uri)
1063 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
1064 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
1066 (defun apply-templates/list (list &key param-bindings sort-predicate mode)
1067 (when sort-predicate
1068 (setf list (sort list sort-predicate)))
1069 (let* ((n (length list))
1070 (s/d (lambda () n)))
1071 (loop
1072 for i from 1
1073 for child in list
1075 (apply-templates (xpath:make-context child s/d i)
1076 :param-bindings param-bindings
1077 :mode mode))))
1079 (defvar *stack-limit* 200)
1081 (defun invoke-with-stack-limit (fn)
1082 (let ((*stack-limit* (1- *stack-limit*)))
1083 (unless (plusp *stack-limit*)
1084 (xslt-error "*stack-limit* reached; stack overflow"))
1085 (funcall fn)))
1087 (defun invoke-template (ctx template param-bindings)
1088 (let ((*lexical-variable-values*
1089 (make-variable-value-array (template-n-variables template))))
1090 (with-stack-limit ()
1091 (loop
1092 for (name-cons value) in param-bindings
1093 for (nil index nil) = (find name-cons
1094 (template-params template)
1095 :test #'equal
1096 :key #'car)
1098 (when index
1099 (setf (lexical-variable-value index) value)))
1100 (funcall (template-body template) ctx))))
1102 (defun apply-default-templates (ctx mode)
1103 (let ((node (xpath:context-node ctx)))
1104 (cond
1105 ((or (xpath-protocol:node-type-p node :processing-instruction)
1106 (xpath-protocol:node-type-p node :comment)))
1107 ((or (xpath-protocol:node-type-p node :text)
1108 (xpath-protocol:node-type-p node :attribute))
1109 (write-text (xpath-protocol:node-text node)))
1111 (apply-templates/list
1112 (xpath::force
1113 (xpath-protocol:child-pipe node))
1114 :mode mode)))))
1116 (defvar *apply-imports*)
1118 (defun apply-applicable-templates (ctx templates param-bindings finally)
1119 (labels ((apply-imports (&optional actual-param-bindings)
1120 (if templates
1121 (let* ((this (pop templates))
1122 (low (template-apply-imports-limit this))
1123 (high (template-import-priority this)))
1124 (setf templates
1125 (remove-if-not
1126 (lambda (x)
1127 (<= low (template-import-priority x) high))
1128 templates))
1129 (invoke-template ctx this actual-param-bindings))
1130 (funcall finally))))
1131 (let ((*apply-imports* #'apply-imports))
1132 (apply-imports param-bindings))))
1134 (defun apply-templates (ctx &key param-bindings mode)
1135 (apply-applicable-templates ctx
1136 (find-templates ctx (or mode *default-mode*))
1137 param-bindings
1138 (lambda ()
1139 (apply-default-templates ctx mode))))
1141 (defun call-template (ctx name &optional param-bindings)
1142 (apply-applicable-templates ctx
1143 (find-named-templates name)
1144 param-bindings
1145 (lambda ()
1146 (error "cannot find named template: ~s"
1147 name))))
1149 (defun find-templates (ctx mode)
1150 (let* ((matching-candidates
1151 (remove-if-not (lambda (template)
1152 (template-matches-p template ctx))
1153 (mode-templates mode)))
1154 (npriorities
1155 (if matching-candidates
1156 (1+ (reduce #'max
1157 matching-candidates
1158 :key #'template-import-priority))
1160 (priority-groups (make-array npriorities :initial-element nil)))
1161 (dolist (template matching-candidates)
1162 (push template
1163 (elt priority-groups (template-import-priority template))))
1164 (loop
1165 for i from (1- npriorities) downto 0
1166 for group = (elt priority-groups i)
1167 for template = (maximize #'template< group)
1168 when template
1169 collect template)))
1171 (defun find-named-templates (name)
1172 (gethash name (stylesheet-named-templates *stylesheet*)))
1174 (defun template< (a b) ;assuming same import priority
1175 (let ((p (template-priority a))
1176 (q (template-priority b)))
1177 (cond
1178 ((< p q) t)
1179 ((> p q) nil)
1181 (xslt-cerror "conflicting templates:~_~A,~_~A"
1182 (template-match-expression a)
1183 (template-match-expression b))
1184 (< (template-position a) (template-position b))))))
1186 (defun maximize (< things)
1187 (when things
1188 (let ((max (car things)))
1189 (dolist (other (cdr things))
1190 (when (funcall < max other)
1191 (setf max other)))
1192 max)))
1194 (defun template-matches-p (template ctx)
1195 (find (xpath:context-node ctx)
1196 (xpath:all-nodes (funcall (template-match-thunk template) ctx))))
1198 (defun invoke-with-output-sink (fn output-spec output)
1199 (etypecase output
1200 (pathname
1201 (with-open-file (s output
1202 :direction :output
1203 :element-type '(unsigned-byte 8)
1204 :if-exists :rename-and-delete)
1205 (invoke-with-output-sink fn output-spec s)))
1206 ((or stream null)
1207 (invoke-with-output-sink fn
1208 output-spec
1209 (make-output-sink output-spec output)))
1210 ((or hax:abstract-handler sax:abstract-handler)
1211 (with-xml-output output
1212 (funcall fn)))))
1214 (defun make-output-sink (output-spec stream)
1215 (let* ((ystream
1216 (if stream
1217 (let ((et (stream-element-type stream)))
1218 (cond
1219 ((or (null et) (subtypep et '(unsigned-byte 8)))
1220 (runes:make-octet-stream-ystream stream))
1221 ((subtypep et 'character)
1222 (runes:make-character-stream-ystream stream))))
1223 (runes:make-rod-ystream)))
1224 (omit-xml-declaration-p
1225 (equal (output-omit-xml-declaration output-spec) "yes"))
1226 (sax-target
1227 (make-instance 'cxml::sink
1228 :ystream ystream
1229 :omit-xml-declaration-p omit-xml-declaration-p)))
1230 (cond
1231 ((equalp (output-method output-spec) "HTML")
1232 (make-instance 'combi-sink
1233 :hax-target (make-instance 'chtml::sink
1234 :ystream ystream)
1235 :sax-target sax-target
1236 :encoding (output-encoding output-spec)))
1237 ((equalp (output-method output-spec) "TEXT")
1238 (make-text-filter sax-target))
1240 sax-target))))
1242 (defstruct template
1243 match-expression
1244 match-thunk
1245 name
1246 import-priority
1247 apply-imports-limit
1248 priority
1249 position
1250 mode
1251 mode-qname
1252 params
1253 body
1254 n-variables)
1256 (defun expression-priority (form)
1257 (let ((step (second form)))
1258 (if (and (null (cddr form))
1259 (listp step)
1260 (member (car step) '(:child :attribute))
1261 (null (cddr step)))
1262 (let ((name (second step)))
1263 (cond
1264 ((or (stringp name)
1265 (and (consp name)
1266 (or (eq (car name) :qname)
1267 (eq (car name) :processing-instruction))))
1268 0.0)
1269 ((and (consp name)
1270 (or (eq (car name) :namespace)
1271 (eq (car name) '*)))
1272 -0.25)
1274 -0.5)))
1275 0.5)))
1277 (defun valid-expression-p (expr)
1278 (cond
1279 ((atom expr) t)
1280 ((eq (first expr) :path)
1281 (every (lambda (x)
1282 (let ((filter (third x)))
1283 (or (null filter) (valid-expression-p filter))))
1284 (cdr expr)))
1285 ((eq (first expr) :variable) ;(!)
1286 nil)
1288 (every #'valid-expression-p (cdr expr)))))
1290 (defun parse-xpath (str)
1291 (handler-case
1292 (xpath:parse-xpath str)
1293 (xpath:xpath-error (c)
1294 (xslt-error "~A" c))))
1296 ;; zzz also use naive-pattern-expression here?
1297 (defun parse-key-pattern (str)
1298 (let ((parsed
1299 (mapcar #'(lambda (item)
1300 `(:path (:root :node)
1301 (:descendant-or-self *)
1302 ,@(cdr item)))
1303 (parse-pattern str))))
1304 (if (null (rest parsed))
1305 (first parsed)
1306 `(:union ,@parsed))))
1308 (defun parse-pattern (str)
1309 ;; zzz check here for anything not allowed as an XSLT pattern
1310 ;; zzz can we hack id() and key() here?
1311 (let ((form (parse-xpath str)))
1312 (unless (consp form)
1313 (xslt-error "not a valid pattern: ~A" str))
1314 (labels ((process-form (form)
1315 (cond ((eq (car form) :union)
1316 (alexandria:mappend #'process-form (rest form)))
1317 ((not (or (eq (car form) :path)
1318 (and (eq (car form) :filter)
1319 (let ((filter (second form)))
1320 (and (consp filter)
1321 (member (car filter)
1322 '(:key :id))))
1323 (equal (third form) '(:true)))
1324 (member (car form) '(:key :id))))
1325 (xslt-error "not a valid pattern: ~A ~A" str form))
1326 ((not (valid-expression-p form))
1327 (xslt-error "invalid filter"))
1328 (t (list form)))))
1329 (process-form form))))
1331 (defun naive-pattern-expression (x)
1332 (ecase (car x)
1333 (:path `(:path (:ancestor-or-self :node) ,@(cdr x)))
1334 ((:filter :key :id) x)))
1336 (defun compile-value-thunk (value env)
1337 (if (and (listp value) (eq (car value) 'progn))
1338 (let ((inner-thunk (compile-instruction value env)))
1339 (lambda (ctx)
1340 (apply-to-result-tree-fragment ctx inner-thunk)))
1341 (compile-xpath value env)))
1343 (defun compile-var-bindings/nointern (forms env)
1344 (loop
1345 for (name value) in forms
1346 collect (multiple-value-bind (local-name uri)
1347 (decode-qname name env nil)
1348 (list (cons local-name uri)
1349 (xslt-trace-thunk
1350 (compile-value-thunk value env)
1351 "local variable ~s = ~s" name :result)))))
1353 (defun compile-var-bindings (forms env)
1354 (loop
1355 for (cons thunk) in (compile-var-bindings/nointern forms env)
1356 for (local-name . uri) = cons
1357 collect (list cons
1358 (push-variable local-name
1360 *lexical-variable-declarations*)
1361 thunk)))
1363 (defun compile-template (<template> env position)
1364 (stp:with-attributes (match name priority mode) <template>
1365 (unless (or name match)
1366 (xslt-error "missing match in template"))
1367 (multiple-value-bind (params body-pos)
1368 (loop
1369 for i from 0
1370 for child in (stp:list-children <template>)
1371 while (namep child "param")
1372 collect (parse-param child) into params
1373 finally (return (values params i)))
1374 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1375 (param-bindings (compile-var-bindings params env))
1376 (body (parse-body <template> body-pos (mapcar #'car params)))
1377 (body-thunk (compile-instruction `(progn ,@body) env))
1378 (outer-body-thunk
1379 (xslt-trace-thunk
1380 #'(lambda (ctx)
1381 (unwind-protect
1382 (progn
1383 ;; set params that weren't initialized by apply-templates
1384 (loop for (name index param-thunk) in param-bindings
1385 when (eq (lexical-variable-value index nil) 'unbound)
1386 do (setf (lexical-variable-value index)
1387 (funcall param-thunk ctx)))
1388 (funcall body-thunk ctx))))
1389 "template: match = ~s name = ~s" match name))
1390 (n-variables (length *lexical-variable-declarations*)))
1391 (append
1392 (when name
1393 (multiple-value-bind (local-name uri)
1394 (decode-qname name env nil)
1395 (list
1396 (make-template :name (cons local-name uri)
1397 :import-priority *import-priority*
1398 :apply-imports-limit *apply-imports-limit*
1399 :params param-bindings
1400 :body outer-body-thunk
1401 :n-variables n-variables))))
1402 (when match
1403 (mapcar (lambda (expression)
1404 (let ((match-thunk
1405 (xslt-trace-thunk
1406 (compile-xpath
1407 `(xpath:xpath
1408 ,(naive-pattern-expression expression))
1409 env)
1410 "match-thunk for template (match ~s): ~s --> ~s"
1411 match expression :result))
1412 (p (if priority
1413 (parse-number:parse-number priority)
1414 (expression-priority expression))))
1415 (make-template :match-expression expression
1416 :match-thunk match-thunk
1417 :import-priority *import-priority*
1418 :apply-imports-limit *apply-imports-limit*
1419 :priority p
1420 :position position
1421 :mode-qname mode
1422 :params param-bindings
1423 :body outer-body-thunk
1424 :n-variables n-variables)))
1425 (parse-pattern match))))))))
1426 #+(or)
1427 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")