SSAX.scm 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236
  1. ; Functional XML parsing framework: SAX/DOM and SXML parsers
  2. ; with support for XML Namespaces and validation
  3. ;
  4. ; This is a package of low-to-high level lexing and parsing procedures
  5. ; that can be combined to yield a SAX, a DOM, a validating parsers, or
  6. ; a parser intended for a particular document type. The procedures in
  7. ; the package can be used separately to tokenize or parse various
  8. ; pieces of XML documents. The package supports XML Namespaces,
  9. ; internal and external parsed entities, user-controlled handling of
  10. ; whitespace, and validation. This module therefore is intended to be
  11. ; a framework, a set of "Lego blocks" you can use to build a parser
  12. ; following any discipline and performing validation to any degree. As
  13. ; an example of the parser construction, this file includes a
  14. ; semi-validating SXML parser.
  15. ; The present XML framework has a "sequential" feel of SAX yet a
  16. ; "functional style" of DOM. Like a SAX parser, the framework scans
  17. ; the document only once and permits incremental processing. An
  18. ; application that handles document elements in order can run as
  19. ; efficiently as possible. _Unlike_ a SAX parser, the framework does
  20. ; not require an application register stateful callbacks and surrender
  21. ; control to the parser. Rather, it is the application that can drive
  22. ; the framework -- calling its functions to get the current lexical or
  23. ; syntax element. These functions do not maintain or mutate any state
  24. ; save the input port. Therefore, the framework permits parsing of XML
  25. ; in a pure functional style, with the input port being a monad (or a
  26. ; linear, read-once parameter).
  27. ; Besides the PORT, there is another monad -- SEED. Most of the
  28. ; middle- and high-level parsers are single-threaded through the
  29. ; seed. The functions of this framework do not process or affect the
  30. ; SEED in any way: they simply pass it around as an instance of an
  31. ; opaque datatype. User functions, on the other hand, can use the
  32. ; seed to maintain user's state, to accumulate parsing results, etc. A
  33. ; user can freely mix his own functions with those of the
  34. ; framework. On the other hand, the user may wish to instantiate a
  35. ; high-level parser: ssax:make-elem-parser or ssax:make-parser. In
  36. ; the latter case, the user must provide functions of specific
  37. ; signatures, which are called at predictable moments during the
  38. ; parsing: to handle character data, element data, or processing
  39. ; instructions (PI). The functions are always given the SEED, among
  40. ; other parameters, and must return the new SEED.
  41. ; From a functional point of view, XML parsing is a combined
  42. ; pre-post-order traversal of a "tree" that is the XML document
  43. ; itself. This down-and-up traversal tells the user about an element
  44. ; when its start tag is encountered. The user is notified about the
  45. ; element once more, after all element's children have been
  46. ; handled. The process of XML parsing therefore is a fold over the
  47. ; raw XML document. Unlike a fold over trees defined in [1], the
  48. ; parser is necessarily single-threaded -- obviously as elements
  49. ; in a text XML document are laid down sequentially. The parser
  50. ; therefore is a tree fold that has been transformed to accept an
  51. ; accumulating parameter [1,2].
  52. ; Formally, the denotational semantics of the parser can be expressed
  53. ; as
  54. ; parser:: (Start-tag -> Seed -> Seed) ->
  55. ; (Start-tag -> Seed -> Seed -> Seed) ->
  56. ; (Char-Data -> Seed -> Seed) ->
  57. ; XML-text-fragment -> Seed -> Seed
  58. ; parser fdown fup fchar "<elem attrs> content </elem>" seed
  59. ; = fup "<elem attrs>" seed
  60. ; (parser fdown fup fchar "content" (fdown "<elem attrs>" seed))
  61. ;
  62. ; parser fdown fup fchar "char-data content" seed
  63. ; = parser fdown fup fchar "content" (fchar "char-data" seed)
  64. ;
  65. ; parser fdown fup fchar "elem-content content" seed
  66. ; = parser fdown fup fchar "content" (
  67. ; parser fdown fup fchar "elem-content" seed)
  68. ; Compare the last two equations with the left fold
  69. ; fold-left kons elem:list seed = fold-left kons list (kons elem seed)
  70. ; The real parser created my ssax:make-parser is slightly more complicated,
  71. ; to account for processing instructions, entity references, namespaces,
  72. ; processing of document type declaration, etc.
  73. ; The XML standard document referred to in this module is
  74. ; http://www.w3.org/TR/1998/REC-xml-19980210.html
  75. ;
  76. ; The present file also defines a procedure that parses the text of an
  77. ; XML document or of a separate element into SXML, an
  78. ; S-expression-based model of an XML Information Set. SXML is also an
  79. ; Abstract Syntax Tree of an XML document. SXML is similar
  80. ; but not identical to DOM; SXML is particularly suitable for
  81. ; Scheme-based XML/HTML authoring, SXPath queries, and tree
  82. ; transformations. See SXML.html for more details.
  83. ; SXML is a term implementation of evaluation of the XML document [3].
  84. ; The other implementation is context-passing.
  85. ; The present frameworks fully supports the XML Namespaces Recommendation:
  86. ; http://www.w3.org/TR/REC-xml-names/
  87. ; Other links:
  88. ; [1] Jeremy Gibbons, Geraint Jones, "The Under-appreciated Unfold,"
  89. ; Proc. ICFP'98, 1998, pp. 273-279.
  90. ; [2] Richard S. Bird, The promotion and accumulation strategies in
  91. ; transformational programming, ACM Trans. Progr. Lang. Systems,
  92. ; 6(4):487-504, October 1984.
  93. ; [3] Ralf Hinze, "Deriving Backtracking Monad Transformers,"
  94. ; Functional Pearl. Proc ICFP'00, pp. 186-197.
  95. ; IMPORT
  96. ; parser-error ssax:warn, see Handling of errors, below
  97. ; functions declared in files util.scm, input-parse.scm and look-for-str.scm
  98. ; char-encoding.scm for various platform-specific character-encoding functions.
  99. ; From SRFI-13: string-concatenate/shared and string-concatenate-reverse/shared
  100. ; If a particular implementation lacks SRFI-13 support, please
  101. ; include the file srfi-13-local.scm
  102. ; Handling of errors
  103. ; This package relies on a function parser-error, which must be defined
  104. ; by a user of the package. The function has the following signature:
  105. ; parser-error PORT MESSAGE SPECIALISING-MSG*
  106. ; Many procedures of this package call 'parser-error' whenever a
  107. ; parsing, well-formedness or validation error is encountered. The
  108. ; first argument is a port, which typically points to the offending
  109. ; character or its neighborhood. Most of the Scheme systems let the
  110. ; user query a PORT for the current position. The MESSAGE argument
  111. ; indicates a failed XML production or a failed XML constraint. The
  112. ; latter is referred to by its anchor name in the XML Recommendation
  113. ; or XML Namespaces Recommendation. The parsing library (e.g.,
  114. ; next-token, assert-curr-char) invoke 'parser-error' as well, in
  115. ; exactly the same way. See input-parse.scm for more details.
  116. ; See
  117. ; http://pair.com/lisovsky/download/parse-error.scm
  118. ; for an excellent example of such a redefined parser-error function.
  119. ;
  120. ; In addition, the present code invokes a function ssax:warn
  121. ; ssax:warn PORT MESSAGE SPECIALISING-MSG*
  122. ; to notify the user about warnings that are NOT errors but still
  123. ; may alert the user.
  124. ;
  125. ; Again, parser-error and ssax:warn are supposed to be defined by the
  126. ; user. However, if a run-test macro below is set to include
  127. ; self-tests, this present code does provide the definitions for these
  128. ; functions to allow tests to run.
  129. ; Misc notes
  130. ; It seems it is highly desirable to separate tests out in a dedicated
  131. ; file.
  132. ;
  133. ; Jim Bender wrote on Mon, 9 Sep 2002 20:03:42 EDT on the SSAX-SXML
  134. ; mailing list (message A fine-grained "lego")
  135. ; The task was to record precise source location information, as PLT
  136. ; does with its current XML parser. That parser records the start and
  137. ; end location (filepos, line#, column#) for pi, elements, attributes,
  138. ; chuncks of "pcdata".
  139. ; As suggested above, though, in some cases I needed to be able force
  140. ; open an interface that did not yet exist. For instance, I added an
  141. ; "end-char-data-hook", which would be called at the end of char-data
  142. ; fragment. This returns a function of type (seed -> seed) which is
  143. ; invoked on the current seed only if read-char-data has indeed reached
  144. ; the end of a block of char data (after reading a new token.
  145. ; But the deepest interface that I needed to expose was that of reading
  146. ; attributes. In the official distribution, this is not even a separate
  147. ; function. Instead, it is embedded within SSAX:read-attributes. This
  148. ; required some small re-structuring as well.
  149. ; This definitely will not be to everyone's taste (nor needed by most).
  150. ; Certainly, the existing make-parser interface addresses most custom
  151. ; needs. And likely 80-90 lines of a "link specification" to create a
  152. ; parser from many tiny little lego blocks may please only a few, while
  153. ; appalling others.
  154. ; The code is available at http://celtic.benderweb.net/ssax-lego.plt or
  155. ; http://celtic.benderweb.net/ssax-lego.tar.gz
  156. ; In the examples directory, I provide:
  157. ; - a unit version of the make-parser interface,
  158. ; - a simple SXML parser using that interface,
  159. ; - an SXML parser which directly uses the "new lego",
  160. ; - a pseudo-SXML parser, which records source location information
  161. ; - and lastly a parser which returns the structures used in PLT's xml
  162. ; collection, with source location information
  163. ; $Id: SSAX.scm,v 5.1 2004/07/07 16:02:30 sperber Exp $
  164. ;^^^^^^^^^
  165. ; See the Makefile in the ../tests directory
  166. ; (in particular, the rule vSSAX) for an example of how
  167. ; to run this code on various Scheme systems.
  168. ; See SSAX examples for many samples of using this code,
  169. ; again, on a variety of Scheme systems.
  170. ; See http://ssax.sf.net/
  171. ; The following macro runs built-in test cases -- or does not run,
  172. ; depending on which of the two cases below you commented out
  173. ; Case 1: no tests:
  174. ;(define-macro run-test (lambda body '(begin #f)))
  175. ;(define-syntax run-test (syntax-rules () ((run-test . args) (begin #f))))
  176. ; Case 2: with tests.
  177. ; The following macro could've been defined just as
  178. ; (define-macro run-test (lambda body `(begin (display "\n-->Test\n") ,@body)))
  179. ;
  180. ; Instead, it's more involved, to make up for case-insensitivity of
  181. ; symbols on some Scheme systems. In Gambit, symbols are case
  182. ; sensitive: (eq? 'A 'a) is #f and (eq? 'Aa (string->symbol "Aa")) is
  183. ; #t. On some systems, symbols are case-insensitive and just the
  184. ; opposite is true. Therefore, we introduce a notation '"ASymbol" (a
  185. ; quoted string) that stands for a case-_sensitive_ ASymbol -- on any
  186. ; R5RS Scheme system. This notation is valid only within the body of
  187. ; run-test.
  188. ; The notation is implemented by scanning the run-test's
  189. ; body and replacing every occurrence of (quote "str") with the result
  190. ; of (string->symbol "str"). We can do such a replacement at macro-expand
  191. ; time (rather than at run time).
  192. ; Here's the previous version of run-test, implemented as a low-level
  193. ; macro.
  194. ; (define-macro run-test
  195. ; (lambda body
  196. ; (define (re-write body)
  197. ; (cond
  198. ; ((vector? body)
  199. ; (list->vector (re-write (vector->list body))))
  200. ; ((not (pair? body)) body)
  201. ; ((and (eq? 'quote (car body)) (pair? (cdr body))
  202. ; (string? (cadr body)))
  203. ; (string->symbol (cadr body)))
  204. ; (else (cons (re-write (car body)) (re-write (cdr body))))))
  205. ; (cons 'begin (re-write body))))
  206. ;
  207. ; For portability, it is re-written as syntax-rules. The syntax-rules
  208. ; version is less powerful: for example, it can't handle
  209. ; (case x (('"Foo") (do-on-Foo))) whereas the low-level macro
  210. ; could correctly place a case-sensitive symbol at the right place.
  211. ; We also do not scan vectors (because we don't use them here).
  212. ; Twice-deep quasiquotes aren't handled either.
  213. ; Still, the syntax-rules version satisfies our immediate needs.
  214. ; Incidentally, I originally didn't believe that the macro below
  215. ; was at all possible.
  216. ;
  217. ; The macro is written in a continuation-passing style. A continuation
  218. ; typically has the following structure: (k-head ! . args)
  219. ; When the continuation is invoked, we expand into
  220. ; (k-head <computed-result> . arg). That is, the dedicated symbol !
  221. ; is the placeholder for the result.
  222. ;
  223. ; It seems that the most modular way to write the run-test macro would
  224. ; be the following
  225. ;
  226. ; (define-syntax run-test
  227. ; (syntax-rules ()
  228. ; ((run-test . ?body)
  229. ; (letrec-syntax
  230. ; ((scan-exp ; (scan-exp body k)
  231. ; (syntax-rules (quote quasiquote !)
  232. ; ((scan-exp (quote (hd . tl)) k)
  233. ; (scan-lit-lst (hd . tl) (do-wrap ! quasiquote k)))
  234. ; ((scan-exp (quote x) (k-head ! . args))
  235. ; (k-head
  236. ; (if (string? (quote x)) (string->symbol (quote x)) (quote x))
  237. ; . args))
  238. ; ((scan-exp (hd . tl) k)
  239. ; (scan-exp hd (do-tl ! scan-exp tl k)))
  240. ; ((scan-exp x (k-head ! . args))
  241. ; (k-head x . args))))
  242. ; (do-tl
  243. ; (syntax-rules (!)
  244. ; ((do-tl processed-hd fn () (k-head ! . args))
  245. ; (k-head (processed-hd) . args))
  246. ; ((do-tl processed-hd fn old-tl k)
  247. ; (fn old-tl (do-cons ! processed-hd k)))))
  248. ; ...
  249. ; (do-finish
  250. ; (syntax-rules ()
  251. ; ((do-finish (new-body)) new-body)
  252. ; ((do-finish new-body) (begin . new-body))))
  253. ; ...
  254. ; (scan-exp ?body (do-finish !))
  255. ; ))))
  256. ;
  257. ; Alas, that doesn't work on all systems. We hit yet another dark
  258. ; corner of the R5RS macros. The reason is that run-test is used in
  259. ; the code below to introduce definitions. For example:
  260. ; (run-test
  261. ; (define (ssax:warn port msg . other-msg)
  262. ; (apply cerr (cons* nl "Warning: " msg other-msg)))
  263. ; )
  264. ; This code expands to
  265. ; (begin
  266. ; (define (ssax:warn port msg . other-msg) ...))
  267. ; so the definition gets spliced in into the top level. Right?
  268. ; Well, On Petite Chez Scheme it is so. However, many other systems
  269. ; don't like this approach. The reason is that the invocation of
  270. ; (run-test (define (ssax:warn port msg . other-msg) ...))
  271. ; first expands into
  272. ; (letrec-syntax (...)
  273. ; (scan-exp ((define (ssax:warn port msg . other-msg) ...)) ...))
  274. ; because of the presence of (letrec-syntax ...), the begin form that
  275. ; is generated eventually is no longer at the top level! The begin
  276. ; form in Scheme is an overloading of two distinct forms: top-level
  277. ; begin and the other begin. The forms have different rules: for example,
  278. ; (begin (define x 1)) is OK for a top-level begin but not OK for
  279. ; the other begin. Some Scheme systems see the that the macro
  280. ; (run-test ...) expands into (letrec-syntax ...) and decide right there
  281. ; that any further (begin ...) forms are NOT top-level begin forms.
  282. ; The only way out is to make sure all our macros are top-level.
  283. ; The best approach <sigh> seems to be to make run-test one huge
  284. ; top-level macro.
  285. (define-syntax run-test
  286. (syntax-rules (define)
  287. ((run-test "scan-exp" (define vars body))
  288. (define vars (run-test "scan-exp" body)))
  289. ((run-test "scan-exp" ?body)
  290. (letrec-syntax
  291. ((scan-exp ; (scan-exp body k)
  292. (syntax-rules (quote quasiquote !)
  293. ((scan-exp '() (k-head ! . args))
  294. (k-head '() . args))
  295. ((scan-exp (quote (hd . tl)) k)
  296. (scan-lit-lst (hd . tl) (do-wrap ! quasiquote k)))
  297. ((scan-exp (quasiquote (hd . tl)) k)
  298. (scan-lit-lst (hd . tl) (do-wrap ! quasiquote k)))
  299. ((scan-exp (quote x) (k-head ! . args))
  300. (k-head
  301. (if (string? (quote x)) (string->symbol (quote x)) (quote x))
  302. . args))
  303. ((scan-exp (hd . tl) k)
  304. (scan-exp hd (do-tl ! scan-exp tl k)))
  305. ((scan-exp x (k-head ! . args))
  306. (k-head x . args))))
  307. (do-tl
  308. (syntax-rules (!)
  309. ((do-tl processed-hd fn () (k-head ! . args))
  310. (k-head (processed-hd) . args))
  311. ((do-tl processed-hd fn old-tl k)
  312. (fn old-tl (do-cons ! processed-hd k)))))
  313. (do-cons
  314. (syntax-rules (!)
  315. ((do-cons processed-tl processed-hd (k-head ! . args))
  316. (k-head (processed-hd . processed-tl) . args))))
  317. (do-wrap
  318. (syntax-rules (!)
  319. ((do-wrap val fn (k-head ! . args))
  320. (k-head (fn val) . args))))
  321. (do-finish
  322. (syntax-rules ()
  323. ((do-finish new-body) new-body)))
  324. (scan-lit-lst ; scan literal list
  325. (syntax-rules (quote unquote unquote-splicing !)
  326. ((scan-lit-lst '() (k-head ! . args))
  327. (k-head '() . args))
  328. ((scan-lit-lst (quote (hd . tl)) k)
  329. (do-tl quote scan-lit-lst ((hd . tl)) k))
  330. ((scan-lit-lst (unquote x) k)
  331. (scan-exp x (do-wrap ! unquote k)))
  332. ((scan-lit-lst (unquote-splicing x) k)
  333. (scan-exp x (do-wrap ! unquote-splicing k)))
  334. ((scan-lit-lst (quote x) (k-head ! . args))
  335. (k-head
  336. ,(if (string? (quote x)) (string->symbol (quote x)) (quote x))
  337. . args))
  338. ((scan-lit-lst (hd . tl) k)
  339. (scan-lit-lst hd (do-tl ! scan-lit-lst tl k)))
  340. ((scan-lit-lst x (k-head ! . args))
  341. (k-head x . args))))
  342. )
  343. (scan-exp ?body (do-finish !))))
  344. ((run-test body ...)
  345. (begin
  346. (run-test "scan-exp" body) ...))
  347. ))
  348. ;========================================================================
  349. ; Data Types
  350. ; TAG-KIND
  351. ; a symbol 'START, 'END, 'PI, 'DECL, 'COMMENT, 'CDSECT
  352. ; or 'ENTITY-REF that identifies a markup token
  353. ; UNRES-NAME
  354. ; a name (called GI in the XML Recommendation) as given in an xml
  355. ; document for a markup token: start-tag, PI target, attribute name.
  356. ; If a GI is an NCName, UNRES-NAME is this NCName converted into
  357. ; a Scheme symbol. If a GI is a QName, UNRES-NAME is a pair of
  358. ; symbols: (PREFIX . LOCALPART)
  359. ; RES-NAME
  360. ; An expanded name, a resolved version of an UNRES-NAME.
  361. ; For an element or an attribute name with a non-empty namespace URI,
  362. ; RES-NAME is a pair of symbols, (URI-SYMB . LOCALPART).
  363. ; Otherwise, it's a single symbol.
  364. ; ELEM-CONTENT-MODEL
  365. ; A symbol:
  366. ; ANY - anything goes, expect an END tag.
  367. ; EMPTY-TAG - no content, and no END-tag is coming
  368. ; EMPTY - no content, expect the END-tag as the next token
  369. ; PCDATA - expect character data only, and no children elements
  370. ; MIXED
  371. ; ELEM-CONTENT
  372. ; URI-SYMB
  373. ; A symbol representing a namespace URI -- or other symbol chosen
  374. ; by the user to represent URI. In the former case,
  375. ; URI-SYMB is created by %-quoting of bad URI characters and
  376. ; converting the resulting string into a symbol.
  377. ; NAMESPACES
  378. ; A list representing namespaces in effect. An element of the list
  379. ; has one of the following forms:
  380. ; (PREFIX URI-SYMB . URI-SYMB) or
  381. ; (PREFIX USER-PREFIX . URI-SYMB)
  382. ; USER-PREFIX is a symbol chosen by the user
  383. ; to represent the URI.
  384. ; (#f USER-PREFIX . URI-SYMB)
  385. ; Specification of the user-chosen prefix and a URI-SYMBOL.
  386. ; (*DEFAULT* USER-PREFIX . URI-SYMB)
  387. ; Declaration of the default namespace
  388. ; (*DEFAULT* #f . #f)
  389. ; Un-declaration of the default namespace. This notation
  390. ; represents overriding of the previous declaration
  391. ; A NAMESPACES list may contain several elements for the same PREFIX.
  392. ; The one closest to the beginning of the list takes effect.
  393. ; ATTLIST
  394. ; An ordered collection of (NAME . VALUE) pairs, where NAME is
  395. ; a RES-NAME or an UNRES-NAME. The collection is an ADT
  396. ; STR-HANDLER
  397. ; A procedure of three arguments: STRING1 STRING2 SEED
  398. ; returning a new SEED
  399. ; The procedure is supposed to handle a chunk of character data
  400. ; STRING1 followed by a chunk of character data STRING2.
  401. ; STRING2 is a short string, often "\n" and even ""
  402. ; ENTITIES
  403. ; An assoc list of pairs:
  404. ; (named-entity-name . named-entity-body)
  405. ; where named-entity-name is a symbol under which the entity was
  406. ; declared, named-entity-body is either a string, or
  407. ; (for an external entity) a thunk that will return an
  408. ; input port (from which the entity can be read).
  409. ; named-entity-body may also be #f. This is an indication that a
  410. ; named-entity-name is currently being expanded. A reference to
  411. ; this named-entity-name will be an error: violation of the
  412. ; WFC nonrecursion.
  413. ;
  414. ; As an extension to the original SSAX, Guile allows a
  415. ; named-entity-name of *DEFAULT* to indicate a fallback procedure,
  416. ; called as (FALLBACK PORT NAME). The procedure should return a
  417. ; string.
  418. ; XML-TOKEN -- a record
  419. ; In Gambit, you can use the following declaration:
  420. ; (define-structure xml-token kind head)
  421. ; The following declaration is "standard" as it follows SRFI-9:
  422. ;;(define-record-type xml-token (make-xml-token kind head) xml-token?
  423. ;; (kind xml-token-kind)
  424. ;; (head xml-token-head) )
  425. ; No field mutators are declared as SSAX is a pure functional parser
  426. ;
  427. ; But to make the code more portable, we define xml-token simply as
  428. ; a pair. It suffices for us. Furthermore, xml-token-kind and xml-token-head
  429. ; can be defined as simple procedures. However, they are declared as
  430. ; macros below for efficiency.
  431. (define (make-xml-token kind head) (cons kind head))
  432. (define xml-token? pair?)
  433. (define-syntax xml-token-kind
  434. (syntax-rules () ((xml-token-kind token) (car token))))
  435. (define-syntax xml-token-head
  436. (syntax-rules () ((xml-token-head token) (cdr token))))
  437. ; (define-macro xml-token-kind (lambda (token) `(car ,token)))
  438. ; (define-macro xml-token-head (lambda (token) `(cdr ,token)))
  439. ; This record represents a markup, which is, according to the XML
  440. ; Recommendation, "takes the form of start-tags, end-tags, empty-element tags,
  441. ; entity references, character references, comments, CDATA section delimiters,
  442. ; document type declarations, and processing instructions."
  443. ;
  444. ; kind -- a TAG-KIND
  445. ; head -- an UNRES-NAME. For xml-tokens of kinds 'COMMENT and
  446. ; 'CDSECT, the head is #f
  447. ;
  448. ; For example,
  449. ; <P> => kind='START, head='P
  450. ; </P> => kind='END, head='P
  451. ; <BR/> => kind='EMPTY-EL, head='BR
  452. ; <!DOCTYPE OMF ...> => kind='DECL, head='DOCTYPE
  453. ; <?xml version="1.0"?> => kind='PI, head='xml
  454. ; &my-ent; => kind = 'ENTITY-REF, head='my-ent
  455. ;
  456. ; Character references are not represented by xml-tokens as these references
  457. ; are transparently resolved into the corresponding characters.
  458. ;
  459. ; XML-DECL -- a record
  460. ; The following is Gambit-specific, see below for a portable declaration
  461. ;(define-structure xml-decl elems entities notations)
  462. ; The record represents a datatype of an XML document: the list of
  463. ; declared elements and their attributes, declared notations, list of
  464. ; replacement strings or loading procedures for parsed general
  465. ; entities, etc. Normally an xml-decl record is created from a DTD or
  466. ; an XML Schema, although it can be created and filled in in many other
  467. ; ways (e.g., loaded from a file).
  468. ;
  469. ; elems: an (assoc) list of decl-elem or #f. The latter instructs
  470. ; the parser to do no validation of elements and attributes.
  471. ;
  472. ; decl-elem: declaration of one element:
  473. ; (elem-name elem-content decl-attrs)
  474. ; elem-name is an UNRES-NAME for the element.
  475. ; elem-content is an ELEM-CONTENT-MODEL.
  476. ; decl-attrs is an ATTLIST, of (ATTR-NAME . VALUE) associations
  477. ; !!!This element can declare a user procedure to handle parsing of an
  478. ; element (e.g., to do a custom validation, or to build a hash of
  479. ; IDs as they're encountered).
  480. ;
  481. ; decl-attr: an element of an ATTLIST, declaration of one attribute
  482. ; (attr-name content-type use-type default-value)
  483. ; attr-name is an UNRES-NAME for the declared attribute
  484. ; content-type is a symbol: CDATA, NMTOKEN, NMTOKENS, ...
  485. ; or a list of strings for the enumerated type.
  486. ; use-type is a symbol: REQUIRED, IMPLIED, FIXED
  487. ; default-value is a string for the default value, or #f if not given.
  488. ;
  489. ;
  490. ; see a function make-empty-xml-decl to make a XML declaration entry
  491. ; suitable for a non-validating parsing.
  492. ;-------------------------
  493. ; Utilities
  494. ; ssax:warn PORT MESSAGE SPECIALISING-MSG*
  495. ; to notify the user about warnings that are NOT errors but still
  496. ; may alert the user.
  497. ; Result is unspecified.
  498. ; We need to define the function to allow the self-tests to run.
  499. ; Normally the definition of ssax:warn is to be provided by the user.
  500. (run-test
  501. (define (ssax:warn port msg . other-msg)
  502. (apply cerr (cons* nl "Warning: " msg other-msg)))
  503. )
  504. ; parser-error PORT MESSAGE SPECIALISING-MSG*
  505. ; to let the user know of a syntax error or a violation of a
  506. ; well-formedness or validation constraint.
  507. ; Result is unspecified.
  508. ; We need to define the function to allow the self-tests to run.
  509. ; Normally the definition of parser-error is to be provided by the user.
  510. (run-test
  511. (define (parser-error port msg . specializing-msgs)
  512. (apply error (cons msg specializing-msgs)))
  513. )
  514. ; The following is a function that is often used in validation tests,
  515. ; to make sure that the computed result matches the expected one.
  516. ; This function is a standard equal? predicate with one exception.
  517. ; On Scheme systems where (string->symbol "A") and a symbol A
  518. ; are the same, equal_? is precisely equal?
  519. ; On other Scheme systems, we compare symbols disregarding their case.
  520. ; Since this function is used only in tests, we don't have to
  521. ; strive to make it efficient.
  522. (run-test
  523. (define (equal_? e1 e2)
  524. (if (eq? 'A (string->symbol "A")) (equal? e1 e2)
  525. (cond
  526. ((symbol? e1)
  527. (and (symbol? e2)
  528. (string-ci=? (symbol->string e1) (symbol->string e2))))
  529. ((pair? e1)
  530. (and (pair? e2)
  531. (equal_? (car e1) (car e2)) (equal_? (cdr e1) (cdr e2))))
  532. ((vector? e1)
  533. (and (vector? e2) (equal_? (vector->list e1) (vector->list e2))))
  534. (else
  535. (equal? e1 e2)))))
  536. )
  537. ; The following function, which is often used in validation tests,
  538. ; lets us conveniently enter newline, CR and tab characters in a character
  539. ; string.
  540. ; unesc-string: ESC-STRING -> STRING
  541. ; where ESC-STRING is a character string that may contain
  542. ; %n -- for #\newline
  543. ; %r -- for #\return
  544. ; %t -- for #\tab
  545. ; %% -- for #\%
  546. ;
  547. ; The result of unesc-string is a character string with all %-combinations
  548. ; above replaced with their character equivalents
  549. (run-test
  550. (define (unesc-string str)
  551. (call-with-input-string str
  552. (lambda (port)
  553. (let loop ((frags '()))
  554. (let* ((token (next-token '() '(#\% *eof*) "unesc-string" port))
  555. (cterm (read-char port))
  556. (frags (cons token frags)))
  557. (if (eof-object? cterm) (string-concatenate-reverse/shared frags)
  558. (let ((cchar (read-char port))) ; char after #\%
  559. (if (eof-object? cchar)
  560. (error "unexpected EOF after reading % in unesc-string:" str)
  561. (loop
  562. (cons
  563. (case cchar
  564. ((#\n) (string #\newline))
  565. ((#\r) (string char-return))
  566. ((#\t) (string char-tab))
  567. ((#\%) "%")
  568. (else (error "bad %-char in unesc-string:" cchar)))
  569. frags))))))))))
  570. )
  571. ; Test if a string is made of only whitespace
  572. ; An empty string is considered made of whitespace as well
  573. (define (string-whitespace? str)
  574. (let ((len (string-length str)))
  575. (cond
  576. ((zero? len) #t)
  577. ((= 1 len) (char-whitespace? (string-ref str 0)))
  578. ((= 2 len) (and (char-whitespace? (string-ref str 0))
  579. (char-whitespace? (string-ref str 1))))
  580. (else
  581. (let loop ((i 0))
  582. (or (>= i len)
  583. (and (char-whitespace? (string-ref str i))
  584. (loop (inc i)))))))))
  585. ; Find val in alist
  586. ; Return (values found-el remaining-alist) or
  587. ; (values #f alist)
  588. (define (assq-values val alist)
  589. (let loop ((alist alist) (scanned '()))
  590. (cond
  591. ((null? alist) (values #f scanned))
  592. ((equal? val (caar alist))
  593. (values (car alist) (append scanned (cdr alist))))
  594. (else
  595. (loop (cdr alist) (cons (car alist) scanned))))))
  596. ; From SRFI-1
  597. (define (fold-right kons knil lis1)
  598. (let recur ((lis lis1))
  599. (if (null? lis) knil
  600. (let ((head (car lis)))
  601. (kons head (recur (cdr lis)))))))
  602. ; Left fold combinator for a single list
  603. (define (fold kons knil lis1)
  604. (let lp ((lis lis1) (ans knil))
  605. (if (null? lis) ans
  606. (lp (cdr lis) (kons (car lis) ans)))))
  607. ;========================================================================
  608. ; Lower-level parsers and scanners
  609. ;
  610. ; They deal with primitive lexical units (Names, whitespaces, tags)
  611. ; and with pieces of more generic productions. Most of these parsers
  612. ; must be called in appropriate context. For example, ssax:complete-start-tag
  613. ; must be called only when the start-tag has been detected and its GI
  614. ; has been read.
  615. ;------------------------------------------------------------------------
  616. ; Low-level parsing code
  617. ; Skip the S (whitespace) production as defined by
  618. ; [3] S ::= (#x20 | #x9 | #xD | #xA)
  619. ; The procedure returns the first not-whitespace character it
  620. ; encounters while scanning the PORT. This character is left
  621. ; on the input stream.
  622. (define ssax:S-chars (map ascii->char '(32 10 9 13)))
  623. (define (ssax:skip-S port)
  624. (skip-while ssax:S-chars port))
  625. ; Read a Name lexem and return it as string
  626. ; [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':'
  627. ; | CombiningChar | Extender
  628. ; [5] Name ::= (Letter | '_' | ':') (NameChar)*
  629. ;
  630. ; This code supports the XML Namespace Recommendation REC-xml-names,
  631. ; which modifies the above productions as follows:
  632. ;
  633. ; [4] NCNameChar ::= Letter | Digit | '.' | '-' | '_'
  634. ; | CombiningChar | Extender
  635. ; [5] NCName ::= (Letter | '_') (NCNameChar)*
  636. ; As the Rec-xml-names says,
  637. ; "An XML document conforms to this specification if all other tokens
  638. ; [other than element types and attribute names] in the document which
  639. ; are required, for XML conformance, to match the XML production for
  640. ; Name, match this specification's production for NCName."
  641. ; Element types and attribute names must match the production QName,
  642. ; defined below.
  643. ; Check to see if a-char may start a NCName
  644. (define (ssax:ncname-starting-char? a-char)
  645. (and (char? a-char)
  646. (or
  647. (char-alphabetic? a-char)
  648. (char=? #\_ a-char))))
  649. ; Read a NCName starting from the current position in the PORT and
  650. ; return it as a symbol.
  651. (define (ssax:read-NCName port)
  652. (let ((first-char (peek-char port)))
  653. (or (ssax:ncname-starting-char? first-char)
  654. (parser-error port "XMLNS [4] for '" first-char "'")))
  655. (string->symbol
  656. (next-token-of
  657. (lambda (c)
  658. (cond
  659. ((eof-object? c) #f)
  660. ((char-alphabetic? c) c)
  661. ((string-index "0123456789.-_" c) c)
  662. (else #f)))
  663. port)))
  664. ; Read a (namespace-) Qualified Name, QName, from the current
  665. ; position in the PORT.
  666. ; From REC-xml-names:
  667. ; [6] QName ::= (Prefix ':')? LocalPart
  668. ; [7] Prefix ::= NCName
  669. ; [8] LocalPart ::= NCName
  670. ; Return: an UNRES-NAME
  671. (define (ssax:read-QName port)
  672. (let ((prefix-or-localpart (ssax:read-NCName port)))
  673. (case (peek-char port)
  674. ((#\:) ; prefix was given after all
  675. (read-char port) ; consume the colon
  676. (cons prefix-or-localpart (ssax:read-NCName port)))
  677. (else prefix-or-localpart) ; Prefix was omitted
  678. )))
  679. ; The prefix of the pre-defined XML namespace
  680. (define ssax:Prefix-XML (string->symbol "xml"))
  681. (run-test
  682. (assert (eq? '_
  683. (call-with-input-string "_" ssax:read-NCName)))
  684. (assert (eq? '_
  685. (call-with-input-string "_" ssax:read-QName)))
  686. (assert (eq? (string->symbol "_abc_")
  687. (call-with-input-string "_abc_;" ssax:read-NCName)))
  688. (assert (eq? (string->symbol "_abc_")
  689. (call-with-input-string "_abc_;" ssax:read-QName)))
  690. (assert (eq? (string->symbol "_a.b")
  691. (call-with-input-string "_a.b " ssax:read-QName)))
  692. (assert (equal? (cons (string->symbol "_a.b") (string->symbol "d.1-ef-"))
  693. (call-with-input-string "_a.b:d.1-ef-;" ssax:read-QName)))
  694. (assert (equal? (cons (string->symbol "a") (string->symbol "b"))
  695. (call-with-input-string "a:b:c" ssax:read-QName)))
  696. (assert (failed? (call-with-input-string ":abc" ssax:read-NCName)))
  697. (assert (failed? (call-with-input-string "1:bc" ssax:read-NCName)))
  698. )
  699. ; Compare one RES-NAME or an UNRES-NAME with the other.
  700. ; Return a symbol '<, '>, or '= depending on the result of
  701. ; the comparison.
  702. ; Names without PREFIX are always smaller than those with the PREFIX.
  703. (define name-compare
  704. (letrec ((symbol-compare
  705. (lambda (symb1 symb2)
  706. (cond
  707. ((eq? symb1 symb2) '=)
  708. ((string<? (symbol->string symb1) (symbol->string symb2))
  709. '<)
  710. (else '>)))))
  711. (lambda (name1 name2)
  712. (cond
  713. ((symbol? name1) (if (symbol? name2) (symbol-compare name1 name2)
  714. '<))
  715. ((symbol? name2) '>)
  716. ((eq? name2 ssax:largest-unres-name) '<)
  717. ((eq? name1 ssax:largest-unres-name) '>)
  718. ((eq? (car name1) (car name2)) ; prefixes the same
  719. (symbol-compare (cdr name1) (cdr name2)))
  720. (else (symbol-compare (car name1) (car name2)))))))
  721. ; An UNRES-NAME that is postulated to be larger than anything that can occur in
  722. ; a well-formed XML document.
  723. ; name-compare enforces this postulate.
  724. (define ssax:largest-unres-name (cons
  725. (string->symbol "#LARGEST-SYMBOL")
  726. (string->symbol "#LARGEST-SYMBOL")))
  727. (run-test
  728. (assert (eq? '= (name-compare 'ABC 'ABC)))
  729. (assert (eq? '< (name-compare 'ABC 'ABCD)))
  730. (assert (eq? '> (name-compare 'XB 'ABCD)))
  731. (assert (eq? '> (name-compare '(HTML . PRE) 'PRE)))
  732. (assert (eq? '< (name-compare 'HTML '(HTML . PRE))))
  733. (assert (eq? '= (name-compare '(HTML . PRE) '(HTML . PRE))))
  734. (assert (eq? '< (name-compare '(HTML . PRE) '(XML . PRE))))
  735. (assert (eq? '> (name-compare '(HTML . PRE) '(HTML . P))))
  736. (assert (eq? '< (name-compare '(HTML . PRE) ssax:largest-unres-name)))
  737. (assert (eq? '< (name-compare '(ZZZZ . ZZZ) ssax:largest-unres-name)))
  738. (assert (eq? '> (name-compare ssax:largest-unres-name '(ZZZZ . ZZZ) )))
  739. )
  740. ; procedure: ssax:read-markup-token PORT
  741. ; This procedure starts parsing of a markup token. The current position
  742. ; in the stream must be #\<. This procedure scans enough of the input stream
  743. ; to figure out what kind of a markup token it is seeing. The procedure returns
  744. ; an xml-token structure describing the token. Note, generally reading
  745. ; of the current markup is not finished! In particular, no attributes of
  746. ; the start-tag token are scanned.
  747. ;
  748. ; Here's a detailed break out of the return values and the position in the PORT
  749. ; when that particular value is returned:
  750. ; PI-token: only PI-target is read.
  751. ; To finish the Processing Instruction and disregard it,
  752. ; call ssax:skip-pi. ssax:read-attributes may be useful
  753. ; as well (for PIs whose content is attribute-value
  754. ; pairs)
  755. ; END-token: The end tag is read completely; the current position
  756. ; is right after the terminating #\> character.
  757. ; COMMENT is read and skipped completely. The current position
  758. ; is right after "-->" that terminates the comment.
  759. ; CDSECT The current position is right after "<!CDATA["
  760. ; Use ssax:read-cdata-body to read the rest.
  761. ; DECL We have read the keyword (the one that follows "<!")
  762. ; identifying this declaration markup. The current
  763. ; position is after the keyword (usually a
  764. ; whitespace character)
  765. ;
  766. ; START-token We have read the keyword (GI) of this start tag.
  767. ; No attributes are scanned yet. We don't know if this
  768. ; tag has an empty content either.
  769. ; Use ssax:complete-start-tag to finish parsing of
  770. ; the token.
  771. (define ssax:read-markup-token ; procedure ssax:read-markup-token port
  772. (let ()
  773. ; we have read "<!-". Skip through the rest of the comment
  774. ; Return the 'COMMENT token as an indication we saw a comment
  775. ; and skipped it.
  776. (define (skip-comment port)
  777. (assert-curr-char '(#\-) "XML [15], second dash" port)
  778. (if (not (find-string-from-port? "-->" port))
  779. (parser-error port "XML [15], no -->"))
  780. (make-xml-token 'COMMENT #f))
  781. ; we have read "<![" that must begin a CDATA section
  782. (define (read-cdata port)
  783. (assert (string=? "CDATA[" (read-string 6 port)))
  784. (make-xml-token 'CDSECT #f))
  785. (lambda (port)
  786. (assert-curr-char '(#\<) "start of the token" port)
  787. (case (peek-char port)
  788. ((#\/) (read-char port)
  789. (begin0 (make-xml-token 'END (ssax:read-QName port))
  790. (ssax:skip-S port)
  791. (assert-curr-char '(#\>) "XML [42]" port)))
  792. ((#\?) (read-char port) (make-xml-token 'PI (ssax:read-NCName port)))
  793. ((#\!)
  794. (case (peek-next-char port)
  795. ((#\-) (read-char port) (skip-comment port))
  796. ((#\[) (read-char port) (read-cdata port))
  797. (else (make-xml-token 'DECL (ssax:read-NCName port)))))
  798. (else (make-xml-token 'START (ssax:read-QName port)))))
  799. ))
  800. ; The current position is inside a PI. Skip till the rest of the PI
  801. (define (ssax:skip-pi port)
  802. (if (not (find-string-from-port? "?>" port))
  803. (parser-error port "Failed to find ?> terminating the PI")))
  804. ; The current position is right after reading the PITarget. We read the
  805. ; body of PI and return is as a string. The port will point to the
  806. ; character right after '?>' combination that terminates PI.
  807. ; [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
  808. (define (ssax:read-pi-body-as-string port)
  809. (ssax:skip-S port) ; skip WS after the PI target name
  810. (string-concatenate/shared
  811. (let loop ()
  812. (let ((pi-fragment
  813. (next-token '() '(#\?) "reading PI content" port)))
  814. (if (eqv? #\> (peek-next-char port))
  815. (begin
  816. (read-char port)
  817. (cons pi-fragment '()))
  818. (cons* pi-fragment "?" (loop)))))))
  819. (run-test
  820. (assert (equal? "p1 content "
  821. (call-with-input-string "<?pi1 p1 content ?>"
  822. (lambda (port)
  823. (ssax:read-markup-token port)
  824. (ssax:read-pi-body-as-string port)))))
  825. (assert (equal? "pi2? content? ?"
  826. (call-with-input-string "<?pi2 pi2? content? ??>"
  827. (lambda (port)
  828. (ssax:read-markup-token port)
  829. (ssax:read-pi-body-as-string port)))))
  830. )
  831. ;(define (ssax:read-pi-body-as-name-values port)
  832. ; The current pos in the port is inside an internal DTD subset
  833. ; (e.g., after reading #\[ that begins an internal DTD subset)
  834. ; Skip until the "]>" combination that terminates this DTD
  835. (define (ssax:skip-internal-dtd port)
  836. (if (not (find-string-from-port? "]>" port))
  837. (parser-error port
  838. "Failed to find ]> terminating the internal DTD subset")))
  839. ; procedure+: ssax:read-cdata-body PORT STR-HANDLER SEED
  840. ;
  841. ; This procedure must be called after we have read a string "<![CDATA["
  842. ; that begins a CDATA section. The current position must be the first
  843. ; position of the CDATA body. This function reads _lines_ of the CDATA
  844. ; body and passes them to a STR-HANDLER, a character data consumer.
  845. ;
  846. ; The str-handler is a STR-HANDLER, a procedure STRING1 STRING2 SEED.
  847. ; The first STRING1 argument to STR-HANDLER never contains a newline.
  848. ; The second STRING2 argument often will. On the first invocation of
  849. ; the STR-HANDLER, the seed is the one passed to ssax:read-cdata-body
  850. ; as the third argument. The result of this first invocation will be
  851. ; passed as the seed argument to the second invocation of the line
  852. ; consumer, and so on. The result of the last invocation of the
  853. ; STR-HANDLER is returned by the ssax:read-cdata-body. Note a
  854. ; similarity to the fundamental 'fold' iterator.
  855. ;
  856. ; Within a CDATA section all characters are taken at their face value,
  857. ; with only three exceptions:
  858. ; CR, LF, and CRLF are treated as line delimiters, and passed
  859. ; as a single #\newline to the STR-HANDLER
  860. ; "]]>" combination is the end of the CDATA section.
  861. ; &gt; is treated as an embedded #\> character
  862. ; Note, &lt; and &amp; are not specially recognized (and are not expanded)!
  863. (define ssax:read-cdata-body
  864. (let ((cdata-delimiters (list char-return #\newline #\] #\&)))
  865. (lambda (port str-handler seed)
  866. (let loop ((seed seed))
  867. (let ((fragment (next-token '() cdata-delimiters
  868. "reading CDATA" port)))
  869. ; that is, we're reading the char after the 'fragment'
  870. (case (read-char port)
  871. ((#\newline) (loop (str-handler fragment nl seed)))
  872. ((#\])
  873. (if (not (eqv? (peek-char port) #\]))
  874. (loop (str-handler fragment "]" seed))
  875. (let check-after-second-braket
  876. ((seed (if (string-null? fragment) seed
  877. (str-handler fragment "" seed))))
  878. (case (peek-next-char port) ; after the second bracket
  879. ((#\>) (read-char port) seed) ; we have read "]]>"
  880. ((#\]) (check-after-second-braket
  881. (str-handler "]" "" seed)))
  882. (else (loop (str-handler "]]" "" seed)))))))
  883. ((#\&) ; Note that #\& within CDATA may stand for itself
  884. (let ((ent-ref ; it does not have to start an entity ref
  885. (next-token-of (lambda (c)
  886. (and (not (eof-object? c)) (char-alphabetic? c) c)) port)))
  887. (cond ; "&gt;" is to be replaced with #\>
  888. ((and (string=? "gt" ent-ref) (eqv? (peek-char port) #\;))
  889. (read-char port)
  890. (loop (str-handler fragment ">" seed)))
  891. (else
  892. (loop
  893. (str-handler ent-ref ""
  894. (str-handler fragment "&" seed)))))))
  895. (else ; Must be CR: if the next char is #\newline, skip it
  896. (if (eqv? (peek-char port) #\newline) (read-char port))
  897. (loop (str-handler fragment nl seed)))
  898. ))))))
  899. ; a few lines of validation code
  900. (run-test (letrec
  901. ((consumer (lambda (fragment foll-fragment seed)
  902. (cons* (if (equal? foll-fragment (string #\newline))
  903. " NL" foll-fragment) fragment seed)))
  904. (test (lambda (str expected-result)
  905. (newline) (display "body: ") (write str)
  906. (newline) (display "Result: ")
  907. (let ((result
  908. (reverse
  909. (call-with-input-string (unesc-string str)
  910. (lambda (port) (ssax:read-cdata-body port consumer '()))
  911. ))))
  912. (write result)
  913. (assert (equal? result expected-result)))))
  914. )
  915. (test "]]>" '())
  916. (test "abcd]]>" '("abcd" ""))
  917. (test "abcd]]]>" '("abcd" "" "]" ""))
  918. (test "abcd]]]]>" '("abcd" "" "]" "" "]" ""))
  919. (test "abcd]]]]]>" '("abcd" "" "]" "" "]" "" "]" ""))
  920. (test "abcd]]]a]]>" '("abcd" "" "]" "" "]]" "" "a" ""))
  921. (test "abc%r%ndef%n]]>" '("abc" " NL" "def" " NL"))
  922. (test "%r%n%r%n]]>" '("" " NL" "" " NL"))
  923. (test "%r%n%r%na]]>" '("" " NL" "" " NL" "a" ""))
  924. (test "%r%r%r%na]]>" '("" " NL" "" " NL" "" " NL" "a" ""))
  925. (test "abc&!!!]]>" '("abc" "&" "" "" "!!!" ""))
  926. (test "abc]]&gt;&gt&amp;]]]&gt;and]]>"
  927. '("abc" "" "]]" "" "" ">" "" "&" "gt" "" "" "&" "amp" "" ";" "" "]" ""
  928. "]]" "" "" ">" "and" ""))
  929. ))
  930. ; procedure+: ssax:read-char-ref PORT
  931. ;
  932. ; [66] CharRef ::= '&#' [0-9]+ ';'
  933. ; | '&#x' [0-9a-fA-F]+ ';'
  934. ;
  935. ; This procedure must be called after we we have read "&#"
  936. ; that introduces a char reference.
  937. ; The procedure reads this reference and returns the corresponding char
  938. ; The current position in PORT will be after ";" that terminates
  939. ; the char reference
  940. ; Faults detected:
  941. ; WFC: XML-Spec.html#wf-Legalchar
  942. ;
  943. ; According to Section "4.1 Character and Entity References"
  944. ; of the XML Recommendation:
  945. ; "[Definition: A character reference refers to a specific character
  946. ; in the ISO/IEC 10646 character set, for example one not directly
  947. ; accessible from available input devices.]"
  948. ; Therefore, we use a ucscode->string function to convert a character
  949. ; code into the character -- *regardless* of the current character
  950. ; encoding of the input stream.
  951. (define (ssax:read-char-ref port)
  952. (let* ((base
  953. (cond ((eqv? (peek-char port) #\x) (read-char port) 16)
  954. (else 10)))
  955. (name (next-token '() '(#\;) "XML [66]" port))
  956. (char-code (string->number name base)))
  957. (read-char port) ; read the terminating #\; char
  958. (if (integer? char-code) (ucscode->string char-code)
  959. (parser-error port "[wf-Legalchar] broken for '" name "'"))))
  960. ; procedure+: ssax:handle-parsed-entity PORT NAME ENTITIES
  961. ; CONTENT-HANDLER STR-HANDLER SEED
  962. ;
  963. ; Expand and handle a parsed-entity reference
  964. ; port - a PORT
  965. ; name - the name of the parsed entity to expand, a symbol
  966. ; entities - see ENTITIES
  967. ; content-handler -- procedure PORT ENTITIES SEED
  968. ; that is supposed to return a SEED
  969. ; str-handler - a STR-HANDLER. It is called if the entity in question
  970. ; turns out to be a pre-declared entity
  971. ;
  972. ; The result is the one returned by CONTENT-HANDLER or STR-HANDLER
  973. ; Faults detected:
  974. ; WFC: XML-Spec.html#wf-entdeclared
  975. ; WFC: XML-Spec.html#norecursion
  976. (define ssax:predefined-parsed-entities
  977. `(
  978. (,(string->symbol "amp") . "&")
  979. (,(string->symbol "lt") . "<")
  980. (,(string->symbol "gt") . ">")
  981. (,(string->symbol "apos") . "'")
  982. (,(string->symbol "quot") . "\"")))
  983. (define (ssax:handle-parsed-entity port name entities
  984. content-handler str-handler seed)
  985. (cond ; First we check the list of the declared entities
  986. ((assq name entities) =>
  987. (lambda (decl-entity)
  988. (let ((ent-body (cdr decl-entity)) ; mark the list to prevent recursion
  989. (new-entities (cons (cons name #f) entities)))
  990. (cond
  991. ((string? ent-body)
  992. (call-with-input-string ent-body
  993. (lambda (port) (content-handler port new-entities seed))))
  994. ((procedure? ent-body)
  995. (let ((port (ent-body)))
  996. (begin0
  997. (content-handler port new-entities seed)
  998. (close-input-port port))))
  999. (else
  1000. (parser-error port "[norecursion] broken for " name))))))
  1001. ((assq name ssax:predefined-parsed-entities)
  1002. => (lambda (decl-entity)
  1003. (str-handler (cdr decl-entity) "" seed)))
  1004. ((assq '*DEFAULT* entities) =>
  1005. (lambda (decl-entity)
  1006. (let ((fallback (cdr decl-entity))
  1007. (new-entities (cons (cons name #f) entities)))
  1008. (cond
  1009. ((procedure? fallback)
  1010. (call-with-input-string (fallback port name)
  1011. (lambda (port) (content-handler port new-entities seed))))
  1012. (else
  1013. (parser-error port "[norecursion] broken for " name))))))
  1014. (else (parser-error port "[wf-entdeclared] broken for " name))))
  1015. ; The ATTLIST Abstract Data Type
  1016. ; Currently is implemented as an assoc list sorted in the ascending
  1017. ; order of NAMES.
  1018. (define (make-empty-attlist) '())
  1019. ; Add a name-value pair to the existing attlist preserving the order
  1020. ; Return the new list, in the sorted ascending order.
  1021. ; Return #f if a pair with the same name already exists in the attlist
  1022. (define (attlist-add attlist name-value)
  1023. (if (null? attlist) (cons name-value attlist)
  1024. (case (name-compare (car name-value) (caar attlist))
  1025. ((=) #f)
  1026. ((<) (cons name-value attlist))
  1027. (else (cons (car attlist) (attlist-add (cdr attlist) name-value)))
  1028. )))
  1029. (define attlist-null? null?)
  1030. ; Given an non-null attlist, return a pair of values: the top and the rest
  1031. (define (attlist-remove-top attlist)
  1032. (values (car attlist) (cdr attlist)))
  1033. (define (attlist->alist attlist) attlist)
  1034. (define attlist-fold fold)
  1035. ; procedure+: ssax:read-attributes PORT ENTITIES
  1036. ;
  1037. ; This procedure reads and parses a production Attribute*
  1038. ; [41] Attribute ::= Name Eq AttValue
  1039. ; [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
  1040. ; | "'" ([^<&'] | Reference)* "'"
  1041. ; [25] Eq ::= S? '=' S?
  1042. ;
  1043. ;
  1044. ; The procedure returns an ATTLIST, of Name (as UNRES-NAME), Value (as string)
  1045. ; pairs. The current character on the PORT is a non-whitespace character
  1046. ; that is not an ncname-starting character.
  1047. ;
  1048. ; Note the following rules to keep in mind when reading an 'AttValue'
  1049. ; "Before the value of an attribute is passed to the application
  1050. ; or checked for validity, the XML processor must normalize it as follows:
  1051. ; - a character reference is processed by appending the referenced
  1052. ; character to the attribute value
  1053. ; - an entity reference is processed by recursively processing the
  1054. ; replacement text of the entity [see ENTITIES]
  1055. ; [named entities amp lt gt quot apos are assumed pre-declared]
  1056. ; - a whitespace character (#x20, #xD, #xA, #x9) is processed by appending #x20
  1057. ; to the normalized value, except that only a single #x20 is appended for a
  1058. ; "#xD#xA" sequence that is part of an external parsed entity or the
  1059. ; literal entity value of an internal parsed entity
  1060. ; - other characters are processed by appending them to the normalized value "
  1061. ;
  1062. ;
  1063. ; Faults detected:
  1064. ; WFC: XML-Spec.html#CleanAttrVals
  1065. ; WFC: XML-Spec.html#uniqattspec
  1066. (define ssax:read-attributes ; ssax:read-attributes port entities
  1067. (let ((value-delimeters (append ssax:S-chars '(#\< #\&))))
  1068. ; Read the AttValue from the PORT up to the delimiter
  1069. ; (which can be a single or double-quote character,
  1070. ; or even a symbol *eof*)
  1071. ; 'prev-fragments' is the list of string fragments, accumulated
  1072. ; so far, in reverse order.
  1073. ; Return the list of fragments with newly read fragments
  1074. ; prepended.
  1075. (define (read-attrib-value delimiter port entities prev-fragments)
  1076. (let* ((new-fragments
  1077. (cons (next-token '() (cons delimiter value-delimeters)
  1078. "XML [10]" port)
  1079. prev-fragments))
  1080. (cterm (read-char port)))
  1081. (cond
  1082. ((or (eof-object? cterm) (eqv? cterm delimiter))
  1083. new-fragments)
  1084. ((eqv? cterm char-return) ; treat a CR and CRLF as a LF
  1085. (if (eqv? (peek-char port) #\newline) (read-char port))
  1086. (read-attrib-value delimiter port entities
  1087. (cons " " new-fragments)))
  1088. ((memv cterm ssax:S-chars)
  1089. (read-attrib-value delimiter port entities
  1090. (cons " " new-fragments)))
  1091. ((eqv? cterm #\&)
  1092. (cond
  1093. ((eqv? (peek-char port) #\#)
  1094. (read-char port)
  1095. (read-attrib-value delimiter port entities
  1096. (cons (ssax:read-char-ref port) new-fragments)))
  1097. (else
  1098. (read-attrib-value delimiter port entities
  1099. (read-named-entity port entities new-fragments)))))
  1100. (else (parser-error port "[CleanAttrVals] broken")))))
  1101. ; we have read "&" that introduces a named entity reference.
  1102. ; read this reference and return the result of
  1103. ; normalizing of the corresponding string
  1104. ; (that is, read-attrib-value is applied to the replacement
  1105. ; text of the entity)
  1106. ; The current position will be after ";" that terminates
  1107. ; the entity reference
  1108. (define (read-named-entity port entities fragments)
  1109. (let ((name (ssax:read-NCName port)))
  1110. (assert-curr-char '(#\;) "XML [68]" port)
  1111. (ssax:handle-parsed-entity port name entities
  1112. (lambda (port entities fragments)
  1113. (read-attrib-value '*eof* port entities fragments))
  1114. (lambda (str1 str2 fragments)
  1115. (if (equal? "" str2) (cons str1 fragments)
  1116. (cons* str2 str1 fragments)))
  1117. fragments)))
  1118. (lambda (port entities)
  1119. (let loop ((attr-list (make-empty-attlist)))
  1120. (if (not (ssax:ncname-starting-char? (ssax:skip-S port))) attr-list
  1121. (let ((name (ssax:read-QName port)))
  1122. (ssax:skip-S port)
  1123. (assert-curr-char '(#\=) "XML [25]" port)
  1124. (ssax:skip-S port)
  1125. (let ((delimiter
  1126. (assert-curr-char '(#\' #\" ) "XML [10]" port)))
  1127. (loop
  1128. (or (attlist-add attr-list
  1129. (cons name
  1130. (string-concatenate-reverse/shared
  1131. (read-attrib-value delimiter port entities
  1132. '()))))
  1133. (parser-error port "[uniqattspec] broken for " name))))))))
  1134. ))
  1135. ; a few lines of validation code
  1136. (run-test (letrec
  1137. ((test (lambda (str decl-entities expected-res)
  1138. (newline) (display "input: ") (write str)
  1139. (newline) (display "Result: ")
  1140. (let ((result
  1141. (call-with-input-string (unesc-string str)
  1142. (lambda (port)
  1143. (ssax:read-attributes port decl-entities)))))
  1144. (write result) (newline)
  1145. (assert (equal? result expected-res))))))
  1146. (test "" '() '())
  1147. (test "href='http://a%tb%r%n%r%n%nc'" '()
  1148. `((,(string->symbol "href") . "http://a b c")))
  1149. (test "href='http://a%tb%r%r%n%rc'" '()
  1150. `((,(string->symbol "href") . "http://a b c")))
  1151. (test "_1 ='12&amp;' _2= \"%r%n%t12&#10;3\">" '()
  1152. `((_1 . "12&") (_2 . ,(unesc-string " 12%n3"))))
  1153. (test "%tAbc='&lt;&amp;&gt;&#x0A;'%nNext='12&ent;34' />"
  1154. '((ent . "&lt;xx&gt;"))
  1155. `((,(string->symbol "Abc") . ,(unesc-string "<&>%n"))
  1156. (,(string->symbol "Next") . "12<xx>34")))
  1157. (test "%tAbc='&lt;&amp;&gt;&#x0d;'%nNext='12&ent;34' />"
  1158. '((ent . "&lt;xx&gt;"))
  1159. `((,(string->symbol "Abc") . ,(unesc-string "<&>%r"))
  1160. (,(string->symbol "Next") . "12<xx>34")))
  1161. (test "%tAbc='&lt;&amp;&gt;&#x0A;'%nNext='12&en;34' />"
  1162. `((en . ,(lambda () (open-input-string "&quot;xx&apos;"))))
  1163. `((,(string->symbol "Abc") . ,(unesc-string "<&>%n"))
  1164. (,(string->symbol "Next") . "12\"xx'34")))
  1165. (test "%tAbc='&lt;&amp;&gt;&#x0A;'%nNext='12&ent;34' />"
  1166. '((ent . "&lt;&ent1;T;&gt;") (ent1 . "&amp;"))
  1167. `((,(string->symbol "Abc") . ,(unesc-string "<&>%n"))
  1168. (,(string->symbol "Next") . "12<&T;>34")))
  1169. (test "%tAbc='&lt;&amp;&gt;&#x0A;'%nNext='12&ent;34' />"
  1170. `((*DEFAULT* . ,(lambda (port name)
  1171. (case name
  1172. ((ent) "&lt;&ent1;T;&gt;")
  1173. ((ent1) "&amp;")
  1174. (else (error "unrecognized" name))))))
  1175. `((,(string->symbol "Abc") . ,(unesc-string "<&>%n"))
  1176. (,(string->symbol "Next") . "12<&T;>34")))
  1177. (assert (failed?
  1178. (test "%tAbc='&lt;&amp;&gt;&#x0A;'%nNext='12&ent;34' />"
  1179. '((ent . "<&ent1;T;&gt;") (ent1 . "&amp;")) '())))
  1180. (assert (failed?
  1181. (test "%tAbc='&lt;&amp;&gt;&#x0A;'%nNext='12&ent;34' />"
  1182. '((ent . "&lt;&ent;T;&gt;") (ent1 . "&amp;")) '())))
  1183. (assert (failed?
  1184. (test "%tAbc='&lt;&amp;&gt;&#x0A;'%nNext='12&ent;34' />"
  1185. '((ent . "&lt;&ent1;T;&gt;") (ent1 . "&ent;")) '())))
  1186. (test "html:href='http://a%tb%r%n%r%n%nc'" '()
  1187. `(((,(string->symbol "html") . ,(string->symbol "href"))
  1188. . "http://a b c")))
  1189. (test "html:href='ref1' html:src='ref2'" '()
  1190. `(((,(string->symbol "html") . ,(string->symbol "href"))
  1191. . "ref1")
  1192. ((,(string->symbol "html") . ,(string->symbol "src"))
  1193. . "ref2")))
  1194. (test "html:href='ref1' xml:html='ref2'" '()
  1195. `(((,(string->symbol "html") . ,(string->symbol "href"))
  1196. . "ref1")
  1197. ((,ssax:Prefix-XML . ,(string->symbol "html"))
  1198. . "ref2")))
  1199. (assert (failed? (test "html:href='ref1' html:href='ref2'" '() '())))
  1200. (assert (failed? (test "html:href='<' html:href='ref2'" '() '())))
  1201. (assert (failed? (test "html:href='ref1' html:href='&ref2;'" '() '())))
  1202. ))
  1203. ; ssax:resolve-name PORT UNRES-NAME NAMESPACES apply-default-ns?
  1204. ;
  1205. ; Convert an UNRES-NAME to a RES-NAME given the appropriate NAMESPACES
  1206. ; declarations.
  1207. ; the last parameter apply-default-ns? determines if the default
  1208. ; namespace applies (for instance, it does not for attribute names)
  1209. ;
  1210. ; Per REC-xml-names/#nsc-NSDeclared, "xml" prefix is considered pre-declared
  1211. ; and bound to the namespace name "http://www.w3.org/XML/1998/namespace".
  1212. ;
  1213. ; This procedure tests for the namespace constraints:
  1214. ; http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared
  1215. (define (ssax:resolve-name port unres-name namespaces apply-default-ns?)
  1216. (cond
  1217. ((pair? unres-name) ; it's a QNAME
  1218. (cons
  1219. (cond
  1220. ((assq (car unres-name) namespaces) => cadr)
  1221. ((eq? (car unres-name) ssax:Prefix-XML) ssax:Prefix-XML)
  1222. (else
  1223. (parser-error port "[nsc-NSDeclared] broken; prefix " (car unres-name))))
  1224. (cdr unres-name)))
  1225. (apply-default-ns? ; Do apply the default namespace, if any
  1226. (let ((default-ns (assq '*DEFAULT* namespaces)))
  1227. (if (and default-ns (cadr default-ns))
  1228. (cons (cadr default-ns) unres-name)
  1229. unres-name))) ; no default namespace declared
  1230. (else unres-name))) ; no prefix, don't apply the default-ns
  1231. (run-test
  1232. (let* ((namespaces
  1233. '((HTML UHTML . URN-HTML)
  1234. (HTML UHTML-1 . URN-HTML)
  1235. (A UHTML . URN-HTML)))
  1236. (namespaces-def
  1237. (cons
  1238. '(*DEFAULT* DEF . URN-DEF) namespaces))
  1239. (namespaces-undef
  1240. (cons
  1241. '(*DEFAULT* #f . #f) namespaces-def))
  1242. (port (current-input-port)))
  1243. (assert (equal? 'ABC
  1244. (ssax:resolve-name port 'ABC namespaces #t)))
  1245. (assert (equal? '(DEF . ABC)
  1246. (ssax:resolve-name port 'ABC namespaces-def #t)))
  1247. (assert (equal? 'ABC
  1248. (ssax:resolve-name port 'ABC namespaces-def #f)))
  1249. (assert (equal? 'ABC
  1250. (ssax:resolve-name port 'ABC namespaces-undef #t)))
  1251. (assert (equal? '(UHTML . ABC)
  1252. (ssax:resolve-name port '(HTML . ABC) namespaces-def #t)))
  1253. (assert (equal? '(UHTML . ABC)
  1254. (ssax:resolve-name port '(HTML . ABC) namespaces-def #f)))
  1255. (assert (equal? `(,ssax:Prefix-XML . space)
  1256. (ssax:resolve-name port
  1257. `(,(string->symbol "xml") . space) namespaces-def #f)))
  1258. (assert (failed?
  1259. (ssax:resolve-name port '(XXX . ABC) namespaces-def #f)))
  1260. ))
  1261. ; procedure+: ssax:uri-string->symbol URI-STR
  1262. ; Convert a URI-STR to an appropriate symbol
  1263. (define (ssax:uri-string->symbol uri-str)
  1264. (string->symbol uri-str))
  1265. ; procedure+: ssax:complete-start-tag TAG PORT ELEMS ENTITIES NAMESPACES
  1266. ;
  1267. ; This procedure is to complete parsing of a start-tag markup. The
  1268. ; procedure must be called after the start tag token has been
  1269. ; read. TAG is an UNRES-NAME. ELEMS is an instance of xml-decl::elems;
  1270. ; it can be #f to tell the function to do _no_ validation of elements
  1271. ; and their attributes.
  1272. ;
  1273. ; This procedure returns several values:
  1274. ; ELEM-GI: a RES-NAME.
  1275. ; ATTRIBUTES: element's attributes, an ATTLIST of (RES-NAME . STRING)
  1276. ; pairs. The list does NOT include xmlns attributes.
  1277. ; NAMESPACES: the input list of namespaces amended with namespace
  1278. ; (re-)declarations contained within the start-tag under parsing
  1279. ; ELEM-CONTENT-MODEL
  1280. ; On exit, the current position in PORT will be the first character after
  1281. ; #\> that terminates the start-tag markup.
  1282. ;
  1283. ; Faults detected:
  1284. ; VC: XML-Spec.html#enum
  1285. ; VC: XML-Spec.html#RequiredAttr
  1286. ; VC: XML-Spec.html#FixedAttr
  1287. ; VC: XML-Spec.html#ValueType
  1288. ; WFC: XML-Spec.html#uniqattspec (after namespaces prefixes are resolved)
  1289. ; VC: XML-Spec.html#elementvalid
  1290. ; WFC: REC-xml-names/#dt-NSName
  1291. ; Note, although XML Recommendation does not explicitly say it,
  1292. ; xmlns and xmlns: attributes don't have to be declared (although they
  1293. ; can be declared, to specify their default value)
  1294. ; Procedure: ssax:complete-start-tag tag-head port elems entities namespaces
  1295. (define ssax:complete-start-tag
  1296. (let ((xmlns (string->symbol "xmlns"))
  1297. (largest-dummy-decl-attr (list ssax:largest-unres-name #f #f #f)))
  1298. ; Scan through the attlist and validate it, against decl-attrs
  1299. ; Return an assoc list with added fixed or implied attrs.
  1300. ; Note that both attlist and decl-attrs are ATTLISTs, and therefore,
  1301. ; sorted
  1302. (define (validate-attrs port attlist decl-attrs)
  1303. ; Check to see decl-attr is not of use type REQUIRED. Add
  1304. ; the association with the default value, if any declared
  1305. (define (add-default-decl decl-attr result)
  1306. (let*-values
  1307. (((attr-name content-type use-type default-value)
  1308. (apply values decl-attr)))
  1309. (and (eq? use-type 'REQUIRED)
  1310. (parser-error port "[RequiredAttr] broken for" attr-name))
  1311. (if default-value
  1312. (cons (cons attr-name default-value) result)
  1313. result)))
  1314. (let loop ((attlist attlist) (decl-attrs decl-attrs) (result '()))
  1315. (if (attlist-null? attlist)
  1316. (attlist-fold add-default-decl result decl-attrs)
  1317. (let*-values
  1318. (((attr attr-others)
  1319. (attlist-remove-top attlist))
  1320. ((decl-attr other-decls)
  1321. (if (attlist-null? decl-attrs)
  1322. (values largest-dummy-decl-attr decl-attrs)
  1323. (attlist-remove-top decl-attrs)))
  1324. )
  1325. (case (name-compare (car attr) (car decl-attr))
  1326. ((<)
  1327. (if (or (eq? xmlns (car attr))
  1328. (and (pair? (car attr)) (eq? xmlns (caar attr))))
  1329. (loop attr-others decl-attrs (cons attr result))
  1330. (parser-error port "[ValueType] broken for " attr)))
  1331. ((>)
  1332. (loop attlist other-decls
  1333. (add-default-decl decl-attr result)))
  1334. (else ; matched occurrence of an attr with its declaration
  1335. (let*-values
  1336. (((attr-name content-type use-type default-value)
  1337. (apply values decl-attr)))
  1338. ; Run some tests on the content of the attribute
  1339. (cond
  1340. ((eq? use-type 'FIXED)
  1341. (or (equal? (cdr attr) default-value)
  1342. (parser-error port "[FixedAttr] broken for " attr-name)))
  1343. ((eq? content-type 'CDATA) #t) ; everything goes
  1344. ((pair? content-type)
  1345. (or (member (cdr attr) content-type)
  1346. (parser-error port "[enum] broken for " attr-name "="
  1347. (cdr attr))))
  1348. (else
  1349. (ssax:warn port "declared content type " content-type
  1350. " not verified yet")))
  1351. (loop attr-others other-decls (cons attr result)))))
  1352. ))))
  1353. ; Add a new namespace declaration to namespaces.
  1354. ; First we convert the uri-str to a uri-symbol and search namespaces for
  1355. ; an association (_ user-prefix . uri-symbol).
  1356. ; If found, we return the argument namespaces with an association
  1357. ; (prefix user-prefix . uri-symbol) prepended.
  1358. ; Otherwise, we prepend (prefix uri-symbol . uri-symbol)
  1359. (define (add-ns port prefix uri-str namespaces)
  1360. (and (equal? "" uri-str)
  1361. (parser-error port "[dt-NSName] broken for " prefix))
  1362. (let ((uri-symbol (ssax:uri-string->symbol uri-str)))
  1363. (let loop ((nss namespaces))
  1364. (cond
  1365. ((null? nss)
  1366. (cons (cons* prefix uri-symbol uri-symbol) namespaces))
  1367. ((eq? uri-symbol (cddar nss))
  1368. (cons (cons* prefix (cadar nss) uri-symbol) namespaces))
  1369. (else (loop (cdr nss)))))))
  1370. ; partition attrs into proper attrs and new namespace declarations
  1371. ; return two values: proper attrs and the updated namespace declarations
  1372. (define (adjust-namespace-decl port attrs namespaces)
  1373. (let loop ((attrs attrs) (proper-attrs '()) (namespaces namespaces))
  1374. (cond
  1375. ((null? attrs) (values proper-attrs namespaces))
  1376. ((eq? xmlns (caar attrs)) ; re-decl of the default namespace
  1377. (loop (cdr attrs) proper-attrs
  1378. (if (equal? "" (cdar attrs)) ; un-decl of the default ns
  1379. (cons (cons* '*DEFAULT* #f #f) namespaces)
  1380. (add-ns port '*DEFAULT* (cdar attrs) namespaces))))
  1381. ((and (pair? (caar attrs)) (eq? xmlns (caaar attrs)))
  1382. (loop (cdr attrs) proper-attrs
  1383. (add-ns port (cdaar attrs) (cdar attrs) namespaces)))
  1384. (else
  1385. (loop (cdr attrs) (cons (car attrs) proper-attrs) namespaces)))))
  1386. ; The body of the function
  1387. (lambda (tag-head port elems entities namespaces)
  1388. (let*-values
  1389. (((attlist) (ssax:read-attributes port entities))
  1390. ((empty-el-tag?)
  1391. (begin
  1392. (ssax:skip-S port)
  1393. (and
  1394. (eqv? #\/
  1395. (assert-curr-char '(#\> #\/) "XML [40], XML [44], no '>'" port))
  1396. (assert-curr-char '(#\>) "XML [44], no '>'" port))))
  1397. ((elem-content decl-attrs) ; see xml-decl for their type
  1398. (if elems ; elements declared: validate!
  1399. (cond
  1400. ((assoc tag-head elems) =>
  1401. (lambda (decl-elem) ; of type xml-decl::decl-elem
  1402. (values
  1403. (if empty-el-tag? 'EMPTY-TAG (cadr decl-elem))
  1404. (caddr decl-elem))))
  1405. (else
  1406. (parser-error port "[elementvalid] broken, no decl for " tag-head)))
  1407. (values ; non-validating parsing
  1408. (if empty-el-tag? 'EMPTY-TAG 'ANY)
  1409. #f) ; no attributes declared
  1410. ))
  1411. ((merged-attrs) (if decl-attrs (validate-attrs port attlist decl-attrs)
  1412. (attlist->alist attlist)))
  1413. ((proper-attrs namespaces)
  1414. (adjust-namespace-decl port merged-attrs namespaces))
  1415. )
  1416. ;(cerr "proper attrs: " proper-attrs nl)
  1417. ; build the return value
  1418. (values
  1419. (ssax:resolve-name port tag-head namespaces #t)
  1420. (fold-right
  1421. (lambda (name-value attlist)
  1422. (or
  1423. (attlist-add attlist
  1424. (cons (ssax:resolve-name port (car name-value) namespaces #f)
  1425. (cdr name-value)))
  1426. (parser-error port "[uniqattspec] after NS expansion broken for "
  1427. name-value)))
  1428. (make-empty-attlist)
  1429. proper-attrs)
  1430. namespaces
  1431. elem-content)))))
  1432. (run-test
  1433. (let* ((urn-a (string->symbol "urn:a"))
  1434. (urn-b (string->symbol "urn:b"))
  1435. (urn-html (string->symbol "http://w3c.org/html"))
  1436. (namespaces
  1437. `((#f '"UHTML" . ,urn-html)
  1438. ('"A" '"UA" . ,urn-a)))
  1439. (test
  1440. (lambda (tag-head-name elems str)
  1441. (call-with-input-string str
  1442. (lambda (port)
  1443. (call-with-values
  1444. (lambda ()
  1445. (ssax:complete-start-tag
  1446. (call-with-input-string tag-head-name
  1447. (lambda (port) (ssax:read-QName port)))
  1448. port
  1449. elems '() namespaces))
  1450. list))))))
  1451. ; First test with no validation of elements
  1452. ;(test "TAG1" #f "")
  1453. (assert (equal? `('"TAG1" () ,namespaces ANY)
  1454. (test "TAG1" #f ">")))
  1455. (assert (equal? `('"TAG1" () ,namespaces EMPTY-TAG)
  1456. (test "TAG1" #f "/>")))
  1457. (assert (equal? `('"TAG1" (('"HREF" . "a")) ,namespaces EMPTY-TAG)
  1458. (test "TAG1" #f "HREF='a'/>")))
  1459. (assert (equal? `(('"UA" . '"TAG1") (('"HREF" . "a"))
  1460. ,(cons `(*DEFAULT* '"UA" . ,urn-a) namespaces) ANY)
  1461. (test "TAG1" #f "HREF='a' xmlns='urn:a'>")))
  1462. (assert (equal? `('"TAG1" (('"HREF" . "a"))
  1463. ,(cons '(*DEFAULT* #f . #f) namespaces) ANY)
  1464. (test "TAG1" #f "HREF='a' xmlns=''>")))
  1465. (assert (failed? (test "UA:TAG1" #f "HREF='a' xmlns=''/>")))
  1466. (assert (equal? `(('"UA" . '"TAG1") ((('"UA" . '"HREF") . "a"))
  1467. ,(cons '(*DEFAULT* #f . #f) namespaces) ANY)
  1468. (test "A:TAG1" #f "A:HREF='a' xmlns=''>")))
  1469. (assert (equal? `(('"UA" . '"TAG1") ((('"UA" . '"HREF") . "a"))
  1470. ,(cons `(*DEFAULT* ,urn-b . ,urn-b) namespaces) ANY)
  1471. (test "A:TAG1" #f "A:HREF='a' xmlns='urn:b'>")))
  1472. (assert (failed? (test "B:TAG1" #f "A:HREF='a' xmlns:b=''/>")))
  1473. (assert (equal? `((,urn-b . '"TAG1") ((('"UA" . '"HREF") . "a"))
  1474. ,(cons `('"B" ,urn-b . ,urn-b) namespaces) ANY)
  1475. (test "B:TAG1" #f "A:HREF='a' xmlns:B='urn:b'>")))
  1476. (assert (equal? `((,urn-b . '"TAG1") ((('"UA" . '"HREF") . "a")
  1477. ((,urn-b . '"SRC") . "b"))
  1478. ,(cons `('"B" ,urn-b . ,urn-b) namespaces) ANY)
  1479. (test "B:TAG1" #f
  1480. "B:SRC='b' A:HREF='a' xmlns:B='urn:b'>")))
  1481. (assert (equal? `((,urn-b . '"TAG1") ((('"UA" . '"HREF") . "a")
  1482. ((,urn-b . '"HREF") . "b"))
  1483. ,(cons `('"B" ,urn-b . ,urn-b) namespaces) ANY)
  1484. (test "B:TAG1" #f
  1485. "B:HREF=\"b\" A:HREF='a' xmlns:B='urn:b'>")))
  1486. ; must be an error! Duplicate attr
  1487. (assert (failed? (test "B:TAG1" #f
  1488. "HREF=\"b\" HREF='a' xmlns:B='urn:a'/>")))
  1489. ; must be an error! Duplicate attr after ns expansion
  1490. (assert (failed? (test "B:TAG1" #f
  1491. "B:HREF=\"b\" A:HREF='a' xmlns:B='urn:a'/>")))
  1492. (assert (equal? `(('"UA" . '"TAG1") (('"HREF" . "a")
  1493. (('"UA" . '"HREF") . "b"))
  1494. ,(cons `(*DEFAULT* '"UA" . ,urn-a) namespaces) ANY)
  1495. (test "TAG1" #f
  1496. "A:HREF=\"b\" HREF='a' xmlns='urn:a'>")))
  1497. (assert (equal? `('"TAG1" ((('"UHTML" . '"HREF") . "a")
  1498. ((,urn-b . '"HREF") . "b"))
  1499. ,(append `(
  1500. ('"HTML" '"UHTML" . ,urn-html)
  1501. ('"B" ,urn-b . ,urn-b))
  1502. namespaces) ANY)
  1503. (test "TAG1" #f
  1504. "B:HREF=\"b\" xmlns:B='urn:b' xmlns:HTML='http://w3c.org/html' HTML:HREF='a' >")))
  1505. ; Now test the validating parsing
  1506. ; No decl for tag1
  1507. (assert (failed? (test "TAG1" '((TAG2 ANY ()))
  1508. "B:HREF='b' xmlns:B='urn:b'>")))
  1509. ; No decl for HREF elem
  1510. ;; (cond-expand
  1511. ;; ((not (or scm mit-scheme)) ; Regretfully, SCM treats '() as #f
  1512. ;; (assert (failed?
  1513. ;; (test "TAG1" '(('"TAG1" ANY ()))
  1514. ;; "B:HREF='b' xmlns:B='urn:b'>"))))
  1515. ;; (else #t))
  1516. ; No decl for HREF elem
  1517. (assert (failed?
  1518. (test "TAG1" '(('"TAG1" ANY (('"HREF1" CDATA IMPLIED #f))))
  1519. "B:HREF='b' xmlns:B='urn:b'>")))
  1520. (assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces EMPTY-TAG)
  1521. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f))))
  1522. "HREF='b'/>")))
  1523. (assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
  1524. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f))))
  1525. "HREF='b'>")))
  1526. ; Req'd attribute not given error
  1527. (assert (failed?
  1528. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f))))
  1529. ">")))
  1530. ; Wrong content-type of the attribute
  1531. (assert (failed?
  1532. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" ("c") REQUIRED #f))))
  1533. "HREF='b'>")))
  1534. (assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
  1535. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" ("c" "b") IMPLIED #f))))
  1536. "HREF='b'>")))
  1537. (assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
  1538. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA IMPLIED "c"))))
  1539. "HREF='b'>")))
  1540. ; Bad fixed attribute
  1541. (assert (failed?
  1542. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA FIXED "c"))))
  1543. "HREF='b'>")))
  1544. (assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
  1545. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA FIXED "b"))))
  1546. "HREF='b'>")))
  1547. (assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
  1548. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA FIXED "b")))) ">")))
  1549. (assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
  1550. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA IMPLIED "b")))) ">")))
  1551. (assert (equal? `('"TAG1" () ,namespaces PCDATA)
  1552. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA IMPLIED #f)))) ">")))
  1553. ; Undeclared attr
  1554. (assert (failed?
  1555. (test "TAG1"
  1556. '(('"TAG1" PCDATA ((('"A" . '"HREF") CDATA IMPLIED "c"))))
  1557. "HREF='b'>")))
  1558. (assert (equal? `('"TAG1" (('"HREF" . "b") (('"UA" . '"HREF") . "c"))
  1559. ,namespaces PCDATA)
  1560. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f)
  1561. (('"A" . '"HREF") CDATA IMPLIED "c"))))
  1562. "HREF='b'>")))
  1563. (assert (equal? `(('"UA" . '"TAG1")
  1564. (('"HREF" . "b") (('"UA" . '"HREF") . "c"))
  1565. ,namespaces PCDATA)
  1566. (test "A:TAG1" '((('"A" . '"TAG1") PCDATA
  1567. (('"HREF" NMTOKEN REQUIRED #f)
  1568. (('"A" . '"HREF") CDATA IMPLIED "c"))))
  1569. "HREF='b'>")))
  1570. (assert (equal? `((,urn-b . '"TAG1") (('"HREF" . "b"))
  1571. ,(cons `('"B" ,urn-b . ,urn-b) namespaces) PCDATA)
  1572. (test "B:TAG1" '((('"B" . '"TAG1") PCDATA (('"HREF" CDATA REQUIRED #f)
  1573. (('"xmlns" . '"B") CDATA IMPLIED "urn:b"))))
  1574. "HREF='b'>")))
  1575. (assert (equal? `((,urn-b . '"TAG1") (((,urn-b . '"HREF") . "b"))
  1576. ,(cons `('"B" ,urn-b . ,urn-b) namespaces) PCDATA)
  1577. (test "B:TAG1" '((('"B" . '"TAG1") PCDATA
  1578. ((('"B" . '"HREF") CDATA REQUIRED #f)
  1579. (('"xmlns" . '"B") CDATA IMPLIED "urn:b"))))
  1580. "B:HREF='b'>")))
  1581. (assert (equal? `((,urn-b . '"TAG1") (('"HREF" . "b"))
  1582. ,(cons `(*DEFAULT* ,urn-b . ,urn-b) namespaces) PCDATA)
  1583. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f)
  1584. ('"xmlns" CDATA IMPLIED "urn:b"))))
  1585. "HREF='b'>")))
  1586. ; xmlns not declared
  1587. (assert (equal? `((,urn-b . '"TAG1") (('"HREF" . "b"))
  1588. ,(cons `(*DEFAULT* ,urn-b . ,urn-b) namespaces) PCDATA)
  1589. (test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f)
  1590. )))
  1591. "HREF='b' xmlns='urn:b'>")))
  1592. ; xmlns:B not declared
  1593. (assert (equal? `((,urn-b . '"TAG1") (((,urn-b . '"HREF") . "b"))
  1594. ,(cons `('"B" ,urn-b . ,urn-b) namespaces) PCDATA)
  1595. (test "B:TAG1" '((('"B" . '"TAG1") PCDATA
  1596. ((('"B" . '"HREF") CDATA REQUIRED #f)
  1597. )))
  1598. "B:HREF='b' xmlns:B='urn:b'>")))
  1599. ))
  1600. ; procedure+: ssax:read-external-id PORT
  1601. ;
  1602. ; This procedure parses an ExternalID production:
  1603. ; [75] ExternalID ::= 'SYSTEM' S SystemLiteral
  1604. ; | 'PUBLIC' S PubidLiteral S SystemLiteral
  1605. ; [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
  1606. ; [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
  1607. ; [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9]
  1608. ; | [-'()+,./:=?;!*#@$_%]
  1609. ;
  1610. ; This procedure is supposed to be called when an ExternalID is expected;
  1611. ; that is, the current character must be either #\S or #\P that start
  1612. ; correspondingly a SYSTEM or PUBLIC token. This procedure returns the
  1613. ; SystemLiteral as a string. A PubidLiteral is disregarded if present.
  1614. (define (ssax:read-external-id port)
  1615. (let ((discriminator (ssax:read-NCName port)))
  1616. (assert-curr-char ssax:S-chars "space after SYSTEM or PUBLIC" port)
  1617. (ssax:skip-S port)
  1618. (let ((delimiter
  1619. (assert-curr-char '(#\' #\" ) "XML [11], XML [12]" port)))
  1620. (cond
  1621. ((eq? discriminator (string->symbol "SYSTEM"))
  1622. (begin0
  1623. (next-token '() (list delimiter) "XML [11]" port)
  1624. (read-char port) ; reading the closing delim
  1625. ))
  1626. ((eq? discriminator (string->symbol "PUBLIC"))
  1627. (skip-until (list delimiter) port)
  1628. (assert-curr-char ssax:S-chars "space after PubidLiteral" port)
  1629. (ssax:skip-S port)
  1630. (let* ((delimiter
  1631. (assert-curr-char '(#\' #\" ) "XML [11]" port))
  1632. (systemid
  1633. (next-token '() (list delimiter) "XML [11]" port)))
  1634. (read-char port) ; reading the closing delim
  1635. systemid))
  1636. (else
  1637. (parser-error port "XML [75], " discriminator
  1638. " rather than SYSTEM or PUBLIC"))))))
  1639. ;-----------------------------------------------------------------------------
  1640. ; Higher-level parsers and scanners
  1641. ;
  1642. ; They parse productions corresponding to the whole (document) entity
  1643. ; or its higher-level pieces (prolog, root element, etc).
  1644. ; Scan the Misc production in the context
  1645. ; [1] document ::= prolog element Misc*
  1646. ; [22] prolog ::= XMLDecl? Misc* (doctypedec l Misc*)?
  1647. ; [27] Misc ::= Comment | PI | S
  1648. ;
  1649. ; The following function should be called in the prolog or epilog contexts.
  1650. ; In these contexts, whitespaces are completely ignored.
  1651. ; The return value from ssax:scan-Misc is either a PI-token,
  1652. ; a DECL-token, a START token, or EOF.
  1653. ; Comments are ignored and not reported.
  1654. (define (ssax:scan-Misc port)
  1655. (let loop ((c (ssax:skip-S port)))
  1656. (cond
  1657. ((eof-object? c) c)
  1658. ((not (char=? c #\<))
  1659. (parser-error port "XML [22], char '" c "' unexpected"))
  1660. (else
  1661. (let ((token (ssax:read-markup-token port)))
  1662. (case (xml-token-kind token)
  1663. ((COMMENT) (loop (ssax:skip-S port)))
  1664. ((PI DECL START) token)
  1665. (else
  1666. (parser-error port "XML [22], unexpected token of kind "
  1667. (xml-token-kind token)
  1668. ))))))))
  1669. ; procedure+: ssax:read-char-data PORT EXPECT-EOF? STR-HANDLER SEED
  1670. ;
  1671. ; This procedure is to read the character content of an XML document
  1672. ; or an XML element.
  1673. ; [43] content ::=
  1674. ; (element | CharData | Reference | CDSect | PI
  1675. ; | Comment)*
  1676. ; To be more precise, the procedure reads CharData, expands CDSect
  1677. ; and character entities, and skips comments. The procedure stops
  1678. ; at a named reference, EOF, at the beginning of a PI or a start/end tag.
  1679. ;
  1680. ; port
  1681. ; a PORT to read
  1682. ; expect-eof?
  1683. ; a boolean indicating if EOF is normal, i.e., the character
  1684. ; data may be terminated by the EOF. EOF is normal
  1685. ; while processing a parsed entity.
  1686. ; str-handler
  1687. ; a STR-HANDLER
  1688. ; seed
  1689. ; an argument passed to the first invocation of STR-HANDLER.
  1690. ;
  1691. ; The procedure returns two results: SEED and TOKEN.
  1692. ; The SEED is the result of the last invocation of STR-HANDLER, or the
  1693. ; original seed if STR-HANDLER was never called.
  1694. ;
  1695. ; TOKEN can be either an eof-object (this can happen only if
  1696. ; expect-eof? was #t), or:
  1697. ; - an xml-token describing a START tag or an END-tag;
  1698. ; For a start token, the caller has to finish reading it.
  1699. ; - an xml-token describing the beginning of a PI. It's up to an
  1700. ; application to read or skip through the rest of this PI;
  1701. ; - an xml-token describing a named entity reference.
  1702. ;
  1703. ; CDATA sections and character references are expanded inline and
  1704. ; never returned. Comments are silently disregarded.
  1705. ;
  1706. ; As the XML Recommendation requires, all whitespace in character data
  1707. ; must be preserved. However, a CR character (#xD) must be disregarded
  1708. ; if it appears before a LF character (#xA), or replaced by a #xA character
  1709. ; otherwise. See Secs. 2.10 and 2.11 of the XML Recommendation. See also
  1710. ; the canonical XML Recommendation.
  1711. ; ssax:read-char-data port expect-eof? str-handler seed
  1712. (define ssax:read-char-data
  1713. (let
  1714. ((terminators-usual (list #\< #\& char-return))
  1715. (terminators-usual-eof (list #\< '*eof* #\& char-return))
  1716. (handle-fragment
  1717. (lambda (fragment str-handler seed)
  1718. (if (string-null? fragment) seed
  1719. (str-handler fragment "" seed))))
  1720. )
  1721. (lambda (port expect-eof? str-handler seed)
  1722. ; Very often, the first character we encounter is #\<
  1723. ; Therefore, we handle this case in a special, fast path
  1724. (if (eqv? #\< (peek-char port))
  1725. ; The fast path
  1726. (let ((token (ssax:read-markup-token port)))
  1727. (case (xml-token-kind token)
  1728. ((START END) ; The most common case
  1729. (values seed token))
  1730. ((CDSECT)
  1731. (let ((seed (ssax:read-cdata-body port str-handler seed)))
  1732. (ssax:read-char-data port expect-eof? str-handler seed)))
  1733. ((COMMENT) (ssax:read-char-data port expect-eof?
  1734. str-handler seed))
  1735. (else
  1736. (values seed token))))
  1737. ; The slow path
  1738. (let ((char-data-terminators
  1739. (if expect-eof? terminators-usual-eof terminators-usual)))
  1740. (let loop ((seed seed))
  1741. (let* ((fragment
  1742. (next-token '() char-data-terminators
  1743. "reading char data" port))
  1744. (term-char (peek-char port)) ; one of char-data-terminators
  1745. )
  1746. (if (eof-object? term-char)
  1747. (values
  1748. (handle-fragment fragment str-handler seed)
  1749. term-char)
  1750. (case term-char
  1751. ((#\<)
  1752. (let ((token (ssax:read-markup-token port)))
  1753. (case (xml-token-kind token)
  1754. ((CDSECT)
  1755. (loop
  1756. (ssax:read-cdata-body port str-handler
  1757. (handle-fragment fragment str-handler seed))))
  1758. ((COMMENT)
  1759. (loop (handle-fragment fragment str-handler seed)))
  1760. (else
  1761. (values
  1762. (handle-fragment fragment str-handler seed)
  1763. token)))))
  1764. ((#\&)
  1765. (case (peek-next-char port)
  1766. ((#\#) (read-char port)
  1767. (loop (str-handler fragment
  1768. (ssax:read-char-ref port)
  1769. seed)))
  1770. (else
  1771. (let ((name (ssax:read-NCName port)))
  1772. (assert-curr-char '(#\;) "XML [68]" port)
  1773. (values
  1774. (handle-fragment fragment str-handler seed)
  1775. (make-xml-token 'ENTITY-REF name))))))
  1776. (else ; This must be a CR character
  1777. (if (eqv? (peek-next-char port) #\newline)
  1778. (read-char port))
  1779. (loop (str-handler fragment (string #\newline) seed))))
  1780. ))))))))
  1781. ; a few lines of validation code
  1782. (run-test (letrec
  1783. ((a-tag (make-xml-token 'START (string->symbol "BR")))
  1784. (a-ref (make-xml-token 'ENTITY-REF (string->symbol "lt")))
  1785. (eof-object (lambda () eof-object)) ; a unique value
  1786. (str-handler (lambda (fragment foll-fragment seed)
  1787. (if (string-null? foll-fragment) (cons fragment seed)
  1788. (cons* foll-fragment fragment seed))))
  1789. (test (lambda (str expect-eof? expected-data expected-token)
  1790. (newline) (display "body: ") (write str)
  1791. (newline) (display "Result: ")
  1792. (let*-values
  1793. (((seed token)
  1794. (call-with-input-string (unesc-string str)
  1795. (lambda (port)
  1796. (ssax:read-char-data port expect-eof? str-handler '()))))
  1797. ((result) (reverse seed)))
  1798. (write result)
  1799. (display " ")
  1800. (display token)
  1801. (assert (equal? result (map unesc-string expected-data))
  1802. (if (eq? expected-token eof-object)
  1803. (eof-object? token)
  1804. (equal? token expected-token))))))
  1805. )
  1806. (test "" #t '() eof-object)
  1807. (assert (failed? (test "" #f '() eof-object)))
  1808. (test " " #t '(" ") eof-object)
  1809. (test "<BR/>" #f '() a-tag)
  1810. (test " <BR />" #f '(" ") a-tag)
  1811. (test " &lt;" #f '(" ") a-ref)
  1812. (test " a&lt;" #f '(" a") a-ref)
  1813. (test " a &lt;" #f '(" a ") a-ref)
  1814. (test " <!-- comment--> a a<BR/>" #f '(" " " a a") a-tag)
  1815. (test " <!-- comment-->%ra a<BR/>" #f '(" " "" "%n" "a a") a-tag)
  1816. (test " <!-- comment-->%r%na a<BR/>" #f '(" " "" "%n" "a a") a-tag)
  1817. (test " <!-- comment-->%r%na%t%r%r%na<BR/>" #f
  1818. '(" " "" "%n" "a%t" "%n" "" "%n" "a") a-tag)
  1819. (test "a<!-- comment--> a a<BR/>" #f '("a" " a a") a-tag)
  1820. (test "&#x21;<BR/>" #f '("" "!") a-tag)
  1821. (test "&#x21;%n<BR/>" #f '("" "!" "%n") a-tag)
  1822. (test "%t&#x21;%n<BR/>" #f '("%t" "!" "%n") a-tag)
  1823. (test "%t&#x21;%na a<BR/>" #f '("%t" "!" "%na a") a-tag)
  1824. (test "%t&#x21;%ra a<BR/>" #f '("%t" "!" "" "%n" "a a") a-tag)
  1825. (test "%t&#x21;%r%na a<BR/>" #f '("%t" "!" "" "%n" "a a") a-tag)
  1826. (test " %ta &#x21; b <BR/>" #f '(" %ta " "!" " b ") a-tag)
  1827. (test " %ta &#x20; b <BR/>" #f '(" %ta " " " " b ") a-tag)
  1828. (test "<![CDATA[<]]><BR/>" #f '("<") a-tag)
  1829. (test "<![CDATA[]]]><BR/>" #f '("]") a-tag)
  1830. (test "%t<![CDATA[<]]><BR/>" #f '("%t" "<") a-tag)
  1831. (test "%t<![CDATA[<]]>a b<BR/>" #f '("%t" "<" "a b") a-tag)
  1832. (test "%t<![CDATA[<]]> a b<BR/>" #f '("%t" "<" " a b") a-tag)
  1833. (test "%td <![CDATA[ <%r%r%n]]> a b<BR/>" #f
  1834. '("%td " " <" "%n" "" "%n" " a b") a-tag)
  1835. ))
  1836. ; procedure+: ssax:assert-token TOKEN KIND GI
  1837. ; Make sure that TOKEN is of anticipated KIND and has anticipated GI
  1838. ; Note GI argument may actually be a pair of two symbols, Namespace
  1839. ; URI or the prefix, and of the localname.
  1840. ; If the assertion fails, error-cont is evaluated by passing it
  1841. ; three arguments: token kind gi. The result of error-cont is returned.
  1842. (define (ssax:assert-token token kind gi error-cont)
  1843. (or
  1844. (and (xml-token? token)
  1845. (eq? kind (xml-token-kind token))
  1846. (equal? gi (xml-token-head token)))
  1847. (error-cont token kind gi)))
  1848. ;========================================================================
  1849. ; Highest-level parsers: XML to SXML
  1850. ; These parsers are a set of syntactic forms to instantiate a SSAX parser.
  1851. ; A user can instantiate the parser to do the full validation, or
  1852. ; no validation, or any particular validation. The user specifies
  1853. ; which PI he wants to be notified about. The user tells what to do
  1854. ; with the parsed character and element data. The latter handlers
  1855. ; determine if the parsing follows a SAX or a DOM model.
  1856. ; syntax: ssax:make-pi-parser my-pi-handlers
  1857. ; Create a parser to parse and process one Processing Element (PI).
  1858. ; my-pi-handlers
  1859. ; An assoc list of pairs (PI-TAG . PI-HANDLER)
  1860. ; where PI-TAG is an NCName symbol, the PI target, and
  1861. ; PI-HANDLER is a procedure PORT PI-TAG SEED
  1862. ; where PORT points to the first symbol after the PI target.
  1863. ; The handler should read the rest of the PI up to and including
  1864. ; the combination '?>' that terminates the PI. The handler should
  1865. ; return a new seed.
  1866. ; One of the PI-TAGs may be the symbol *DEFAULT*. The corresponding
  1867. ; handler will handle PIs that no other handler will. If the
  1868. ; *DEFAULT* PI-TAG is not specified, ssax:make-pi-parser will assume
  1869. ; the default handler that skips the body of the PI
  1870. ;
  1871. ; The output of the ssax:make-pi-parser is a procedure
  1872. ; PORT PI-TAG SEED
  1873. ; that will parse the current PI according to the user-specified handlers.
  1874. ;
  1875. ; The previous version of ssax:make-pi-parser was a low-level macro:
  1876. ; (define-macro ssax:make-pi-parser
  1877. ; (lambda (my-pi-handlers)
  1878. ; `(lambda (port target seed)
  1879. ; (case target
  1880. ; ; Generate the body of the case statement
  1881. ; ,@(let loop ((pi-handlers my-pi-handlers) (default #f))
  1882. ; (cond
  1883. ; ((null? pi-handlers)
  1884. ; (if default `((else (,default port target seed)))
  1885. ; '((else
  1886. ; (ssax:warn port "Skipping PI: " target nl)
  1887. ; (ssax:skip-pi port)
  1888. ; seed))))
  1889. ; ((eq? '*DEFAULT* (caar pi-handlers))
  1890. ; (loop (cdr pi-handlers) (cdar pi-handlers)))
  1891. ; (else
  1892. ; (cons
  1893. ; `((,(caar pi-handlers)) (,(cdar pi-handlers) port target seed))
  1894. ; (loop (cdr pi-handlers) default)))))))))
  1895. (define-syntax ssax:make-pi-parser
  1896. (syntax-rules ()
  1897. ((ssax:make-pi-parser orig-handlers)
  1898. (letrec-syntax
  1899. ; Generate the clauses of the case statement
  1900. ((loop
  1901. (syntax-rules (*DEFAULT*)
  1902. ((loop () #f accum port target seed) ; no default
  1903. (make-case
  1904. ((else
  1905. (ssax:warn port "Skipping PI: " target nl)
  1906. (ssax:skip-pi port)
  1907. seed)
  1908. . accum)
  1909. () target))
  1910. ((loop () default accum port target seed)
  1911. (make-case
  1912. ((else (default port target seed)) . accum)
  1913. () target))
  1914. ((loop ((*DEFAULT* . default) . handlers) old-def accum
  1915. port target seed)
  1916. (loop handlers default accum port target seed))
  1917. ((loop ((tag . handler) . handlers) default accum port target seed)
  1918. (loop handlers default
  1919. (((tag) (handler port target seed)) . accum)
  1920. port target seed))
  1921. ))
  1922. (make-case ; Reverse the clauses, make the 'case'
  1923. (syntax-rules ()
  1924. ((make-case () clauses target)
  1925. (case target . clauses))
  1926. ((make-case (clause . clauses) accum target)
  1927. (make-case clauses (clause . accum) target)))
  1928. ))
  1929. (lambda (port target seed)
  1930. (loop orig-handlers #f () port target seed))
  1931. ))))
  1932. (run-test
  1933. (pp (ssax:make-pi-parser ()))
  1934. (pp (ssax:make-pi-parser ((xml . (lambda (port target seed) seed)))))
  1935. (pp (ssax:make-pi-parser ((xml . (lambda (port target seed) seed))
  1936. (html . list)
  1937. (*DEFAULT* . ssax:warn))))
  1938. )
  1939. ; syntax: ssax:make-elem-parser my-new-level-seed my-finish-element
  1940. ; my-char-data-handler my-pi-handlers
  1941. ; Create a parser to parse and process one element, including its
  1942. ; character content or children elements. The parser is typically
  1943. ; applied to the root element of a document.
  1944. ; my-new-level-seed
  1945. ; procedure ELEM-GI ATTRIBUTES NAMESPACES EXPECTED-CONTENT SEED
  1946. ; where ELEM-GI is a RES-NAME of the element
  1947. ; about to be processed.
  1948. ; This procedure is to generate the seed to be passed
  1949. ; to handlers that process the content of the element.
  1950. ; This is the function identified as 'fdown' in the denotational
  1951. ; semantics of the XML parser given in the title comments to this
  1952. ; file.
  1953. ;
  1954. ; my-finish-element
  1955. ; procedure ELEM-GI ATTRIBUTES NAMESPACES PARENT-SEED SEED
  1956. ; This procedure is called when parsing of ELEM-GI is finished.
  1957. ; The SEED is the result from the last content parser (or
  1958. ; from my-new-level-seed if the element has the empty content).
  1959. ; PARENT-SEED is the same seed as was passed to my-new-level-seed.
  1960. ; The procedure is to generate a seed that will be the result
  1961. ; of the element parser.
  1962. ; This is the function identified as 'fup' in the denotational
  1963. ; semantics of the XML parser given in the title comments to this
  1964. ; file.
  1965. ;
  1966. ; my-char-data-handler
  1967. ; A STR-HANDLER
  1968. ;
  1969. ; my-pi-handlers
  1970. ; See ssax:make-pi-handler above
  1971. ;
  1972. ; The generated parser is a
  1973. ; procedure START-TAG-HEAD PORT ELEMS ENTITIES
  1974. ; NAMESPACES PRESERVE-WS? SEED
  1975. ; The procedure must be called after the start tag token has been
  1976. ; read. START-TAG-HEAD is an UNRES-NAME from the start-element tag.
  1977. ; ELEMS is an instance of xml-decl::elems.
  1978. ; See ssax:complete-start-tag::preserve-ws?
  1979. ; Faults detected:
  1980. ; VC: XML-Spec.html#elementvalid
  1981. ; WFC: XML-Spec.html#GIMatch
  1982. (define-syntax ssax:make-elem-parser
  1983. (syntax-rules ()
  1984. ((ssax:make-elem-parser my-new-level-seed my-finish-element
  1985. my-char-data-handler my-pi-handlers)
  1986. (lambda (start-tag-head port elems entities namespaces
  1987. preserve-ws? seed)
  1988. (define xml-space-gi (cons ssax:Prefix-XML
  1989. (string->symbol "space")))
  1990. (let handle-start-tag ((start-tag-head start-tag-head)
  1991. (port port) (entities entities)
  1992. (namespaces namespaces)
  1993. (preserve-ws? preserve-ws?) (parent-seed seed))
  1994. (let*-values
  1995. (((elem-gi attributes namespaces expected-content)
  1996. (ssax:complete-start-tag start-tag-head port elems
  1997. entities namespaces))
  1998. ((seed)
  1999. (my-new-level-seed elem-gi attributes
  2000. namespaces expected-content parent-seed)))
  2001. (case expected-content
  2002. ((EMPTY-TAG)
  2003. (my-finish-element
  2004. elem-gi attributes namespaces parent-seed seed))
  2005. ((EMPTY) ; The end tag must immediately follow
  2006. (ssax:assert-token
  2007. (and (eqv? #\< (ssax:skip-S port)) (ssax:read-markup-token port))
  2008. 'END start-tag-head
  2009. (lambda (token exp-kind exp-head)
  2010. (parser-error port "[elementvalid] broken for " token
  2011. " while expecting "
  2012. exp-kind exp-head)))
  2013. (my-finish-element
  2014. elem-gi attributes namespaces parent-seed seed))
  2015. (else ; reading the content...
  2016. (let ((preserve-ws? ; inherit or set the preserve-ws? flag
  2017. (cond
  2018. ((assoc xml-space-gi attributes) =>
  2019. (lambda (name-value)
  2020. (equal? "preserve" (cdr name-value))))
  2021. (else preserve-ws?))))
  2022. (let loop ((port port) (entities entities)
  2023. (expect-eof? #f) (seed seed))
  2024. (let*-values
  2025. (((seed term-token)
  2026. (ssax:read-char-data port expect-eof?
  2027. my-char-data-handler seed)))
  2028. (if (eof-object? term-token)
  2029. seed
  2030. (case (xml-token-kind term-token)
  2031. ((END)
  2032. (ssax:assert-token term-token 'END start-tag-head
  2033. (lambda (token exp-kind exp-head)
  2034. (parser-error port "[GIMatch] broken for "
  2035. term-token " while expecting "
  2036. exp-kind exp-head)))
  2037. (my-finish-element
  2038. elem-gi attributes namespaces parent-seed seed))
  2039. ((PI)
  2040. (let ((seed
  2041. ((ssax:make-pi-parser my-pi-handlers)
  2042. port (xml-token-head term-token) seed)))
  2043. (loop port entities expect-eof? seed)))
  2044. ((ENTITY-REF)
  2045. (let ((seed
  2046. (ssax:handle-parsed-entity
  2047. port (xml-token-head term-token)
  2048. entities
  2049. (lambda (port entities seed)
  2050. (loop port entities #t seed))
  2051. my-char-data-handler
  2052. seed))) ; keep on reading the content after ent
  2053. (loop port entities expect-eof? seed)))
  2054. ((START) ; Start of a child element
  2055. (if (eq? expected-content 'PCDATA)
  2056. (parser-error port "[elementvalid] broken for "
  2057. elem-gi
  2058. " with char content only; unexpected token "
  2059. term-token))
  2060. ; Do other validation of the element content
  2061. (let ((seed
  2062. (handle-start-tag
  2063. (xml-token-head term-token)
  2064. port entities namespaces
  2065. preserve-ws? seed)))
  2066. (loop port entities expect-eof? seed)))
  2067. (else
  2068. (parser-error port "XML [43] broken for "
  2069. term-token))))))))
  2070. )))
  2071. ))))
  2072. ; syntax: ssax:make-parser user-handler-tag user-handler-proc ...
  2073. ;
  2074. ; Create an XML parser, an instance of the XML parsing framework.
  2075. ; This will be a SAX, a DOM, or a specialized parser depending
  2076. ; on the supplied user-handlers.
  2077. ; user-handler-tag is a symbol that identifies a procedural expression
  2078. ; that follows the tag. Given below are tags and signatures of the
  2079. ; corresponding procedures. Not all tags have to be specified. If some
  2080. ; are omitted, reasonable defaults will apply.
  2081. ;
  2082. ; tag: DOCTYPE
  2083. ; handler-procedure: PORT DOCNAME SYSTEMID INTERNAL-SUBSET? SEED
  2084. ; If internal-subset? is #t, the current position in the port
  2085. ; is right after we have read #\[ that begins the internal DTD subset.
  2086. ; We must finish reading of this subset before we return
  2087. ; (or must call skip-internal-subset if we aren't interested in reading it).
  2088. ; The port at exit must be at the first symbol after the whole
  2089. ; DOCTYPE declaration.
  2090. ; The handler-procedure must generate four values:
  2091. ; ELEMS ENTITIES NAMESPACES SEED
  2092. ; See xml-decl::elems for ELEMS. It may be #f to switch off the validation.
  2093. ; NAMESPACES will typically contain USER-PREFIXes for selected URI-SYMBs.
  2094. ; The default handler-procedure skips the internal subset,
  2095. ; if any, and returns (values #f '() '() seed)
  2096. ; tag: UNDECL-ROOT
  2097. ; handler-procedure: ELEM-GI SEED
  2098. ; where ELEM-GI is an UNRES-NAME of the root element. This procedure
  2099. ; is called when an XML document under parsing contains _no_ DOCTYPE
  2100. ; declaration.
  2101. ; The handler-procedure, as a DOCTYPE handler procedure above,
  2102. ; must generate four values:
  2103. ; ELEMS ENTITIES NAMESPACES SEED
  2104. ; The default handler-procedure returns (values #f '() '() seed)
  2105. ; tag: DECL-ROOT
  2106. ; handler-procedure: ELEM-GI SEED
  2107. ; where ELEM-GI is an UNRES-NAME of the root element. This procedure
  2108. ; is called when an XML document under parsing does contains the DOCTYPE
  2109. ; declaration.
  2110. ; The handler-procedure must generate a new SEED (and verify
  2111. ; that the name of the root element matches the doctype, if the handler
  2112. ; so wishes).
  2113. ; The default handler-procedure is the identity function.
  2114. ; tag: NEW-LEVEL-SEED
  2115. ; handler-procedure: see ssax:make-elem-parser, my-new-level-seed
  2116. ; tag: FINISH-ELEMENT
  2117. ; handler-procedure: see ssax:make-elem-parser, my-finish-element
  2118. ; tag: CHAR-DATA-HANDLER
  2119. ; handler-procedure: see ssax:make-elem-parser, my-char-data-handler
  2120. ; tag: PI
  2121. ; handler-procedure: see ssax:make-pi-parser
  2122. ; The default value is '()
  2123. ; The generated parser is a
  2124. ; procedure PORT SEED
  2125. ; This procedure parses the document prolog and then exits to
  2126. ; an element parser (created by ssax:make-elem-parser) to handle
  2127. ; the rest.
  2128. ;
  2129. ; [1] document ::= prolog element Misc*
  2130. ; [22] prolog ::= XMLDecl? Misc* (doctypedec | Misc*)?
  2131. ; [27] Misc ::= Comment | PI | S
  2132. ;
  2133. ; [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
  2134. ; ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
  2135. ; [29] markupdecl ::= elementdecl | AttlistDecl
  2136. ; | EntityDecl
  2137. ; | NotationDecl | PI
  2138. ; | Comment
  2139. ;
  2140. ; This is ssax:make-parser with all the (specialization) handlers given
  2141. ; as positional arguments. It is called by ssax:make-parser, see below
  2142. (define-syntax ssax:make-parser/positional-args
  2143. (syntax-rules ()
  2144. ((ssax:make-parser/positional-args
  2145. *handler-DOCTYPE
  2146. *handler-UNDECL-ROOT
  2147. *handler-DECL-ROOT
  2148. *handler-NEW-LEVEL-SEED
  2149. *handler-FINISH-ELEMENT
  2150. *handler-CHAR-DATA-HANDLER
  2151. *handler-PI)
  2152. (lambda (port seed)
  2153. ; We must've just scanned the DOCTYPE token
  2154. ; Handle the doctype declaration and exit to
  2155. ; scan-for-significant-prolog-token-2, and eventually, to the
  2156. ; element parser.
  2157. (define (handle-decl port token-head seed)
  2158. (or (eq? (string->symbol "DOCTYPE") token-head)
  2159. (parser-error port "XML [22], expected DOCTYPE declaration, found "
  2160. token-head))
  2161. (assert-curr-char ssax:S-chars "XML [28], space after DOCTYPE" port)
  2162. (ssax:skip-S port)
  2163. (let*-values
  2164. (((docname) (ssax:read-QName port))
  2165. ((systemid)
  2166. (and (ssax:ncname-starting-char? (ssax:skip-S port))
  2167. (ssax:read-external-id port)))
  2168. ((internal-subset?)
  2169. (begin (ssax:skip-S port)
  2170. (eqv? #\[ (assert-curr-char '(#\> #\[)
  2171. "XML [28], end-of-DOCTYPE" port))))
  2172. ((elems entities namespaces seed)
  2173. (*handler-DOCTYPE port docname systemid
  2174. internal-subset? seed))
  2175. )
  2176. (scan-for-significant-prolog-token-2 port elems entities namespaces
  2177. seed)))
  2178. ; Scan the leading PIs until we encounter either a doctype declaration
  2179. ; or a start token (of the root element)
  2180. ; In the latter two cases, we exit to the appropriate continuation
  2181. (define (scan-for-significant-prolog-token-1 port seed)
  2182. (let ((token (ssax:scan-Misc port)))
  2183. (if (eof-object? token)
  2184. (parser-error port "XML [22], unexpected EOF")
  2185. (case (xml-token-kind token)
  2186. ((PI)
  2187. (let ((seed
  2188. ((ssax:make-pi-parser *handler-PI)
  2189. port (xml-token-head token) seed)))
  2190. (scan-for-significant-prolog-token-1 port seed)))
  2191. ((DECL) (handle-decl port (xml-token-head token) seed))
  2192. ((START)
  2193. (let*-values
  2194. (((elems entities namespaces seed)
  2195. (*handler-UNDECL-ROOT (xml-token-head token) seed)))
  2196. (element-parser (xml-token-head token) port elems
  2197. entities namespaces #f seed)))
  2198. (else (parser-error port "XML [22], unexpected markup "
  2199. token))))))
  2200. ; Scan PIs after the doctype declaration, till we encounter
  2201. ; the start tag of the root element. After that we exit
  2202. ; to the element parser
  2203. (define (scan-for-significant-prolog-token-2 port elems entities
  2204. namespaces seed)
  2205. (let ((token (ssax:scan-Misc port)))
  2206. (if (eof-object? token)
  2207. (parser-error port "XML [22], unexpected EOF")
  2208. (case (xml-token-kind token)
  2209. ((PI)
  2210. (let ((seed
  2211. ((ssax:make-pi-parser *handler-PI)
  2212. port (xml-token-head token) seed)))
  2213. (scan-for-significant-prolog-token-2 port elems entities
  2214. namespaces seed)))
  2215. ((START)
  2216. (element-parser (xml-token-head token) port elems
  2217. entities namespaces #f
  2218. (*handler-DECL-ROOT (xml-token-head token) seed)))
  2219. (else (parser-error port "XML [22], unexpected markup "
  2220. token))))))
  2221. ; A procedure start-tag-head port elems entities namespaces
  2222. ; preserve-ws? seed
  2223. (define element-parser
  2224. (ssax:make-elem-parser *handler-NEW-LEVEL-SEED
  2225. *handler-FINISH-ELEMENT
  2226. *handler-CHAR-DATA-HANDLER
  2227. *handler-PI))
  2228. ; Get the ball rolling ...
  2229. (scan-for-significant-prolog-token-1 port seed)
  2230. ))))
  2231. ; The following meta-macro turns a regular macro (with positional
  2232. ; arguments) into a form with keyword (labeled) arguments. We later
  2233. ; use the meta-macro to convert ssax:make-parser/positional-args into
  2234. ; ssax:make-parser. The latter provides a prettier (with labeled
  2235. ; arguments and defaults) interface to
  2236. ; ssax:make-parser/positional-args
  2237. ;
  2238. ; ssax:define-labeled-arg-macro LABELED-ARG-MACRO-NAME
  2239. ; (POS-MACRO-NAME ARG-DESCRIPTOR ...)
  2240. ; expands into the definition of a macro
  2241. ; LABELED-ARG-MACRO-NAME KW-NAME KW-VALUE KW-NAME1 KW-VALUE1 ...
  2242. ; which, in turn, expands into
  2243. ; POS-MACRO-NAME ARG1 ARG2 ...
  2244. ; where each ARG1 etc. comes either from KW-VALUE or from
  2245. ; the deafult part of ARG-DESCRIPTOR. ARG1 corresponds to the first
  2246. ; ARG-DESCRIPTOR, ARG2 corresponds to the second descriptor, etc.
  2247. ; Here ARG-DESCRIPTOR describes one argument of the positional macro.
  2248. ; It has the form
  2249. ; (ARG-NAME DEFAULT-VALUE)
  2250. ; or
  2251. ; (ARG-NAME)
  2252. ; In the latter form, the default value is not given, so that the invocation of
  2253. ; LABELED-ARG-MACRO-NAME must mention the corresponding parameter.
  2254. ; ARG-NAME can be anything: an identifier, a string, or even a number.
  2255. (define-syntax ssax:define-labeled-arg-macro
  2256. (syntax-rules ()
  2257. ((ssax:define-labeled-arg-macro
  2258. labeled-arg-macro-name
  2259. (positional-macro-name
  2260. (arg-name . arg-def) ...))
  2261. (define-syntax labeled-arg-macro-name
  2262. (syntax-rules ()
  2263. ((labeled-arg-macro-name . kw-val-pairs)
  2264. (letrec-syntax
  2265. ((find
  2266. (syntax-rules (arg-name ...)
  2267. ((find k-args (arg-name . default) arg-name
  2268. val . others) ; found arg-name among kw-val-pairs
  2269. (next val . k-args)) ...
  2270. ((find k-args key arg-no-match-name val . others)
  2271. (find k-args key . others))
  2272. ((find k-args (arg-name default)) ; default must be here
  2273. (next default . k-args)) ...
  2274. ))
  2275. (next ; pack the continuation to find
  2276. (syntax-rules ()
  2277. ((next val vals key . keys)
  2278. (find ((val . vals) . keys) key . kw-val-pairs))
  2279. ((next val vals) ; processed all arg-descriptors
  2280. (rev-apply (val) vals))))
  2281. (rev-apply
  2282. (syntax-rules ()
  2283. ((rev-apply form (x . xs))
  2284. (rev-apply (x . form) xs))
  2285. ((rev-apply form ()) form))))
  2286. (next positional-macro-name ()
  2287. (arg-name . arg-def) ...))))))))
  2288. ; The definition of ssax:make-parser
  2289. (ssax:define-labeled-arg-macro ssax:make-parser
  2290. (ssax:make-parser/positional-args
  2291. (DOCTYPE
  2292. (lambda (port docname systemid internal-subset? seed)
  2293. (when internal-subset?
  2294. (ssax:warn port "Internal DTD subset is not currently handled ")
  2295. (ssax:skip-internal-dtd port))
  2296. (ssax:warn port "DOCTYPE DECL " docname " "
  2297. systemid " found and skipped")
  2298. (values #f '() '() seed)
  2299. ))
  2300. (UNDECL-ROOT
  2301. (lambda (elem-gi seed) (values #f '() '() seed)))
  2302. (DECL-ROOT
  2303. (lambda (elem-gi seed) seed))
  2304. (NEW-LEVEL-SEED) ; required
  2305. (FINISH-ELEMENT) ; required
  2306. (CHAR-DATA-HANDLER) ; required
  2307. (PI ())
  2308. ))
  2309. (run-test
  2310. (letrec ((simple-parser
  2311. (lambda (str doctype-fn)
  2312. (call-with-input-string str
  2313. (lambda (port)
  2314. ((ssax:make-parser
  2315. NEW-LEVEL-SEED
  2316. (lambda (elem-gi attributes namespaces
  2317. expected-content seed)
  2318. '())
  2319. FINISH-ELEMENT
  2320. (lambda (elem-gi attributes namespaces parent-seed seed)
  2321. (let
  2322. ((seed (if (null? namespaces) (reverse seed)
  2323. (cons (list '*NAMESPACES* namespaces)
  2324. (reverse seed)))))
  2325. (let ((seed (if (attlist-null? attributes) seed
  2326. (cons
  2327. (cons '@
  2328. (map (lambda (attr)
  2329. (list (car attr) (cdr attr)))
  2330. (attlist->alist attributes)))
  2331. seed))))
  2332. (cons (cons elem-gi seed) parent-seed))))
  2333. CHAR-DATA-HANDLER
  2334. (lambda (string1 string2 seed)
  2335. (if (string-null? string2) (cons string1 seed)
  2336. (cons* string2 string1 seed)))
  2337. DOCTYPE
  2338. (lambda (port docname systemid internal-subset? seed)
  2339. (when internal-subset?
  2340. (ssax:warn port
  2341. "Internal DTD subset is not currently handled ")
  2342. (ssax:skip-internal-dtd port))
  2343. (ssax:warn port "DOCTYPE DECL " docname " "
  2344. systemid " found and skipped")
  2345. (doctype-fn docname seed))
  2346. UNDECL-ROOT
  2347. (lambda (elem-gi seed)
  2348. (doctype-fn elem-gi seed))
  2349. )
  2350. port '())))))
  2351. (dummy-doctype-fn (lambda (elem-gi seed) (values #f '() '() seed)))
  2352. (test
  2353. (lambda (str doctype-fn expected)
  2354. (cout nl "Parsing: " str nl)
  2355. (let ((result (simple-parser (unesc-string str) doctype-fn)))
  2356. (write result)
  2357. (assert (equal? result expected)))))
  2358. )
  2359. (test "<BR/>" dummy-doctype-fn '(('"BR")))
  2360. (assert (failed? (test "<BR>" dummy-doctype-fn '())))
  2361. (test "<BR></BR>" dummy-doctype-fn '(('"BR")))
  2362. (assert (failed? (test "<BR></BB>" dummy-doctype-fn '())))
  2363. (test " <A HREF='URL'> link <I>itlink </I> &amp;amp;</A>"
  2364. dummy-doctype-fn
  2365. '(('"A" (@ ('"HREF" "URL")) " link " ('"I" "itlink ")
  2366. " " "&" "amp;")))
  2367. (test
  2368. " <A HREF='URL' xml:space='preserve'> link <I>itlink </I> &amp;amp;</A>" dummy-doctype-fn
  2369. '(('"A" (@ ('"HREF" "URL") (('"xml" . '"space") "preserve"))
  2370. " link " ('"I" "itlink ") " " "&" "amp;")))
  2371. (test " <A HREF='URL' xml:space='preserve'> link <I xml:space='default'>itlink </I> &amp;amp;</A>" dummy-doctype-fn
  2372. '(('"A" (@ ('"HREF" "URL") (('"xml" . '"space") "preserve"))
  2373. " link "
  2374. ('"I" (@ (('"xml" . '"space") "default")) "itlink ")
  2375. " " "&" "amp;")))
  2376. (test "<itemize><item>This is item 1 </item>%n<!-- Just:a comment --><item>Item 2</item>%n </itemize>" dummy-doctype-fn
  2377. `(('"itemize" ('"item" "This is item 1 ")
  2378. ,(unesc-string "%n") ('"item" "Item 2") ,(unesc-string "%n "))))
  2379. (test " <P><![CDATA[<BR>%n<![CDATA[<BR>]]&gt;]]></P>"
  2380. dummy-doctype-fn `(('"P" "<BR>" ,nl "<![CDATA[<BR>" "]]" "" ">")))
  2381. (test " <P><![CDATA[<BR>%r<![CDATA[<BR>]]&gt;]]></P>"
  2382. dummy-doctype-fn `(('"P" "<BR>" ,nl "<![CDATA[<BR>" "]]" "" ">")))
  2383. (test "<?xml version='1.0'?>%n%n<Reports TStamp='1'></Reports>"
  2384. dummy-doctype-fn '(('"Reports" (@ ('"TStamp" "1")))))
  2385. (test "%n<?PI xxx?><!-- Comment %n -%r-->%n<?PI1 zzz?><T/>"
  2386. dummy-doctype-fn '(('"T")))
  2387. (test "<!DOCTYPE T SYSTEM 'system1' ><!-- comment -->%n<T/>"
  2388. (lambda (elem-gi seed) (assert (equal? elem-gi ''"T"))
  2389. (values #f '() '() seed))
  2390. '(('"T")))
  2391. (test "<!DOCTYPE T PUBLIC '//EN/T' \"system1\" [ <!ELEMENT a 'aa'> ]>%n<?pi?><T/>"
  2392. (lambda (elem-gi seed) (assert (equal? elem-gi ''"T"))
  2393. (values #f '() '() seed))
  2394. '(('"T")))
  2395. (test "<BR/>"
  2396. (lambda (elem-gi seed)
  2397. (values '(('"BR" EMPTY ())) '() '() seed)) '(('"BR")))
  2398. (test "<BR></BR>"
  2399. (lambda (elem-gi seed)
  2400. (values '(('"BR" EMPTY ())) '() '() seed)) '(('"BR")))
  2401. (assert (failed? (test "<BR>aa</BR>"
  2402. (lambda (elem-gi seed)
  2403. (values '(('"BR" EMPTY ())) '() '() seed)) '())))
  2404. (test "<BR>aa</BR>"
  2405. (lambda (elem-gi seed)
  2406. (values '(('"BR" PCDATA ())) '() '() seed)) '(('"BR" "aa")))
  2407. (assert (failed? (test "<BR>a<I>a</I></BR>"
  2408. (lambda (elem-gi seed)
  2409. (values '(('"BR" PCDATA ())) '() '() seed)) '())))
  2410. (test "<BR>a<I>a</I></BR>"
  2411. (lambda (elem-gi seed)
  2412. (values '(('"BR" ANY ()) ('"I" PCDATA ())) '() '() seed))
  2413. '(('"BR" "a" ('"I" "a"))))
  2414. (test "<DIV>Example: \"&example;\"</DIV>"
  2415. (lambda (elem-gi seed)
  2416. (values #f '((example . "<P>An ampersand (&#38;) may be escaped numerically (&#38;#38;) or with a general entity (&amp;amp;).</P>")) '() seed))
  2417. '(('"DIV" "Example: \""
  2418. ('"P" "An ampersand (" "&" ") may be escaped numerically (" "&" "#38;) or with a general entity (" "&" "amp;).") "\"")))
  2419. (test "<DIV>Example: \"&example;\" <P/></DIV>"
  2420. (lambda (elem-gi seed)
  2421. (values #f '(('"quote" . "<I>example:</I> ex")
  2422. ('"example" . "<Q>&quote;!</Q>?")) '() seed))
  2423. '(('"DIV" "Example: \"" ('"Q" ('"I" "example:") " ex" "!") "?"
  2424. "\" " ('"P"))))
  2425. (assert (failed?
  2426. (test "<DIV>Example: \"&example;\" <P/></DIV>"
  2427. (lambda (elem-gi seed)
  2428. (values #f '(('"quote" . "<I>example:")
  2429. ('"example" . "<Q>&quote;</I>!</Q>?")) '() seed))
  2430. '())))
  2431. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
  2432. (lambda (elem-gi seed)
  2433. (values #f '() '() seed))
  2434. '((('"URI1" . '"DIV") (@ ('"B" "B") (('"URI1" . '"B") "A"))
  2435. (*NAMESPACES* (('"A" '"URI1" . '"URI1")
  2436. (*DEFAULT* '"URI1" . '"URI1")))
  2437. (('"URI1" . '"P")
  2438. (*NAMESPACES* ((*DEFAULT* #f . #f) ('"A" '"URI1" . '"URI1")
  2439. (*DEFAULT* '"URI1" . '"URI1")))
  2440. ('"BR"
  2441. (*NAMESPACES* ((*DEFAULT* #f . #f)
  2442. ('"A" '"URI1" . '"URI1")
  2443. (*DEFAULT* '"URI1" . '"URI1"))))))))
  2444. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
  2445. (lambda (elem-gi seed)
  2446. (values #f '() '((#f '"UA" . '"URI1")) seed))
  2447. '((('"UA" . '"DIV") (@ ('"B" "B") (('"UA" . '"B") "A"))
  2448. (*NAMESPACES* (('"A" '"UA" . '"URI1")
  2449. (*DEFAULT* '"UA" . '"URI1") (#f '"UA" . '"URI1")))
  2450. (('"UA" . '"P")
  2451. (*NAMESPACES* ((*DEFAULT* #f . #f) ('"A" '"UA" . '"URI1")
  2452. (*DEFAULT* '"UA" . '"URI1") (#f '"UA" . '"URI1")))
  2453. ('"BR"
  2454. (*NAMESPACES* ((*DEFAULT* #f . #f) ('"A" '"UA" . '"URI1")
  2455. (*DEFAULT* '"UA" . '"URI1")
  2456. (#f '"UA" . '"URI1"))))))))
  2457. ; uniqattr should fail
  2458. (assert (failed?
  2459. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
  2460. (lambda (elem-gi seed)
  2461. (values
  2462. `(('"DIV" ANY (('"B" CDATA IMPLIED #f)
  2463. (('"A" . '"B") CDATA IMPLIED #f)
  2464. (('"C" . '"B") CDATA IMPLIED "xx")
  2465. (('"xmlns" . '"C") CDATA IMPLIED "URI1")
  2466. ))
  2467. (('"A" . '"P") ANY ()) ('"BR" '"EMPTY" ()))
  2468. '() '((#f '"UA" . '"URI1")) seed))
  2469. '())))
  2470. ; prefix C undeclared
  2471. (assert (failed?
  2472. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
  2473. (lambda (elem-gi seed)
  2474. (values
  2475. '(('"DIV" ANY (('"B" CDATA IMPLIED #f)
  2476. ('"xmlns" CDATA IMPLIED "URI1")
  2477. (('"A" . '"B") CDATA IMPLIED #f)
  2478. (('"C" . '"B") CDATA IMPLIED "xx")
  2479. ))
  2480. (('"A" . '"P") ANY ()) ('"BR" EMPTY ()))
  2481. '() '((#f '"UA" . '"URI1")) seed))
  2482. '())))
  2483. ; contradiction to xmlns declaration
  2484. (assert (failed?
  2485. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
  2486. (lambda (elem-gi seed)
  2487. (values
  2488. '(('"DIV" ANY (('"B" CDATA IMPLIED #f)
  2489. ('"xmlns" CDATA FIXED "URI2")
  2490. (('"A" . '"B") CDATA IMPLIED #f)
  2491. ))
  2492. (('"A" . '"P") ANY ()) ('"BR" EMPTY ()))
  2493. '() '((#f '"UA" . '"URI1")) seed))
  2494. '())))
  2495. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
  2496. (lambda (elem-gi seed)
  2497. (values
  2498. '(('"DIV" ANY (('"B" CDATA IMPLIED #f)
  2499. ('"xmlns" CDATA FIXED "URI1")
  2500. (('"A" . '"B") CDATA IMPLIED #f)
  2501. ))
  2502. (('"A" . '"P") ANY ()) ('"BR" EMPTY ()))
  2503. '() '((#f '"UA" . '"URI1")) seed))
  2504. '((('"UA" . '"DIV") (@ ('"B" "B") (('"UA" . '"B") "A"))
  2505. (*NAMESPACES* ((*DEFAULT* '"UA" . '"URI1")
  2506. ('"A" '"UA" . '"URI1") (#f '"UA" . '"URI1")))
  2507. (('"UA" . '"P")
  2508. (*NAMESPACES* ((*DEFAULT* #f . #f)
  2509. (*DEFAULT* '"UA" . '"URI1")
  2510. ('"A" '"UA" . '"URI1") (#f '"UA" . '"URI1")))
  2511. ('"BR"
  2512. (*NAMESPACES* ((*DEFAULT* #f . #f) (*DEFAULT* '"UA" . '"URI1")
  2513. ('"A" '"UA" . '"URI1") (#f '"UA" . '"URI1"))))))))
  2514. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
  2515. (lambda (elem-gi seed)
  2516. (values
  2517. '(('"DIV" ANY (('"B" CDATA IMPLIED #f)
  2518. (('"A" . '"B") CDATA IMPLIED #f)
  2519. (('"C" . '"B") CDATA IMPLIED "xx")
  2520. (('"xmlns" . '"C") CDATA IMPLIED "URI2")
  2521. ))
  2522. (('"A" . '"P") ANY ()) ('"BR" EMPTY ()))
  2523. '() '((#f '"UA" . '"URI1")) seed))
  2524. '((('"UA" . '"DIV") (@ ('"B" "B") (('"UA" . '"B") "A")
  2525. (('"URI2" . '"B") "xx"))
  2526. (*NAMESPACES* ((*DEFAULT* '"UA" . '"URI1")
  2527. ('"A" '"UA" . '"URI1")
  2528. ('"C" '"URI2" . '"URI2")
  2529. (#f '"UA" . '"URI1")))
  2530. (('"UA" . '"P")
  2531. (*NAMESPACES* ((*DEFAULT* #f . #f) (*DEFAULT* '"UA" . '"URI1")
  2532. ('"A" '"UA" . '"URI1")
  2533. ('"C" '"URI2" . '"URI2") (#f '"UA" . '"URI1")))
  2534. ('"BR"
  2535. (*NAMESPACES* ((*DEFAULT* #f . #f)
  2536. (*DEFAULT* '"UA" . '"URI1")
  2537. ('"A" '"UA" . '"URI1")
  2538. ('"C" '"URI2" . '"URI2")
  2539. (#f '"UA" . '"URI1"))))))))
  2540. ))
  2541. ;========================================================================
  2542. ; Highest-level parsers: XML to SXML
  2543. ;
  2544. ; First, a few utility procedures that turned out useful
  2545. ; ssax:reverse-collect-str LIST-OF-FRAGS -> LIST-OF-FRAGS
  2546. ; given the list of fragments (some of which are text strings)
  2547. ; reverse the list and concatenate adjacent text strings.
  2548. ; We can prove from the general case below that if LIST-OF-FRAGS
  2549. ; has zero or one element, the result of the procedure is equal?
  2550. ; to its argument. This fact justifies the shortcut evaluation below.
  2551. (define (ssax:reverse-collect-str fragments)
  2552. (cond
  2553. ((null? fragments) '()) ; a shortcut
  2554. ((null? (cdr fragments)) fragments) ; see the comment above
  2555. (else
  2556. (let loop ((fragments fragments) (result '()) (strs '()))
  2557. (cond
  2558. ((null? fragments)
  2559. (if (null? strs) result
  2560. (cons (string-concatenate/shared strs) result)))
  2561. ((string? (car fragments))
  2562. (loop (cdr fragments) result (cons (car fragments) strs)))
  2563. (else
  2564. (loop (cdr fragments)
  2565. (cons
  2566. (car fragments)
  2567. (if (null? strs) result
  2568. (cons (string-concatenate/shared strs) result)))
  2569. '())))))))
  2570. ; ssax:reverse-collect-str-drop-ws LIST-OF-FRAGS -> LIST-OF-FRAGS
  2571. ; given the list of fragments (some of which are text strings)
  2572. ; reverse the list and concatenate adjacent text strings.
  2573. ; We also drop "unsignificant" whitespace, that is, whitespace
  2574. ; in front, behind and between elements. The whitespace that
  2575. ; is included in character data is not affected.
  2576. ; We use this procedure to "intelligently" drop "insignificant"
  2577. ; whitespace in the parsed SXML. If the strict compliance with
  2578. ; the XML Recommendation regarding the whitespace is desired, please
  2579. ; use the ssax:reverse-collect-str procedure instead.
  2580. (define (ssax:reverse-collect-str-drop-ws fragments)
  2581. (cond
  2582. ((null? fragments) '()) ; a shortcut
  2583. ((null? (cdr fragments)) ; another shortcut
  2584. (if (and (string? (car fragments)) (string-whitespace? (car fragments)))
  2585. '() fragments)) ; remove trailing ws
  2586. (else
  2587. (let loop ((fragments fragments) (result '()) (strs '())
  2588. (all-whitespace? #t))
  2589. (cond
  2590. ((null? fragments)
  2591. (if all-whitespace? result ; remove leading ws
  2592. (cons (string-concatenate/shared strs) result)))
  2593. ((string? (car fragments))
  2594. (loop (cdr fragments) result (cons (car fragments) strs)
  2595. (and all-whitespace?
  2596. (string-whitespace? (car fragments)))))
  2597. (else
  2598. (loop (cdr fragments)
  2599. (cons
  2600. (car fragments)
  2601. (if all-whitespace? result
  2602. (cons (string-concatenate/shared strs) result)))
  2603. '() #t)))))))
  2604. ; procedure: ssax:xml->sxml PORT NAMESPACE-PREFIX-ASSIG
  2605. ;
  2606. ; This is an instance of a SSAX parser above that returns an SXML
  2607. ; representation of the XML document to be read from PORT.
  2608. ; NAMESPACE-PREFIX-ASSIG is a list of (USER-PREFIX . URI-STRING)
  2609. ; that assigns USER-PREFIXes to certain namespaces identified by
  2610. ; particular URI-STRINGs. It may be an empty list.
  2611. ; The procedure returns an SXML tree. The port points out to the
  2612. ; first character after the root element.
  2613. (define (ssax:xml->sxml port namespace-prefix-assig)
  2614. (letrec
  2615. ((namespaces
  2616. (map (lambda (el)
  2617. (cons* #f (car el) (ssax:uri-string->symbol (cdr el))))
  2618. namespace-prefix-assig))
  2619. (RES-NAME->SXML
  2620. (lambda (res-name)
  2621. (string->symbol
  2622. (string-append
  2623. (symbol->string (car res-name))
  2624. ":"
  2625. (symbol->string (cdr res-name))))))
  2626. )
  2627. (let ((result
  2628. (reverse
  2629. ((ssax:make-parser
  2630. NEW-LEVEL-SEED
  2631. (lambda (elem-gi attributes namespaces
  2632. expected-content seed)
  2633. '())
  2634. FINISH-ELEMENT
  2635. (lambda (elem-gi attributes namespaces parent-seed seed)
  2636. (let ((seed (ssax:reverse-collect-str seed))
  2637. (attrs
  2638. (attlist-fold
  2639. (lambda (attr accum)
  2640. (cons (list
  2641. (if (symbol? (car attr)) (car attr)
  2642. (RES-NAME->SXML (car attr)))
  2643. (cdr attr)) accum))
  2644. '() attributes)))
  2645. (cons
  2646. (cons
  2647. (if (symbol? elem-gi) elem-gi
  2648. (RES-NAME->SXML elem-gi))
  2649. (if (null? attrs) seed
  2650. (cons (cons '@ attrs) seed)))
  2651. parent-seed)))
  2652. CHAR-DATA-HANDLER
  2653. (lambda (string1 string2 seed)
  2654. (if (string-null? string2) (cons string1 seed)
  2655. (cons* string2 string1 seed)))
  2656. DOCTYPE
  2657. (lambda (port docname systemid internal-subset? seed)
  2658. (when internal-subset?
  2659. (ssax:warn port
  2660. "Internal DTD subset is not currently handled ")
  2661. (ssax:skip-internal-dtd port))
  2662. (ssax:warn port "DOCTYPE DECL " docname " "
  2663. systemid " found and skipped")
  2664. (values #f '() namespaces seed))
  2665. UNDECL-ROOT
  2666. (lambda (elem-gi seed)
  2667. (values #f '() namespaces seed))
  2668. PI
  2669. ((*DEFAULT* .
  2670. (lambda (port pi-tag seed)
  2671. (cons
  2672. (list '*PI* pi-tag (ssax:read-pi-body-as-string port))
  2673. seed))))
  2674. )
  2675. port '()))))
  2676. (cons '*TOP*
  2677. (if (null? namespace-prefix-assig) result
  2678. (cons
  2679. (list '@ (cons '*NAMESPACES*
  2680. (map (lambda (ns) (list (car ns) (cdr ns)))
  2681. namespace-prefix-assig)))
  2682. result)))
  2683. )))
  2684. ; For backwards compatibility
  2685. (define SSAX:XML->SXML ssax:xml->sxml)
  2686. ; a few lines of validation code
  2687. (run-test (letrec
  2688. ((test (lambda (str namespace-assig expected-res)
  2689. (newline) (display "input: ")
  2690. (write (unesc-string str)) (newline) (display "Result: ")
  2691. (let ((result
  2692. (call-with-input-string (unesc-string str)
  2693. (lambda (port)
  2694. (ssax:xml->sxml port namespace-assig)))))
  2695. (pp result)
  2696. (assert (equal_? result expected-res))))))
  2697. (test " <BR/>" '() '(*TOP* (BR)))
  2698. (test "<BR></BR>" '() '(*TOP* (BR)))
  2699. (test " <BR CLEAR='ALL'%nCLASS='Class1'/>" '()
  2700. '(*TOP* (BR (@ (CLEAR "ALL") (CLASS "Class1")))))
  2701. (test " <A HREF='URL'> link <I>itlink </I> &amp;amp;</A>" '()
  2702. '(*TOP* (A (@ (HREF "URL")) " link " (I "itlink ") " &amp;")))
  2703. (test " <A HREF='URL' xml:space='preserve'> link <I>itlink </I> &amp;amp;</A>" '()
  2704. '(*TOP* (A (@ (xml:space "preserve") (HREF "URL"))
  2705. " link " (I "itlink ") " &amp;")))
  2706. (test " <A HREF='URL' xml:space='preserve'> link <I xml:space='default'>itlink </I> &amp;amp;</A>" '()
  2707. '(*TOP* (A (@ (xml:space "preserve") (HREF "URL"))
  2708. " link " (I (@ (xml:space "default"))
  2709. "itlink ") " &amp;")))
  2710. (test " <P><?pi1 p1 content ?>?<?pi2 pi2? content? ??></P>" '()
  2711. '(*TOP* (P (*PI* pi1 "p1 content ") "?"
  2712. (*PI* pi2 "pi2? content? ?"))))
  2713. (test " <P>some text <![CDATA[<]]>1%n&quot;<B>strong</B>&quot;%r</P>"
  2714. '()
  2715. `(*TOP* (P ,(unesc-string "some text <1%n\"")
  2716. (B "strong") ,(unesc-string "\"%n"))))
  2717. (test " <P><![CDATA[<BR>%n<![CDATA[<BR>]]&gt;]]></P>" '()
  2718. `(*TOP* (P ,(unesc-string "<BR>%n<![CDATA[<BR>]]>"))))
  2719. ; (test "<T1><T2>it&apos;s%r%nand that%n</T2>%r%n%r%n%n</T1>" '()
  2720. ; '(*TOP* (T1 (T2 "it's%nand that%n") "%n%n%n")))
  2721. (test "<T1><T2>it&apos;s%r%nand that%n</T2>%r%n%r%n%n</T1>" '()
  2722. `(*TOP* (T1 (T2 ,(unesc-string "it's%nand that%n")) ,(unesc-string "%n%n%n"))))
  2723. (test "<T1><T2>it&apos;s%rand that%n</T2>%r%n%r%n%n</T1>" '()
  2724. `(*TOP* (T1 (T2 ,(unesc-string "it's%nand that%n")) ,(unesc-string "%n%n%n"))))
  2725. (test "<!DOCTYPE T SYSTEM 'system1' ><!-- comment -->%n<T/>" '()
  2726. '(*TOP* (T)))
  2727. (test "<?xml version='1.0'?>%n<WEIGHT unit=\"pound\">%n<NET certified='certified'> 67 </NET>%n<GROSS> 95 </GROSS>%n</WEIGHT>" '()
  2728. `(*TOP* (*PI* xml "version='1.0'") (WEIGHT (@ (unit "pound"))
  2729. ,nl (NET (@ (certified "certified")) " 67 ") ,nl
  2730. (GROSS " 95 ") ,nl)
  2731. ))
  2732. ; (test "<?xml version='1.0'?>%n<WEIGHT unit=\"pound\">%n<NET certified='certified'> 67 </NET>%n<GROSS> 95 </GROSS>%n</WEIGHT>" '()
  2733. ; '(*TOP* (*PI* xml "version='1.0'") (WEIGHT (@ (unit "pound"))
  2734. ; "%n" (NET (@ (certified "certified")) " 67 ")
  2735. ; "%n" (GROSS " 95 ") "%n")
  2736. ; ))
  2737. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>" '()
  2738. '(*TOP* (URI1:DIV (@ (URI1:B "A") (B "B")) (URI1:P (BR)))))
  2739. (test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>" '((UA . "URI1"))
  2740. '(*TOP* (@ (*NAMESPACES* (UA "URI1")))
  2741. (UA:DIV (@ (UA:B "A") (B "B")) (UA:P (BR)))))
  2742. ; A few tests from XML Namespaces Recommendation
  2743. (test (string-append
  2744. "<x xmlns:edi='http://ecommerce.org/schema'>"
  2745. "<!-- the 'taxClass' attribute's ns http://ecommerce.org/schema -->"
  2746. "<lineItem edi:taxClass='exempt'>Baby food</lineItem>" nl
  2747. "</x>") '()
  2748. `(*TOP*
  2749. (x (lineItem
  2750. (@ (http://ecommerce.org/schema:taxClass "exempt"))
  2751. "Baby food") ,nl)))
  2752. (test (string-append
  2753. "<x xmlns:edi='http://ecommerce.org/schema'>"
  2754. "<!-- the 'taxClass' attribute's ns http://ecommerce.org/schema -->"
  2755. "<lineItem edi:taxClass='exempt'>Baby food</lineItem>"
  2756. "</x>") '((EDI . "http://ecommerce.org/schema"))
  2757. '(*TOP*
  2758. (@ (*NAMESPACES* (EDI "http://ecommerce.org/schema")))
  2759. (x (lineItem
  2760. (@ (EDI:taxClass "exempt"))
  2761. "Baby food"))))
  2762. (test (string-append
  2763. "<bk:book xmlns:bk='urn:loc.gov:books' "
  2764. "xmlns:isbn='urn:ISBN:0-395-36341-6'>"
  2765. "<bk:title>Cheaper by the Dozen</bk:title>"
  2766. "<isbn:number>1568491379</isbn:number></bk:book>")
  2767. '()
  2768. '(*TOP* (urn:loc.gov:books:book
  2769. (urn:loc.gov:books:title "Cheaper by the Dozen")
  2770. (urn:ISBN:0-395-36341-6:number "1568491379"))))
  2771. (test (string-append
  2772. "<!-- initially, the default namespace is 'books' -->"
  2773. "<book xmlns='urn:loc.gov:books' "
  2774. "xmlns:isbn='urn:ISBN:0-395-36341-6'>"
  2775. "<title>Cheaper by the Dozen</title>"
  2776. "<isbn:number>1568491379</isbn:number>"
  2777. "<notes>"
  2778. "<!-- make HTML the default namespace for some commentary -->"
  2779. "<p xmlns='urn:w3-org-ns:HTML'>"
  2780. "This is a <i>funny</i> book!"
  2781. "</p>"
  2782. "</notes>"
  2783. "</book>") '()
  2784. '(*TOP* (urn:loc.gov:books:book
  2785. (urn:loc.gov:books:title "Cheaper by the Dozen")
  2786. (urn:ISBN:0-395-36341-6:number "1568491379")
  2787. (urn:loc.gov:books:notes
  2788. (urn:w3-org-ns:HTML:p
  2789. "This is a " (urn:w3-org-ns:HTML:i "funny")
  2790. " book!")))))
  2791. (test (string-append
  2792. "<Beers>"
  2793. "<!-- the default namespace is now that of HTML -->"
  2794. "<table xmlns='http://www.w3.org/TR/REC-html40'>"
  2795. "<th><td>Name</td><td>Origin</td><td>Description</td></th>"
  2796. "<tr>"
  2797. "<!-- no default namespace inside table cells -->"
  2798. "<td><brandName xmlns=\"\">Huntsman</brandName></td>"
  2799. "<td><origin xmlns=''>Bath, UK</origin></td>"
  2800. "<td>"
  2801. "<details xmlns=''><class>Bitter</class><hop>Fuggles</hop>"
  2802. "<pro>Wonderful hop, light alcohol, good summer beer</pro>"
  2803. "<con>Fragile; excessive variance pub to pub</con>"
  2804. "</details>"
  2805. "</td>"
  2806. "</tr>"
  2807. "</table>"
  2808. "</Beers>")
  2809. '((html . "http://www.w3.org/TR/REC-html40"))
  2810. '(*TOP*
  2811. (@ (*NAMESPACES* (html "http://www.w3.org/TR/REC-html40")))
  2812. (Beers (html:table
  2813. (html:th (html:td "Name")
  2814. (html:td "Origin")
  2815. (html:td "Description"))
  2816. (html:tr (html:td (brandName "Huntsman"))
  2817. (html:td (origin "Bath, UK"))
  2818. (html:td
  2819. (details
  2820. (class "Bitter")
  2821. (hop "Fuggles")
  2822. (pro "Wonderful hop, light alcohol, good summer beer")
  2823. (con "Fragile; excessive variance pub to pub"))))))))
  2824. (test (string-append
  2825. "<!-- 1 --><RESERVATION xmlns:HTML='http://www.w3.org/TR/REC-html40'>"
  2826. "<!-- 2 --><NAME HTML:CLASS=\"largeSansSerif\">Layman, A</NAME>"
  2827. "<!-- 3 --><SEAT CLASS='Y' HTML:CLASS=\"largeMonotype\">33B</SEAT>"
  2828. "<!-- 4 --><HTML:A HREF='/cgi-bin/ResStatus'>Check Status</HTML:A>"
  2829. "<!-- 5 --><DEPARTURE>1997-05-24T07:55:00+1</DEPARTURE></RESERVATION>")
  2830. '((HTML . "http://www.w3.org/TR/REC-html40"))
  2831. '(*TOP*
  2832. (@ (*NAMESPACES* (HTML "http://www.w3.org/TR/REC-html40")))
  2833. (RESERVATION
  2834. (NAME (@ (HTML:CLASS "largeSansSerif")) "Layman, A")
  2835. (SEAT (@ (HTML:CLASS "largeMonotype") (CLASS "Y")) "33B")
  2836. (HTML:A (@ (HREF "/cgi-bin/ResStatus")) "Check Status")
  2837. (DEPARTURE "1997-05-24T07:55:00+1"))))
  2838. ; Part of RDF from the XML Infoset
  2839. (test (string-concatenate/shared '(
  2840. "<?xml version='1.0' encoding='utf-8' standalone='yes'?>"
  2841. "<!-- this can be decoded as US-ASCII or iso-8859-1 as well,"
  2842. " since it contains no characters outside the US-ASCII repertoire -->"
  2843. "<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'"
  2844. " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema#'"
  2845. " xmlns='http://www.w3.org/2001/02/infoset#'>"
  2846. "<rdfs:Class ID='Boolean'/>"
  2847. "<Boolean ID='Boolean.true'/>"
  2848. "<Boolean ID='Boolean.false'/>"
  2849. "<!--Info item classes-->"
  2850. "<rdfs:Class ID='InfoItem'/>"
  2851. "<rdfs:Class ID='Document' rdfs:subClassOf='#InfoItem'/>"
  2852. "<rdfs:Class ID='Element' rdfs:subClassOf='#InfoItem'/>"
  2853. "<rdfs:Class ID='Attribute' rdfs:subClassOf='#InfoItem'/>"
  2854. "<rdfs:Class ID='InfoItemSet'
  2855. rdfs:subClassOf='http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag'/>"
  2856. "<rdfs:Class ID='AttributeSet' rdfs:subClassOf='#InfoItemSet'/>"
  2857. "<!--Info item properties-->"
  2858. "<rdfs:Property ID='allDeclarationsProcessed'>"
  2859. "<rdfs:domain resource='#Document'/>"
  2860. "<rdfs:range resource='#Boolean'/></rdfs:Property>"
  2861. "<rdfs:Property ID='attributes'>"
  2862. "<rdfs:domain resource='#Element'/>"
  2863. "<rdfs:range resource='#AttributeSet'/>"
  2864. "</rdfs:Property>"
  2865. "</rdf:RDF>"))
  2866. '((RDF . "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
  2867. (RDFS . "http://www.w3.org/2000/01/rdf-schema#")
  2868. (ISET . "http://www.w3.org/2001/02/infoset#"))
  2869. '(*TOP* (@ (*NAMESPACES*
  2870. (RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
  2871. (RDFS "http://www.w3.org/2000/01/rdf-schema#")
  2872. (ISET "http://www.w3.org/2001/02/infoset#")))
  2873. (*PI* xml "version='1.0' encoding='utf-8' standalone='yes'")
  2874. (RDF:RDF
  2875. (RDFS:Class (@ (ID "Boolean")))
  2876. (ISET:Boolean (@ (ID "Boolean.true")))
  2877. (ISET:Boolean (@ (ID "Boolean.false")))
  2878. (RDFS:Class (@ (ID "InfoItem")))
  2879. (RDFS:Class (@ (RDFS:subClassOf "#InfoItem") (ID "Document")))
  2880. (RDFS:Class (@ (RDFS:subClassOf "#InfoItem") (ID "Element")))
  2881. (RDFS:Class (@ (RDFS:subClassOf "#InfoItem") (ID "Attribute")))
  2882. (RDFS:Class
  2883. (@ (RDFS:subClassOf
  2884. "http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag")
  2885. (ID "InfoItemSet")))
  2886. (RDFS:Class
  2887. (@ (RDFS:subClassOf "#InfoItemSet") (ID "AttributeSet")))
  2888. (RDFS:Property
  2889. (@ (ID "allDeclarationsProcessed"))
  2890. (RDFS:domain (@ (resource "#Document")))
  2891. (RDFS:range (@ (resource "#Boolean"))))
  2892. (RDFS:Property
  2893. (@ (ID "attributes"))
  2894. (RDFS:domain (@ (resource "#Element")))
  2895. (RDFS:range (@ (resource "#AttributeSet")))))))
  2896. ; Part of RDF from RSS of the Daemon News Mall
  2897. (test (string-concatenate/shared (list-intersperse '(
  2898. "<?xml version='1.0'?><rdf:RDF "
  2899. "xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' "
  2900. "xmlns='http://my.netscape.com/rdf/simple/0.9/'>"
  2901. "<channel>"
  2902. "<title>Daemon News Mall</title>"
  2903. "<link>http://mall.daemonnews.org/</link>"
  2904. "<description>Central source for all your BSD needs</description>"
  2905. "</channel>"
  2906. "<item>"
  2907. "<title>Daemon News Jan/Feb Issue NOW Available! Subscribe $24.95</title>"
  2908. "<link>http://mall.daemonnews.org/?page=shop/flypage&amp;product_id=880</link>"
  2909. "</item>"
  2910. "<item>"
  2911. "<title>The Design and Implementation of the 4.4BSD Operating System $54.95</title>"
  2912. "<link>http://mall.daemonnews.org/?page=shop/flypage&amp;product_id=912&amp;category_id=1761</link>"
  2913. "</item>"
  2914. "</rdf:RDF>")
  2915. (string #\newline)
  2916. ))
  2917. '((RDF . "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
  2918. (RSS . "http://my.netscape.com/rdf/simple/0.9/")
  2919. (ISET . "http://www.w3.org/2001/02/infoset#"))
  2920. `(*TOP* (@ (*NAMESPACES*
  2921. (RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
  2922. (RSS "http://my.netscape.com/rdf/simple/0.9/")
  2923. (ISET "http://www.w3.org/2001/02/infoset#")))
  2924. (*PI* xml "version='1.0'")
  2925. (RDF:RDF ,nl
  2926. (RSS:channel ,nl
  2927. (RSS:title "Daemon News Mall") ,nl
  2928. (RSS:link "http://mall.daemonnews.org/") ,nl
  2929. (RSS:description "Central source for all your BSD needs") ,nl) ,nl
  2930. (RSS:item ,nl
  2931. (RSS:title
  2932. "Daemon News Jan/Feb Issue NOW Available! Subscribe $24.95") ,nl
  2933. (RSS:link
  2934. "http://mall.daemonnews.org/?page=shop/flypage&product_id=880") ,nl) ,nl
  2935. (RSS:item ,nl
  2936. (RSS:title
  2937. "The Design and Implementation of the 4.4BSD Operating System $54.95") ,nl
  2938. (RSS:link
  2939. "http://mall.daemonnews.org/?page=shop/flypage&product_id=912&category_id=1761") ,nl) ,nl)))
  2940. (test (string-concatenate/shared
  2941. '("<Forecasts TStamp='958082142'>"
  2942. "<TAF TStamp='958066200' LatLon='36.583, -121.850' BId='724915'"
  2943. " SName='KMRY, MONTEREY PENINSULA'>"
  2944. "<VALID TRange='958068000, 958154400'>111730Z 111818</VALID>"
  2945. "<PERIOD TRange='958068000, 958078800'>"
  2946. "<PREVAILING>31010KT P6SM FEW030</PREVAILING>"
  2947. "</PERIOD>"
  2948. "<PERIOD TRange='958078800, 958104000' Title='FM2100'>"
  2949. "<PREVAILING>29016KT P6SM FEW040</PREVAILING>"
  2950. "</PERIOD>"
  2951. "<PERIOD TRange='958104000, 958154400' Title='FM0400'>"
  2952. "<PREVAILING>29010KT P6SM SCT200</PREVAILING>"
  2953. "<VAR Title='BECMG 0708' TRange='958114800, 958118400'>VRB05KT</VAR>"
  2954. "</PERIOD></TAF>"
  2955. "</Forecasts>"))
  2956. '()
  2957. '(*TOP* (Forecasts
  2958. (@ (TStamp "958082142"))
  2959. (TAF (@ (TStamp "958066200")
  2960. (SName "KMRY, MONTEREY PENINSULA")
  2961. (LatLon "36.583, -121.850")
  2962. (BId "724915"))
  2963. (VALID (@ (TRange "958068000, 958154400")) "111730Z 111818")
  2964. (PERIOD (@ (TRange "958068000, 958078800"))
  2965. (PREVAILING "31010KT P6SM FEW030"))
  2966. (PERIOD (@ (Title "FM2100") (TRange "958078800, 958104000"))
  2967. (PREVAILING "29016KT P6SM FEW040"))
  2968. (PERIOD (@ (Title "FM0400") (TRange "958104000, 958154400"))
  2969. (PREVAILING "29010KT P6SM SCT200")
  2970. (VAR (@ (Title "BECMG 0708")
  2971. (TRange "958114800, 958118400"))
  2972. "VRB05KT"))))))
  2973. ))
  2974. (run-test
  2975. (newline)
  2976. (display "All tests passed")
  2977. (newline)
  2978. )