1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays hashtables sequence-parser
4 html.parser.utils kernel namespaces sequences
5 unicode.case unicode.categories combinators.short-circuit
9 TUPLE: tag name attributes text closing? ;
22 : closing-tag? ( string -- ? )
24 [ { [ first CHAR: / = ] [ peek CHAR: / = ] } 1|| ] if-empty ;
26 : <tag> ( name attributes closing? -- tag )
32 : make-tag ( string attribs -- tag )
33 [ [ closing-tag? ] keep "/" trim1 ] dip rot <tag> ;
35 : new-tag ( text name -- tag )
40 : (read-quote) ( sequence-parser ch -- string )
41 '[ [ current _ = ] take-until ] [ advance drop ] bi ;
43 : read-single-quote ( sequence-parser -- string )
44 CHAR: ' (read-quote) ;
46 : read-double-quote ( sequence-parser -- string )
47 CHAR: " (read-quote) ;
49 : read-quote ( sequence-parser -- string )
50 dup get+increment CHAR: ' =
51 [ read-single-quote ] [ read-double-quote ] if ;
53 : read-key ( sequence-parser -- string )
55 [ current { [ CHAR: = = ] [ blank? ] } 1|| ] take-until ;
57 : read-token ( sequence-parser -- string )
58 [ current blank? ] take-until ;
60 : read-value ( sequence-parser -- string )
62 dup current quote? [ read-quote ] [ read-token ] if
65 : read-comment ( sequence-parser -- )
66 "-->" take-until-sequence comment new-tag push-tag ;
68 : read-dtd ( sequence-parser -- )
69 ">" take-until-sequence dtd new-tag push-tag ;
71 : read-bang ( sequence-parser -- )
72 advance dup { [ current CHAR: - = ] [ peek-next CHAR: - = ] } 1&&
73 [ advance advance read-comment ] [ read-dtd ] if ;
75 : read-tag ( sequence-parser -- string )
76 [ [ current "><" member? ] take-until ]
77 [ dup current CHAR: < = [ advance ] unless drop ] bi ;
79 : read-until-< ( sequence-parser -- string )
80 [ current CHAR: < = ] take-until ;
82 : parse-text ( sequence-parser -- )
83 read-until-< [ text new-tag push-tag ] unless-empty ;
85 : parse-key/value ( sequence-parser -- key value )
87 [ skip-whitespace "=" take-sequence ]
88 [ swap [ read-value ] [ drop dup ] if ] tri ;
90 : (parse-attributes) ( sequence-parser -- )
92 dup sequence-parse-end? [
95 [ parse-key/value swap set ] [ (parse-attributes) ] bi
98 : parse-attributes ( sequence-parser -- hashtable )
99 [ (parse-attributes) ] H{ } make-assoc ;
101 : (parse-tag) ( string -- string' hashtable )
103 [ read-token >lower ] [ parse-attributes ] bi
106 : read-< ( sequence-parser -- string/f )
107 advance dup current [
108 CHAR: ! = [ read-bang f ] [ read-tag ] if
113 : parse-tag ( sequence-parser -- )
114 read-< [ (parse-tag) make-tag push-tag ] unless-empty ;
116 : (parse-html) ( sequence-parser -- )
118 [ parse-text ] [ parse-tag ] [ (parse-html) ] tri
121 : tag-parse ( quot -- vector )
122 V{ } clone tagstack [ parse-sequence ] with-variable ; inline
126 : parse-html ( string -- vector )
127 [ (parse-html) tagstack get ] tag-parse ;