stringify.ml 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. open Types
  2. let tab = " "
  3. let indent = Str.global_replace (Str.regexp "^\\(.\\)") (tab ^ "\\1")
  4. let rec cat sep fn = function
  5. | [] -> ""
  6. | [hd] -> fn hd
  7. | hd :: tl -> fn hd ^ sep ^ cat sep fn tl
  8. let rec value2str = function
  9. | Lit lit -> lit
  10. | Str str -> "\"" ^ str ^ "\""
  11. | Lst values -> cat " " value2str values
  12. | Dim (x, u) when float_of_int (int_of_float x) = x ->
  13. string_of_int (int_of_float x) ^ u
  14. | Dim (x, u) -> string_of_float x ^ u
  15. | Fn (name, arg) -> name ^ "(" ^ value2str arg ^ ")"
  16. | Imp -> "!important"
  17. let prop2str (name, value) = name ^ ": " ^ value2str value ^ ";"
  18. let block body = " {\n" ^ indent body ^ "\n}"
  19. let rec decl2str = function
  20. | Group (selectors, props) ->
  21. cat ", " (String.concat " ") selectors ^ block (cat "\n" prop2str props)
  22. | Media (queries, groups) ->
  23. "@media " ^ String.concat ", " queries ^ block (cat "\n\n" decl2str groups)
  24. | Import (filename, []) ->
  25. "@import \"" ^ filename ^ "\";"
  26. | Import (filename, queries) ->
  27. "@import \"" ^ filename ^ "\" " ^ String.concat ", " queries ^ ";"
  28. | Charset charset ->
  29. "@charset \"" ^ charset ^ "\";"
  30. | Page (None, props) ->
  31. "@page" ^ block (cat "\n" prop2str props)
  32. | Page (Some query, props) ->
  33. "@page " ^ query ^ block (cat "\n" prop2str props)
  34. | Fontface props ->
  35. "@font-face " ^ block (cat "\n" prop2str props)
  36. | Namespace (None, uri) ->
  37. "@namespace \"" ^ uri ^ "\";"
  38. | Namespace (Some prefix, uri) ->
  39. "@namespace " ^ prefix ^ " \"" ^ uri ^ "\";"
  40. let decls2str = cat "\n\n" decl2str