Debian Codegraph @

src/rocq_elpi_glob_quotation.ml

raw symbols SCIP
1 (* rocq-elpi: Coq terms as the object language of elpi *)
2 (* license: GNU Lesser General Public License Version 2.1 or later *)
3 (* ------------------------------------------------------------------------- *)
4
5 module API = Elpi.API
6 module E = API.RawData
7 module U = API.Utils
8 module S = API.State
9 module Q = API.Quotation
10 module F = API.FlexibleData
11 module A = API.Ast
12
13 open Rocq_elpi_HOAS
14
15 open Names
16 open Rocq_elpi_utils
17
18 (* ***************** {{ quotation }} for Glob_terms ********************** *)
19
20 open Glob_term
21
22 (* HACK: names not visible by evars *)
23 let mk_restricted_name i = Printf.sprintf "_elpi_restricted_%d_" i
24 let is_restricted_name =
25 let rex = Str.regexp "_elpi_restricted_[0-9]+_" in
26 fun s -> Str.(string_match rex (Id.to_string s) 0)
27
28 let section_ids env =
29 let named_ctx = Environ.named_context env in
30 Context.Named.fold_inside
31 (fun acc x -> Names.Id.Set.add (Context.Named.Declaration.get_id x) acc)
32 ~init:Names.Id.Set.empty named_ctx
33
34 type glob_ctx = {
35 taken : Names.Id.Set.t; (* union of the two below *)
36 section : Names.Id.Set.t;
37 bound : Names.Id.Set.t;
38 bound_list : Names.Id.t list;
39 (* the set above, but with the order in which they pccur in the Coq context (head one is last intro) *)
40 env : Environ.env;
41 hyps : A.Term.t list;
42 }
43
44 let empty_glob_ctx env : glob_ctx =
45 { env; bound = Names.Id.Set.empty; bound_list = []; taken = section_ids env; section = section_ids env; hyps = [] }
46
47 let glob_ctx : glob_ctx option S.component =
48 S.declare_component ~name:"rocq-elpi:glob-environment" ~descriptor:interp_state
49 ~pp:(fun _ _ -> ()) ~init:(fun () -> None)
50 ~start:(fun _ -> Some (empty_glob_ctx (Global.env ()))) ()
51
52 let set_glob_ctx state e = S.set glob_ctx state (Some e)
53
54
55 let ensure_some f = function
56 | None -> Some (f (empty_glob_ctx (Global.env ())))
57 | Some x -> Some (f x)
58
59 let push_glob_ctx state name ctxast =
60 S.update glob_ctx state (ensure_some (fun { env; bound; bound_list; section; hyps; taken } ->
61 assert(not(Names.Id.Set.mem name taken));
62 let d = Context.Named.Declaration.LocalAssum(Context.make_annot name Sorts.Relevant,Constr.mkProp) in
63 let env = push_named d env in
64 let bound = Names.Id.Set.add (*Environ.push_named_context_val*) name bound in
65 let bound_list = name :: bound_list in
66 let hyps = match ctxast with Some h -> h :: hyps | None -> hyps in
67 let taken = Names.Id.Set.add name taken in
68 { env; bound; bound_list; section; hyps; taken }
69 ))
70
71 let glob_ctx_of_coq_ctx { names; env } =
72 let genv = Global.env () in
73 let section = section_ids genv in
74 let bound_list = Environ.named_context env |> List.map Context.Named.Declaration.get_id in
75 let bound_list = List.filter (fun x -> not @@ Names.Id.Set.mem x section) bound_list in
76 { env = genv;
77 bound = Names.Id.Set.of_list bound_list;
78 bound_list;
79 section;
80 hyps = [];
81 taken = names;
82 }
83
84
85 let get_glob_env state = Option.get @@ ensure_some (fun x -> x) @@ S.get glob_ctx state
86
87 let update_subst l na =
88 let in_range id l = List.exists (fun (_,id') -> Id.equal id id') l in
89 let l' = Nameops.Name.fold_right Id.List.remove_assoc na l in
90 Nameops.Name.fold_right
91 (fun id _ ->
92 if in_range id l' then
93 let id' = Namegen.next_ident_away_from id (fun id' -> in_range id' l') in
94 (id,id')::l, Name id'
95 else l,na)
96 na (l,na)
97
98 let update_subst_id l na =
99 let in_range id l = List.exists (fun (_,id') -> Id.equal id id') l in
100 let l' = Id.List.remove_assoc na l in
101 if in_range na l' then
102 let id' = Namegen.next_ident_away_from na (fun id' -> in_range id' l') in
103 (na,id')::l, id'
104 else l,na
105
106 let drop_relevance (a,_,c,d,e) = (a,c,d,e)
107
108 let rename_var l id =
109 try
110 let id' = Id.List.assoc id l in
111 id'
112 with Not_found ->
113 id
114
115 let rec rename_glob_vars l c = DAst.map_with_loc (fun ?loc -> function
116 | GVar id as r ->
117 let id' = rename_var l id in
118 if id == id' then r else GVar id'
119 | GRef (GlobRef.VarRef _,_) as r -> r
120 | GProd (na,r,bk,t,c) ->
121 let l',na' = update_subst l na in
122 GProd (na',r,bk,rename_glob_vars l t,rename_glob_vars l' c)
123 | GLambda (na,r,bk,t,c) ->
124 let l',na' = update_subst l na in
125 GLambda (na',r,bk,rename_glob_vars l t,rename_glob_vars l' c)
126 | GLetIn (na,r,b,t,c) ->
127 let l',na' = update_subst l na in
128 GLetIn (na',r,rename_glob_vars l b,Option.map (rename_glob_vars l) t,rename_glob_vars l' c)
129 (* Lazy strategy: we fail if a collision with renaming occurs, rather than renaming further *)
130 | GCases (ci,po,tomatchl,cls)->
131 (* TODO
132 let test_pred_pat (na,ino) =
133 test_na l na; Option.iter (fun {v=(_,nal)} -> List.iter (test_na l) nal) ino in
134 let test_clause idl = List.iter (test_id l) idl in *)
135 let po = Option.map (rename_glob_vars l) po in
136 let tomatchl = Util.List.map_left (fun (tm,x) -> (rename_glob_vars l tm,x)) tomatchl in
137 let cls = Util.List.map_left (CAst.map (fun (idl,p,c) -> (idl,p,rename_glob_vars l c))) cls in
138 GCases (ci,po,tomatchl,cls)
139 | GLetTuple (nal,(na,po),c,b) ->
140 let l',na' = update_subst l na in
141 let l'', nal = CList.fold_left_map update_subst l nal in
142 GLetTuple (nal,(na',Option.map (rename_glob_vars l') po),
143 rename_glob_vars l c,rename_glob_vars l'' b)
144 | GIf (c,(na,po),b1,b2) ->
145 let l',na' = update_subst l na in
146 GIf (rename_glob_vars l c,(na',Option.map (rename_glob_vars l') po),
147 rename_glob_vars l b1,rename_glob_vars l b2)
148 | GRec (k,idl,decls,bs,ts) ->
149 let l', idl = CArray.fold_left_map update_subst_id l idl in
150 let decls, bs, ts = CArray.split3 @@ CArray.map3 (fun dl ty bo ->
151 let l'', dl = CList.fold_left_map (fun l (na,r,k,bbd,bty) ->
152 let l, na = update_subst l na in
153 l, (na,r,k,Option.map (rename_glob_vars l) bbd, rename_glob_vars l bty)) l' dl in
154 dl, rename_glob_vars l'' ty, rename_glob_vars l'' bo) decls bs ts in
155 GRec (k,idl,decls,bs,ts)
156 | _ -> DAst.get (Glob_ops.map_glob_constr (rename_glob_vars l) c)
157 ) c
158
159 let under_glob_ctx1 name ~tyast ~k t state =
160 match Context.binder_name name with
161 | Names.Name.Anonymous -> k name t state
162 | Names.Name.Name id ->
163 (* let () = Printf.eprintf " intro %s\n" (Id.to_string id) in *)
164 let { taken } = get_glob_env state in
165 let t, id =
166 if Names.Id.Set.mem id taken then
167 let new_id = Names.Id.of_string_soft (Format.asprintf "_elpi_renamed_%s_%d" (Id.to_string id) (Names.Id.Set.cardinal taken)) in
168 (* let () = Printf.eprintf "%s -> %s\n" (Id.to_string id) (Id.to_string new_id) in *)
169 rename_glob_vars [id,new_id] t, new_id
170 else t, id in
171 let name = Context.map_annot (fun _ -> Names.Name.Name id) name in
172 let aid = Context.map_annot (fun _ -> id) name in
173 let state = push_glob_ctx state id (Some (tyast aid)) in
174 k name t state
175
176 let rec under_glob_ctxn names ~tyasts ~k ts state acc =
177 match names, tyasts with
178 | [], [] -> k (List.rev acc) ts state
179 | name :: names, tyast :: tyasts ->
180 begin match Context.binder_name name with
181 | Names.Name.Anonymous -> under_glob_ctxn names ~tyasts ~k ts state acc
182 | Names.Name.Name id ->
183 (* let () = Printf.eprintf " intro %s\n" (Id.to_string id) in *)
184 let { taken } = get_glob_env state in
185 let ts, id =
186 if Names.Id.Set.mem id taken then
187 let new_id = Names.Id.of_string_soft (Format.asprintf "_elpi_renamed_%s_%d" (Id.to_string id) (Names.Id.Set.cardinal taken)) in
188 (* let () = Printf.eprintf "%s -> %s\n" (Id.to_string id) (Id.to_string new_id) in *)
189 List.map (rename_glob_vars [id,new_id]) ts, new_id
190 else ts, id in
191 let name = Context.map_annot (fun _ -> Names.Name.Name id) name in
192 let aid = Context.map_annot (fun _ -> id) name in
193 let state = push_glob_ctx state id (Some (tyast aid)) in
194 under_glob_ctxn names ~tyasts ~k ts state (name::acc)
195 end
196 | _ -> assert false
197
198 (* Set by the parser that declares an ARGUMENT EXTEND to Coq *)
199 let get_ctx, set_ctx, _update_ctx =
200 let bound_vars =
201 S.declare_component ~name:"rocq-elpi:glob-quotation-bound-vars" ~descriptor:interp_state
202 ~init:(fun () -> None)
203 ~pp:(fun fmt -> function Some (x,_) -> () | None -> ())
204 ~start:(fun x -> x) ()
205 in
206 S.(get bound_vars, set bound_vars, update bound_vars)
207
208 let set_coq_ctx_hyps s (x,h) =
209 let s = set_ctx s (Some (upcast @@ x, h)) in
210 set_glob_ctx s (glob_ctx_of_coq_ctx (upcast x))
211
212 let under_ctx name ty bo ~k ~depth state =
213 let coq_ctx, hyps as orig_ctx = Option.default (upcast @@ empty_conv_context ~options:(default_options ()) state,[]) (get_ctx state) in
214 let orig_glob_ctx = S.get glob_ctx state in
215 let state =
216 let id =
217 match Context.binder_name name with
218 | Name id -> id
219 | Anonymous ->
220 Id.of_string_soft
221 (Printf.sprintf "_elpi_ctx_entry_%d_" (Id.Map.cardinal coq_ctx.name2db)) in
222 let name2db = Id.Map.add id depth coq_ctx.name2db in
223 let state, ctx_entry =
224 match bo with
225 | None -> state, mk_decl ~depth name ~ty
226 | Some bo -> state, mk_def ~depth name ~bo ~ty in
227 let new_hyp = { E.hsrc = ctx_entry; hdepth = depth } in
228 let state = set_coq_ctx_hyps state ({ coq_ctx with name2db }, new_hyp :: hyps) in
229 let state = push_glob_ctx state id None in
230 state in
231 let state, y, gl = k ~depth:(depth+1) state in
232 let state = set_coq_ctx_hyps state orig_ctx in
233 let state = S.set glob_ctx state orig_glob_ctx in
234 state, y, gl
235
236 let is_hole x = match DAst.get x with GHole _ -> true | _ -> false
237
238 let universe_level_name evd ({CAst.v=id} as lid) =
239 try Evd.universe_of_name evd id
240 with Not_found ->
241 CErrors.user_err ?loc:lid.CAst.loc
242 (Pp.(str "Undeclared universe: " ++ Id.print id ++ str "."))
243
244 let sort_name env sigma l = match l with
245 | [] -> assert false
246 | [u, 0] ->
247 begin match u with
248 | GSet -> Sorts.set
249 | GSProp -> Sorts.sprop
250 | GProp -> Sorts.prop
251 | GUniv u -> Sorts.sort_of_univ (Univ.Universe.make u)
252 | GLocalUniv l ->
253 let u = universe_level_name sigma l in
254 Sorts.sort_of_univ (Univ.Universe.make u)
255 | GRawUniv _ -> nYI "GRawUniv"
256 end
257 | [_] | _ :: _ :: _ ->
258 nYI "(glob)HOAS for Type@{i j}"
259
260 let glob_level loc state = function
261 | UAnonymous _ -> nYI "UAnonymous"
262 | UNamed s ->
263 match s with
264 | GSProp
265 | GProp ->
266 CErrors.user_err ?loc
267 Pp.(str "Universe instances cannot contain non-Set small levels, polymorphic" ++
268 str " universe instances must be greater or equal to Set.");
269 | GSet -> Univ.Level.set
270 | GUniv u -> u
271 | GRawUniv u -> nYI "GRawUniv"
272 | GLocalUniv l -> universe_level_name (get_sigma state) l
273
274 let nogls f ~depth state = let state, x = f ~depth state in state, x, ()
275
276 let rigid_anon_type = function GSort(None, UAnonymous {rigid=UnivRigid}) -> true | _ -> false
277 let named_type = function GSort(None, UNamed _) -> true | _ -> false
278 let name_of_type = function GSort(None, UNamed u) -> u | _ -> assert false
279 let dest_GProd = function GProd(n,_,_,s,t) -> n,s,t | _ -> assert false
280 let dest_GLambda = function GLambda(n,_,_,s,t) -> n,s,t | _ -> assert false
281 let dest_GLetIn = function GLetIn(n,_,bo,s,t) -> n,bo,s,t | _ -> assert false
282 let mkGLambda (n,b,s,t) = GLambda(n,None,b,s,t)
283
284 let dummy_loc = Loc.make_loc (0,0)
285
286 let fresh_uv =
287 let i = ref 0 in
288 let aux () =
289 incr i;
290 let candidate = A.Name.from_string @@ "X" ^ string_of_int !i ^ "_" in
291 candidate
292 in
293 aux
294
295 let glob_intros ctx bo =
296 List.fold_right (fun (name,r,_,ov,ty) bo ->
297 DAst.make
298 (match ov with
299 | None -> GLambda(name,r,Explicit,ty,bo)
300 | Some v -> GLetIn(name,r,v,Some ty,bo)))
301 ctx bo
302
303 let glob_intros_prod ctx bo =
304 List.fold_right (fun (name,r,_,ov,ty) bo ->
305 DAst.make
306 (match ov with
307 | None -> GProd(name,r,Explicit,ty,bo)
308 | Some v -> GLetIn(name,r,v,Some ty,bo)))
309 ctx bo
310
311
312
313 let name_of_id id = A.Name.from_string (Names.Id.to_string id)
314
315 let name_of = function
316 | Names.Name.Anonymous -> None
317 | Names.Name.Name id -> Some (name_of_id id)
318
319 [%%if coq = "9.0" || coq = "9.1" || coq = "9.2"]
320 let is_elpi_code_r = ref (fun _ -> assert false)
321 let get_elpi_code_r = ref (fun _ -> assert false)
322 let is_elpi_code_appArg_r = ref (fun _ -> assert false)
323 let get_elpi_code_appArg_r = ref (fun _ -> assert false)
324
325 let is_elpi_code x = !is_elpi_code_r x
326 let get_elpi_code x = !get_elpi_code_r x
327 let is_elpi_code_appArg x = !is_elpi_code_appArg_r x
328 let get_elpi_code_appArg x = !get_elpi_code_appArg_r x
329 [%%else]
330 let elpi_code_tag = Genintern.create_uniform_genconstr "elpi_code"
331 let elpi_code_appArg_tag = Genintern.create_uniform_genconstr "elpi_code_appArg"
332
333 let tag_helpers (type raw glb) (tag:(raw, glb) GenConstr.tag) =
334 let check (GenConstr.Glb (tag', _)) = Option.has_some @@ GenConstr.eq tag tag' in
335 let get (GenConstr.Glb (tag', v)) : glb =
336 let Refl = Option.get @@ GenConstr.eq tag tag' in
337 v
338 in
339 check, get
340
341 let is_elpi_code, get_elpi_code = tag_helpers elpi_code_tag
342 let is_elpi_code_appArg, get_elpi_code_appArg = tag_helpers elpi_code_appArg_tag
343 [%%endif]
344
345 let gterm2lpast ~pattern ~language state glob =
346
347 let rec lookup_bound ~loc ~coqloc name state =
348 let { env; bound; section } = get_glob_env state in
349 match Names.Id.Set.mem name bound with
350 | _ -> A.Term.mkBound ~loc ~language @@ name_of_id name
351 | exception Not_found ->
352 if Id.Set.mem name section then
353 in_elpiast_gr ~loc (GlobRef.VarRef name)
354 else
355 CErrors.user_err ~loc:coqloc
356 Pp.(str"Free Coq variable " ++ Id.print name ++ str " in context: " ++
357 prlist_with_sep spc Id.print (Environ.named_context env |> Termops.ids_of_named_context));
358
359 and under_binder ~loc name ty bo state t ~k =
360 under_glob_ctx1 name ~tyast:(mk_tyast ~loc ~ty ~bo) ~k state t
361
362 and under_binders ~loc names tys bos state ts ~k =
363 under_glob_ctxn names ~tyasts:(List.map2 (fun ty bo -> mk_tyast ~loc ~ty ~bo) tys bos) ~k state ts []
364
365 and mk_tyast ~loc ~ty ~bo id =
366 match bo with
367 | None -> mk_decl state ~loc id ~ty
368 | Some bo -> mk_def state ~loc id ~ty ~bo
369
370 and mk_decl state ~loc name ~ty =
371 let v = A.Term.mkBound ~loc ~language @@ name_of_id @@ Context.binder_name name in
372 in_elpiast_decl ~loc ~v (Context.map_annot (fun x -> Name.Name x) name) ~ty
373
374 and mk_def state ~loc name ~ty ~bo =
375 let v = A.Term.mkBound ~loc ~language @@ name_of_id @@ Context.binder_name name in
376 in_elpiast_def ~loc ~v (Context.map_annot (fun x -> Name.Name x) name) ~ty ~bo
377
378 and gterm2lp state ({ CAst.loc; v } as x) : A.Term.t =
379 debug Pp.(fun () ->
380 str"gterm2lp:" ++ str " term=" ++Printer.pr_glob_constr_env (get_glob_env state).env (get_sigma state) x);
381 let coqloc = Option.default dummy_loc loc in
382 let loc = Rocq_elpi_utils.of_coq_loc coqloc in
383 match (DAst.get_thunk v) (*.CAst.v*) with
384 | GRef(GlobRef.ConstRef p,_ul) when Structures.PrimitiveProjections.mem p ->
385 let hd = in_elpiast_gr ~loc (GlobRef.ConstRef p) in
386 hd
387 | GRef(gr, ul) when Global.is_polymorphic gr ->
388 begin match ul with
389 | None ->
390 let s = A.Term.mkVar ~loc ~hdloc:loc (fresh_uv ()) [] in
391 in_elpiast_poly_gr ~loc gr s
392 | Some (ql,l) ->
393 let () = if not (CList.is_empty ql) then nYI "sort poly" in
394 let l' = List.map (glob_level x.CAst.loc state) l in
395 in_elpiast_poly_gr_instance ~loc gr (UVars.Instance.of_array ([||], Array.of_list l'))
396 end
397 | GRef(gr,_ul) -> in_elpiast_gr ~loc gr
398 | GVar(id) -> lookup_bound ~loc ~coqloc id state
399 | GSort _ as t when rigid_anon_type t ->
400 let s = A.Term.mkVar ~loc ~hdloc:loc (fresh_uv ()) [] in
401 in_elpiast_flex_sort ~loc s
402 | GSort _ as t when named_type t ->
403 let u = name_of_type t in
404 let env = get_glob_env state in
405 in_elpiast_sort ~loc state (sort_name env (get_sigma state) u)
406 | GSort(_) -> nYI "(glob)HOAS for Type@{i j}"
407
408 | GProd _ as t ->
409 let (name,s,t) = dest_GProd t in
410 let s = gterm2lp state s in
411 under_binder ~loc (EConstr.annotR name) s None t state ~k:(fun name t state ->
412 in_elpiast_prod ~loc name s (gterm2lp state t))
413 | GLambda _ as t ->
414 let (name,s,t) = dest_GLambda t in
415 let s = gterm2lp state s in
416 under_binder ~loc (EConstr.annotR name) s None t state ~k:(fun name t state ->
417 in_elpiast_lam ~loc name s (gterm2lp state t))
418 | GLetIn _ as t ->
419 let (name,bo , oty, t) = dest_GLetIn t in
420 let bo = gterm2lp state bo in
421 let ty =
422 match oty with
423 | None ->
424 let { bound_list = args } = get_glob_env state in
425 A.Term.mkVar ~loc ~hdloc:loc (fresh_uv ())
426 (List.map (fun x -> A.Term.mkBound ~loc ~language (name_of_id x)) args)
427 | Some ty -> gterm2lp state ty in
428 under_binder ~loc (EConstr.annotR name) ty (Some bo) t state ~k:(fun name t state ->
429 in_elpiast_let ~loc name ~ty ~bo (gterm2lp state t))
430
431 | GGenarg arg when is_elpi_code arg ->
432 let loc, text = get_elpi_code arg in
433 let ast = Q.elpi ~language:Q.elpi_language state loc text in
434 if A.Term.is_spill_from_quotation ast then
435 let { hyps } = get_glob_env state in
436 if hyps = [] then ast
437 else A.Term.extend_spill_hyp_from_quotation ast hyps
438 else ast
439 | GGenarg arg when is_elpi_code_appArg arg ->
440 begin match get_elpi_code_appArg arg with
441 | _, [] -> assert false
442 | loc, hd :: stuff ->
443 let stuff = List.map (fun s -> DAst.make ~loc:coqloc @@ GVar(Id.of_string s)) stuff in
444 let stuff = List.map (gterm2lp state) stuff in
445 let ast = Q.elpi ~language:Q.elpi_language state loc hd in
446 A.Term.apply_elpi_var_from_quotation ast stuff
447 end
448
449 | GGenarg _ -> nYI "(glob)HOAS for GGenarg"
450
451 | GHole GImpossibleCase -> nYI "(glob)HOAS for GHole GImpossibleCase"
452 | GHole (GNamedHole _) -> CErrors.user_err ~loc:coqloc Pp.(str"elpi: ?[name] syntax not supported")
453
454 | GHole (GImplicitArg _|GInternalHole|GQuestionMark _|GBinderType _|GCasesType) when pattern -> A.Term.mkDiscard ~loc
455
456 | GHole (GImplicitArg _)
457 (*A.Term.mkDiscard ~loc (* since the user did not write it, can override with @ *)*)
458 | GHole (GBinderType _)
459 | GHole GInternalHole
460 | GHole GCasesType
461 | GHole (GQuestionMark _) ->
462 let { bound_list = args } = get_glob_env state in
463 let args = List.filter (fun n -> not(is_restricted_name n)) args in
464 A.Term.mkVar ~loc ~hdloc:loc (fresh_uv ())
465 (List.map (fun x -> A.Term.mkBound ~loc ~language (name_of_id x)) (List.rev args))
466
467 | GCast(t,_,c_ty) ->
468 let t = gterm2lp state t in
469 let c_ty = gterm2lp state c_ty in
470 let id = Id.of_string "self" in
471 let name = Names.Name.Name id in
472 let self = A.Term.mkBound ~loc ~language (name_of_id id) in
473 in_elpiast_let ~loc (EConstr.annotR name) ~bo:t ~ty:c_ty self
474
475 | GEvar(_k,_subst) -> nYI "(glob)HOAS for GEvar"
476 | GPatVar _ -> nYI "(glob)HOAS for GPatVar"
477
478 | GProj ((ref,us),args,c) when
479 Structures.PrimitiveProjections.mem ref &&
480 List.for_all is_hole args ->
481 let p = Option.get (Structures.PrimitiveProjections.find_opt ref) in
482 let c = gterm2lp state c in
483 let p = in_elpiast_primitive ~loc (Projection (Names.Projection.make p false)) in
484 in_elpiast_appl ~loc p [c]
485
486 | GProj ((ref,us),args,c) ->
487 let hd = gterm2lp state (DAst.make (GRef (GlobRef.ConstRef ref,us))) in
488 let args = CList.map (gterm2lp state) args in
489 let c = gterm2lp state c in
490 in_elpiast_appl ~loc hd (args@[c])
491
492 | GApp(hd,args) ->
493 let hd = gterm2lp state hd in
494 let args = CList.map (gterm2lp state) args in
495 in_elpiast_appl ~loc hd args
496
497 | GLetTuple(kargs,(as_name,oty),t,b) ->
498 let t = gterm2lp state t in
499 let rt =
500 match oty with
501 | Some oty -> gterm2lp state DAst.(make (mkGLambda(as_name,Explicit,mkGHole,oty)))
502 | None -> gterm2lp state mkGHole in
503 let b =
504 List.fold_right (fun name bo ->
505 DAst.make (mkGLambda(name,Explicit,mkGHole,bo)))
506 kargs b in
507 let b = gterm2lp state b in
508 in_elpiast_match ~loc t rt [b]
509
510 | GCases(_, oty, [ t, (as_name, oind) ], bs) ->
511 let open Declarations in
512 let { env } = get_glob_env state in
513 let ind, args_name =
514 match oind with
515 | Some {CAst.v=ind, arg_names} -> ind, arg_names
516 | None ->
517 match bs with
518 | {CAst.v=(_,[x],_)} :: _ ->
519 begin match DAst.get x with
520 | PatCstr((ind,_),_,_) -> ind, []
521 | _ -> nYI "(glob)HOAS match oty ind" end
522 | _ -> nYI "(glob)HOAS match oty ind" in
523 let { mind_packets; mind_nparams }, { mind_consnames } as indspecif =
524 Inductive.lookup_mind_specif env ind in
525 let no_constructors = Array.length mind_consnames in
526 if Array.length mind_packets <> 1 then nYI "(glob)HOAS mutual inductive";
527 let t = gterm2lp state t in
528 let rt =
529 (* We try hard to stick in there the inductive type, so that
530 * the term can be read back (mkCases needs the ind) *)
531 (* TODO: add whd reduction in spine *)
532 let ty =
533 Inductive.type_of_inductive (indspecif,UVars.Instance.empty) in
534 let safe_tail = function [] -> [] | _ :: x -> x in
535 let best_name n l = match n, l with
536 | _, (Name x) :: rest -> Name x,DAst.make (GVar x), rest
537 | Name x, _ :: rest -> Name x,DAst.make (GVar x), rest
538 | Anonymous, Anonymous :: rest -> Anonymous,mkGHole, rest
539 | Name x, [] -> Name x,DAst.make (GVar x), []
540 | Anonymous, [] -> Anonymous,mkGHole, [] in
541 let rec spine n names args ty =
542 let open Constr in
543 match kind ty with
544 | Sort _ ->
545 DAst.make (mkGLambda(as_name,Explicit,
546 Glob_ops.mkGApp (DAst.make (GRef(GlobRef.IndRef ind,None))) (List.rev args),
547 Option.default mkGHole oty))
548 | Prod (name, src, tgt) when n = 0 ->
549 let name, var, names = best_name name.Context.binder_name names in
550 DAst.make (mkGLambda(name,Explicit,
551 mkGHole,spine (n-1) (safe_tail names) (var :: args) tgt))
552 | LetIn (name, v, _, b) ->
553 spine n names args (Vars.subst1 v b)
554 | Cast (t, _, _) -> spine n names args t
555 | Prod (_, _, t) ->
556 spine (n-1) (safe_tail names) (mkGHole :: args) t
557 | _ -> assert false in
558 gterm2lp state (spine mind_nparams args_name [] ty) in
559 let bs =
560 List.map (fun {CAst.v=(fv,pat,bo)} ->
561 match List.map DAst.get pat with
562 | [PatCstr((indc,cno as k),cargs,Name.Anonymous)] ->
563 assert(Names.Ind.CanOrd.equal indc ind);
564 let cargs = List.map (fun x -> match DAst.get x with
565 | PatVar n -> n
566 | _ -> nYI "(glob)HOAS match deep pattern") cargs in
567 `Case(k,cargs,bo)
568 | [PatVar Name.Anonymous] ->
569 `Def bo
570 | _ -> nYI "(glob)HOAS match complex pattern") bs in
571 let def,bs = List.partition (function `Def _ -> true | _ -> false) bs in
572 assert(List.length def <= 1);
573 let bs = CList.init no_constructors (fun i ->
574 let cno = i + 1 in
575 match CList.find_map (function
576 | `Case((_,n as k),vars,bo) when n = cno -> Some (k,vars,bo)
577 | `Case _ -> None
578 | `Def _ -> assert false) bs
579 with
580 | Some v -> v
581 | None ->
582 match def with
583 | [`Def bo] ->
584 let missing_k = ind,cno in
585 let k_args = Inductiveops.constructor_nallargs (Global.env()) missing_k in
586 missing_k, CList.make k_args Name.Anonymous, bo
587 | _ ->
588 err Pp.(str"Missing constructor "++Id.print mind_consnames.(i))) in
589 let bs = CList.map (fun (k,vars,bo) ->
590 let bo =
591 List.fold_right (fun name bo ->
592 DAst.make (mkGLambda(name,Explicit,mkGHole,bo)))
593 vars bo in
594 let bo = gterm2lp state bo in
595 bo) bs in
596 in_elpiast_match ~loc (*ci_ind ci_npar ci_cstr_ndecls ci_cstr_nargs*) t rt bs
597 | GCases _ -> nYI "(glob)HOAS complex match expression"
598 | GIf _ -> nYI "(glob)HOAS if-then-else"
599
600 | GRec(GFix([|Some rno|],0),[|name|],[|tctx|],[|ty|],[|bo|]) ->
601 let ty = glob_intros_prod tctx ty in
602 let ty = gterm2lp state ty in
603 let bo = glob_intros tctx bo in
604 under_binder ~loc (EConstr.nameR name) ty None bo state ~k:(fun name t state ->
605 in_elpiast_fix ~loc name rno ty (gterm2lp state bo))
606 | GRec(GFix(rnos,focus_idx),names,tctxs,tys,bos) ->
607 let n_fix = Array.length names in
608 let names = Array.map EConstr.nameR names |> Array.to_list in
609 let tys = Array.map2 glob_intros_prod tctxs tys in
610 let tys = Array.map (gterm2lp state) tys |> Array.to_list in
611 let bos = Array.map2 glob_intros tctxs bos |> Array.to_list in
612 under_binders ~loc names tys (List.init n_fix (fun _ -> None)) bos state ~k:(fun actual_names bos state ->
613 let names_rnos_tys = CList.map3 (fun rno name ty ->
614 (name, (match rno with Some r -> r | None -> nYI "(glob)HOAS non-struct fix/cofix"), ty))
615 (Array.to_list rnos) actual_names tys in
616 let bos = List.map (gterm2lp state) bos in
617 in_elpiast_mfix ~loc names_rnos_tys focus_idx bos)
618 | GRec _ -> nYI "(glob)HOAS non-struct fix/cofix"
619 | GInt i -> in_elpiast_primitive ~loc (Uint63 i)
620 | GFloat f -> in_elpiast_primitive ~loc (Float64 f)
621 | GString s -> in_elpiast_primitive ~loc (Pstring s)
622 | GArray _ -> nYI "HOAS for persistent arrays"
623 in
624 gterm2lp state glob
625
626 let lconstr_eoi = Procq.eoi_entry Procq.Constr.lconstr
627
628 let parse_string f ?loc x =
629 let offset = Option.map (fun l -> l.Loc.bp) loc in
630 let strm = Gramlib.Stream.of_string ?offset x in
631 Procq.Entry.parse f (Procq.Parsable.make ?loc strm)
632
633 let coq_quotation ~language state loc src =
634 let cloc = to_coq_loc loc in
635 let ce = parse_string ~loc:cloc lconstr_eoi src in
636 (* Format.eprintf "quotation: %s in %s\n%!" src (Pp.string_of_ppcmds (Printer.pr_named_context_of (get_glob_env state).env (get_sigma state))); *)
637 let glob = Constrintern.intern_constr (get_glob_env state).env (get_sigma state) ce in
638 gterm2lpast ~language state glob
639
640 let coq = Q.register_named_quotation ~name:"coq" (coq_quotation ~pattern:false) ~descriptor:interp_quotations
641 let () = Rocq_elpi_HOAS.set_coq coq
642
643 let _coqpat = Q.register_named_quotation ~name:"pat" (coq_quotation ~pattern:true) ~descriptor:interp_quotations
644
645 let coq_quotation ~language:_ state loc src = coq_quotation ~language:coq state loc src
646
647 (* Install the quotation *)
648 let () = Q.set_default_quotation (coq_quotation ~pattern:false) ~descriptor:interp_quotations
649
650 let _ = API.Quotation.register_named_quotation ~name:"gref" ~descriptor:interp_quotations
651 (fun ~language state loc src ->
652 let gr = locate_gref src in
653 in_elpiast_gref ~loc gr)
654 ;;
655
656 let gterm2lp ~loc ~base glob ~depth state =
657 let t = gterm2lpast ~pattern:false ~language:coq state glob in
658 let coq_ctx, _ = Option.default (upcast @@ empty_conv_context ~options:(default_options ()) state,[]) (get_ctx state) in
659 let ctx = Names.Id.Map.fold (fun id i m ->
660 API.Ast.Scope.Map.add (API.Ast.Name.from_string @@ Names.Id.to_string id,coq) i m
661 ) coq_ctx.name2db API.Ast.Scope.Map.empty in
662 handle_elpi_compiler_errors ~loc (fun () ->
663 API.RawQuery.term_to_raw_term ~ctx state base ~depth t)
664
665 let runtime_gterm2lp ~loc ~base glob ~depth state =
666 let t = gterm2lpast ~pattern:false ~language:coq state glob in
667 let coq_ctx, _ = Option.default (upcast @@ empty_conv_context ~options:(default_options ()) state,[]) (get_ctx state) in
668 let ctx = Names.Id.Map.fold (fun id i m ->
669 API.Ast.Scope.Map.add (API.Ast.Name.from_string @@ Names.Id.to_string id,coq) i m
670 ) coq_ctx.name2db API.Ast.Scope.Map.empty in
671 handle_elpi_compiler_errors ~loc (fun () ->
672 API.Utils.term_to_raw_term ~ctx state base ~depth t)
673
674 let rec gparams2lp ~loc ~base inp params (kont : depth:int -> S.t -> S.t * _) ~depth state =
675 match params with
676 | [] -> kont ~depth state
677 | (name,_rel,imp,ob,src) :: params ->
678 if ob <> None then Rocq_elpi_utils.nYI "defined parameters in a record/inductive declaration";
679 let state, src = gterm2lp ~loc ~depth ~base src state in
680 let k = nogls (gparams2lp ~loc ~base inp params kont) in
681 let name = EConstr.annotR name in
682 let state, tgt, () = under_ctx name src None ~k ~depth state in
683 let state, imp = in_elpi_imp ~depth state imp in
684 state, inp name ~imp src tgt
685
686 let gindparams2lp ~loc ~base params ~k ~depth s =
687 gparams2lp ~loc ~base in_elpi_inductive_parameter params k ~depth s
688 let garityparams2lp ~loc ~base params ~k ~depth s =
689 gparams2lp ~loc ~base in_elpi_arity_parameter params k ~depth s
690
691 let garity2lp ~loc ~base t ~depth state =
692 let state, t = gterm2lp ~loc t ~depth ~base state in
693 state, in_elpi_arity t
694
695 let rec gfields2lp ~loc ~base fields ~depth state =
696 match fields with
697 | [] -> state, in_elpi_indtdecl_endrecord ()
698 | (f,({ name; is_coercion; is_canonical } as att)) :: fields ->
699 let state, f = gterm2lp ~loc ~base f ~depth state in
700 let state, fields, () = under_ctx (EConstr.annotR name) f None ~k:(nogls (gfields2lp ~loc ~base fields)) ~depth state in
701 in_elpi_indtdecl_field ~depth state att f fields
702
703 let grecord2lp ~loc ~base ~name ~constructorname arity fields ~depth state =
704 let space, record_name = name in
705 let qrecord_name = Id.of_string_soft @@ String.concat "." (space @ [Id.to_string record_name]) in
706 let state, arity = gterm2lp ~loc ~base arity ~depth state in
707 let state, fields = gfields2lp ~loc ~base fields ~depth state in
708 let constructor = match constructorname with
709 | None -> Name.Name (Id.of_string ("Build_" ^ Id.to_string record_name))
710 | Some x -> Name.Name x in
711 state, in_elpi_indtdecl_record (Name.Name qrecord_name) arity constructor fields
712
713
714 let gterm2lpast = gterm2lpast ~language:coq