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 ] [ peek ] bi [ CHAR: / = ] bi@ or ] 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-single-quote ( state-parser -- string )
39 [ [ current CHAR: ' = ] take-until ] [ next drop ] bi ;
41 : read-double-quote ( state-parser -- string )
42 [ [ current CHAR: " = ] take-until ] [ next drop ] bi ;
44 : read-quote ( state-parser -- string )
45 dup get+increment CHAR: ' =
46 [ read-single-quote ] [ read-double-quote ] if ;
48 : read-key ( state-parser -- string )
50 [ current { [ CHAR: = = ] [ blank? ] } 1|| ] take-until ;
52 : read-= ( state-parser -- )
54 [ [ current CHAR: = = ] take-until drop ] [ next drop ] bi ;
56 : read-token ( state-parser -- string )
57 [ current blank? ] take-until ;
59 : read-value ( state-parser -- string )
61 dup current quote? [ read-quote ] [ read-token ] if
64 : read-comment ( state-parser -- )
65 "-->" take-until-sequence comment new-tag push-tag ;
67 : read-dtd ( state-parser -- )
68 ">" take-until-sequence dtd new-tag push-tag ;
70 : read-bang ( state-parser -- )
71 next dup { [ current CHAR: - = ] [ peek-next CHAR: - = ] } 1&& [
78 : read-tag ( state-parser -- string )
79 [ [ current "><" member? ] take-until ]
80 [ dup current CHAR: < = [ next ] unless drop ] bi ;
82 : read-until-< ( state-parser -- string )
83 [ current CHAR: < = ] take-until ;
85 : parse-text ( state-parser -- )
86 read-until-< [ text new-tag push-tag ] unless-empty ;
88 : (parse-attributes) ( state-parser -- )
90 dup state-parse-end? [
94 [ read-key >lower ] [ read-= ] [ read-value ] tri
96 ] keep (parse-attributes)
99 : parse-attributes ( state-parser -- hashtable )
100 [ (parse-attributes) ] H{ } make-assoc ;
102 : (parse-tag) ( string -- string' hashtable )
104 [ read-token >lower ] [ parse-attributes ] bi
107 : read-< ( state-parser -- string/f )
109 CHAR: ! = [ read-bang f ] [ read-tag ] if
114 : parse-tag ( state-parser -- )
115 read-< [ (parse-tag) make-tag push-tag ] unless-empty ;
117 : (parse-html) ( state-parser -- )
119 [ parse-text ] [ parse-tag ] [ (parse-html) ] tri
122 : tag-parse ( quot -- vector )
123 V{ } clone tagstack [ state-parse ] with-variable ; inline
125 : parse-html ( string -- vector )
126 [ (parse-html) tagstack get ] tag-parse ;