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
open Mo_def
open Mo_types

open Source
open Trivia
open Type
module E = Syntax
module I = Idllib.Syntax
module Set = Idllib.Resolve_import.Set

(* use a functor to allocate temporary shared state *)
module MakeState() = struct

  let env = ref Env.empty
  let hide = ref Set.empty
  module RevMap = Map.Make (struct type t = string * I.typ' let compare = compare end)
  let rev = ref RevMap.empty

  (* For monomorphization *)
  module Stamp = Type.ConEnv
  let stamp = ref Stamp.empty

  module TypeMap = Map.Make (struct type t = con * typ list let compare = compare end)
  let type_map = ref TypeMap.empty

  let normalize_name name =
    String.map (fun c ->
        if c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
        then c else '_'
      ) name

  let monomorphize_con vs c =
    let name = normalize_name (Cons.name c) in
    match Cons.kind c with
    | Def _ ->
      let id = (c, vs) in
      let (k, n) =
        match TypeMap.find_opt id !type_map with
        | None ->
          (match Stamp.find_opt c !stamp with
           | None ->
             let keys = Stamp.keys !stamp in
             let k = List.length (List.filter (fun d -> Cons.name c = Cons.name d) keys) in
             stamp := Stamp.add c (k, 0) !stamp;
             type_map := TypeMap.add id (k, 0) !type_map;
             (k, 0)
           | Some (k, n) ->
             stamp := Stamp.add c (k, n + 1) !stamp;
             type_map := TypeMap.add id (k, n + 1) !type_map;
             (k, n + 1))
        | Some kn -> kn
      in
      begin
        match (k, n) with
        | _ when k < 0 || n < 0 -> assert false
        | (0, 0) -> name
        | (0, n) -> Printf.sprintf "%s_%d" name n
        | (k, 0) -> Printf.sprintf "%s__%d" name k
        | (k, n) -> Printf.sprintf "%s__%d_%d" name k n
      end
    | _ -> assert false

  let prim = let open I in
    function
    | Type.Null -> PrimT Null
    | Bool -> PrimT Bool
    | Nat -> PrimT Nat
    | Nat8 -> PrimT Nat8
    | Nat16 -> PrimT Nat16
    | Nat32 -> PrimT Nat32
    | Nat64 -> PrimT Nat64
    | Int -> PrimT Int
    | Int8 -> PrimT Int8
    | Int16 -> PrimT Int16
    | Int32 -> PrimT Int32
    | Int64 -> PrimT Int64
    | Float -> PrimT Float64
    | Char -> PrimT Nat32
    | Text -> PrimT Text
    | Blob -> BlobT
    | Principal -> PrincipalT
    | Region
    | Error -> assert false

  let rec typ t =
    (match t with
    | Any -> I.(PrimT Reserved)
    | Non -> I.(PrimT Empty)
    | Prim p -> prim p
    | Var (s, i) -> assert false
    | Con (c, ts) ->
      (match Cons.kind c with
       | Def (_, t) ->
         I.(match open_ ts t with
            | Prim p -> prim p
            | Any -> PrimT Reserved
            | Non -> PrimT Empty
            | t ->
              let id = monomorphize_con ts c in
              match Env.find_opt id !env with
              | Some PreT -> VarT (id @@ no_region)
              | Some (VarT _ as seen) ->
                assert (Set.mem id !hide);
                seen
              | Some seen ->
                assert (Set.mem id !hide |> not);
                VarT (RevMap.find (Cons.name c, seen) !rev @@ no_region)
              | None -> begin
                  env := Env.add id PreT !env;
                  let t = typ (normalize t) in
                  let rev_key = Cons.name c, t.it in
                  match RevMap.find_opt rev_key !rev with
                  | None ->
                    env := Env.add id t.it !env;
                    rev := RevMap.add rev_key id !rev;
                    VarT (id @@ no_region)
                  | Some id' ->
                    let canonical = VarT (id' @@ no_region) in
                    env := Env.add id canonical !env;
                    hide := Set.add id !hide;
                    canonical
                end)
        | _ -> assert false)
    | Typ c -> assert false
    | Tup ts ->
       if ts = [] then
         I.(PrimT Null)
       else
         I.RecordT (tuple ts)
    | Array t -> I.VecT (typ t)
    | Opt t -> I.OptT (typ t)
    | Obj (Object, fs) ->
       I.RecordT (fields fs)
    | Obj (Actor, fs) -> I.ServT (meths fs)
    | Obj (Module, _)
    | Obj (Memory, _) -> assert false
    | Variant fs ->
       I.VariantT (fields fs)
    | Func (Shared s, c, tbs, ts1, ts2) ->
       let nons = List.map (fun _ -> Non) tbs in
       let ts1, ts2 =
         (List.map (open_ nons) ts1,
          List.map (open_ nons) ts2) in
       let t1 = args ts1 in
       (match ts2, c with
       | [], Returns -> I.FuncT ([I.Oneway @@ no_region], t1, [])
       | ts, Promises ->
         I.FuncT (
           (match s with
            | Query -> [I.Query @@ no_region]
            | Composite -> [I.Composite @@ no_region]
            | Write -> []),
           t1, args ts)
       | _ -> assert false)
    | Named (n, t) ->
      (* drop name, Candid only allows names on function argument and return types *)
      (typ t).it
    | Func _
    | Async _
    | Mut _
    | Pre -> assert false
    ) @@ no_region
  and field {lab; typ = t; src = {region; _}} =
    let open Idllib.Escape in
    match unescape lab with
    | Nat nat ->
       I.{label = I.Id nat @@ no_region; typ = typ t} @@ region
    | Id id ->
       I.{label = I.Named id @@ no_region; typ = typ t} @@ region
  and fields fs =
    List.map field
      (List.filter (fun f -> not (is_typ f.typ)) fs)
  and tuple ts =
    List.mapi (fun i x ->
        let id = Lib.Uint32.of_int i in
        I.{label = I.Unnamed id @@ no_region; typ = typ x} @@ no_region
      ) ts
  and args ts =
    List.map arg_typ ts
  and arg_typ t =
    match t with
    | Named (name, t) ->
       let open Idllib.Escape in
       (match unescape name with
       | Nat nat ->
          I.{name = None; typ = typ t} @@ no_region
       | Id id ->
          I.{name = Some (id @@ no_region); typ = typ t} @@ no_region)
    | t ->
      I.{name = None; typ = typ t} @@ no_region
  and meths fs =
    List.fold_right (fun f list ->
        match f.typ with
        | Typ c ->
           list
        | _ ->
           let meth =
             I.{var = Idllib.Escape.unescape_method f.lab @@ no_region;
                meth = typ f.typ} @@ f.src.region in
           meth :: list
      ) fs []

  let is_actor_con c =
    match Cons.kind c with
    | Def ([], Obj (Actor, _)) -> true
    | _ -> false

  let chase_decs env =
    ConSet.iter (fun c ->
        if is_actor_con c then ignore (typ (Con (c,[])))
      ) env.Scope.con_env

  let gather_decs () =
    Env.fold (fun id t list ->
        if Set.mem id !hide then list else
        (* TODO: pass corresponding Motoko source region? *)
        let dec = I.TypD (id @@ no_region, t @@ no_region) @@ no_region in
        dec::list
      ) !env []

  let actor prog =
    let open E in
    let { body = cub; _ } = (CompUnit.comp_unit_of_prog false prog).it in
    match cub.it with
    | ProgU _ | ModuleU _ -> None
    | ActorU _ -> Some (typ cub.note.note_typ)
    | ActorClassU _ ->
       (match normalize cub.note.note_typ with
        | Func (Local, Returns, [tb], ts1, [t2]) ->
          let args = List.map arg_typ (List.map (open_ [Non]) ts1) in
          let (_, _, rng) = as_async (normalize (open_ [Non] t2)) in
          let actor = typ rng in
          Some (I.ClassT (args, actor) @@ cub.at)
        | _ -> assert false
       )
end

let prog (progs, senv) : I.prog =
  let prog = CompUnit.combine_progs progs in
  let trivia = prog.note.E.trivia in
  let open MakeState() in
  let actor = actor prog in
  if actor = None then chase_decs senv;
  let decs = gather_decs () in
  let it = I.{decs; actor} in
  {it; at = prog.at; note = I.{filename = ""; trivia}}

let of_actor_type t : I.prog =
  let open MakeState() in
  let actor = Some (typ t) in
  let decs = gather_decs () in
  let prog = I.{decs; actor} in
  {it = prog; at = no_region; note = I.{filename = ""; trivia = empty_triv_table}}

let of_service_type ts t : I.arg_typ list * I.prog =
  let open MakeState() in
  let args = List.map arg_typ ts  in
  let actor = Some (typ t) in
  let decs = gather_decs () in
  let prog = I.{decs; actor} in
  args,
  {it = prog; at = no_region; note = I.{filename = ""; trivia = empty_triv_table}}