SSAX.scm 122 KB

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