1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays hashtables html.parser.state
4 html.parser.utils kernel namespaces sequences
5 unicode.case unicode.categories combinators.short-circuit
10 TUPLE: tag name attributes text closing? ;
20 : closing-tag? ( string -- ? )
22 [ { [ first CHAR: / = ] [ peek CHAR: / = ] } 1|| ] if-empty ;
24 : <tag> ( name attributes closing? -- tag )
30 : make-tag ( string attribs -- tag )
31 [ [ closing-tag? ] keep "/" trim1 ] dip rot <tag> ;
33 : new-tag ( text name -- tag )
38 : (read-quote) ( state-parser ch -- string )
39 '[ [ current _ = ] take-until ] [ next drop ] bi ;
41 : read-single-quote ( state-parser -- string )
42 CHAR: ' (read-quote) ;
44 : read-double-quote ( state-parser -- string )
45 CHAR: " (read-quote) ;
47 : read-quote ( state-parser -- string )
48 dup get+increment CHAR: ' =
49 [ read-single-quote ] [ read-double-quote ] if ;
51 : read-key ( state-parser -- string )
53 [ current { [ CHAR: = = ] [ blank? ] } 1|| ] take-until ;
55 : read-= ( state-parser -- )
57 [ [ current CHAR: = = ] take-until drop ] [ next drop ] bi ;
59 : read-token ( state-parser -- string )
60 [ current blank? ] take-until ;
62 : read-value ( state-parser -- string )
64 dup current quote? [ read-quote ] [ read-token ] if
67 : read-comment ( state-parser -- )
68 "-->" take-until-sequence comment new-tag push-tag ;
70 : read-dtd ( state-parser -- )
71 ">" take-until-sequence dtd new-tag push-tag ;
73 : read-bang ( state-parser -- )
74 next dup { [ current CHAR: - = ] [ peek-next CHAR: - = ] } 1&& [
81 : read-tag ( state-parser -- string )
82 [ [ current "><" member? ] take-until ]
83 [ dup current CHAR: < = [ next ] unless drop ] bi ;
85 : read-until-< ( state-parser -- string )
86 [ current CHAR: < = ] take-until ;
88 : parse-text ( state-parser -- )
89 read-until-< [ text new-tag push-tag ] unless-empty ;
91 : (parse-attributes) ( state-parser -- )
93 dup state-parse-end? [
97 [ read-key >lower ] [ read-= ] [ read-value ] tri
99 ] keep (parse-attributes)
102 : parse-attributes ( state-parser -- hashtable )
103 [ (parse-attributes) ] H{ } make-assoc ;
105 : (parse-tag) ( string -- string' hashtable )
107 [ read-token >lower ] [ parse-attributes ] bi
110 : read-< ( state-parser -- string/f )
112 CHAR: ! = [ read-bang f ] [ read-tag ] if
117 : parse-tag ( state-parser -- )
118 read-< [ (parse-tag) make-tag push-tag ] unless-empty ;
120 : (parse-html) ( state-parser -- )
122 [ parse-text ] [ parse-tag ] [ (parse-html) ] tri
125 : tag-parse ( quot -- vector )
126 V{ } clone tagstack [ state-parse ] with-variable ; inline
128 : parse-html ( string -- vector )
129 [ (parse-html) tagstack get ] tag-parse ;