Debian Codegraph @

lib/www/css.scm

raw
1 ;;;
2 ;;; css.scm - Generate and parse CSS
3 ;;;
4 ;;; Copyright (c) 2014-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (define-module www.css
35 (use gauche.generator)
36 (use gauche.lazy)
37 (use gauche.unicode)
38 (use parser.peg)
39 (use util.match)
40 (use text.tree)
41 (use scheme.list)
42 (use srfi.13)
43 (export construct-css simple-selector?
44 parse-css parse-css-file
45 parse-css-selector-string)
46 )
47 (select-module www.css)
48
49 ;;;
50 ;;; S-expression CSS
51 ;;;
52 ;;; <s-css> : {<style-rule> | <at-rule>} ...
53 ;;;
54 ;;; <style-rule> : (style-rule <pattern> <declaration> ...)
55 ;;; | (style-decls <declaration> ...)
56 ;;;
57 ;;; <pattern> : <selector> | (:or <selector> ...)
58 ;;; <selector> : <simple-selector>
59 ;;; | <chained-selector>
60 ;;; <chained-selector> : (<simple-selector> . (<op>? . <chained-selector>))
61 ;;; <op> : > | + | ~
62 ;;; <simple-selector> : <element-name>
63 ;;; | (<element-name> <option> ...)
64 ;;; <option> : (id <name>) ; E#id
65 ;;; | (class <ident>) ; E.class
66 ;;; | (has <ident>) ; E[attrib]
67 ;;; | (= <ident> <attrib-value>) ; E[attrib=val]
68 ;;; | (~= <ident> <attrib-value>) ; E[attrib~=val]
69 ;;; | (:= <ident> <attrib-value>) ; E[attrib|=val]
70 ;;; | (*= <ident> <attrib-value>) ; E[attrib*=val]
71 ;;; | (^= <ident> <attrib-value>) ; E[attrib^=val]
72 ;;; | ($= <ident> <attrib-value>) ; E[attrib$=val]
73 ;;; | (:not <negation-arg>) ; E:not(s)
74 ;;; | (: <ident>) ; E:pseudo-class
75 ;;; | (: (<fn> <ident> ...)) ; E:pseudo-class(arg)
76 ;;; | (:: <ident>) ; E::pseudo-element
77 ;;; <element-name> : <ident> | *
78 ;;; <attrib-value> : <ident> | <string>
79 ;;; <negation-arg> | <element-name> | * | <option> ; except <negation-arg>
80 ;;;
81 ;;; <declaration> : (<ident> <expr> <expr2> ... <important>?)
82 ;;; <important> : !important
83 ;;; <expr> : <term>
84 ;;; | (/ <term> <term> ...)
85 ;;; | (:or <term> <term> ...)
86 ;;; | #(<term> <term> ...) ; juxtaposition
87 ;;; <term> : <quantity> | (- <quantity>) | (+ <quantity>)
88 ;;; | <string> | <ident> | <url> | <hexcolor> | <function>
89 ;;; <quantity> : <number>
90 ;;; | (<number> %)
91 ;;; | (<number> <ident>)
92 ;;; <url> | (url <string>)
93 ;;; <hexcolor> | (color <string>) ; <string> must be hexdigits
94 ;;; <function> | (<fn> <arg> ...)
95 ;;; <arg> | <term> | #(<term> ...) | (/ <term> <term> ...)
96 ;;;
97 ;;; <at-rule> : <at-media-rule> | <at-import-rule>
98 ;;; ; NB: Other at-rules are not supported yet
99 ;;; <at-media-rule> : (@media (<symbol> ...) <style-rule> ...)
100 ;;; <at-import-rule> : (@import <import-path> (<symbol> ...))
101 ;;; <import-path> : <string> | <url>
102 ;;;
103 ;;; NB: style-decls shouldn't appear in a complete stylesheet, but can
104 ;;; appear when the 'style' attribute of the document is parsed.
105 ;;; It is also useful to render the value for the style attribute.
106 ;;;
107 ;;; NB: Negaton op is :not instead of not, since (not <negation-arg>)
108 ;;; would be ambiguous from the simple node named "not" with one option.
109
110 ;;
111 ;; Some utilities on S-expr CSS
112 ;;
113
114 ;; API
115 ;; Returns canonicalized simple selector (element . options) or #f
116 (define (simple-selector? sel)
117 (define (option? x)
118 (match x
119 [(a b . _) (memq a '(id class has = ~= := *= ^= $= :not : ::))]
120 [_ #f]))
121 (match sel
122 [(? symbol?) (list sel)]
123 [((? symbol?) (? option?) ...) sel]
124 [_ #f]))
125
126 ;;
127 ;; S-expr CSS -> CSS
128 ;;
129
130 ;; API
131 (define (construct-css sexpr :optional (oport (current-output-port)))
132 (define (render top)
133 (match top
134 [((or 'style-rule 'style-decls) _ ...)
135 (write-tree (render-style-rule-or-decl top) oport)
136 (newline oport)]
137 [('@media media . rules)
138 (write-tree `("@media "
139 ,@(intersperse "," media)
140 " {"
141 ,@(map render-style-rule-or-decl rules)
142 "}\n")
143 oport)]
144 [('@import path mediaqueries)
145 (write-tree `("@import "
146 ,(match path
147 [('url s) (format "url(~s)" s)]
148 [s (format "~s" s)])
149 ,@(if (null? mediaqueries)
150 '("")
151 `(" " ,@(intersperse "," mediaqueries)))
152 ";\n")
153 oport)]
154 [_ (error "invalid or unsupported sexpr css:" top)]))
155 (define (render-style-rule-or-decl top)
156 (match top
157 [('style-rule pattern . decls) (render-style-rule pattern decls)]
158 [('style-decls . decls) (intersperse ";" (map render-decl decls))]
159 [_ (error "invalid or unsupported sexpr css:" top)]))
160 (define (render-style-rule pattern decls)
161 `(,(render-pattern pattern) "{"
162 ,(intersperse ";" (map render-decl decls))
163 "}\n"))
164 (define (render-pattern pattern)
165 (match pattern
166 [(':or selector ...) (intersperse "," (map render-selector selector))]
167 [_ (render-selector pattern)]))
168 (define (render-selector selector)
169 (if-let1 s (simple-selector? selector)
170 (render-simple-selector s)
171 (let loop ([sels selector])
172 (cond [(null? sels) '()]
173 [(simple-selector? (car sels))
174 => (^s `(,(render-simple-selector s)" " ,@(loop (cdr sels))))]
175 [(memq (car sels) '(> + ~)) `(,(car sels) ,@(loop (cdr sels)))]
176 [else (error "invalid selector in sexpr css:" selector)]))))
177 (define (render-simple-selector s)
178 `(,(car s) ,@(map render-options (cdr s))))
179 (define (render-options op)
180 (match op
181 [('id name) `("#" ,name)]
182 [('class name) `("." ,name)]
183 [('has name) `("[" ,name "]")]
184 [((and (or '= '~= '^= '$= '*=) op) ident value)
185 `("[" ,ident ,op ,(render-attrval value) "]")]
186 [(':= ident value) `("[" ,ident "|=" ,(render-attrval value) "]")]
187 [(':not not-arg) `(":not(" ,(if (symbol? not-arg)
188 not-arg
189 (render-options not-arg)) ")")]
190 [(': (fn arg ...)) `(":" ,(render-fn fn arg))]
191 [(': ident) `(":" ,ident)]
192 [(':: ident) `("::" ,ident)]
193 [_ (error "invalid selector option:" op)]))
194 (define (render-attrval val) (if (string? val) (escape-string val) val))
195 (define (escape-string val)
196 (if (string-index val #\')
197 `(#\",(regexp-replace-all* val #/\"/ "\\22") #\")
198 `(#\',val #\')))
199 (define (render-fn fn args)
200 `(,fn "(" ,@(intersperse "," (map render-arg args)) ")"))
201 (define (render-arg arg)
202 (match arg
203 [#(v ...) (intersperse " " (map render-attrval v))]
204 [(:an+b a b) `(,(if (= a 1) "" a)
205 n
206 ,(if (= b 0) "" (format "~@d" b)))]
207 [('/ v ...) (intersperse "/" (map render-attrval v))]
208 [v (render-attrval v)]))
209
210 (define (render-decl decl)
211 (match decl
212 [(ident expr . exprs)
213 (if (and (pair? exprs)
214 (eq? (last exprs) '!important))
215 `(,ident ":" ,@($ intersperse " " $ map render-expr
216 $ cons expr (drop-right exprs 1))
217 " !important")
218 `(,ident ":" ,@($ intersperse " " $ map render-expr
219 $ cons expr exprs)))]
220 [_ (error "invalid declaration:" decl)]))
221 (define (render-expr expr)
222 (match expr
223 [('/ term ...) (intersperse "/" (map render-term term))]
224 [(':or term ...) (intersperse "," (map render-expr term))]
225 [#(term ...) (intersperse " " (map render-expr term))]
226 [term (render-term term)]))
227 (define (render-term term)
228 (match term
229 [('- quantity) `(- ,(render-quantity quantity))]
230 [('+ quantity) `(+ ,(render-quantity quantity))]
231 [('color digs) `("#" ,digs)]
232 [#(expr ...) (intersperse " " (map render-expr expr))]
233 [((? number?) x) (render-quantity term)]
234 [((? symbol? fn) expr ...)
235 `(,fn "(" ,@(intersperse "," (map render-expr expr)) ")")] ;also url
236 [(? string?) (escape-string term)]
237 [(? symbol?) term]
238 [(? number?) term]
239 [_ (error "invalid term:" term)]))
240 (define (render-quantity quant)
241 (match quant
242 [(num '%) `(,num "%")]
243 [(num unit) `(,num ,unit)]
244 [num num]))
245
246 (for-each render sexpr))
247
248 ;; experimental
249 (define ($/ parser . parsers)
250 (if (null? parsers)
251 parser
252 ($or ($try parser) (apply $/ parsers))))
253
254 ;;
255 ;; CSS -> S-expr CSS
256 ;;
257
258 ;; Core syntax
259 ;; http://www.w3.org/TR/css3-syntax/
260
261 ;; CSS grammar definition is layered in order to allow different support
262 ;; levels of the client. It's conceptually parallel to Lisp syntax---
263 ;; the S-expression defines the core syntax, and more complex syntax is
264 ;; defined on top of S-expr.
265
266 ;; The API provides access for the lower layer, with the option to hook
267 ;; a translator for certain syntax units.
268
269 ;; NB: @charset rule is not handled here; we need to switch port encodings
270
271 ;; 4.3 Tokenizer
272 ;; css-token-generator :: [Char] -> ( () -> Token )
273 ;; Token = (IDENT . name) | (FUNCTION . name) | (AT-KEYWORD . name)
274 ;; | (HASH name flag) | (STRING . value) | (BAD-STRING)
275 ;; | (URL . value) | (BAD-URL)
276 ;; | (DELIM . char) | (NUMBER . value) | (PERCENTAGE . value)
277 ;; | (DIMENSION value unit)
278 ;; | (UNICODE-RANGE start end)
279 ;; | (INCLUDE-MATCH) | (DASH-MATCH) | (PREFIX-MATCH) | (SUFFIX-MATCH)
280 ;; | (SUBSTRING-MATCH) | (COLUMN) | (WHITESPACE) | (CDO) | (CDC)
281 ;; | (COLON) | (SEMICOLON) | (COMMA) | (OPEN-BRACKET) | (CLOSE-BRACKET)
282 ;; | (OPEN-PAREN) | (CLOSE-PAREN) | (OPEN-BRACE) | (CLOSE-BRACE)
283
284 (define %w ($many_ ($. #[ \t\r\n\f])))
285 (define %s ($many1_ ($. #[ \t\r\n\f])))
286 (define %nl ($or ($. "\n") ($. "\r\n") ($. "\n") ($. "\f")))
287 ;; comment => vlid
288 (define %comment
289 ($seq ($. "/*")
290 ($many_ ($none-of #[*]))
291 ($many1_ ($. #\*))
292 ($many_ ($seq ($none-of #[/*])
293 ($many_ ($none-of #[*]))
294 ($many1_ ($. #\*))))
295 ($. #\/)))
296
297 ;; nonascii [^\0-\237] => char
298 (define %nonascii ($none-of #[\x00-\x9f]))
299 ;; unicode \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])? => char
300 (define %unicode ($let ([ ($. #\\) ]
301 [code ($many ($. #[0-9a-fA-F]) 1 6)]
302 [ ($optional ($or ($. "\r\n") ($. #[ \n\r\t\f]))) ])
303 ($return ($ integer->char
304 $ (cut string->number <> 16)
305 $ list->string code))))
306 ;; escape {unicode}|\\[^\n\r\f0-9a-f] => char
307 (define %escape ($/ %unicode ($seq ($. #\\) ($none-of #[\n\r\f0-9a-f]))))
308 ;; nmstart [_a-z]|{nonascii}|{escape} => char
309 (define %nmstart ($/ ($. #[_a-zA-Z]) %nonascii %escape))
310
311 ;; nonascii [^\0-\237] => char
312 (define %nonascii ($none-of #[\x00-\x9f]))
313 ;; unicode \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])? => char
314 (define %unicode ($let ([ ($. #\\) ]
315 [code ($many ($. #[0-9a-fA-F]) 1 6)]
316 [ ($optional ($or ($. "\r\n") ($. #[ \n\r\t\f]))) ])
317 ($return ($ integer->char
318 $ (cut string->number <> 16)
319 $ list->string code))))
320 ;; escape {unicode}|\\[^\n\r\f0-9a-f] => char
321 (define %escape ($/ %unicode
322 ($seq ($. #\\) ($none-of #[\n\r\f0-9a-f]))))
323
324 ;; nmstart [_a-z]|{nonascii}|{escape} => char
325 (define %nmstart ($/ ($. #[_a-zA-Z]) %nonascii %escape))
326 ;; nmchar [_a-z0-9-]|{nonascii}|{escape} => char
327 (define %nmchar ($/ ($. #[_a-zA-Z0-9-]) %nonascii %escape))
328
329 ;; name {nmchar}+ => string
330 (define %name ($->string ($many1 %nmchar)))
331
332 ;; ident [-]?{nmstart}{nmchar}* => string
333 (define %ident ($->symbol ($optional ($. #\-)) %nmstart ($many %nmchar)))
334
335 (define %hexdigit ($. #[0-9a-fA-F]))
336
337 ;; num [0-9]+|[0-9]*\.[0-9]+
338 (define %num
339 (let* ([digs ($many1 ($. #[0-9]))]
340 [frac ($->rope ($. #\.) digs)])
341 ($lift ($ string->number $ rope->string $)
342 ($/ ($->rope digs ($optional frac))
343 ($->rope frac)))))
344
345 ;; string {string1}|{string2}
346 ;; string1 \"([^\n\r\f\\"]|\\{nl}|{escape})*\"
347 ;; string2 \'([^\n\r\f\\']|\\{nl}|{escape})*\'
348 (define %string
349 ($->rope
350 ($/ ($between ($. #\")
351 ($many ($/ ($none-of #[\n\r\f\"\\])
352 ($seq ($. #\\) %nl)
353 %escape))
354 ($or ($. #\") ($eos)))
355 ($between ($. #\')
356 ($many ($/ ($none-of #[\n\r\f\'\\])
357 ($seq ($. #\\) %nl)
358 %escape))
359 ($or ($. #\') ($eos))))))
360
361 (define %bad-string
362 ($/ ($seq ($. #\")
363 ($many_ ($/ ($none-of #[\n\r\f\"])
364 ($seq ($. #\\) %nl)
365 %escape))
366 ($. #\newline))
367 ($seq ($. #\')
368 ($many_ ($/ ($none-of #[\n\r\f\'])
369 ($seq ($. #\\) %nl)
370 %escape))
371 ($. #\newline))))
372
373 (define %url
374 ($lift (^[_ _ r _ _] (rope->string r))
375 ($. "url(") %w
376 ($->rope ($/ %string
377 ($many ($/ ($one-of #[!#$%&*-~])
378 %nonascii
379 %escape))))
380 %w ($. #\))))
381
382 (define %unicode-range
383 (letrec [(code (^[cs] (string->number (list->string cs) 16)))]
384 ($seq ($. #[Uu]) ($. #\+)
385 ($/ ($lift (^[cs1 _ cs2] `(UNICODE-RANGE ,(code cs1) ,(code cs2)))
386 ($many %hexdigit 1 6) ($. #\-) ($many %hexdigit 1 6))
387 ($let* ([ds ($many %hexdigit 1 5)]
388 [ws ($many ($. #\?) 1 (- 6 (length ds)))])
389 ($return
390 `(UNICODE-RANGE ,(code (append ds (map (^_ #\0) ws)))
391 ,(max (code (append ds (map (^_ #\f) ws)))
392 #x10ffff))))
393 ($lift (^[cs] `(UNICODE-RANGE ,(code cs) ,(code cs)))
394 ($many %hexdigit 1 6))))))
395
396 ;; Tokenizer
397 ;; comment returns :comment, which is ignored by the token generator
398 ;; note that this parser never fails except at the end of input.
399 (define %tokenize
400 ($/ ($seq %comment ($return :comment))
401 ($seq %s ($return '(WHITESPACE)))
402 %unicode-range
403 ($seq ($. "~=") ($return '(INCLUDE-MATCH)))
404 ($seq ($. "|=") ($return '(DASH-MATCH)))
405 ($seq ($. "^=") ($return '(PREFIX-MATCH)))
406 ($seq ($. "$=") ($return '(SUFFIX-MATCH)))
407 ($seq ($. "*=") ($return '(SUBSTRING-MATCH)))
408 ($seq ($. "||") ($return '(COLUMN)))
409 ($seq ($. "<!--") ($return '(CDO)))
410 ($seq ($. "-->") ($return '(CDC)))
411 ($seq ($. #\:) ($return '(COLON)))
412 ($seq ($. #\;) ($return '(SEMICOLON)))
413 ($seq ($. #\,) ($return '(COMMA)))
414 ($seq ($. #\[) ($return '(OPEN-BRACKET)))
415 ($seq ($. #\]) ($return '(CLOSE-BRACKET)))
416 ($seq ($. #\() ($return '(OPEN-PAREN)))
417 ($seq ($. #\)) ($return '(CLOSE-PAREN)))
418 ($seq ($. #\{) ($return '(OPEN-BRACE)))
419 ($seq ($. #\}) ($return '(CLOSE-BRACE)))
420 ($lift (^[val] `(URL . ,val)) %url)
421 ($lift (^[ident _] `(FUNCTION . ,ident)) %ident ($. #\())
422 ($lift (^[ident] `(IDENT . ,ident)) %ident)
423 ($lift (^[_ ident] `(AT-KEYWORD . ,ident)) ($. #\@) %ident)
424 ($lift (^[_ val] `(HASH ,val #t)) ($. #\#) %ident)
425 ($lift (^[_ val] `(HASH ,val #f)) ($. #\#) %name)
426 ($lift (^[val] `(STRING . ,val)) %string)
427 ($lift (^[_] '(BAD-STRING)) %bad-string)
428 ($lift (^[val _] `(PERCENTAGE . ,val)) %num ($. #\%))
429 ($lift (^[val unit] `(DIMENSION ,val ,unit)) %num %ident)
430 ($lift (^[val] `(NUMBER . ,val)) %num)
431 ($let ([c ($any)]) ($return `(DELIM . ,c)))))
432
433 (define (css-token-generator chars)
434 (define cs chars)
435 (rec (gen)
436 (if (null? cs)
437 (eof-object)
438 (receive (val next) (peg-run-parser %tokenize cs)
439 (set! cs next)
440 (if (eq? val :comment) (gen) val)))))
441
442 (define (css-tokenize chars)
443 (generator->lseq (css-token-generator chars)))
444
445 ;;
446 ;; 5. Core parser
447 ;;
448
449 ;; Accept token of specific type
450 (define ($tok type)
451 (^s
452 (cond [(null? s) (return-failure/expect type s)]
453 [(eq? (caar s) type) (return-result (cdar s) (cdr s))]
454 [else (return-failure/expect type s)])))
455
456 (define ($delim char)
457 (^s
458 (cond [(null? s) (return-failure/expect char s)]
459 [(and (eqv? (caar s) 'DELIM) (eqv? (cdar s) char))
460 (return-result (cdar s) (cdr s))]
461 [else (return-failure/expect char s)])))
462
463 (define (%preserved-token s)
464 (if (null? s)
465 (return-failure/unexpect "EOF" s)
466 (return-result (car s) (cdr s))))
467
468 (define %WS* ($many_ ($tok 'WHITESPACE)))
469
470 (define %component-value
471 ($lazy
472 ($between %WS*
473 ($/ %brace-block %paren-block %bracket-block %function-call
474 %preserved-token)
475 %WS*)))
476
477 (define %component-value+ ; whitespace preserving
478 ($lazy ($/ ($seq ($tok 'WHITESPACE) ($return '(WHITESPACE)))
479 %brace-block %paren-block %bracket-block %function-call+
480 %preserved-token)))
481
482 (define (block-parser opener closer tag :optional (preserve-ws? #f))
483 ($lift (^[_ _ v _] `(,tag ,@v))
484 ($tok opener) %WS*
485 ($many ($seq ($not ($tok closer))
486 (if preserve-ws? %component-value+ %component-value)))
487 ($tok closer)))
488
489 (define %brace-block (block-parser 'OPEN-BRACE 'CLOSE-BRACE 'brace-block))
490 (define %paren-block (block-parser 'OPEN-PAREN 'CLOSE-PAREN 'paren-block))
491 (define %bracket-block (block-parser 'OPEN-BRACKET 'CLOSE-BRACKET 'bracket-block))
492 ;; like %brace-block but we preserve whitespaces at the toplevel inside
493 ;; the block. necessary to handle @media directive.
494 (define %brace-block+ (block-parser 'OPEN-BRACE 'CLOSE-BRACE 'brace-block #t))
495
496 (define %function-call
497 ($lift (^[fn args _] `(funcall ,fn ,@args))
498 ($tok 'FUNCTION)
499 ($many ($seq ($not ($tok 'CLOSE-PAREN)) %component-value))
500 ($tok 'CLOSE-PAREN)))
501
502 (define %function-call+
503 ($lift (^[fn args _] `(funcall ,fn ,@args))
504 ($tok 'FUNCTION)
505 ($many ($seq ($not ($tok 'CLOSE-PAREN)) %component-value+))
506 ($tok 'CLOSE-PAREN)))
507
508 (define %at-rule
509 ($lift (^[keyword _ args block] `(,keyword ,args ,block))
510 ($tok 'AT-KEYWORD) %WS*
511 ($many ($seq ($not ($tok 'OPEN-BRACE))
512 ($not ($tok 'SEMICOLON))
513 %component-value))
514 ($/ %brace-block+ ($tok 'SEMICOLON))))
515
516 (define %qualified-rule
517 ;; NB: We preserve whitespaces between qualifiers, for it is
518 ;; required to parse selectors; see below.
519 ($lift (^[_ words block _] (list words block))
520 %WS*
521 ($many ($seq ($not ($tok 'OPEN-BRACE))
522 ($/ %paren-block %bracket-block %function-call
523 %preserved-token ($tok 'WHITESPACE))))
524 %brace-block %WS*))
525
526 (define %important
527 ($let ([ ($delim #\!) ]
528 [ %WS* ]
529 [v ($tok 'IDENT)])
530 (if (string-ci=? (symbol->string v) "important")
531 ($return '!important)
532 ($fail "!important expected"))))
533
534 (define %declaration
535 ($lift (^[name _ _ block important _] (list name block important))
536 ($tok 'IDENT) %WS* ($tok 'COLON)
537 ($many ($seq ($not ($tok 'SEMICOLON))
538 ($not ($delim #\!))
539 %component-value))
540 ($optional %important)
541 %WS*))
542
543 (define %declaration-list
544 ($lazy
545 ($seq %WS* ($/ ($sep-by ($optional %declaration) ($tok 'SEMICOLON))
546 ($list %at-rule %declaration-list)))))
547
548 (define %inter-rule-spaces
549 ($many_ ($/ ($tok 'CDO) ($tok 'CDC) ($tok 'WHITESPACE))))
550
551 (define %rule-list
552 ($many ($/ ($tok 'WHITESPACE) %qualified-rule %at-rule)))
553
554 ;;
555 ;; Higher-level parser
556 ;;
557 ;; The core syntax defined in section 5 of css3 spec is very tolerable---
558 ;; it accepts variety of syntaxes that doesn't make sense at all. This
559 ;; layer uses higher-level semantics to get a meaningful representation.
560
561 ;; Selector syntax
562 ;; http://www.w3.org/TR/css3-selectors/
563
564 (define %attr-selector-internal
565 ($lift (^[_ name _ opval _]
566 (if opval `(,(car opval) ,name ,(cdr opval)) `(has ,name)))
567 %WS* ($tok 'IDENT) %WS*
568 ($optional
569 ($lift (^[op _ val] (cons op val))
570 ($/ ($seq ($delim #\=) ($return '=))
571 ($seq ($tok 'INCLUDE-MATCH) ($return '~=))
572 ($seq ($tok 'DASH-MATCH) ($return ':=))
573 ($seq ($tok 'PREFIX-MATCH) ($return '^=))
574 ($seq ($tok 'SUFFIX-MATCH) ($return '$=))
575 ($seq ($tok 'SUBSTRING-MATCH) ($return '*=)))
576 %WS*
577 ($/ ($tok 'IDENT) ($tok 'STRING))))
578 %WS*))
579
580 (define (%attr-selector s)
581 (match s
582 [(('bracket-block . content) . rest)
583 (receive (r v s) (%attr-selector-internal content)
584 (if (and (parse-success? r)
585 (null? s))
586 (return-result v rest)
587 (return-failure/message "attr-selector" s)))]
588 [_ (return-failure/message "attr-selector" s)]))
589
590 (define %class-selector
591 ($lift (^[_ class] `(class ,class)) ($delim #\.) ($tok 'IDENT)))
592
593 (define %id-selector
594 ($let ([hashval ($tok 'HASH)])
595 (if (cadr hashval) ; hashval is ident
596 ($return `(id ,(car hashval)))
597 ($fail "identifier required for id selector"))))
598
599 (define %pseudo-fn-arg
600 ;; NB: To support an+b syntax
601 ($/ ($tok 'DIMENSION)
602 ($tok 'NUMBER)
603 ($tok 'STRING)
604 ($tok 'IDENT)))
605
606 (define %negation-selector-arg
607 ($lazy
608 ($/ %type-selector %attr-selector %class-selector %id-selector
609 %pseudo-selector)))
610
611 (define %sign
612 ($or ($seq ($delim #\+) ($return +))
613 ($seq ($delim #\-) ($return -))))
614
615 (define %optional-sign
616 ($optional %sign +))
617
618 (define-syntax %match1
619 (syntax-rules ()
620 [(_ pat body0 body ...)
621 (lambda (s)
622 (if (pair? s)
623 (match (car s)
624 [pat ((begin body0 body ...) (cdr s))]
625 [_ (return-failure/expect (write-to-string 'pat) s)])
626 (return-failure/expect (write-to-string 'pat) s)))]
627 [(_ pat)
628 (lambda (s)
629 (if (pair? s)
630 (match (car s)
631 [pat (return-result (car s) (cdr s))]
632 [_ (return-failure/expect (write-to-string 'pat) s)])
633 (return-failure/expect (write-to-string 'pat) s)))]))
634
635 (define (symbol-foldcase sym)
636 (string->symbol
637 (string-foldcase
638 (symbol->string sym))))
639
640 (define (%one-of-ident-ci idents)
641 (%match1 ('IDENT . (and ident
642 (= symbol-foldcase
643 (? (cut memq <> idents)))))
644 ($return ident)))
645
646 (define (%%an+b a b)
647 ($return
648 (if (= a 0)
649 b
650 `(:an+b ,a ,b))))
651
652 (define (%n-b a n-b)
653 (rxmatch-if (#/^n(-\d+)$/ (symbol->string n-b))
654 (_ b)
655 (%%an+b a (string->number b))
656 ($fail "n-b")))
657
658 (define %an+b
659 ($between %WS*
660 ($/ ($let ([sign %optional-sign])
661 ($or ($let ([a ($or (%match1 ('DIMENSION a (or 'n 'N))
662 ($return a))
663 ($seq (%one-of-ident-ci '(n))
664 ($return 1))
665 ($seq (%one-of-ident-ci '(-n))
666 ($return -1)))]
667 [b ($optional
668 ($lift (cut <> <>)
669 ($between %WS* %sign %WS*)
670 ($tok 'NUMBER))
671 0)])
672 (%%an+b (sign a) b))
673 ($let ([a ($or (%match1 ('DIMENSION a (or 'n- 'N-))
674 ($return a))
675 ($seq (%one-of-ident-ci '(n-))
676 ($return 1))
677 ($seq (%one-of-ident-ci '(-n-))
678 ($return -1)))]
679 %WS*
680 [b ($tok 'NUMBER)])
681 (%%an+b (sign a) (- b)))
682 (%match1 ('DIMENSION a n-b)
683 (%n-b (sign a) n-b))
684 (%match1 ('IDENT . n-b)
685 (if-let1 n-b* (symbol-sans-prefix n-b '-)
686 (%n-b -1 n-b*)
687 (%n-b 1 n-b)))))
688 ($lift (cut <> <>)
689 %optional-sign
690 ($tok 'NUMBER))
691 (%one-of-ident-ci '(even odd)))
692 %WS*))
693
694 ;; NB: negation-selector is also treated in pseudo-fn
695 (define (%pseudo-fn s)
696 (match s
697 [(('funcall name . arg-tokens) . rest)
698 (receive (r v s) (case (symbol-foldcase name)
699 [(not)
700 (%negation-selector-arg arg-tokens)]
701 [(nth-child nth-last-child nth-of-type nth-last-of-type)
702 (%an+b arg-tokens)]
703 [else
704 (%pseudo-fn-arg arg-tokens)])
705 (if (and (parse-success? r)
706 (null? s))
707 (return-result (list name v) rest)
708 (return-failure/message "pseudo-fn" s)))]
709 [_ (return-failure/message "pseudo-fn" s)]))
710
711 (define %pseudo-selector
712 ($lift (^[_ elem? sel]
713 (match sel
714 [('not not-arg) `(:not ,not-arg)]
715 [(? symbol?) `(,(if elem? ':: ':) ,sel)]
716 [_ `(,(if elem? ':: ':) ,sel)]))
717 ($tok 'COLON) ($optional ($tok 'COLON))
718 ($/ ($tok 'IDENT) %pseudo-fn)))
719
720 (define %selector-option
721 ($/ %attr-selector
722 %class-selector
723 %id-selector
724 %pseudo-selector))
725
726 (define %type-selector
727 ;; TODO: namespace support & case conversion
728 ($/ ($tok 'IDENT) ($seq ($delim #\*) ($return '*))))
729
730 (define %simple-selector
731 ($/ ($lift (^[type opts] (if (null? opts) type (cons type opts)))
732 %type-selector ($many %selector-option))
733 ($lift (^[ops] `(* ,@ops)) ($many1 %selector-option))))
734
735 (define %selector-seq
736 ($lazy
737 ($lift (^[sel rest] (if rest (cons sel rest) (list sel)))
738 %simple-selector
739 ($optional
740 ($try
741 ($lift (^[op rest] (if op (cons op rest) rest))
742 ($/ ($between %WS*
743 ($/ ($seq ($delim #\>) ($return '>))
744 ($seq ($delim #\+) ($return '+))
745 ($seq ($delim #\~) ($return '~)))
746 %WS*)
747 ($seq0 ($seq ($tok 'WHITESPACE) ($return #f))
748 %WS*))
749 %selector-seq))))))
750
751 (define %selector-group ;; section 5
752 ($lift (^[sels] (cond [(null? sels) #f]
753 [(null? (cdr sels)) (car sels)]
754 [else (cons ':or sels)]))
755 ($sep-by ($lift (^[_ seq _] (if (null? (cdr seq)) (car seq) seq))
756 %WS* %selector-seq %WS*)
757 ($tok 'COMMA))))
758
759 ;; TOKENS is the first item of the value of %qualified-rule. Interpret
760 ;; it as a selector and returns <pattern> structure of S-expr CSS.
761 ;; If it can't be parsed, returns #f.
762 (define (parse-selectors tokens)
763 (guard (e [(<parse-error> e) #f])
764 (receive (val next) (peg-run-parser %selector-group tokens)
765 (and (null? next) val))))
766
767 ;; default declaration value parser
768 ;; This part roughly follows CSS2.1 spec appendix G.
769 ;; The difficulty is in expression;
770 ;; CSS spec dosn't define general precedence among juxtaposition, comma and
771 ;; slash operators, leaving its interpretation to each property. However,
772 ;; the current defined property seems to use this rule:
773 ;; - A rule of thumb is that '/' > juxtaposition > ','
774 ;; - For some shorthand properties, '/' > ',' > juxtaposition
775 ;; TODO: We need another rule for the argument of 'calc'.
776
777 (define (%function-expr s)
778 (match s
779 [(('funcall name . arg-tokens) . rest)
780 (receive (r v s) (%comma-separated-exprs arg-tokens)
781 (if (and (parse-success? r)
782 (null? s))
783 (return-result (cons name v) rest)
784 (return-failure/expect "list of function arguments" s)))]
785 [_ (return-failure/expect "list of function arguments" s)]))
786
787 (define %term
788 ($/ ($lift (^[u qual] (if u `(,(string->symbol (string u)) ,qual) qual))
789 ($optional ($/ ($delim #\+) ($delim #\-)))
790 ($/ ($tok 'NUMBER)
791 ($lift (^[val] `(,val %)) ($tok 'PERCENTAGE))
792 ($tok 'DIMENSION)))
793 ($tok 'STRING)
794 ($tok 'IDENT)
795 ($lift (^[v] `(url ,v)) ($tok 'URL))
796 ($lift (^[v] `(color ,(x->string (car v)))) ($tok 'HASH))
797 %function-expr))
798
799 (define %term-/
800 ($lift (^[a b] (if b `(/ ,a ,b) a))
801 %term ($optional ($seq ($delim #\/) %term))))
802
803 (define %comma-separated-exprs
804 ($sep-by ($lift (^[v vs] (if (null? vs) v (list->vector (cons v vs))))
805 %term-/ ($many %term-/))
806 ($tok 'COMMA)))
807
808 (define %juxtaposed-exprs
809 ($lift (^[vs] (match vs [(x) x] [xs (list->vector xs)]))
810 ($many ($/ ($lift (^[a _ b] `(/ ,a ,b))
811 %term ($delim #\/) %term)
812 ($lift (^[v vs] (if (null? vs) v (cons* ':or v vs)))
813 %term ($many ($seq ($tok 'COMMA) %term)))))))
814
815 (define *juxta-properties*
816 '(margin padding
817 border border-top border-right border-bottom border-left
818 font list-style pause cue))
819
820 (define (%decl-value property)
821 (if (memq property *juxta-properties*)
822 %juxtaposed-exprs
823 ($let ([exprs %comma-separated-exprs])
824 ($return (match exprs [(x) x] [(xs ...) `(:or ,@xs)])))))
825
826 ;; val :: (property-name . tokens)
827 (define (parse-declaration val)
828 (match val
829 [(name tokens important?)
830 (receive (r v s) ((%decl-value (car val)) tokens)
831 (if (and (parse-success? r)
832 (null? s))
833 `(,name ,v ,@(cond-list [important? '!important]))
834 (begin
835 (css-parser-warn "Ignored unparsable value for property ~s: ~s\n"
836 (car val) (cdr val))
837 #f)))]
838 [_ #f]))
839
840 (define (parse-declarations block)
841 (match block
842 [('brace-block . component-values)
843 (receive (vals next) (peg-run-parser %declaration-list component-values)
844 (and (null? next)
845 (filter-map parse-declaration vals)))]
846 [_ #f]))
847
848 ;; Interpret %qualified-rule as a style-rule and returns <ruleset> structure of
849 ;; S-expr CSS. (section 8.1 of CSS3 sytnax)
850 ;; If it can't be parsed, returns #f.
851 (define (parse-style-rule selector-tokens block-token)
852 (let ([selector (parse-selectors selector-tokens)]
853 [decls (parse-declarations block-token)])
854 (if (and selector decls)
855 `(style-rule ,selector ,@decls)
856 (begin
857 (unless selector
858 (css-parser-warn "Ignored unparsable selector: ~s\n"
859 selector-tokens))
860 (unless decls
861 (css-parser-warn "Ignored unparsable declarations block: ~s\n"
862 block-token))
863 #f))))
864
865 ;; Parse %at-rule. This must be customizable. For now, we only handle
866 ;; @media.
867 (define (parse-at-rule at-keyword args block-token
868 qualified-rule-handler)
869 (or (and-let* ([ (eq? at-keyword 'media) ]
870 [syms (map (^a (match a [('IDENT . x) x] [_ #f])) args)]
871 [tokens (match block-token [('brace-block . xs) xs] [_ #f])])
872 (let loop ([tokens tokens]
873 [decls '()])
874 (if (null? tokens)
875 `(@media ,syms
876 ,@(map (^p (qualified-rule-handler (car p) (cdr p)))
877 (reverse decls)))
878 (receive (sels rest)
879 (break (^t (match t [('brace-block . _) #t] [_ #f])) tokens)
880 (if (null? rest)
881 (begin
882 (unless (every (^s (match s [('WHITESPACE) #t][_ #f])) sels)
883 (css-parser-warn "A selector in media block missing rules: ~s\n"
884 sels))
885 (loop '() decls))
886 (loop (cdr rest) (acons sels (car rest) decls)))))))
887 (and (eq? at-keyword 'import)
888 (match args
889 [(url . media)
890 (and-let* ([import-path (match url
891 [('STRING . s) s]
892 [('URL . s) `(url ,s)]
893 [_ #f])]
894 [media-kinds (filter-map (^x (match x
895 [('IDENT . s) s]
896 [_ #f]))
897 media)])
898 `(@import ,import-path ,media-kinds))]
899 [_ #f]))
900 (begin
901 (css-parser-warn "Ignored unsupported at-rule: ~s\n"
902 (list at-keyword args block-token))
903 #f)))
904
905 ;; Integrated stylesheet parser
906 (define (make-stylesheet-parser qualified-rule-handler at-rule-handler)
907 ($seq %inter-rule-spaces
908 ($many ($seq0
909 ($/ ($lift (^[a] (at-rule-handler (car a) (cadr a) (caddr a)
910 qualified-rule-handler))
911 %at-rule)
912 ($lift (^[q] (qualified-rule-handler (car q) (cadr q)))
913 %qualified-rule))
914 %inter-rule-spaces))))
915
916 (define (parse-stylesheet tokens
917 :key (qualified-rule-handler parse-style-rule)
918 (at-rule-handler parse-at-rule))
919 (receive (r rest)
920 (peg-run-parser (make-stylesheet-parser qualified-rule-handler
921 at-rule-handler)
922 tokens)
923 (filter identity r)))
924
925 ;; API
926 ;; TODO: Handle @charset
927 (define (parse-css-file file :key (encoding #f))
928 (call-with-input-file file parse-css
929 :encoding (or encoding (gauche-character-encoding))))
930
931 ;; API
932 (define (parse-css :optional (port (current-input-port)))
933 ($ parse-stylesheet
934 $ css-tokenize $ generator->lseq $ port->char-generator port))
935
936 ;; API
937 ;; A utility function to parse only selector part.
938 ;; We can't simply use parse-selectors, for it assumes the tokens is
939 ;; processed as %qualified-rule.
940 ;; Returns #f if input is unparsable. It is ok that input has extra
941 ;; blocks; they're ignored.
942 (define (parse-css-selector-string s)
943 (receive (r v s) ($ %selector-only $ css-tokenize $ x->lseq s)
944 (and (parse-success? r)
945 (parse-selectors v))))
946
947 (define %selector-only
948 ($seq %WS*
949 ($many ($seq ($not ($tok 'OPEN-BRACE))
950 ($/ %paren-block %bracket-block %function-call+
951 %preserved-token ($tok 'WHITESPACE))))))
952
953 ;; TODO: make this customizable
954 (define css-parser-warn warn)