1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: assocs namespaces make kernel sequences accessors
4 combinators strings splitting io io.streams.string present
5 xml.writer xml.data xml.entities html.forms
6 html.templates html.templates.chloe.syntax continuations ;
7 IN: html.templates.chloe.compiler
9 : chloe-attrs-only ( assoc -- assoc' )
10 [ drop chloe-name? ] assoc-filter ;
12 : non-chloe-attrs-only ( assoc -- assoc' )
13 [ drop chloe-name? not ] assoc-filter ;
15 : chloe-tag? ( tag -- ? )
16 dup xml? [ body>> ] when
18 { [ dup tag? not ] [ f ] }
19 { [ dup chloe-name? not ] [ f ] }
27 DEFER: compile-element
29 : compile-children ( tag -- )
30 [ compile-element ] each ;
32 : [write] ( string -- ) string-buffer get push-all ;
36 [ >string , \ write , ] [ delete-all ] bi
42 : [code-with] ( obj quot -- )
43 reset-buffer [ , ] [ % ] bi* ;
45 : expand-attr ( value -- )
46 [ value present write ] [code-with] ;
48 : compile-attr ( value -- )
49 reset-buffer "@" ?head [ , [ value present ] % ] [ , ] if ;
51 : compile-attrs ( assoc -- )
54 swap name>string [write]
56 "@" ?head [ expand-attr ] [ escape-quoted-string [write] ] if
60 : compile-start-tag ( tag -- )
62 [ name>string [write] ] [ attrs>> compile-attrs ] bi
65 : compile-end-tag ( tag -- )
70 : compile-tag ( tag -- )
72 [ main>> tag-stack get push ]
76 [ drop tag-stack get pop* ]
79 ERROR: unknown-chloe-tag tag ;
81 : compile-chloe-tag ( tag -- )
82 dup main>> dup tags get at
83 [ curry assert-depth ]
87 : compile-element ( element -- )
89 { [ dup chloe-tag? ] [ compile-chloe-tag ] }
90 { [ dup [ tag? ] [ xml? ] bi or ] [ compile-tag ] }
91 { [ dup string? ] [ escape-string [write] ] }
92 { [ dup comment? ] [ drop ] }
93 [ [ write-xml ] [code-with] ]
96 : with-compiler ( quot -- quot' )
98 SBUF" " string-buffer set
99 V{ } clone tag-stack set
104 : compile-chunk ( seq -- )
105 [ compile-element ] each ;
107 : compile-quot ( quot -- )
110 SBUF" " string-buffer set
113 ] [ ] make , ; inline
115 : process-children ( tag quot -- )
116 [ [ compile-children ] compile-quot ] [ % ] bi* ; inline
118 : compile-children>string ( tag -- )
119 [ with-string-writer ] process-children ;
121 : compile-with-scope ( quot -- )
122 compile-quot [ with-scope ] [code] ; inline
124 : if-not-nested ( quot -- )
125 nested-template? get swap unless ; inline
127 : compile-prologue ( xml -- )
129 [ prolog>> [ write-xml ] [code-with] ]
130 [ before>> compile-chunk ]
133 [ if-not-nested ] [code] ;
135 : compile-epilogue ( xml -- )
136 [ after>> compile-chunk ] compile-quot
137 [ if-not-nested ] [code] ;
139 : compile-template ( xml -- quot )