Source file anonymous_variable.ml
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
open! Core
open Ppxlib
module Name : sig
type t
include Identifiable.S with type t := t
val to_css_variable : t -> string
end = struct
include String
let to_css_variable t = [%string {|var(--%{t})|}]
end
let curr = ref 0
let sanitize_filename filename =
let basename = Filename.basename filename in
let without_extension =
match String.rsplit2 basename ~on:'.' with
| Some (base, _ext) -> base
| None -> basename
in
String.map without_extension ~f:(fun c -> if Char.is_alphanum c then c else '_')
;;
let mint_name ~loc =
incr curr;
let filename = Ppx_here_expander.expand_filename loc.loc_start.pos_fname in
let sanitized_filename = sanitize_filename filename in
Name.of_string [%string "ppx_css_%{sanitized_filename}_anon_variable_%{!curr#Int}"]
;;
type t =
{ name : Name.t
; expression : expression
}
[@@deriving fields ~getters]
let of_expression ~loc expression =
let name = mint_name ~loc in
{ name; expression }
;;
module Collection = struct
type nonrec t =
{ variables : t list
; unique_name : string
}
let empty = { unique_name = "ppx_css_empty_anonymous_variables"; variables = [] }
let of_list variables =
match variables with
| [] -> empty
| _ :: _ ->
let unique_name = gen_symbol ~prefix:"ppx_css__internal_anonymous_variables" () in
{ variables; unique_name }
;;
end
module For_testing = struct
let restart_identifiers () = curr := 0
end