File: htmllex.mll

package info (click to toggle)
hevea 2.36-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,780 kB
  • sloc: ml: 19,453; sh: 503; makefile: 311; ansic: 132
file content (407 lines) | stat: -rw-r--r-- 10,556 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
(***********************************************************************)
(*                                                                     *)
(*                          HEVEA                                      *)
(*                                                                     *)
(*  Luc Maranget, projet Moscova, INRIA Rocquencourt                   *)
(*                                                                     *)
(*  Copyright 2001 Institut National de Recherche en Informatique et   *)
(*  Automatique.  Distributed only by permission.                      *)
(*                                                                     *)
(***********************************************************************)


{

open Lexeme

let to_string = function
  | Open (_,_,txt)  | Close (_,txt)  | Text txt  | Blanks txt -> txt
  | Eof -> "Eof"

let cost = function
  | {tag=FONT ; attrs=attrs;_} -> (1,List.length attrs)
  | _          -> (1,0)


module Make(C:DoOut.Config) = struct
open Lexing

module Out = DoOut.Make(C)

let txt_level = ref 0
and txt_stack = MyStack.create "htmllex"

let error msg _lb =  raise (Emisc.LexError msg)


let init table (s,t)= Hashtbl.add table s t
;;

let block = Hashtbl.create 17
;;

List.iter (init block)
  ["center", () ; "div", (); "blockquote", () ;
  "h1", () ; "h2", () ;"h3", () ;"h4", () ;"h5", () ;"h6", () ;
  "pre", () ; "table", () ; "tr",() ; "td", () ; "th",() ; 
  "ol",() ; "ul",(); "p",() ; "li",() ;
  "dl",() ; "dt", () ; "dd",() ;
  ]
;;

let ptop () =
  if not (MyStack.empty txt_stack) then begin
    let pos = MyStack.top txt_stack in
    Location.print_this_fullpos pos ;
    prerr_endline "This opening tag is pending"
  end

let warnings = ref true

let check_nesting _lb name =
  try
    Hashtbl.find block (String.lowercase_ascii name) ;
    if !txt_level <> 0 && !warnings then begin
      Location.print_fullpos () ;
      prerr_endline 
        ("Warning, block level element: "^name^" nested inside text-level element") ;
      ptop ()
    end
  with
  |  Not_found -> ()

let text = Hashtbl.create 17
;;


List.iter (init text)
  ["tt",TT ; "i",I ; "b",B ; "big",BIG ; "small",SMALL ;
   "strike",STRIKE ; "s",S ; "u",U ; "font",FONT ;
   "em",EM ; "strong",STRONG ; "dfn",DFN ; "code",CODE ; "samp",SAMP ;
   "kbd",KBD ; "var",VAR ; "cite",CITE ; "abbr",ABBR ; "acronym",ACRONYM ; 
   "q",Q ; "sub",SUB ; "sup",SUP ; "a", A ; "span", SPAN ; "script", SCRIPT;
    "style", STYLE; ]
;;

let is_textlevel name =
  try
    let _ = Hashtbl.find text (String.lowercase_ascii name) in
    true
  with
  | Not_found -> false

let is_br name = "br" = (String.lowercase_ascii name)
let is_basefont name = "basefont" = (String.lowercase_ascii name)

let set_basefont attrs lb = 
  List.iter
    (fun (name,v,_) -> match String.lowercase_ascii name,v with
    | "size",Some s ->
        begin try
          Emisc.basefont := int_of_string s
        with
        | _ -> error "BASEFONT syntax" lb
        end
    | _ -> ())
    attrs

let get_value lb = function
  | Some s -> s
  | _ -> error "Bad attribute syntax" lb

let is_size_relative v =
  match v with
  | "xx-small" | "x-small" | "small" | "medium"
  | "large" | "x-large" | "xx-large" 
      -> false
  | _ -> true
  
let font_value lb v =  
  let v = get_value lb v in
  try
    let k = String.index v ':' in
    let tag = String.sub v 0 k
    and v = String.sub v (k+1) (String.length v - (k+1)) in
    let tag =
      match String.lowercase_ascii tag with
      | "font-family" -> Ffamily
      | "font-style" -> Fstyle
      | "font-variant" -> Fvariant
      | "font-weight" -> Fweight
      | "font-size" ->
(* Catch case 'font-size:xxx%' which does not commute
   (with other font-size styles *)
          if is_size_relative v then raise Exit
          else Fsize
      | "color" -> Fcolor
      | "background-color" -> Fbgcolor
      | _ -> raise Exit in
    begin (* checks just one style *)
      try ignore (String.index v ';') ; raise Exit
      with
      | Exit -> raise Exit
      | _ -> ()
    end ;
    tag,v
  with _ -> raise Exit

let norm_attrs lb attrs =
   List.map
        (fun (name,value,txt) ->
          match String.lowercase_ascii name with
          | "size" ->  SIZE (get_value lb value),txt
          | "color" -> COLOR (get_value lb value),txt
          | "face" -> FACE (get_value lb value),txt
          | "style" ->
              begin try
                let st,v = font_value lb value in
                ASTYLE (st,v),txt
              with Exit -> OTHER,txt
              end
          | _      -> OTHER, txt)
    attrs

let ouvre lb name attrs txt =
  let uname = String.lowercase_ascii name in
  try
    let tag = Hashtbl.find text uname in
    let attrs = norm_attrs lb attrs in
    incr txt_level ;
    MyStack.push txt_stack (Location.get_pos ()) ;
    Open (tag,attrs,txt)
  with
  | Not_found -> assert false

and ferme _lb name txt =
  try
    let tag = Hashtbl.find text (String.lowercase_ascii name) in
    decr txt_level ;
    begin if not (MyStack.empty txt_stack) then
      let _  = MyStack.pop txt_stack in ()
    end ;
    Close (tag,txt)
  with
  | Not_found -> Text txt

let buff = Out.create_buff ()
and abuff = Out.create_buff ()

let put s = Out.put buff s
and putc c = Out.put_char buff c

let aput s = Out.put abuff s




}
 
let blank = [' ''\t''\n''\r']
let tag = ['a'-'z''A'-'Z''0'-'9']+
let class_name = ['a'-'z''A'-'Z''0'-'9''-']+
let attr_name = ['a'-'z''A'-'Z']['a'-'z''A'-'Z''-''0'-'9'':']*

rule main = parse
| (blank|"&nbsp;"|"&XA0;")+ as lxm {Blanks lxm}
| "<!--"
  {put (lexeme lexbuf) ;
  in_comment lexbuf ;
  Text (Out.to_string buff)}
| "<!"
  {put (lexeme lexbuf) ;
  in_tag lexbuf ;
  Text (Out.to_string buff)}
| '<' (tag as tag) as lxm
    {put lxm ;
    if is_textlevel tag then begin
      let attrs = read_attrs lexbuf in    
      ouvre lexbuf tag attrs (Out.to_string buff)
    end else if is_basefont tag then begin
      let attrs = read_attrs lexbuf in    
      set_basefont attrs lexbuf ;
      Text (Out.to_string buff)          
    end else begin
      check_nesting lexbuf tag ;
      in_tag lexbuf ;
      let txt = Out.to_string buff in
      if is_br tag then 
        Blanks txt
      else
        Text txt
    end}
|  "</"  (tag as tag) as lxm
    {put lxm ;
    in_tag lexbuf ;
    ferme lexbuf tag (Out.to_string buff)}
| eof {Eof}
| _ as c
    {putc c ;
    text lexbuf ;
    Text (Out.to_string buff)}

and text = parse
| [^'<'] as c
  {putc c ; text lexbuf}
| "" {()}

and read_attrs = parse
| blank+ as lxm
    {aput lxm ; read_attrs lexbuf}
| attr_name as name
  {aput name ;
  let v = read_avalue lexbuf in
  let atxt = Out.to_string abuff in
  put atxt ;
  (name,v,atxt)::read_attrs lexbuf}
| '>' {Out.put_char buff '>' ; []}
| ""  {error "Attribute syntax (read_attrs)" lexbuf}

and read_avalue = parse
| blank* '=' blank*
    {let lxm = lexeme lexbuf in
    aput lxm ;
    Some (read_aavalue lexbuf)}
| "" {None}

and read_aavalue = parse
| '\'' ([^'\'']* as x) '\''
| '"' ([^'"']* as x) '"' as lxm
    {aput lxm ;
    x}
| '#'?['a'-'z''A'-'Z''0'-'9''-''+''_'':''.']+ as lxm
    {aput lxm ;
    lxm}
(* '"' *)
| "" {error "Attribute syntax (read_aavalue)" lexbuf}

and in_tag = parse
| '>' {putc '>'}
| _ as c   {putc c ; in_tag lexbuf}
| eof {error "End of file in tag" lexbuf}

and in_comment = parse
| "-->" '\n'?
   {put (lexeme lexbuf)}
| _ as c
   {putc c ; in_comment lexbuf}
| eof
   {error "End of file in comment" lexbuf}

and styles = parse
| blank+ { styles lexbuf }
| eof    { [] }
| blank* '.' ([^'{'' ''\t''\n']+ as name) blank*
    ((tag blank*)+ as addname)?
    ('{' [^'}']* '}' as cl)
  { Css.Class (name, addname, cl) :: styles lexbuf }
| blank* ([^'{']+ '{' [^'}']* '}' as lxm)
  {Css.Other lxm :: styles lexbuf}

(* Extract classes: values of the CLASS attribute *)
and extract_classes cls = parse
| "<!--" | "-->" (* ignore comment markers *)
  { extract_classes cls lexbuf}
| "<!"|"</"
  { skip_tag lexbuf ; extract_classes cls lexbuf }
| '<' tag
    { let cls = extract_attrs cls lexbuf in
      extract_classes cls lexbuf }
| [^'<']+ { extract_classes cls lexbuf }
| eof      { cls }
| "" { error "Extract classes" lexbuf }

and skip_tag = parse
| [^'>']* '>' { () }
| eof         { error "End of file in tag" lexbuf }

and skip_value = parse
| '\'' [^'\'']* '\''
| '"'  [^'"']*  '"'
| '#'?['a'-'z''A'-'Z''0'-'9''-''+''_'':''.']+
   { () }
| "" { error "Attribute syntax (skip_value)" lexbuf }
(* '"' *)

and extract_value cls = parse
| ['a'-'z''A'-'Z''0'-'9''-''+''_'':''.']+ as name
   { Emisc.Strings.add name cls }
| '\''
    { extract_values_q cls lexbuf }
| '"' (* '"' *)
    { extract_values_qq cls lexbuf }
| "" { error "Attribute syntax (extract_value)" lexbuf }

and extract_values_q cls = parse
| blank+ { extract_values_q cls lexbuf }
| class_name as cl { extract_values_q (Emisc.Strings.add cl cls) lexbuf }
| '\'' { cls }
| "" { error "Class value syntax" lexbuf }

and extract_values_qq cls = parse
| blank+ { extract_values_qq cls lexbuf }
| class_name as cl { extract_values_qq (Emisc.Strings.add cl cls) lexbuf }
| '"' { cls } (* '"' *)
| ""  { error "Class value syntax" lexbuf }

and extract_attrs cls = parse
(* Blanks or attributes with no value *)
| blank+|['a'-'z''A'-'Z''-''0'-'9']+
   { extract_attrs cls lexbuf }
(* Class attribute *)
| ['c''C']['l''L']['a''A']['s''S']['s''S'] blank* '=' blank*  
   { let cls = extract_value cls lexbuf in
     extract_attrs cls lexbuf }
(* Other attributes with a value *)
| attr_name blank* '=' blank*
   { skip_value lexbuf ;
     extract_attrs cls lexbuf }
(* End of tag *)
| '/'? '>' { cls }
| ""  { error "Attribute syntax (extract_attrs)" lexbuf }


{

let tok_buff = ref None
;;

let txt_buff = Out.create_buff ()
;;

let rec read_tokens blanks lb =
  let t = main lb in
  match t with
  | Text txt -> Out.put txt_buff txt ; read_tokens false lb
  | Blanks txt -> Out.put txt_buff txt ; read_tokens blanks lb
  | _ ->
      let txt = Out.to_string txt_buff in
      match txt with
      | "" -> t
      | _  ->
          tok_buff := Some t ;
          if blanks then
            Blanks txt
          else
            Text txt

let reset () =
  txt_level := 0 ;
  MyStack.reset txt_stack ;
  Out.reset txt_buff ;
  Out.reset buff ;
  Out.reset abuff

let next_token lb =
  try match !tok_buff with
  | Some t -> tok_buff := None ; t
  | None   -> read_tokens true lb
  with
  | e ->
      reset () ;
      raise e

let classes lexbuf =
  let r = extract_classes Emisc.Strings.empty lexbuf in
  r
end
}