Some parts of xsl:number (unfinished)
[xuriella.git] / xslt.lisp
blob256d550b600b29d960354c2ea3fa16fad208ae2c
1 ;;; -*- show-trailing-whitespace: t; indent-tabs: 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 ;;;; XSLT-ERROR
38 (define-condition xslt-error (simple-error)
40 (:documentation "The class of all XSLT errors."))
42 (define-condition recoverable-xslt-error (xslt-error)
44 (:documentation "The class of recoverable XSLT errors."))
46 (defun xslt-error (fmt &rest args)
47 (error 'xslt-error :format-control fmt :format-arguments args))
49 (defun xslt-cerror (fmt &rest args)
50 (with-simple-restart (recover "recover")
51 (error 'recoverable-xslt-error
52 :format-control fmt
53 :format-arguments args)))
55 (defvar *debug* nil)
57 (defmacro handler-case* (form &rest clauses)
58 ;; like HANDLER-CASE if *DEBUG* is off. If it's on, don't establish
59 ;; a handler at all so that we see the real stack traces. (We could use
60 ;; HANDLER-BIND here and check at signalling time, but doesn't seem
61 ;; important.)
62 (let ((doit (gensym)))
63 `(flet ((,doit () ,form))
64 (if *debug*
65 (,doit)
66 (handler-case
67 (,doit)
68 ,@clauses)))))
70 (defun compile-xpath (xpath &optional env)
71 (handler-case*
72 (xpath:compile-xpath xpath env)
73 (xpath:xpath-error (c)
74 (xslt-error "~A" c))))
76 (defmacro with-stack-limit ((&optional) &body body)
77 `(invoke-with-stack-limit (lambda () ,@body)))
80 ;;;; Helper function and macro
82 (defun map-pipe-eagerly (fn pipe)
83 (xpath::enumerate pipe :key fn :result nil))
85 (defmacro do-pipe ((var pipe &optional result) &body body)
86 `(block nil
87 (map-pipe-eagerly #'(lambda (,var) ,@body) ,pipe)
88 ,result))
91 ;;;; XSLT-ENVIRONMENT and XSLT-CONTEXT
93 (defparameter *initial-namespaces*
94 '((nil . "")
95 ("xmlns" . #"http://www.w3.org/2000/xmlns/")
96 ("xml" . #"http://www.w3.org/XML/1998/namespace")))
98 (defparameter *namespaces* *initial-namespaces*)
100 (defvar *global-variable-declarations*)
101 (defvar *lexical-variable-declarations*)
103 (defvar *global-variable-values*)
104 (defvar *lexical-variable-values*)
106 (defclass xslt-environment () ())
108 (defun split-qname (str)
109 (handler-case
110 (multiple-value-bind (prefix local-name)
111 (cxml::split-qname str)
112 (unless
113 ;; FIXME: cxml should really offer a function that does
114 ;; checks for NCName and QName in a sensible way for user code.
115 ;; cxml::split-qname is tailored to the needs of the parser.
117 ;; For now, let's just check the syntax explicitly.
118 (and (or (null prefix) (xpath::nc-name-p prefix))
119 (xpath::nc-name-p local-name))
120 (xslt-error "not a qname: ~A" str))
121 (values prefix local-name))
122 (cxml:well-formedness-violation ()
123 (xslt-error "not a qname: ~A" str))))
125 (defun decode-qname (qname env attributep)
126 (multiple-value-bind (prefix local-name)
127 (split-qname qname)
128 (values local-name
129 (if (or prefix (not attributep))
130 (xpath:environment-find-namespace env prefix)
132 prefix)))
134 (defmethod xpath:environment-find-namespace ((env xslt-environment) prefix)
135 (cdr (assoc prefix *namespaces* :test 'equal)))
137 (defun find-variable-index (local-name uri table)
138 (position (cons local-name uri) table :test 'equal))
140 (defun intern-global-variable (local-name uri)
141 (or (find-variable-index local-name uri *global-variable-declarations*)
142 (push-variable local-name uri *global-variable-declarations*)))
144 (defun push-variable (local-name uri table)
145 (prog1
146 (length table)
147 (vector-push-extend (cons local-name uri) table)))
149 (defun lexical-variable-value (index &optional (errorp t))
150 (let ((result (svref *lexical-variable-values* index)))
151 (when errorp
152 (assert (not (eq result 'unbound))))
153 result))
155 (defun (setf lexical-variable-value) (newval index)
156 (assert (not (eq newval 'unbound)))
157 (setf (svref *lexical-variable-values* index) newval))
159 (defun global-variable-value (index &optional (errorp t))
160 (let ((result (svref *global-variable-values* index)))
161 (when errorp
162 (assert (not (eq result 'unbound))))
163 result))
165 (defun (setf global-variable-value) (newval index)
166 (assert (not (eq newval 'unbound)))
167 (setf (svref *global-variable-values* index) newval))
169 (defmethod xpath:environment-find-function
170 ((env xslt-environment) lname uri)
171 (if (string= uri "")
172 (or (xpath:find-xpath-function lname *xsl*)
173 (xpath:find-xpath-function lname uri))
174 (xpath:find-xpath-function lname uri)))
176 (defmethod xpath:environment-find-variable
177 ((env xslt-environment) lname uri)
178 (let ((index
179 (find-variable-index lname uri *lexical-variable-declarations*)))
180 (when index
181 (lambda (ctx)
182 (declare (ignore ctx))
183 (svref *lexical-variable-values* index)))))
185 (defclass lexical-xslt-environment (xslt-environment) ())
187 (defmethod xpath:environment-find-variable
188 ((env lexical-xslt-environment) lname uri)
189 (or (call-next-method)
190 (let ((index
191 (find-variable-index lname uri *global-variable-declarations*)))
192 (when index
193 (xslt-trace-thunk
194 (lambda (ctx)
195 (declare (ignore ctx))
196 (svref *global-variable-values* index))
197 "global ~s (uri ~s) = ~s" lname uri :result)))))
199 (defclass global-variable-environment (xslt-environment)
200 ((initial-global-variable-thunks
201 :initarg :initial-global-variable-thunks
202 :accessor initial-global-variable-thunks)))
204 (defmethod xpath:environment-find-variable
205 ((env global-variable-environment) lname uri)
206 (or (call-next-method)
207 (gethash (cons lname uri) (initial-global-variable-thunks env))))
210 ;;;; TEXT-OUTPUT-SINK
211 ;;;;
212 ;;;; A sink that serializes only text and will error out on any other
213 ;;;; SAX event.
215 (defmacro with-text-output-sink ((var) &body body)
216 `(invoke-with-text-output-sink (lambda (,var) ,@body)))
218 (defclass text-output-sink (sax:default-handler)
219 ((target :initarg :target :accessor text-output-sink-target)))
221 (defmethod sax:characters ((sink text-output-sink) data)
222 (write-string data (text-output-sink-target sink)))
224 (defun invoke-with-text-output-sink (fn)
225 (with-output-to-string (s)
226 (funcall fn (make-instance 'text-output-sink :target s))))
229 ;;;; Names
231 (eval-when (:compile-toplevel :load-toplevel :execute)
232 (defvar *xsl* "http://www.w3.org/1999/XSL/Transform")
233 (defvar *xml* "http://www.w3.org/XML/1998/namespace")
234 (defvar *html* "http://www.w3.org/1999/xhtml"))
236 (defun of-name (local-name)
237 (stp:of-name local-name *xsl*))
239 (defun namep (node local-name)
240 (and (typep node '(or stp:element stp:attribute))
241 (equal (stp:namespace-uri node) *xsl*)
242 (equal (stp:local-name node) local-name)))
245 ;;;; PARSE-STYLESHEET
247 (defstruct stylesheet
248 (modes (make-hash-table :test 'equal))
249 (global-variables ())
250 (output-specification (make-output-specification))
251 (strip-tests nil)
252 (named-templates (make-hash-table :test 'equal))
253 (attribute-sets (make-hash-table :test 'equal)))
255 (defstruct mode (templates nil))
257 (defun find-mode (stylesheet local-name &optional uri)
258 (gethash (cons local-name uri) (stylesheet-modes stylesheet)))
260 (defun ensure-mode (stylesheet &optional local-name uri)
261 (or (find-mode stylesheet local-name uri)
262 (setf (gethash (cons local-name uri) (stylesheet-modes stylesheet))
263 (make-mode))))
265 (defun ensure-mode/qname (stylesheet qname env)
266 (if qname
267 (multiple-value-bind (local-name uri)
268 (decode-qname qname env nil)
269 (ensure-mode stylesheet local-name uri))
270 (find-mode stylesheet nil)))
272 (defun acons-namespaces (element &optional (bindings *namespaces*))
273 (map-namespace-declarations (lambda (prefix uri)
274 (push (cons prefix uri) bindings))
275 element)
276 bindings)
278 (defvar *excluded-namespaces* (list *xsl*))
279 (defvar *empty-mode*)
281 (defvar *xsl-include-stack* nil)
283 (defun uri-to-pathname (uri)
284 (cxml::uri-to-pathname (puri:parse-uri uri)))
286 (defun parse-stylesheet-to-stp (input uri-resolver)
287 (let* ((d (cxml:parse input (make-text-normalizer (cxml-stp:make-builder))))
288 (<transform> (stp:document-element d)))
289 (strip-stylesheet <transform>)
290 ;; FIXME: handle embedded stylesheets
291 (unless (and (equal (stp:namespace-uri <transform>) *xsl*)
292 (or (equal (stp:local-name <transform>) "transform")
293 (equal (stp:local-name <transform>) "stylesheet")))
294 (xslt-error "not a stylesheet"))
295 (dolist (include (stp:filter-children (of-name "include") <transform>))
296 (let* ((uri (puri:merge-uris (stp:attribute-value include "href")
297 (stp:base-uri include)))
298 (uri (if uri-resolver
299 (funcall uri-resolver (puri:render-uri uri nil))
300 uri))
301 (str (puri:render-uri uri nil))
302 (pathname
303 (handler-case
304 (uri-to-pathname uri)
305 (cxml:xml-parse-error (c)
306 (xslt-error "cannot find included stylesheet ~A: ~A"
307 uri c)))))
308 (with-open-file
309 (stream pathname
310 :element-type '(unsigned-byte 8)
311 :if-does-not-exist nil)
312 (unless stream
313 (xslt-error "cannot find included stylesheet ~A at ~A"
314 uri pathname))
315 (when (find str *xsl-include-stack* :test #'equal)
316 (xslt-error "recursive inclusion of ~A" uri))
317 (let* ((*xsl-include-stack* (cons str *xsl-include-stack*))
318 (<transform>2 (parse-stylesheet-to-stp stream uri-resolver)))
319 (stp:do-children (child <transform>2)
320 (stp:insert-child-after <transform>
321 (stp:copy child)
322 include))
323 (stp:detach include)))))
324 <transform>))
326 (defvar *instruction-base-uri*)
327 (defvar *apply-imports-limit*)
328 (defvar *import-priority*)
330 (defun parse-1-stylesheet (env stylesheet designator uri-resolver)
331 (let* ((<transform> (parse-stylesheet-to-stp designator uri-resolver))
332 (*instruction-base-uri* (stp:base-uri <transform>))
333 (*namespaces* (acons-namespaces <transform>))
334 (*apply-imports-limit* (1+ *import-priority*)))
335 (dolist (import (stp:filter-children (of-name "import") <transform>))
336 (let ((uri (puri:merge-uris (stp:attribute-value import "href")
337 (stp:base-uri import))))
338 (parse-imported-stylesheet env stylesheet uri uri-resolver)))
339 (incf *import-priority*)
340 (parse-exclude-result-prefixes! <transform> env)
341 (parse-global-variables! stylesheet <transform>)
342 (parse-templates! stylesheet <transform> env)
343 (parse-output! stylesheet <transform>)
344 (parse-strip/preserve-space! stylesheet <transform> env)
345 (parse-attribute-sets! stylesheet <transform> env)))
347 (defvar *xsl-import-stack* nil)
349 (defun parse-imported-stylesheet (env stylesheet uri uri-resolver)
350 (let* ((uri (if uri-resolver
351 (funcall uri-resolver (puri:render-uri uri nil))
352 uri))
353 (str (puri:render-uri uri nil))
354 (pathname
355 (handler-case
356 (uri-to-pathname uri)
357 (cxml:xml-parse-error (c)
358 (xslt-error "cannot find imported stylesheet ~A: ~A"
359 uri c)))))
360 (with-open-file
361 (stream pathname
362 :element-type '(unsigned-byte 8)
363 :if-does-not-exist nil)
364 (unless stream
365 (xslt-error "cannot find imported stylesheet ~A at ~A"
366 uri pathname))
367 (when (find str *xsl-import-stack* :test #'equal)
368 (xslt-error "recursive inclusion of ~A" uri))
369 (let ((*xsl-import-stack* (cons str *xsl-import-stack*)))
370 (parse-1-stylesheet env stylesheet stream uri-resolver)))))
372 (defun parse-stylesheet (designator &key uri-resolver)
373 (let* ((*import-priority* 0)
374 (puri:*strict-parse* nil)
375 (stylesheet (make-stylesheet))
376 (env (make-instance 'lexical-xslt-environment))
377 (*excluded-namespaces* *excluded-namespaces*)
378 (*global-variable-declarations* (make-empty-declaration-array)))
379 (ensure-mode stylesheet nil)
380 (parse-1-stylesheet env stylesheet designator uri-resolver)
381 ;; reverse attribute sets:
382 (let ((table (stylesheet-attribute-sets stylesheet)))
383 (maphash (lambda (k v)
384 (setf (gethash k table) (nreverse v)))
385 table))
386 stylesheet))
388 (defun parse-attribute-sets! (stylesheet <transform> env)
389 (dolist (elt (stp:filter-children (of-name "attribute-set") <transform>))
390 (push (let* ((sets
391 (mapcar (lambda (qname)
392 (multiple-value-list (decode-qname qname env nil)))
393 (words
394 (stp:attribute-value elt "use-attribute-sets"))))
395 (instructions
396 (stp:map-children 'list #'parse-instruction elt))
397 (*lexical-variable-declarations*
398 (make-empty-declaration-array))
399 (thunk
400 (compile-instruction `(progn ,@instructions) env))
401 (n-variables (length *lexical-variable-declarations*)))
402 (lambda (ctx)
403 (with-stack-limit ()
404 (loop for (local-name uri nil) in sets do
405 (dolist (thunk (find-attribute-set local-name uri))
406 (funcall thunk ctx)))
407 (let ((*lexical-variable-values*
408 (make-variable-value-array n-variables)))
409 (funcall thunk ctx)))))
410 (gethash (multiple-value-bind (local-name uri)
411 (decode-qname (stp:attribute-value elt "name") env nil)
412 (cons local-name uri))
413 (stylesheet-attribute-sets stylesheet)))))
415 (defun parse-exclude-result-prefixes! (<transform> env)
416 (stp:with-attributes (exclude-result-prefixes) <transform>
417 (dolist (prefix (words (or exclude-result-prefixes "")))
418 (when (equal prefix "#default")
419 (setf prefix nil))
420 (push (or (xpath:environment-find-namespace env prefix)
421 (xslt-error "namespace not found: ~A" prefix))
422 *excluded-namespaces*))))
424 (defun parse-strip/preserve-space! (stylesheet <transform> env)
425 (xpath:with-namespaces ((nil #.*xsl*))
426 (dolist (elt (stp:filter-children (lambda (x)
427 (or (namep x "strip-space")
428 (namep x "preserve-space")))
429 <transform>))
430 (let ((*namespaces* (acons-namespaces elt))
431 (mode
432 (if (equal (stp:local-name elt) "strip-space")
433 :strip
434 :preserve)))
435 (dolist (name-test (words (stp:attribute-value elt "elements")))
436 (let* ((pos (search ":*" name-test))
437 (test-function
438 (cond
439 ((eql pos (- (length name-test) 2))
440 (let* ((prefix (subseq name-test 0 pos))
441 (name-test-uri
442 (xpath:environment-find-namespace env prefix)))
443 (unless (xpath::nc-name-p prefix)
444 (xslt-error "not an NCName: ~A" prefix))
445 (lambda (local-name uri)
446 (declare (ignore local-name))
447 (if (equal uri name-test-uri)
448 mode
449 nil))))
450 ((equal name-test "*")
451 (lambda (local-name uri)
452 (declare (ignore local-name uri))
453 mode))
455 (multiple-value-bind (name-test-local-name name-test-uri)
456 (decode-qname name-test env nil)
457 (lambda (local-name uri)
458 (if (and (equal local-name name-test-local-name)
459 (equal uri name-test-uri))
460 mode
461 nil)))))))
462 (push test-function (stylesheet-strip-tests stylesheet))))))))
464 (defstruct (output-specification
465 (:conc-name "OUTPUT-"))
466 method
467 indent
468 omit-xml-declaration
469 encoding)
471 (defun parse-output! (stylesheet <transform>)
472 (let ((outputs (stp:filter-children (of-name "output") <transform>)))
473 (when outputs
474 (when (cdr outputs)
475 ;; FIXME:
476 ;; - concatenate cdata-section-elements
477 ;; - the others must not conflict
478 (error "oops, merging of output elements not supported yet"))
479 (let ((<output> (car outputs))
480 (spec (stylesheet-output-specification stylesheet)))
481 (stp:with-attributes (;; version
482 method
483 indent
484 encoding
485 ;;; media-type
486 ;;; doctype-system
487 ;;; doctype-public
488 omit-xml-declaration
489 ;;; standalone
490 ;;; cdata-section-elements
492 <output>
493 (setf (output-method spec) method)
494 (setf (output-indent spec) indent)
495 (setf (output-encoding spec) encoding)
496 (setf (output-omit-xml-declaration spec) omit-xml-declaration))))))
498 (defun make-empty-declaration-array ()
499 (make-array 1 :fill-pointer 0 :adjustable t))
501 (defun make-variable-value-array (n-lexical-variables)
502 (make-array n-lexical-variables :initial-element 'unbound))
504 (defun compile-global-variable (<variable> env) ;; also for <param>
505 (stp:with-attributes (name select) <variable>
506 (when (and select (stp:list-children <variable>))
507 (xslt-error "variable with select and body"))
508 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
509 (inner (cond
510 (select
511 (compile-xpath select env))
512 ((stp:list-children <variable>)
513 (let* ((inner-sexpr `(progn ,@(parse-body <variable>)))
514 (inner-thunk (compile-instruction inner-sexpr env)))
515 (lambda (ctx)
516 (apply-to-result-tree-fragment ctx inner-thunk))))
518 (lambda (ctx)
519 (declare (ignore ctx))
520 ""))))
521 (n-lexical-variables (length *lexical-variable-declarations*)))
522 (xslt-trace-thunk
523 (lambda (ctx)
524 (let* ((*lexical-variable-values*
525 (make-variable-value-array n-lexical-variables)))
526 (funcall inner ctx)))
527 "global ~s (~s) = ~s" name select :result))))
529 (defstruct (variable-information
530 (:constructor make-variable)
531 (:conc-name "VARIABLE-"))
532 index
533 thunk
534 local-name
536 param-p
537 thunk-setter)
539 (defun parse-global-variable! (<variable> global-env) ;; also for <param>
540 (let ((*namespaces* (acons-namespaces <variable>))
541 (qname (stp:attribute-value <variable> "name")))
542 (unless qname
543 (xslt-error "name missing in ~A" (stp:local-name <variable>)))
544 (multiple-value-bind (local-name uri)
545 (decode-qname qname global-env nil)
546 ;; For the normal compilation environment of templates, install it
547 ;; into *GLOBAL-VARIABLE-DECLARATIONS*:
548 (let ((index (intern-global-variable local-name uri)))
549 ;; For the evaluation of a global variable itself, build a thunk
550 ;; that lazily resolves other variables, stored into
551 ;; INITIAL-GLOBAL-VARIABLE-THUNKS:
552 (let* ((value-thunk :unknown)
553 (global-variable-thunk
554 (lambda (ctx)
555 (let ((v (global-variable-value index nil)))
556 (when (eq v 'seen)
557 (xslt-error "recursive variable definition"))
558 (cond
559 ((eq v 'unbound)
560 ;; (print (list :computing index))
561 (setf (global-variable-value index) 'seen)
562 (setf (global-variable-value index)
563 (funcall value-thunk ctx))
564 #+nil (print (list :done-computing index
565 (global-variable-value index)))
566 #+nil (global-variable-value index))
568 #+nil(print (list :have
569 index v))
570 v)))))
571 (thunk-setter
572 (lambda ()
573 (setf value-thunk
574 (compile-global-variable <variable> global-env)))))
575 (setf (gethash (cons local-name uri)
576 (initial-global-variable-thunks global-env))
577 global-variable-thunk)
578 (make-variable :index index
579 :local-name local-name
580 :uri uri
581 :thunk global-variable-thunk
582 :param-p (namep <variable> "param")
583 :thunk-setter thunk-setter))))))
585 (defun parse-global-variables! (stylesheet <transform>)
586 (xpath:with-namespaces ((nil #.*xsl*))
587 (let* ((table (make-hash-table :test 'equal))
588 (global-env (make-instance 'global-variable-environment
589 :initial-global-variable-thunks table))
590 (specs '()))
591 (xpath:do-node-set
592 (<variable> (xpath:evaluate "variable|param" <transform>))
593 (let ((var (parse-global-variable! <variable> global-env)))
594 (xslt-trace "parsing global variable ~s (uri ~s)"
595 (variable-local-name var)
596 (variable-uri var))
597 (when (find var
598 specs
599 :test (lambda (a b)
600 (and (equal (variable-local-name a)
601 (variable-local-name b))
602 (equal (variable-uri a)
603 (variable-uri b)))))
604 (xslt-error "duplicate definition for global variable ~A"
605 (variable-local-name var)))
606 (push var specs)))
607 ;; now that the global environment knows about all variables, run the
608 ;; thunk setters to perform their compilation
609 (setf specs (nreverse specs))
610 (mapc (lambda (spec) (funcall (variable-thunk-setter spec))) specs)
611 (setf (stylesheet-global-variables stylesheet) specs))))
613 (defun parse-templates! (stylesheet <transform> env)
614 (let ((i 0))
615 (dolist (<template> (stp:filter-children (of-name "template") <transform>))
616 (let ((*namespaces* (acons-namespaces <template>)))
617 (dolist (template (compile-template <template> env i))
618 (let ((name (template-name template)))
619 (if name
620 (let* ((table (stylesheet-named-templates stylesheet))
621 (head (car (gethash name table))))
622 (when (and head (eql (template-import-priority head)
623 (template-import-priority template)))
624 ;; fixme: is this supposed to be a run-time error?
625 (xslt-error "conflicting templates for ~A" name))
626 (push template (gethash name table)))
627 (let ((mode (ensure-mode/qname stylesheet
628 (template-mode-qname template)
629 env)))
630 (setf (template-mode template) mode)
631 (push template (mode-templates mode)))))))
632 (incf i))))
635 ;;;; APPLY-STYLESHEET
637 (defvar *stylesheet*)
638 (defvar *mode*)
640 (deftype xml-designator () '(or runes:xstream runes:rod array stream pathname))
642 (defstruct (parameter
643 (:constructor make-parameter (value local-name &optional uri)))
644 (uri "")
645 local-name
646 value)
648 (defun find-parameter-value (local-name uri parameters)
649 (dolist (p parameters)
650 (when (and (equal (parameter-local-name p) local-name)
651 (equal (parameter-uri p) uri))
652 (return (parameter-value p)))))
654 (defvar *uri-resolver*)
656 (defun parse-allowing-microsoft-bom (pathname handler)
657 (with-open-file (s pathname :element-type '(unsigned-byte 8))
658 (unless (and (eql (read-byte s nil) #xef)
659 (eql (read-byte s nil) #xbb)
660 (eql (read-byte s nil) #xbf))
661 (file-position s 0))
662 (cxml:parse s handler)))
664 (defun %document (uri-string base-uri)
665 (let* ((absolute-uri
666 (puri:merge-uris uri-string base-uri))
667 (resolved-uri
668 (if *uri-resolver*
669 (funcall *uri-resolver* (puri:render-uri absolute-uri nil))
670 absolute-uri))
671 (pathname
672 (handler-case
673 (uri-to-pathname resolved-uri)
674 (cxml:xml-parse-error (c)
675 (xslt-error "cannot find referenced document ~A: ~A"
676 resolved-uri c))))
677 (document
678 (handler-case
679 (parse-allowing-microsoft-bom pathname (stp:make-builder))
680 ((or file-error cxml:xml-parse-error) (c)
681 (xslt-error "cannot parse referenced document ~A: ~A"
682 pathname c))))
683 (xpath-root-node
684 (make-whitespace-stripper document
685 (stylesheet-strip-tests *stylesheet*))))
686 (when (puri:uri-fragment absolute-uri)
687 (xslt-error "use of fragment identifiers in document() not supported"))
688 xpath-root-node))
690 (xpath:define-extension xslt *xsl*)
692 (xpath:define-xpath-function/lazy
693 xslt :document
694 (object &optional node-set)
695 (let ((instruction-base-uri *instruction-base-uri*))
696 (lambda (ctx)
697 (declare (ignore ctx))
698 (let* ((object (funcall object))
699 (node-set (and node-set (funcall node-set)))
700 (uri
701 (when node-set
702 ;; FIXME: should use first node of the node set
703 ;; _in document order_
704 (xpath-protocol:base-uri (xpath:first-node node-set)))))
705 (xpath::make-node-set
706 (if (xpath:node-set-p object)
707 (xpath:map-node-set->list
708 (lambda (node)
709 (%document (xpath:string-value node)
710 (or uri (xpath-protocol:base-uri node))))
711 object)
712 (list (%document (xpath:string-value object)
713 (or uri instruction-base-uri)))))))))
715 (xpath:define-xpath-function/lazy xslt current ()
716 #'(lambda (ctx)
717 (xpath:make-node-set
718 (xpath:make-pipe
719 (xpath:context-starting-node ctx)
720 nil))))
722 (defun apply-stylesheet
723 (stylesheet source-document
724 &key output parameters uri-resolver navigator)
725 (when (typep stylesheet 'xml-designator)
726 (setf stylesheet (parse-stylesheet stylesheet)))
727 (when (typep source-document 'xml-designator)
728 (setf source-document (cxml:parse source-document (stp:make-builder))))
729 (invoke-with-output-sink
730 (lambda ()
731 (handler-case*
732 (let* ((xpath:*navigator* (or navigator :default-navigator))
733 (puri:*strict-parse* nil)
734 (*stylesheet* stylesheet)
735 (*mode* (find-mode stylesheet nil))
736 (*empty-mode* (make-mode))
737 (global-variable-specs
738 (stylesheet-global-variables stylesheet))
739 (*global-variable-values*
740 (make-variable-value-array (length global-variable-specs)))
741 (*uri-resolver* uri-resolver)
742 (xpath-root-node
743 (make-whitespace-stripper
744 source-document
745 (stylesheet-strip-tests stylesheet)))
746 (ctx (xpath:make-context xpath-root-node)))
747 (mapc (lambda (spec)
748 (when (variable-param-p spec)
749 (let ((value
750 (find-parameter-value (variable-local-name spec)
751 (variable-uri spec)
752 parameters)))
753 (when value
754 (setf (global-variable-value (variable-index spec))
755 value)))))
756 global-variable-specs)
757 (mapc (lambda (spec)
758 (funcall (variable-thunk spec) ctx))
759 global-variable-specs)
760 #+nil (print global-variable-specs)
761 #+nil (print *global-variable-values*)
762 (apply-templates ctx))
763 (xpath:xpath-error (c)
764 (xslt-error "~A" c))))
765 stylesheet
766 output))
768 (defun find-attribute-set (local-name uri)
769 (or (gethash (cons local-name uri) (stylesheet-attribute-sets *stylesheet*))
770 (xslt-error "no such attribute set: ~A/~A" local-name uri)))
772 (defun apply-templates/list (list &optional param-bindings sort-predicate)
773 (when sort-predicate
774 (setf list (sort list sort-predicate)))
775 (let* ((n (length list))
776 (s/d (lambda () n)))
777 (loop
778 for i from 1
779 for child in list
781 (apply-templates (xpath:make-context child s/d i)
782 param-bindings))))
784 (defvar *stack-limit* 200)
786 (defun invoke-with-stack-limit (fn)
787 (let ((*stack-limit* (1- *stack-limit*)))
788 (unless (plusp *stack-limit*)
789 (xslt-error "*stack-limit* reached; stack overflow"))
790 (funcall fn)))
792 (defun invoke-template (ctx template param-bindings)
793 (let ((*lexical-variable-values*
794 (make-variable-value-array (template-n-variables template))))
795 (with-stack-limit ()
796 (loop
797 for (name-cons value) in param-bindings
798 for (nil index nil) = (find name-cons
799 (template-params template)
800 :test #'equal
801 :key #'car)
803 (unless index
804 (xslt-error "invalid template parameter ~A" name-cons))
805 (setf (lexical-variable-value index) value))
806 (funcall (template-body template) ctx))))
808 (defun apply-default-templates (ctx)
809 (let ((node (xpath:context-node ctx)))
810 (cond
811 ((or (xpath-protocol:node-type-p node :processing-instruction)
812 (xpath-protocol:node-type-p node :comment)))
813 ((or (xpath-protocol:node-type-p node :text)
814 (xpath-protocol:node-type-p node :attribute))
815 (write-text (xpath-protocol:string-value node)))
817 (apply-templates/list
818 (xpath::force
819 (xpath-protocol:child-pipe node)))))))
821 (defvar *apply-imports*)
823 (defun apply-applicable-templates (ctx templates param-bindings finally)
824 (labels ((apply-imports ()
825 (if templates
826 (let* ((this (pop templates))
827 (low (template-apply-imports-limit this))
828 (high (template-import-priority this)))
829 (setf templates
830 (remove-if-not
831 (lambda (x)
832 (<= low (template-import-priority x) high))
833 templates))
834 (invoke-template ctx this param-bindings))
835 (funcall finally))))
836 (let ((*apply-imports* #'apply-imports))
837 (apply-imports))))
839 (defun apply-templates (ctx &optional param-bindings)
840 (apply-applicable-templates ctx
841 (find-templates ctx)
842 param-bindings
843 (lambda ()
844 (apply-default-templates ctx))))
846 (defun call-template (ctx name &optional param-bindings)
847 (apply-applicable-templates ctx
848 (find-named-templates name)
849 param-bindings
850 (lambda ()
851 (error "cannot find named template: ~s"
852 name))))
854 (defun find-templates (ctx)
855 (let* ((matching-candidates
856 (remove-if-not (lambda (template)
857 (template-matches-p template ctx))
858 (mode-templates *mode*)))
859 (npriorities
860 (if matching-candidates
861 (1+ (reduce #'max
862 matching-candidates
863 :key #'template-import-priority))
865 (priority-groups (make-array npriorities :initial-element nil)))
866 (dolist (template matching-candidates)
867 (push template
868 (elt priority-groups (template-import-priority template))))
869 ;;; (print (map 'list #'length priority-groups))
870 ;;; (force-output)
871 (loop
872 for i from (1- npriorities) downto 0
873 for group = (elt priority-groups i)
874 for template = (maximize #'template< group)
875 when template
876 collect template)))
878 (defun find-named-templates (name)
879 (gethash name (stylesheet-named-templates *stylesheet*)))
881 (defun template< (a b) ;assuming same import priority
882 (let ((p (template-priority a))
883 (q (template-priority b)))
884 (cond
885 ((< p q) t)
886 ((> p q) nil)
888 (xslt-cerror "conflicting templates:~_~A,~_~A"
889 (template-match-expression a)
890 (template-match-expression b))
891 (< (template-position a) (template-position b))))))
893 (defun maximize (< things)
894 (when things
895 (let ((max (car things)))
896 (dolist (other (cdr things))
897 (when (funcall < max other)
898 (setf max other)))
899 max)))
901 (defun template-matches-p (template ctx)
902 (find (xpath:context-node ctx)
903 (xpath:all-nodes (funcall (template-match-thunk template) ctx))))
905 (defun invoke-with-output-sink (fn stylesheet output)
906 (etypecase output
907 (pathname
908 (with-open-file (s output
909 :direction :output
910 :element-type '(unsigned-byte 8)
911 :if-exists :rename-and-delete)
912 (invoke-with-output-sink fn stylesheet s)))
913 ((or stream null)
914 (invoke-with-output-sink fn
915 stylesheet
916 (make-output-sink stylesheet output)))
917 ((or hax:abstract-handler sax:abstract-handler)
918 (with-xml-output output
919 (funcall fn)))))
921 (defun make-output-sink (stylesheet stream)
922 (let* ((ystream
923 (if stream
924 (let ((et (stream-element-type stream)))
925 (cond
926 ((or (null et) (subtypep et '(unsigned-byte 8)))
927 (runes:make-octet-stream-ystream stream))
928 ((subtypep et 'character)
929 (runes:make-character-stream-ystream stream))))
930 (runes:make-rod-ystream)))
931 (output-spec (stylesheet-output-specification stylesheet))
932 (omit-xml-declaration-p
933 (equal (output-omit-xml-declaration output-spec) "yes"))
934 (sax-target
935 (make-instance 'cxml::sink
936 :ystream ystream
937 :omit-xml-declaration-p omit-xml-declaration-p)))
938 (if (equalp (output-method (stylesheet-output-specification stylesheet))
939 "HTML")
940 (make-instance 'combi-sink
941 :hax-target (make-instance 'chtml::sink
942 :ystream ystream)
943 :sax-target sax-target
944 :encoding (output-encoding output-spec))
945 sax-target)))
947 (defstruct template
948 match-expression
949 match-thunk
950 name
951 import-priority
952 apply-imports-limit
953 priority
954 position
955 mode
956 mode-qname
957 params
958 body
959 n-variables)
961 (defun expression-priority (form)
962 (let ((step (second form)))
963 (if (and (null (cddr form))
964 (listp step)
965 (eq :child (car step))
966 (null (cddr step)))
967 (let ((name (second step)))
968 (cond
969 ((or (stringp name)
970 (and (consp name)
971 (or (eq (car name) :qname)
972 (eq (car name) :processing-instruction))))
973 0.0)
974 ((and (consp name)
975 (or (eq (car name) :namespace)
976 (eq (car name) '*)))
977 -0.25)
979 -0.5)))
980 0.5)))
982 (defun valid-expression-p (expr)
983 (cond
984 ((atom expr) t)
985 ((eq (first expr) :path)
986 (every (lambda (x)
987 (let ((filter (third x)))
988 (or (null filter) (valid-expression-p filter))))
989 (cdr expr)))
990 ((eq (first expr) :variable) ;(!)
991 nil)
993 (every #'valid-expression-p (cdr expr)))))
995 (defun parse-pattern (str)
996 ;; zzz check here for anything not allowed as an XSLT pattern
997 ;; zzz can we hack id() and key() here?
998 (let ((form (handler-case
999 (xpath:parse-xpath str)
1000 (xpath:xpath-error (c)
1001 (xslt-error "~A" c)))))
1002 (unless (consp form)
1003 (xslt-error "not a valid pattern: ~A" str))
1004 (labels ((process-form (form)
1005 (cond ((eq (car form) :union)
1006 (alexandria:mappend #'process-form (rest form)))
1007 ((not (eq (car form) :path)) ;zzz: filter statt path
1008 (xslt-error "not a valid pattern: ~A" str))
1009 ((not (valid-expression-p form))
1010 (xslt-error "invalid filter"))
1011 (t (list form)))))
1012 (process-form form))))
1014 (defun compile-value-thunk (value env)
1015 (if (and (listp value) (eq (car value) 'progn))
1016 (let ((inner-thunk (compile-instruction value env)))
1017 (lambda (ctx)
1018 (apply-to-result-tree-fragment ctx inner-thunk)))
1019 (compile-xpath value env)))
1021 (defun compile-var-bindings/nointern (forms env)
1022 (loop
1023 for (name value) in forms
1024 collect (multiple-value-bind (local-name uri)
1025 (decode-qname name env nil)
1026 (list (cons local-name uri)
1027 (xslt-trace-thunk
1028 (compile-value-thunk value env)
1029 "local variable ~s = ~s" name :result)))))
1031 (defun compile-var-bindings (forms env)
1032 (loop
1033 for (cons thunk) in (compile-var-bindings/nointern forms env)
1034 for (local-name . uri) = cons
1035 collect (list cons
1036 (push-variable local-name
1038 *lexical-variable-declarations*)
1039 thunk)))
1041 (defun compile-template (<template> env position)
1042 (stp:with-attributes (match name priority mode) <template>
1043 (unless (or name match)
1044 (xslt-error "missing match in template"))
1045 (multiple-value-bind (params body-pos)
1046 (loop
1047 for i from 0
1048 for child in (stp:list-children <template>)
1049 while (namep child "param")
1050 collect (parse-param child) into params
1051 finally (return (values params i)))
1052 (let* ((*lexical-variable-declarations* (make-empty-declaration-array))
1053 (param-bindings (compile-var-bindings params env))
1054 (body (parse-body <template> body-pos (mapcar #'car params)))
1055 (body-thunk (compile-instruction `(progn ,@body) env))
1056 (outer-body-thunk
1057 (xslt-trace-thunk
1058 #'(lambda (ctx)
1059 (unwind-protect
1060 (progn
1061 ;; set params that weren't initialized by apply-templates
1062 (loop for (name index param-thunk) in param-bindings
1063 when (eq (lexical-variable-value index nil) 'unbound)
1064 do (setf (lexical-variable-value index)
1065 (funcall param-thunk ctx)))
1066 (funcall body-thunk ctx))))
1067 "template: match = ~s name = ~s" match name))
1068 (n-variables (length *lexical-variable-declarations*)))
1069 (append
1070 (when name
1071 (multiple-value-bind (local-name uri)
1072 (decode-qname name env nil)
1073 (list
1074 (make-template :name (cons local-name uri)
1075 :import-priority *import-priority*
1076 :apply-imports-limit *apply-imports-limit*
1077 :params param-bindings
1078 :body outer-body-thunk
1079 :n-variables n-variables))))
1080 (when match
1081 (mapcar (lambda (expression)
1082 (let ((match-thunk
1083 (xslt-trace-thunk
1084 (compile-xpath
1085 `(xpath:xpath
1086 (:path (:ancestor-or-self :node)
1087 ,@(cdr expression)))
1088 env)
1089 "match-thunk for template (match ~s): ~s --> ~s"
1090 match expression :result))
1091 (p (if priority
1092 (parse-number:parse-number priority)
1093 (expression-priority expression))))
1094 (make-template :match-expression expression
1095 :match-thunk match-thunk
1096 :import-priority *import-priority*
1097 :apply-imports-limit *apply-imports-limit*
1098 :priority p
1099 :position position
1100 :mode-qname mode
1101 :params param-bindings
1102 :body outer-body-thunk
1103 :n-variables n-variables)))
1104 (parse-pattern match))))))))
1105 #+(or)
1106 (xuriella::parse-stylesheet #p"/home/david/src/lisp/xuriella/test.xsl")