Debian Codegraph @

ext/sxml/src/serializer.scm

raw
1 ;; SXML serializer into XML and HTML
2 ;
3 ; Partial conformance with
4 ; [1] XSLT 2.0 and XQuery 1.0 Serialization
5 ; W3C Candidate Recommendation 3 November 2005
6 ; http://www.w3.org/TR/2005/CR-xslt-xquery-serialization-20051103/
7 ;
8 ; This software is in Public Domain.
9 ; IT IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
10 ;
11 ; Please send bug reports and comments to:
12 ; [email protected] Dmitry Lizorkin
13
14 ; Prefix for global identifiers in this module is `srl:'
15 ; short for "serialization"
16
17 ; Requires: function `filter' from SRFI-1
18 ; syntax `cond-expand' from SRFI-0
19 ; In particular, for PLT, `filter' can be acquired as follows:
20 ;(require (lib "filter.ss" "srfi/1"))
21
22 ;==========================================================================
23 ; Basic
24
25 ; `map' and `append' in a single pass:
26 ; (srl:map-append func lst) = (apply append (map func lst))
27 ; A simplified analogue of `map-union' from "sxpathlib.scm"
28 (define (srl:map-append func lst)
29 (if (null? lst)
30 lst
31 (append (func (car lst))
32 (srl:map-append func (cdr lst)))))
33
34 ; procedure srl:apply-string-append :: STR-LST -> STRING
35 ; str-lst ::= (listof string)
36 ; Concatenates `str-lst' members into a single string
37 ; (srl:apply-string-append str-lst) = (apply string-append str-lst)
38 ;; (cond-expand
39 ;; (chicken
40 ; In Chicken, procedures are generally limited to 126 arguments
41 ; http://www.call-with-current-continuation.org/
42 ; Due to this Chicken limitation, we cannot apply `string-append' directly
43 ; for a potentially long `str-lst'
44
45 ; Similar to R5RS 'list-tail' but returns the new list consisting of the
46 ; first 'k' members of 'lst'
47 ;; (define (srl:list-head lst k)
48 ;; (if (or (null? lst) (zero? k))
49 ;; '()
50 ;; (cons (car lst) (srl:list-head (cdr lst) (- k 1)))))
51
52 ; Because of Chicken 126-argument limitation, I do not care of intermediate
53 ; garbage produced in the following solution:
54 ;; (define (srl:apply-string-append str-lst)
55 ;; (cond
56 ;; ((null? str-lst) "")
57 ;; ((null? (cdr str-lst)) (car str-lst))
58 ;; (else ; at least two members
59 ;; (let ((middle (inexact->exact (round (/ (length str-lst) 2)))))
60 ;; (string-append
61 ;; (srl:apply-string-append (srl:list-head str-lst middle))
62 ;; (srl:apply-string-append (list-tail str-lst middle)))))))
63 ;; )
64 ;; (else
65 (define (srl:apply-string-append str-lst)
66 (apply string-append str-lst))
67 ;; ))
68
69 ; Analogue of `assoc'
70 ; However, search is performed by `cdr' of each alist member and `string=?' is
71 ; used for comparison
72 (define (srl:assoc-cdr-string= item alist)
73 (cond
74 ((null? alist) #f)
75 ((string=? (cdar alist) item) (car alist))
76 (else (srl:assoc-cdr-string= item (cdr alist)))))
77
78 ; Analogue of `member' for strings that uses case insensitive comparison
79 (define (srl:member-ci str lst)
80 (cond
81 ((null? lst) #f)
82 ((string-ci=? str (car lst)) lst)
83 (else (srl:member-ci str (cdr lst)))))
84
85 ; Analogue of `member'
86 ; The end of the `lst' is returned, from the first member that satisfies
87 ; the `pred?'
88 (define (srl:mem-pred pred? lst)
89 (cond
90 ((null? lst) #f)
91 ((pred? (car lst)) lst)
92 (else (srl:mem-pred pred? (cdr lst)))))
93
94 ;-------------------------------------------------
95 ; Borrowed from "char-encoding.scm"
96
97 ; The newline character
98 (cond-expand
99 ((or scheme48 scsh)
100 (define srl:char-nl (ascii->char 10)))
101 (else
102 (define srl:char-nl (integer->char 10))))
103
104 ; A string consisting of a single newline character
105 (define srl:newline (string srl:char-nl))
106
107 ;-------------------------------------------------
108 ; Borrowed from "sxpathlib.scm"
109
110 ; A simplified implementation of `select-kids' is sufficienf for the serializer
111 (define (srl:select-kids test-pred?)
112 (lambda (node) ; node or node-set
113 (cond
114 ((null? node) node)
115 ((not (pair? node)) '()) ; No children
116 ((symbol? (car node))
117 (filter test-pred? (cdr node)))
118 (else
119 (srl:map-append (srl:select-kids test-pred?) node)))))
120
121 ;-------------------------------------------------
122 ; Borrowed from "modif.scm"
123
124 ; Separates the list into two lists with respect to the predicate
125 ; Returns: (values res-lst1 res-lst2)
126 ; res-lst1 - contains all members from the input lst that satisfy the pred?
127 ; res-lst2 - contains the remaining members of the input lst
128 (define (srl:separate-list pred? lst)
129 (let loop ((lst lst)
130 (satisfy '())
131 (rest '()))
132 (cond
133 ((null? lst)
134 (values (reverse satisfy) (reverse rest)))
135 ((pred? (car lst)) ; the first member satisfies the predicate
136 (loop (cdr lst)
137 (cons (car lst) satisfy) rest))
138 (else
139 (loop (cdr lst)
140 satisfy (cons (car lst) rest))))))
141
142 ;-------------------------------------------------
143 ; Borrowed from "fragments.scm"
144
145 ; A simplified implementation of `sxml:clean-fragments'
146 (define (srl:clean-fragments fragments)
147 (reverse
148 (let loop ((fragments fragments) (result '()))
149 (cond
150 ((null? fragments) result)
151 ((null? (car fragments)) (loop (cdr fragments) result))
152 ((pair? (car fragments))
153 (loop (cdr fragments)
154 (loop (car fragments) result)))
155 (else
156 (loop (cdr fragments)
157 (cons (car fragments) result)))))))
158
159 ; A very much simplified analogue of `sxml:display-fragments' for fragments
160 ; that have no more than two levels of nesting
161 ; fragments-level2 ::= (listof fragments-level1)
162 ; fragments-level1 ::= string | (listof string)
163 (define (srl:display-fragments-2nesting fragments-level2 port)
164 (for-each
165 (lambda (level1)
166 (if (pair? level1)
167 (for-each (lambda (x) (display x port))
168 level1)
169 (display level1 port)))
170 fragments-level2))
171
172
173 ;==========================================================================
174 ; Helper SXML utilities
175
176 ; Splits an SXML `name' into namespace id/uri and local part
177 ; Returns: (cons namespace-id local-part)
178 ; local-part - string
179 ; namespace-id - string or #f if the `name' does not have a prefix
180 (define (srl:split-name name)
181 (let* ((name-str (symbol->string name))
182 (lng (string-length name-str)))
183 (let iter ((i (- lng 1)))
184 (cond
185 ((< i 0) ; name scanned, #\: not found
186 (cons #f name-str))
187 ((char=? (string-ref name-str i) #\:)
188 (cons (substring name-str 0 i)
189 (substring name-str (+ i 1) lng)))
190 (else
191 (iter (- i 1)))))))
192
193 ; Converts SXML atomic object to a string. Keeps non-atomic object unchanged.
194 ; A simplified analogue of applying the XPath `string(.)' function to atomic
195 ; object.
196 (define (srl:atomic->string obj)
197 (cond
198 ((or (pair? obj) ; non-atomic type
199 (string? obj)) obj)
200 ((number? obj)
201 (number->string obj))
202 ((boolean? obj)
203 (if obj "true" "false"))
204 (else ; unexpected type
205 ; ATTENTION: should probably raise an error here
206 obj)))
207
208 ; Whether an SXML element is empty
209 (define (srl:empty-elem? elem)
210 (or (null? (cdr elem)) ; just the name
211 (and (null? (cddr elem)) ; just the name and attributes
212 (pair? (cadr elem)) (eq? (caadr elem) '@))
213 (and (not (null? (cddr elem))) ; name, attributes, and SXML 2.X aux-list
214 (null? (cdddr elem))
215 (pair? (caddr elem)) (eq? (caaddr elem) '@@))))
216
217 ;-------------------------------------------------
218 ; Handling SXML namespaces
219 ; <namespace-assoc> is defined in the SXML specification as
220 ; <namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
221
222 ; Conventional namespace prefix referred to in XML-related specifications
223 ; These prefixes are used for serializing the corresponding namespace URIs by
224 ; default, unless a different prefix is supplied
225 (define srl:conventional-ns-prefixes
226 '((dc . "http://purl.org/dc/elements/1.1/")
227 (fo . "http://www.w3.org/1999/XSL/Format")
228 (rdf . "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
229 (rng . "http://relaxng.org/ns/structure/1.0")
230 (xlink . "http://www.w3.org/1999/xlink")
231 (xqx . "http://www.w3.org/2005/XQueryX")
232 (xsd . "http://www.w3.org/2001/XMLSchema")
233 (xsi . "http://www.w3.org/2001/XMLSchema-instance")
234 (xsl . "http://www.w3.org/1999/XSL/Transform")))
235
236 ; Returns (listof <namespace-assoc>) for the given SXML element
237 (define (srl:namespace-assoc-for-elem elem)
238 ((srl:select-kids (lambda (node) (pair? node)))
239 ((srl:select-kids
240 (lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
241 (append
242 ((srl:select-kids ; compatibility with SXML 3.0
243 (lambda (node) (and (pair? node) (eq? (car node) '@))))
244 ((srl:select-kids
245 (lambda (node) (and (pair? node) (eq? (car node) '@))))
246 elem))
247 ((srl:select-kids ; compatibility with SXML 2.X
248 (lambda (node) (and (pair? node) (eq? (car node) '@@))))
249 elem)))))
250
251 ; Returns (listof <namespace-assoc>) for the SXML document node
252 (define (srl:ns-assoc-for-top doc)
253 ((srl:select-kids (lambda (node) (pair? node)))
254 ((srl:select-kids
255 (lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
256 ((srl:select-kids
257 (lambda (node)
258 ; After sequence normalization [1], the SXML 3.0 aux-list is used
259 ; at the top-level
260 (and (pair? node) (eq? (car node) '@))))
261 doc))))
262
263 ; Extract original prefix-binding from `namespace-assoc-lst'
264 ; namespace-assoc-lst ::= (listof <namespace-assoc>)
265 ; <namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
266 ; Returns: (listof (cons original-prefix "URI"))
267 (define (srl:extract-original-prefix-binding namespace-assoc-lst)
268 (map
269 (lambda (triple) (cons (caddr triple) (cadr triple)))
270 (filter ; specifies original prefix
271 (lambda (memb) (= (length memb) 3))
272 namespace-assoc-lst)))
273
274 ;-------------------------------------------------
275 ; Handling xml:space attribute
276
277 ; Returns the new value of `space-preserve?' in accordance with the value of
278 ; xml:space attribute probably presented for the given SXML element `elem'
279 ; space-preserve? ::= #t | #f - whether the SXML subtree inherits the
280 ; xml:space attribute with the value "preserve"
281 (define (srl:update-space-specifier elem space-preserve?)
282 (let ((xml-space-val
283 ((srl:select-kids string?)
284 ((srl:select-kids
285 (lambda (node) (and (pair? node) (eq? (car node) 'xml:space))))
286 ((srl:select-kids
287 (lambda (node) (and (pair? node) (eq? (car node) '@))))
288 elem)))))
289 (cond
290 ((null? xml-space-val) ; no xml:space attribute
291 space-preserve?)
292 ((string=? (car xml-space-val) "preserve")
293 #t)
294 ((string=? (car xml-space-val) "default")
295 #f)
296 (else space-preserve?))))
297
298
299 ;==========================================================================
300 ; Sequence normalization
301 ; Sect. 2 in [1]
302
303 ; Performs sequence normalization in accordance with [1]
304 ; Returns the SXML document node
305 (define (srl:normalize-sequence node-or-sequence)
306 (letrec
307 ((normaliz-step-1
308 ; "If the sequence that is input to serialization is empty, create a
309 ; sequence S1 that consists of a zero-length string. Otherwise, copy
310 ; each item in the sequence that is input to serialization to create
311 ; the new sequence S1." [1]
312 (lambda (node-or-seq)
313 (cond
314 ((null? node-or-seq) ; empty sequence
315 '(""))
316 ; Effect of `as-nodeset' from "sxpathlib.scm"
317 ((or (not (pair? node-or-seq)) ; single item
318 (symbol? (car node-or-seq))) ; single node
319 (list node-or-seq))
320 (else
321 node-or-seq))))
322 (normaliz-step-2
323 ; "For each item in S1, if the item is atomic, obtain the lexical
324 ; representation of the item by casting it to an xs:string and copy
325 ; the string representation to the new sequence; otherwise, copy the
326 ; item, which will be a node, to the new sequence. The new sequence is
327 ; S2." [1]
328 (lambda (seq)
329 (map
330 (lambda (item) (srl:atomic->string item))
331 seq)))
332 (normaliz-step-3
333 ; "For each subsequence of adjacent strings in S2, copy a single
334 ; string to the new sequence equal to the values of the strings in the
335 ; subsequence concatenated in order, each separated by a single space.
336 ; Copy all other items to the new sequence. The new sequence is S3."
337 (lambda (seq)
338 (let loop ((src (reverse seq))
339 (res '()))
340 (cond
341 ((null? src)
342 res)
343 ((string? (car src))
344 (let adjacent ((src (cdr src))
345 (adj-strs (list (car src))))
346 (cond
347 ((null? src) ; source sequence is over
348 (cons (srl:apply-string-append adj-strs) res))
349 ((string? (car src))
350 (adjacent (cdr src)
351 (cons (car src) (cons " " adj-strs))))
352 (else
353 (loop (cdr src)
354 (cons (car src)
355 (cons (srl:apply-string-append adj-strs)
356 res)))))))
357 (else
358 (loop (cdr src)
359 (cons (car src) res)))))))
360 ; Step 4 from [1] is redundant for SXML, since SXML text nodes are not
361 ; distinquished from strings
362 (normaliz-step-5
363 ; "For each item in S4, if the item is a document node, copy its
364 ; children to the new sequence; otherwise, copy the item to the new
365 ; sequence. The new sequence is S5." [1]
366 (lambda (seq)
367 (cond
368 ((null? seq)
369 seq)
370 ((and (pair? (car seq)) (eq? (caar seq) '*TOP*))
371 ; Document node
372 (append (cdar seq) (normaliz-step-5 (cdr seq))))
373 (else
374 (cons (car seq) (normaliz-step-5 (cdr seq)))))))
375 (normaliz-step-6
376 ; "For each subsequence of adjacent text nodes in S5, copy a single
377 ; text node to the new sequence equal to the values of the text nodes
378 ; in the subsequence concatenated in order. Any text nodes with values
379 ; of zero length are dropped. Copy all other items to the new sequence.
380 ; The new sequence is S6." [1]
381 ; Much like Step 3; however, a space between adjacent strings is not
382 ; inserted and the zero-length strings are removed
383 (lambda (seq)
384 (let loop ((src (reverse seq))
385 (res '()))
386 (cond
387 ((null? src)
388 res)
389 ((string? (car src))
390 (if
391 (string=? (car src) "") ; empty string
392 (loop (cdr src) res)
393 (let adjacent ((src (cdr src))
394 (adj-strs (list (car src))))
395 (cond
396 ((null? src) ; source sequence is over
397 (cons (srl:apply-string-append adj-strs) res))
398 ((string? (car src))
399 ; If it is an empty string, the effect of its presense
400 ; will be removed by string concatenation
401 (adjacent (cdr src)
402 (cons (car src) adj-strs)))
403 (else
404 (loop (cdr src)
405 (cons (car src)
406 (cons
407 (srl:apply-string-append adj-strs)
408 res))))))))
409 (else
410 (loop (cdr src)
411 (cons (car src) res)))))))
412 (normaliz-step-7
413 ; "It is a serialization error [err:SENR0001] if an item in S6 is an
414 ; attribute node or a namespace node. Otherwise, construct a new
415 ; sequence, S7, that consists of a single document node and copy all
416 ; the items in the sequence, which are all nodes, as children of that
417 ; document node." [1]
418 ; On this step, we should take care of SXML aux-lists
419 ; ATTENTION: should generally raise an error in the presense of
420 ; attribute nodes in a sequence. By nature of SXML 3.0, however,
421 ; attribute nodes on the top level are treated as aux-nodes
422 (lambda (seq)
423 (call-with-values
424 (lambda ()
425 (srl:separate-list
426 (lambda (item)
427 (and (pair? item)
428 (or (eq? (car item) '@@) ; aux-list in SXML 2.X
429 (eq? (car item) '@) ; aux-list in SXML 3.0
430 )))
431 seq))
432 (lambda (aux-lists body)
433 (if
434 (null? aux-lists)
435 `(*TOP* ,@body)
436 `(*TOP*
437 (@ ,@(srl:map-append cdr aux-lists))
438 ,@body)))))))
439 ; TODO: According to [1], if the normalized sequence does not have exactly
440 ; one element node node child or has text node children, then the
441 ; serialized output should be an XML external general parsed entity.
442 ; However, external parsed entities are not currently handled by SSAX
443 ; parser. Should think of a compromise between conformance and practical
444 ; usability.
445 (normaliz-step-7
446 (normaliz-step-6
447 (normaliz-step-5
448 (normaliz-step-3
449 (normaliz-step-2
450 (normaliz-step-1 node-or-sequence))))))))
451
452
453 ;==========================================================================
454 ; Character escaping during string serialization
455 ; Escaping in accordance with [1] and [2]:
456 ;
457 ; [2] Extensible Markup Language (XML) 1.0 (Third Edition)
458 ; W3C Recommendation 04 February 2004
459 ; http://www.w3.org/TR/2004/REC-xml-20040204
460
461 ;-------------------------------------------------
462 ; CDATA sections
463
464 ; Returns #f if a given character `ch' is in XML character range [2]
465 ; Otherwise, returns a string representing the character reference for that
466 ; character
467 (define (srl:xml-char-escaped ch)
468 (let ((code (char->integer ch)))
469 (if (or (= code 9) (= code 10) (= code 13)
470 (and (>= code 32) (<= code 55295))
471 (and (>= code 57344) (<= code 65533))
472 (>= code 65536))
473 #f
474 (string-append "&#" (number->string code) ";"
475 ))))
476
477 ; Represents a given string `str' as a CDATA section
478 (define (srl:string->cdata-section str)
479 (let ((flush-buffer
480 ; If a `buffer' is non-empty, converts it to a CDATA string and
481 ; cons'es this string to `res'. Returns a new res
482 (lambda (buffer res)
483 (if (null? buffer)
484 res
485 (cons
486 (string-append
487 "<![CDATA[" (list->string (reverse buffer)) "]]>")
488 res)))))
489 (let loop ((src (string->list str))
490 (buffer '())
491 (res '("")))
492 (cond
493 ((null? src)
494 (srl:apply-string-append
495 (reverse (flush-buffer buffer res))))
496 ((srl:xml-char-escaped (car src))
497 => (lambda (charref)
498 (loop (cdr src)
499 '()
500 (cons charref (flush-buffer buffer res)))))
501 ((and (char=? (car src) #\])
502 (not (null? buffer))
503 (char=? (car buffer) #\]))
504 (loop (cdr src)
505 '()
506 (cons (string (car buffer) (car src)) ;= "]]"
507 (flush-buffer (cdr buffer) res))))
508 (else ; any other character
509 (loop (cdr src)
510 (cons (car src) buffer)
511 res))))))
512
513 ;-------------------------------------------------
514 ; Character data and attribute values
515
516 ; Associative lists of characters to be escaped in XML character data and
517 ; attribute values respectively [2]
518 (define srl:escape-alist-char-data
519 '((#\& . "&amp;") (#\< . "&lt;") (#\> . "&gt;")))
520 (define srl:escape-alist-att-value
521 (append `((#\' . "&apos;") (#\" . "&quot;")
522 ; Escaping the newline character in attribute value
523 (,srl:char-nl . "&#10;"))
524 srl:escape-alist-char-data))
525 (define srl:escape-alist-html-att
526 '((#\& . "&amp;") (#\> . "&gt;") (#\' . "&apos;") (#\" . "&quot;")))
527
528 ; Escape a string with the `srl:xml-char-escaped' and with the `escape-alist'
529 ; supplied
530 ; escape-alist ::= (listof (cons char string))
531 ; html-method? ::= #t | #f
532 ; Returns the escaped string
533 (define (srl:string->escaped str escape-alist html-method?)
534 (let loop ((src (string->list str))
535 (adj-chars '())
536 (res '()))
537 (cond
538 ((null? src)
539 (srl:apply-string-append
540 (reverse (cons (list->string (reverse adj-chars))
541 res))))
542 ((assv (car src) escape-alist) ; current character matches the alist
543 => (lambda (pair)
544 (if
545 ; Subsect. 7.2 in [1]:
546 ; "The HTML output method MUST NOT escape a & character occurring
547 ; in an attribute value immediately followed by a { character"
548 (and (char=? (car src) #\&)
549 html-method?
550 (not (null? (cdr src))) (char=? (cadr src) #\{))
551 (loop (cdr src)
552 (cons (car src) adj-chars)
553 res)
554 (loop (cdr src)
555 '()
556 (cons (cdr pair)
557 (cons (list->string (reverse adj-chars))
558 res))))))
559 ((srl:xml-char-escaped (car src))
560 => (lambda (esc)
561 (loop (cdr src)
562 '()
563 (cons esc
564 (cons (list->string (reverse adj-chars))
565 res)))))
566 (else
567 (loop (cdr src)
568 (cons (car src) adj-chars)
569 res)))))
570
571 (define (srl:string->char-data str)
572 (srl:string->escaped str srl:escape-alist-char-data #f))
573 (define (srl:string->att-value str)
574 (srl:string->escaped str srl:escape-alist-att-value #f))
575 (define (srl:string->html-att str)
576 (srl:string->escaped str srl:escape-alist-html-att #t))
577
578 ;-------------------------------------------------
579 ; Serializing entities produced by HtmlPrag
580 ;
581 ; [3] Neil W. Van Dyke.
582 ; HtmlPrag: Pragmatic Parsing and Emitting of HTML using SXML and SHTML
583 ; Version 0.16, 2005-12-18, http://www.neilvandyke.org/htmlprag/
584
585 ; "..SHTML adds a special & syntax for non-ASCII (or non-Extended-ASCII)
586 ; characters. The syntax is (& val), where val is a symbol or string naming
587 ; with the symbolic name of the character, or an integer with the numeric
588 ; value of the character." [3]
589 ; entity ::= `(& ,val)
590 ; val ::= symbol | string | number
591 ; Returns the string representation for the entity
592 (define (srl:shtml-entity->char-data entity)
593 ; TODO: think of an appropriate error message for an ill-formed entity
594 (if
595 (= (length entity) 2)
596 (let ((val (cadr entity)))
597 (cond
598 ((symbol? val) (string-append "&" (symbol->string val) ";")
599 )
600 ((string? val) (string-append "&" val ";")
601 )
602 ((and (number? val) (integer? val) (> val 0))
603 ; to guarantee well-formedness of the result produced
604 (string-append "&#" (number->string val) ";")
605 )
606 (else ; should signal of an error
607 "")))
608 ""))
609
610
611 ;==========================================================================
612 ; Serialization for markup
613 ; declared-ns-prefixes ::= (listof (cons prefix-string namespace-uri))
614 ; prefix-string, namespace-uri - strings
615
616 ; Returns the string representation for a QName
617 ; prefix-string ::= string or #f if the name contains no prefix
618 ; TODO: should check names for proper characters
619 (define (srl:qname->string prefix-string local-part)
620 (if prefix-string
621 (string-append prefix-string ":" local-part)
622 local-part))
623
624 ;-------------------------------------------------
625 ; Different types of nodes
626
627 ; Returns the list of strings that constitute the serialized representation
628 ; for the attribute. Inserts a whitespace symbol in the beginning
629 ; method ::= 'xml | 'html
630 (define (srl:attribute->str-lst prefix-string local-part att-value method)
631 (let ((attval (srl:atomic->string att-value)))
632 (cond
633 (prefix-string
634 (list " " prefix-string ":" local-part "=\""
635 ((if (eq? method 'html)
636 srl:string->html-att
637 srl:string->att-value) attval)
638 "\""))
639 ((eq? method 'html)
640 (list " " local-part "=\"" (srl:string->html-att attval) "\""))
641 (else ; unprefixed attribute, XML output method
642 (list " " local-part "=\"" (srl:string->att-value attval) "\"")))))
643
644 ; Returns the list of strings that constitute the serialized representation
645 ; for the namespace declaration. Inserts a whitespace symbol in the beginning
646 ; ATTENTION: character escaping for namespace URI may be improper, study this
647 ; issue
648 (define (srl:namespace-decl->str-lst prefix-string namespace-uri)
649 (list " xmlns:" prefix-string "=\""
650 (srl:string->att-value namespace-uri) "\""))
651
652 ; According to SXML specification,
653 ; <comment> ::= ( *COMMENT* "comment string" )
654 ; ATTENTION: in the case of ill-formed comment, should probably report an error
655 ; instead of recovering
656 (define (srl:comment->str-lst comment-node)
657 (let ((proper-string-in-comment?
658 ; Whether a proper string occurs in the comment node. Thus,
659 ; "For compatibility, the string '--' (double-hyphen) MUST NOT occur
660 ; within comments. ... Note that the grammar does not allow a comment
661 ; ending in --->." [2]
662 (lambda (str)
663 (let ((lng (string-length str)))
664 (or
665 (zero? lng) ; empty string allowed in comment [2]
666 (and
667 (not (char=? (string-ref str 0) #\-))
668 (let iter ((i 1)
669 (prev-hyphen? #f))
670 (cond
671 ((>= i lng)
672 (not prev-hyphen?) ; string must not end with hyphen
673 )
674 ((char=? (string-ref str i) #\-)
675 (if prev-hyphen?
676 #f
677 (iter (+ i 1) #t)))
678 (else
679 (iter (+ i 1) #f))))))))))
680 (if (and (= (length comment-node) 2)
681 (string? (cadr comment-node))
682 (proper-string-in-comment? (cadr comment-node)))
683 (list "<!--" (cadr comment-node) "-->")
684 (list "<!--" "-->") ; should probably report of an error
685 )))
686
687 ; According to SXML specification,
688 ; <PI> ::= ( *PI* pi-target
689 ; <annotations>? "processing instruction content string" )
690 ; method ::= 'xml | 'html
691 ; Subsect 7.3 in [1]: "The HTML output method MUST terminate processing
692 ; instructions with > rather than ?>."
693 ; ATTENTION: in the case of ill-formed PI content string, should probably
694 ; report an error instead of recovering
695 (define (srl:processing-instruction->str-lst pi-node method)
696 (let ((string-not-contain-charlist?
697 ; Whether `str' does not contain a sequence of characters from
698 ; `char-lst' as its substring
699 (lambda (str char-lst)
700 (let ((lng (string-length str)))
701 (or
702 (zero? lng) ; empty string doesn't contain
703 (let iter ((i 0)
704 (pattern char-lst))
705 (cond
706 ((>= i lng) #t)
707 ((char=? (string-ref str i) (car pattern))
708 (if (null? (cdr pattern)) ; it is the last member
709 #f ; contains
710 (iter (+ i 1) (cdr pattern))))
711 (else
712 (iter (+ i 1) char-lst)))))))))
713 (if
714 (or (null? (cdr pi-node))
715 (not (symbol? (cadr pi-node)))) ; no target => ill-formed PI
716 '() ; should probably raise an error
717 (let ((content (filter string? (cddr pi-node))))
718 (cond
719 ((null? content) ; PI with no content - correct situation
720 (list "<?" (symbol->string (cadr pi-node))
721 (if (eq? method 'html) ">" "?>")))
722 ; Subsect. 7.3 in [1]: "It is a serialization error to use the HTML
723 ; output method when > appears within a processing instruction in
724 ; the data model instance being serialized."
725 ((and (null? (cdr content)) ; only a single member
726 (string-not-contain-charlist?
727 (car content)
728 (if (eq? method 'html) '(#\>) '(#\? #\>))))
729 (list "<?" (symbol->string (cadr pi-node)) " " (car content)
730 (if (eq? method 'html) ">" "?>")))
731 (else ; should probably signal of an error
732 '()))))))
733
734 ;-------------------------------------------------
735 ; SXML element
736
737 ; Returns: (values
738 ; prefix-string namespace-uri local-part declaration-required?)
739 ; prefix-string - namespace prefix to be given to the serialized name: a string
740 ; or #f if no prefix is required
741 ; namespace-uri - the namespace URI for the given `name', #f if the name has no
742 ; namespace URI
743 ; local-part - local part of the name
744 ; declaration-required ::= #t | #f - whether `prefix' has to be declared
745 (define (srl:name->qname-components
746 name ns-prefix-assig namespace-assoc declared-ns-prefixes)
747 (let ((use-ns-id-or-generate-prefix
748 (lambda (ns-id)
749 (if
750 (and ns-id ; try to use namespace-id as a prefix
751 (not (assq (string->symbol ns-id) ns-prefix-assig))
752 (not (assoc ns-id declared-ns-prefixes)))
753 ns-id
754 ; Otherwise - generate unique prefix
755 ; Returns a prefix-string not presented in ns-prefix-assig and
756 ; declared-ns-prefixes
757 (let loop ((i 1))
758 (let ((candidate (string-append "prfx" (number->string i))))
759 (if (or (assoc candidate declared-ns-prefixes)
760 (assq (string->symbol candidate) ns-prefix-assig))
761 (loop (+ i 1))
762 candidate))))))
763 (n-parts (srl:split-name name)))
764 (cond
765 ((not (car n-parts)) ; no namespace-id => no namespace
766 (values #f #f (cdr n-parts) ; name as a string
767 #f))
768 ((string-ci=? (car n-parts) "xml") ; reserved XML namespace
769 (values (car n-parts) "http://www.w3.org/XML/1998/namespace"
770 (cdr n-parts) #f))
771 (else
772 (call-with-values
773 (lambda ()
774 (cond
775 ((assq (string->symbol (car n-parts)) ; suppose a namespace-id
776 namespace-assoc)
777 => (lambda (lst)
778 (values (cadr lst) (car n-parts))))
779 (else ; first part of a name is a namespace URI
780 (values (car n-parts) #f))))
781 (lambda (namespace-uri ns-id)
782 (cond
783 ((srl:assoc-cdr-string= namespace-uri declared-ns-prefixes)
784 => (lambda (pair)
785 ; Prefix for that namespace URI already declared
786 (values (car pair) namespace-uri (cdr n-parts) #f)))
787 (else ; namespace undeclared
788 (values
789 (cond
790 ((srl:assoc-cdr-string= namespace-uri ns-prefix-assig)
791 => (lambda (pair)
792 ; A candidate namespace prefix is supplied from the user
793 (let ((candidate (symbol->string (car pair))))
794 (if
795 (assoc candidate declared-ns-prefixes)
796 ; The prefix already bound to a different namespace
797 ; Avoid XML prefix re-declaration
798 (use-ns-id-or-generate-prefix ns-id)
799 candidate))))
800 (else
801 (use-ns-id-or-generate-prefix ns-id)))
802 namespace-uri
803 (cdr n-parts)
804 #t ; in any case, prefix declaration is required
805 )))))))))
806
807 (define srl:void-elements
808 '("area" "base" "basefont" "br" "col" "embed"
809 "frame" "hr" "img" "input" "isindex" "keygen"
810 "link" "meta" "param" "source" "track" "wbr"))
811
812 ; Constructs start and end tags for an SXML element `elem'
813 ; method ::= 'xml | 'html
814 ; Returns: (values start-tag end-tag
815 ; ns-prefix-assig namespace-assoc declared-ns-prefixes)
816 ; start-tag ::= (listof string)
817 ; end-tag ::= (listof string) or #f for empty element
818 ; TODO: escape URI attributes for HTML
819 ; TODO: indentation probably should be made between attribute declarations
820 (define (srl:construct-start-end-tags
821 elem method
822 ns-prefix-assig namespace-assoc declared-ns-prefixes)
823 (let ((ns-assoc-here (srl:namespace-assoc-for-elem elem))
824 (empty? (srl:empty-elem? elem)))
825 (let ((ns-prefix-assig
826 (append
827 (srl:extract-original-prefix-binding ns-assoc-here)
828 ns-prefix-assig))
829 (namespace-assoc
830 (append ns-assoc-here namespace-assoc)))
831 (call-with-values
832 (lambda ()
833 (srl:name->qname-components ; element name
834 (car elem) ns-prefix-assig namespace-assoc declared-ns-prefixes))
835 (lambda (elem-prefix elem-uri elem-local elem-decl-required?)
836 (let loop ((attrs
837 (reverse
838 ((srl:select-kids
839 (lambda (node) ; not SXML 3.0 aux-list
840 (and (pair? node) (not (eq? (car node) '@)))))
841 ((srl:select-kids
842 (lambda (node)
843 (and (pair? node) (eq? (car node) '@))))
844 elem))))
845 (start-tag
846 (if (eq? method 'xml)
847 (if empty? '("/>") '(">"))
848 (if (or (not empty?)
849 (and (not elem-prefix)
850 (srl:member-ci
851 elem-local
852 srl:void-elements)))
853 '(">")
854 (list "></" (srl:qname->string elem-prefix elem-local) ">"))))
855 (ns-prefix-assig ns-prefix-assig)
856 (namespace-assoc namespace-assoc)
857 (declared-ns-prefixes
858 ; As if element namespace already declared
859 (if elem-decl-required?
860 (cons (cons elem-prefix elem-uri)
861 declared-ns-prefixes)
862 declared-ns-prefixes)))
863 (if
864 (null? attrs) ; attributes scanned
865 (let ((elem-name (srl:qname->string elem-prefix elem-local)))
866 (values
867 (cons "<"
868 (cons elem-name
869 (if
870 elem-decl-required?
871 (cons
872 (srl:namespace-decl->str-lst elem-prefix elem-uri)
873 start-tag)
874 start-tag)))
875 (if empty? #f
876 (list "</" elem-name ">"))
877 ns-prefix-assig
878 namespace-assoc
879 declared-ns-prefixes))
880 (call-with-values
881 (lambda ()
882 (srl:name->qname-components
883 (caar attrs) ; attribute name
884 ns-prefix-assig namespace-assoc declared-ns-prefixes))
885 (lambda (attr-prefix attr-uri attr-local attr-decl-required?)
886 (let ((start-tag
887 (cons
888 (srl:attribute->str-lst
889 attr-prefix attr-local
890 ; TODO: optimize for HTML output method
891 (if (null? (cdar attrs)) ; no attribute value
892 attr-local
893 (cadar attrs))
894 method)
895 start-tag)))
896 (loop
897 (cdr attrs)
898 (if attr-decl-required?
899 (cons (srl:namespace-decl->str-lst attr-prefix attr-uri)
900 start-tag)
901 start-tag)
902 ns-prefix-assig
903 namespace-assoc
904 (if attr-decl-required?
905 (cons (cons attr-prefix attr-uri) declared-ns-prefixes)
906 declared-ns-prefixes))))))))))))
907
908
909 ;==========================================================================
910 ; Recursively walking the tree of SXML elements
911
912 ; indentation ::= (listof string) or #f - a list of whitespace strings
913 ; depending on the node nesting or #f if no indent is required
914 ; space-preserve? ::= #t | #f - whether the subtree inherits the xml:space
915 ; attribute with the value "preserve"
916 ; cdata-section-elements ::= (listof symbol) - list of element names whose
917 ; child nodes are to be output with CDATA section
918 ; text-node-handler :: string -> string - a function that performs a proper
919 ; character escaping for the given node if it is a text node
920 ; TODO: do not insert whitespaces adjacent to HTML %inline elements in HTML
921 ; output method
922 (define (srl:node->nested-str-lst-recursive
923 node method
924 ns-prefix-assig namespace-assoc declared-ns-prefixes
925 indentation space-preserve?
926 cdata-section-elements text-node-handler)
927 (if
928 (not (pair? node)) ; text node
929 (text-node-handler (srl:atomic->string node))
930 (case (car node) ; node name
931 ((*COMMENT*)
932 (srl:comment->str-lst node))
933 ((*PI*)
934 (srl:processing-instruction->str-lst node method))
935 ((&)
936 (srl:shtml-entity->char-data node))
937 ((*DECL*) ; recovering for non-SXML nodes
938 '())
939 (else ; otherwise - an element node
940 (call-with-values
941 (lambda ()
942 (srl:construct-start-end-tags
943 node method
944 ns-prefix-assig namespace-assoc declared-ns-prefixes))
945 (lambda (start-tag end-tag
946 ns-prefix-assig namespace-assoc declared-ns-prefixes)
947 (if
948 (not end-tag) ; empty element => recursion stops
949 start-tag
950 (let ((space-preserve?
951 (srl:update-space-specifier node space-preserve?))
952 (text-node-handler
953 (cond
954 ((memq (car node) cdata-section-elements)
955 srl:string->cdata-section)
956 ((and (eq? method 'html)
957 (srl:member-ci (symbol->string (car node))
958 '("script" "style")))
959 ; No escaping for strings inside these HTML elements
960 (lambda (str) str))
961 (else
962 srl:string->char-data)))
963 (content ((srl:select-kids
964 (lambda (node) ; TODO: support SXML entities
965 (not (and (pair? node)
966 (memq (car node) '(@ @@ *ENTITY*))))))
967 node)))
968 (call-with-values
969 (lambda ()
970 (cond
971 ((or (not indentation)
972 (and (eq? method 'html)
973 (srl:member-ci
974 (symbol->string (car node))
975 '("pre" "script" "style" "textarea"))))
976 ; No indent - on this level and subsequent levels
977 (values #f #f))
978 ((or space-preserve?
979 (srl:mem-pred ; at least a single text node
980 (lambda (node) (not (pair? node)))
981 content))
982 ; No indent on this level, possible indent on nested levels
983 (values #f indentation))
984 (else
985 (values (cons srl:newline indentation)
986 (cons (car indentation) indentation)))))
987 (lambda (indent-here indent4recursive)
988 (if
989 indent-here
990 (append
991 start-tag
992 (map
993 (lambda (kid)
994 (list
995 indent-here
996 (srl:node->nested-str-lst-recursive
997 kid method
998 ns-prefix-assig namespace-assoc declared-ns-prefixes
999 indent4recursive space-preserve?
1000 cdata-section-elements text-node-handler)))
1001 content)
1002 (cons srl:newline
1003 (cons (cdr indentation) end-tag)))
1004 (append
1005 start-tag
1006 (map
1007 (lambda (kid)
1008 (srl:node->nested-str-lst-recursive
1009 kid method
1010 ns-prefix-assig namespace-assoc declared-ns-prefixes
1011 indent4recursive space-preserve?
1012 cdata-section-elements text-node-handler))
1013 content)
1014 end-tag))))))))))))
1015
1016 (define (srl:display-node-out-recursive
1017 node port method
1018 ns-prefix-assig namespace-assoc declared-ns-prefixes
1019 indentation space-preserve?
1020 cdata-section-elements text-node-handler)
1021 (if
1022 (not (pair? node)) ; text node
1023 (display (text-node-handler (srl:atomic->string node)) port)
1024 (case (car node) ; node name
1025 ((*COMMENT*)
1026 (for-each
1027 (lambda (x) (display x port))
1028 (srl:comment->str-lst node)))
1029 ((*PI*)
1030 (for-each
1031 (lambda (x) (display x port))
1032 (srl:processing-instruction->str-lst node method)))
1033 ((&)
1034 (display (srl:shtml-entity->char-data node) port))
1035 ((*DECL*) ; recovering for non-SXML nodes
1036 #f)
1037 (else ; otherwise - an element node
1038 (call-with-values
1039 (lambda ()
1040 (srl:construct-start-end-tags
1041 node method
1042 ns-prefix-assig namespace-assoc declared-ns-prefixes))
1043 (lambda (start-tag end-tag
1044 ns-prefix-assig namespace-assoc declared-ns-prefixes)
1045 (begin
1046 (srl:display-fragments-2nesting start-tag port)
1047 (if
1048 end-tag ; there exists content
1049 (let ((space-preserve?
1050 (srl:update-space-specifier node space-preserve?))
1051 (text-node-handler
1052 (cond
1053 ((memq (car node) cdata-section-elements)
1054 srl:string->cdata-section)
1055 ((and (eq? method 'html)
1056 (srl:member-ci (symbol->string (car node))
1057 '("script" "style")))
1058 ; No escaping for strings inside these HTML elements
1059 (lambda (str) str))
1060 (else
1061 srl:string->char-data)))
1062 (content ((srl:select-kids
1063 (lambda (node) ; TODO: support SXML entities
1064 (not (and (pair? node)
1065 (memq (car node) '(@ @@ *ENTITY*))))))
1066 node)))
1067 (call-with-values
1068 (lambda ()
1069 (cond
1070 ((or (not indentation)
1071 (and (eq? method 'html)
1072 (srl:member-ci
1073 (symbol->string (car node))
1074 '("pre" "script" "style" "textarea"))))
1075 ; No indent - on this level and subsequent levels
1076 (values #f #f))
1077 ((or space-preserve?
1078 (srl:mem-pred ; at least a single text node
1079 (lambda (node) (not (pair? node)))
1080 content))
1081 ; No indent on this level, possible indent on nested levels
1082 (values #f indentation))
1083 (else
1084 (values (cons srl:newline indentation)
1085 (cons (car indentation) indentation)))))
1086 (lambda (indent-here indent4recursive)
1087 (begin
1088 (for-each ; display content
1089 (if
1090 indent-here
1091 (lambda (kid)
1092 (begin
1093 (for-each
1094 (lambda (x) (display x port))
1095 indent-here)
1096 (srl:display-node-out-recursive
1097 kid port method
1098 ns-prefix-assig namespace-assoc declared-ns-prefixes
1099 indent4recursive space-preserve?
1100 cdata-section-elements text-node-handler)))
1101 (lambda (kid)
1102 (srl:display-node-out-recursive
1103 kid port method
1104 ns-prefix-assig namespace-assoc declared-ns-prefixes
1105 indent4recursive space-preserve?
1106 cdata-section-elements text-node-handler)))
1107 content)
1108 (if indent-here
1109 (begin
1110 (display srl:newline port)
1111 (for-each
1112 (lambda (x) (display x port))
1113 (cdr indentation))))
1114 (for-each
1115 (lambda (x) (display x port))
1116 end-tag)))))))))))))
1117
1118 ;-------------------------------------------------
1119 ; Serializing the document node - start of recursion
1120
1121 ; Creates the serialized representation for the XML declaration
1122 ; Returns: (listof string)
1123 ; version ::= string | number
1124 ; standalone ::= 'yes | 'no | 'omit
1125 (define (srl:make-xml-decl version standalone)
1126 (let ((version (if (number? version) (number->string version) version)))
1127 (if (eq? standalone 'omit)
1128 (list "<?xml version='" version "'?>")
1129 (list "<?xml version='" version "' standalone='"
1130 (symbol->string standalone) "'?>"))))
1131
1132 ; omit-xml-declaration? ::= #t | #f
1133 ; standalone ::= 'yes | 'no | 'omit
1134 ; version ::= string | number
1135 (define (srl:top->nested-str-lst doc
1136 cdata-section-elements indent
1137 method ns-prefix-assig
1138 omit-xml-declaration? standalone version)
1139 (let* ((namespace-assoc (srl:ns-assoc-for-top doc))
1140 (ns-prefix-assig
1141 (append
1142 (srl:extract-original-prefix-binding namespace-assoc)
1143 ns-prefix-assig))
1144 (serialized-content
1145 (map
1146 (if
1147 indent ; => output each member from the newline
1148 (let ((indentation (list indent))) ; for nested elements
1149 (lambda (kid)
1150 (list
1151 srl:newline
1152 (srl:node->nested-str-lst-recursive
1153 kid method
1154 ns-prefix-assig namespace-assoc '()
1155 indentation #f
1156 cdata-section-elements srl:string->char-data))))
1157 (lambda (kid)
1158 (srl:node->nested-str-lst-recursive
1159 kid method
1160 ns-prefix-assig namespace-assoc '()
1161 indent #f
1162 cdata-section-elements srl:string->char-data)))
1163 ((srl:select-kids ; document node content
1164 (lambda (node) ; TODO: support SXML entities
1165 (not (and
1166 (pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
1167 doc))))
1168 (if (or (eq? method 'html) omit-xml-declaration?)
1169 (if (and indent (not (null? serialized-content)))
1170 ; Remove the starting newline
1171 ; ATTENTION: beware of `Gambit cadar bug':
1172 ; http://mailman.iro.umontreal.ca/pipermail/gambit-list/
1173 ; 2005-July/000315.html
1174 (cons (cadar serialized-content) (cdr serialized-content))
1175 serialized-content)
1176 (list (srl:make-xml-decl version standalone) serialized-content))))
1177
1178 (define (srl:display-top-out doc port
1179 cdata-section-elements indent
1180 method ns-prefix-assig
1181 omit-xml-declaration? standalone version)
1182 (let ((no-xml-decl? ; no XML declaration was displayed?
1183 (if (not (or (eq? method 'html) omit-xml-declaration?))
1184 (begin
1185 (for-each ; display xml declaration
1186 (lambda (x) (display x port))
1187 (srl:make-xml-decl version standalone))
1188 #f)
1189 #t))
1190 (content ; document node content
1191 ((srl:select-kids
1192 (lambda (node) ; TODO: support SXML entities
1193 (not (and
1194 (pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
1195 doc))
1196 (namespace-assoc (srl:ns-assoc-for-top doc)))
1197 (let ((ns-prefix-assig
1198 (append
1199 (srl:extract-original-prefix-binding namespace-assoc)
1200 ns-prefix-assig)))
1201 (cond
1202 ((null? content) ; generally a rare practical situation
1203 #t) ; nothing more to do
1204 ((and indent no-xml-decl?)
1205 ; We'll not display newline before (car content)
1206 (let ((indentation (list indent))) ; for nested elements
1207 (for-each
1208 (lambda (kid put-newline?)
1209 (begin
1210 (if put-newline?
1211 (display srl:newline port))
1212 (srl:display-node-out-recursive
1213 kid port method
1214 ns-prefix-assig namespace-assoc '()
1215 indentation #f
1216 cdata-section-elements srl:string->char-data)))
1217 content
1218 ; After sequence normalization, content does not contain #f
1219 (cons #f (cdr content)))))
1220 (else
1221 (for-each
1222 (if
1223 indent ; => output each member from the newline
1224 (let ((indentation (list indent))) ; for nested elements
1225 (lambda (kid)
1226 (begin
1227 (display srl:newline port)
1228 (srl:display-node-out-recursive
1229 kid port method
1230 ns-prefix-assig namespace-assoc '()
1231 indentation #f
1232 cdata-section-elements srl:string->char-data))))
1233 (lambda (kid)
1234 (srl:display-node-out-recursive
1235 kid port method
1236 ns-prefix-assig namespace-assoc '()
1237 indent #f
1238 cdata-section-elements srl:string->char-data)))
1239 content))))))
1240
1241
1242 ;==========================================================================
1243 ; Interface
1244
1245 ;-------------------------------------------------
1246 ; Calling the serializer with all the serialization parameters supported
1247 ; and with no overhead of parameters parsing.
1248 ; ATTENTION: As future versions of this library may provide support for
1249 ; additional serialization parameters, the functions `srl:sxml->string' and
1250 ; `srl:display-sxml' specified in this subsections may have a different number
1251 ; of their arguments in the future versions of the library.
1252
1253 ; Returns a string that contains the serialized representation for `sxml-obj'.
1254 ; cdata-section-elements ::= (listof sxml-name)
1255 ; indent ::= #t | #f | whitespace-string
1256 ; method = 'xml | 'html
1257 ; ns-prefix-assign ::= (listof (cons prefix-symbol namespace-uri-string))
1258 ; omit-xml-declaration? ::= #t | #f
1259 ; standalone ::= 'yes | 'no | 'omit
1260 ; version ::= number | string
1261 (define (srl:sxml->string sxml-obj
1262 cdata-section-elements indent
1263 method ns-prefix-assig
1264 omit-xml-declaration? standalone version)
1265 (srl:apply-string-append
1266 (srl:clean-fragments
1267 (srl:top->nested-str-lst (srl:normalize-sequence sxml-obj)
1268 cdata-section-elements
1269 (if (and indent (not (string? indent)))
1270 " " indent)
1271 method ns-prefix-assig
1272 omit-xml-declaration? standalone version))))
1273
1274 ; Writes the serialized representation of the `sxml-obj' to an output port
1275 ; `port'. The result returned by the function is unspecified.
1276 (define (srl:display-sxml sxml-obj port-or-filename
1277 cdata-section-elements indent
1278 method ns-prefix-assig
1279 omit-xml-declaration? standalone version)
1280 (if
1281 (string? port-or-filename) ; a filename?
1282 (let ((out (open-output-file port-or-filename)))
1283 (begin
1284 (srl:display-top-out (srl:normalize-sequence sxml-obj) out
1285 cdata-section-elements
1286 (if (and indent (not (string? indent)))
1287 " " indent)
1288 method ns-prefix-assig
1289 omit-xml-declaration? standalone version)
1290 (display srl:newline out) ; newline at the end of file
1291 (close-output-port out)))
1292 (srl:display-top-out (srl:normalize-sequence sxml-obj) port-or-filename
1293 cdata-section-elements
1294 (if (and indent (not (string? indent))) " " indent)
1295 method ns-prefix-assig
1296 omit-xml-declaration? standalone version)))
1297
1298 ;-------------------------------------------------
1299 ; Generalized serialization procedure, parameterizable with all the
1300 ; serialization params supported by this implementation
1301
1302 ; procedure srl:parameterizable :: SXML-OBJ [PORT] {PARAM}* ->
1303 ; -> STRING|unspecified
1304 ; sxml-obj - an SXML object to serialize
1305 ; param ::= (cons param-name param-value)
1306 ; param-name ::= symbol
1307 ;
1308 ; 1. cdata-section-elements
1309 ; value ::= (listof sxml-elem-name)
1310 ; sxml-elem-name ::= symbol
1311 ;
1312 ; 2. indent
1313 ; value ::= 'yes | #t | 'no | #f | whitespace-string
1314 ;
1315 ; 3. method
1316 ; value ::= 'xml | 'html
1317 ;
1318 ; 4. ns-prefix-assig
1319 ; value ::= (listof (cons prefix namespace-uri))
1320 ; prefix ::= symbol
1321 ; namespace-uri ::= string
1322 ;
1323 ; 5. omit-xml-declaration?
1324 ; value ::= 'yes | #t | 'no | #f
1325 ;
1326 ; 6. standalone
1327 ; value ::= 'yes | #t | 'no | #f | 'omit
1328 ;
1329 ; 7. version
1330 ; value ::= string | number
1331 ;
1332 ; ATTENTION: If a parameter name is unexpected or a parameter value is
1333 ; ill-formed, the parameter is silently ignored. Probably, a warning message
1334 ; in such a case would be more appropriate.
1335 ;
1336 ; Example:
1337 ; (srl:parameterizable
1338 ; '(tag (@ (attr "value")) (nested "text node") (empty))
1339 ; (current-output-port)
1340 ; '(method . xml) ; XML output method is used by default
1341 ; '(indent . "\t") ; use a single tabulation to indent nested elements
1342 ; '(omit-xml-declaration . #f) ; add XML declaration
1343 ; '(standalone . yes) ; denote a standalone XML document
1344 ; '(version . "1.0")) ; XML version
1345 (define (srl:parameterizable sxml-obj . port-or-filename+params)
1346 (call-with-values
1347 (lambda ()
1348 (if (and (not (null? port-or-filename+params))
1349 (or (output-port? (car port-or-filename+params))
1350 (string? (car port-or-filename+params))))
1351 (values (car port-or-filename+params) (cdr port-or-filename+params))
1352 (values #f port-or-filename+params)))
1353 (lambda (port-or-filename params)
1354 (let loop ((params params)
1355 (cdata-section-elements '())
1356 (indent " ")
1357 (method 'xml)
1358 (ns-prefix-assig srl:conventional-ns-prefixes)
1359 (omit-xml-declaration? #t)
1360 (standalone 'omit)
1361 (version "1.0"))
1362 (cond
1363 ((null? params) ; all parameters parsed
1364 (if port-or-filename
1365 (srl:display-sxml sxml-obj port-or-filename
1366 cdata-section-elements indent
1367 method ns-prefix-assig
1368 omit-xml-declaration? standalone version)
1369 (srl:sxml->string sxml-obj
1370 cdata-section-elements indent
1371 method ns-prefix-assig
1372 omit-xml-declaration? standalone version)))
1373 ((or (not (pair? (car params))) ; not a pair or has no param value
1374 (null? (cdar params)))
1375 (loop (cdr params)
1376 cdata-section-elements indent
1377 method ns-prefix-assig
1378 omit-xml-declaration? standalone version))
1379 (else
1380 (let ((prm-value (cdar params)))
1381 (case (caar params)
1382 ((cdata-section-elements)
1383 (loop (cdr params)
1384 (if (list? prm-value) prm-value cdata-section-elements)
1385 indent method ns-prefix-assig
1386 omit-xml-declaration? standalone version))
1387 ((indent)
1388 (loop (cdr params)
1389 cdata-section-elements
1390 (cond
1391 ((boolean? prm-value)
1392 (if prm-value " " prm-value))
1393 ((string? prm-value) prm-value)
1394 ((eq? prm-value 'yes) " ")
1395 ((eq? prm-value 'no) #f)
1396 (else indent))
1397 method ns-prefix-assig
1398 omit-xml-declaration? standalone version))
1399 ((method)
1400 (loop (cdr params)
1401 cdata-section-elements indent
1402 (if (or (eq? prm-value 'xml) (eq? prm-value 'html))
1403 prm-value method)
1404 ns-prefix-assig
1405 omit-xml-declaration? standalone version))
1406 ((ns-prefix-assig)
1407 (loop (cdr params)
1408 cdata-section-elements indent method
1409 (if (and (list? prm-value)
1410 (not (srl:mem-pred ; no non-pair members
1411 (lambda (x) (not (pair? x)))
1412 prm-value)))
1413 (append prm-value ns-prefix-assig)
1414 ns-prefix-assig)
1415 omit-xml-declaration? standalone version))
1416 ((omit-xml-declaration)
1417 (loop (cdr params)
1418 cdata-section-elements indent
1419 method ns-prefix-assig
1420 (cond
1421 ((boolean? prm-value) prm-value)
1422 ((eq? prm-value 'yes) #t)
1423 ((eq? prm-value 'no) #f)
1424 (else indent))
1425 standalone version))
1426 ((standalone)
1427 (loop (cdr params)
1428 cdata-section-elements indent
1429 method ns-prefix-assig omit-xml-declaration?
1430 (cond
1431 ((memv prm-value '(yes no omit))
1432 prm-value)
1433 ((boolean? prm-value)
1434 (if prm-value 'yes 'no))
1435 (else standalone))
1436 version))
1437 ((version)
1438 (loop (cdr params)
1439 cdata-section-elements indent
1440 method ns-prefix-assig
1441 omit-xml-declaration? standalone
1442 (if (or (string? prm-value) (number? prm-value))
1443 prm-value version)))
1444 (else
1445 (loop (cdr params)
1446 cdata-section-elements indent
1447 method ns-prefix-assig
1448 omit-xml-declaration? standalone version))))))))))
1449
1450 ;-------------------------------------------------
1451 ; High-level functions for popular serialization use-cases
1452 ; These functions use only a subset of serializer functionality, however, this
1453 ; subset seems sufficient for most practical purposes.
1454
1455 ; procedure srl:sxml->xml :: SXML-OBJ [PORT-OR-FILENAME] -> STRING|unspecified
1456 ;
1457 ; Serializes the `sxml-obj' into XML, with indentation to facilitate
1458 ; readability by a human.
1459 ;
1460 ; sxml-obj - an SXML object (a node or a nodeset) to be serialized
1461 ; port-or-filename - an output port or an output file name, an optional
1462 ; argument
1463 ; If `port-or-filename' is not supplied, the functions return a string that
1464 ; contains the serialized representation of the `sxml-obj'.
1465 ; If `port-or-filename' is supplied and is a port, the functions write the
1466 ; serialized representation of `sxml-obj' to this port and return an
1467 ; unspecified result.
1468 ; If `port-or-filename' is supplied and is a string, this string is treated as
1469 ; an output filename, the serialized representation of `sxml-obj' is written to
1470 ; that filename and an unspecified result is returned. If a file with the given
1471 ; name already exists, the effect is unspecified.
1472 (define (srl:sxml->xml sxml-obj . port-or-filename)
1473 (if (null? port-or-filename)
1474 (srl:sxml->string sxml-obj '() #t 'xml
1475 srl:conventional-ns-prefixes #t 'omit "1.0")
1476 (srl:display-sxml sxml-obj (car port-or-filename) '() #t 'xml
1477 srl:conventional-ns-prefixes #t 'omit "1.0")))
1478
1479 ; procedure srl:sxml->xml-noindent :: SXML-OBJ [PORT-OR-FILENAME] ->
1480 ; -> STRING|unspecified
1481 ;
1482 ; Serializes the `sxml-obj' into XML, without indentation.
1483 (define (srl:sxml->xml-noindent sxml-obj . port-or-filename)
1484 (if (null? port-or-filename)
1485 (srl:sxml->string sxml-obj '() #f 'xml
1486 srl:conventional-ns-prefixes #t 'omit "1.0")
1487 (srl:display-sxml sxml-obj (car port-or-filename) '() #f 'xml
1488 srl:conventional-ns-prefixes #t 'omit "1.0")))
1489
1490 ; procedure srl:sxml->html :: SXML-OBJ [PORT-OR-FILENAME] -> STRING|unspecified
1491 ;
1492 ; Serializes the `sxml-obj' into HTML, with indentation to facilitate
1493 ; readability by a human.
1494 ;
1495 ; sxml-obj - an SXML object (a node or a nodeset) to be serialized
1496 ; port-or-filename - an output port or an output file name, an optional
1497 ; argument
1498 ; If `port-or-filename' is not supplied, the functions return a string that
1499 ; contains the serialized representation of the `sxml-obj'.
1500 ; If `port-or-filename' is supplied and is a port, the functions write the
1501 ; serialized representation of `sxml-obj' to this port and return an
1502 ; unspecified result.
1503 ; If `port-or-filename' is supplied and is a string, this string is treated as
1504 ; an output filename, the serialized representation of `sxml-obj' is written to
1505 ; that filename and an unspecified result is returned. If a file with the given
1506 ; name already exists, the effect is unspecified.
1507 (define (srl:sxml->html sxml-obj . port-or-filename)
1508 (if (null? port-or-filename)
1509 (srl:sxml->string sxml-obj '() #t 'html '() #t 'omit "4.0")
1510 (srl:display-sxml sxml-obj (car port-or-filename)
1511 '() #t 'html '() #t 'omit "4.0")))
1512
1513 ; procedure srl:sxml->html-noindent :: SXML-OBJ [PORT-OR-FILENAME] ->
1514 ; -> STRING|unspecified
1515 ;
1516 ; Serializes the `sxml-obj' into HTML, without indentation.
1517 (define (srl:sxml->html-noindent sxml-obj . port-or-filename)
1518 (if (null? port-or-filename)
1519 (srl:sxml->string sxml-obj '() #f 'html '() #t 'omit "4.0")
1520 (srl:display-sxml sxml-obj (car port-or-filename)
1521 '() #f 'html '() #t 'omit "4.0")))