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

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

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

  let env = ref Env.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 (k, n) -> (k, n)
      in
      begin
        match (k, n) with
        | (0, 0) -> name
        | (0, n) when n > 0 -> Printf.sprintf "%s_%d" name n
        | (k, 0) when k > 0 -> Printf.sprintf "%s__%d" name k
        | (k, n) when k > 0 && n > 0 -> Printf.sprintf "%s__%d_%d" name k n
        | _ -> assert false
      end
    | _ -> assert false

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

  let rec typ t =
    (match t with
    | Any -> I.PrimT I.Reserved
    | Non -> I.PrimT I.Empty
    | Prim p -> prim p
    | Var (s, i) -> assert false
    | Con (c, ts) ->
       (match Cons.kind c with
        | Def (_, t) ->
           (match (open_ ts t) with
            | Prim p -> prim p
            | Any -> I.PrimT I.Reserved
            | Non -> I.PrimT I.Empty
            | t ->
               let id = monomorphize_con ts c in
               if not (Env.mem id !env) then
                 begin
                   env := Env.add id (I.PreT @@ no_region) !env;
                   let t = typ (normalize t) in
                   env := Env.add id t !env
                 end;
               I.VarT (id @@ no_region))
        | _ -> assert false)
    | Typ c -> assert false
    | Tup ts ->
       if ts = [] then
         I.PrimT I.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, _) -> assert false
    | 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)
    | 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 typ ts
  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 ->
        (* TODO: pass corresponding Motoko source region? *)
        let dec = I.TypD (id @@ no_region, t) @@ 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 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.typ list * I.prog =
  let open MakeState() in
  let args = List.map 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}}