]> matita.cs.unibo.it Git - helm.git/blob - components/ng_disambiguation/nCicDisambiguate.ml
made executable again
[helm.git] / components / ng_disambiguation / nCicDisambiguate.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id: nCic.ml 9058 2008-10-13 17:42:30Z tassi $ *)
13
14 open Printf
15
16 open DisambiguateTypes
17 open UriManager
18
19 module Ast = CicNotationPt
20 module NRef = NReference 
21
22 let debug_print s = prerr_endline (Lazy.force s);;
23 let debug_print _ = ();;
24
25 let cic_name_of_name = function
26   | Ast.Ident (n, None) ->  n
27   | _ -> assert false
28 ;;
29
30 let rec mk_rels howmany from =
31   match howmany with 
32   | 0 -> []
33   | _ -> (NCic.Rel (howmany + from)) :: (mk_rels (howmany-1) from)
34 ;;
35
36 let refine_term 
37  metasenv subst context uri ~rdb ~use_coercions term expty _ ~localization_tbl=
38   assert (uri=None);
39   debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" 
40     (NCicPp.ppterm ~metasenv ~subst ~context term)));
41   try
42     let localise t = 
43       try NCicUntrusted.NCicHash.find localization_tbl t
44       with Not_found -> 
45         prerr_endline ("NOT LOCALISED" ^ NCicPp.ppterm ~metasenv ~subst ~context t);
46         (*assert false*) HExtlib.dummy_floc
47     in
48     let metasenv, subst, term, _ = 
49       NCicRefiner.typeof 
50         (rdb#set_coerc_db 
51           (if use_coercions then rdb#coerc_db else NCicCoercion.empty_db))
52         metasenv subst context term expty ~localise 
53     in
54      Disambiguate.Ok (term, metasenv, subst, ())
55   with
56   | NCicRefiner.Uncertain loc_msg ->
57       debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^ 
58         NCicPp.ppterm ~metasenv ~subst ~context term)) ;
59       Disambiguate.Uncertain loc_msg
60   | NCicRefiner.RefineFailure loc_msg ->
61       debug_print (lazy (sprintf "PRUNED:\nterm%s\nmessage:%s"
62         (NCicPp.ppterm ~metasenv ~subst ~context term) (snd(Lazy.force loc_msg))));
63       Disambiguate.Ko loc_msg
64 ;;
65
66 let refine_obj 
67   ~rdb metasenv subst context _uri 
68   ~use_coercions obj _ _ugraph ~localization_tbl 
69 =
70   assert (metasenv=[]);
71   assert (subst=[]);
72   let localise t = 
73     try NCicUntrusted.NCicHash.find localization_tbl t
74     with Not_found -> 
75       prerr_endline (NCicPp.ppterm ~metasenv ~subst ~context t);
76       (*assert false*)HExtlib.dummy_floc
77   in
78   try
79     let obj =
80       NCicRefiner.typeof_obj
81         (rdb#set_coerc_db
82            (if use_coercions then rdb#coerc_db 
83             else NCicCoercion.empty_db))
84         obj ~localise 
85     in
86       Disambiguate.Ok (obj, [], [], ())
87   with
88   | NCicRefiner.Uncertain loc_msg ->
89       debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^ 
90         NCicPp.ppobj obj)) ;
91       Disambiguate.Uncertain loc_msg
92   | NCicRefiner.RefineFailure loc_msg ->
93       debug_print (lazy (sprintf "PRUNED:\nobj: %s\nmessage: %s"
94         (NCicPp.ppobj obj) (snd(Lazy.force loc_msg))));
95       Disambiguate.Ko loc_msg
96 ;;
97   
98
99   (* TODO move it to Cic *)
100 let find_in_context name context =
101   let rec aux acc = function
102     | [] -> raise Not_found
103     | hd :: _ when hd = name -> acc
104     | _ :: tl ->  aux (acc + 1) tl
105   in
106   aux 1 context
107
108 let interpretate_term_and_interpretate_term_option 
109   ?(create_dummy_ids=false) 
110     ~obj_context ~mk_choice ~env ~uri ~is_path ~localization_tbl 
111 =
112   (* create_dummy_ids shouldbe used only for interpretating patterns *)
113   assert (uri = None);
114
115   let rec aux ~localize loc context = function
116     | CicNotationPt.AttributedTerm (`Loc loc, term) ->
117         let res = aux ~localize loc context term in
118         if localize then 
119          NCicUntrusted.NCicHash.add localization_tbl res loc;
120        res
121     | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
122     | CicNotationPt.Appl (CicNotationPt.Appl inner :: args) ->
123         aux ~localize loc context (CicNotationPt.Appl (inner @ args))
124     | CicNotationPt.Appl 
125         (CicNotationPt.AttributedTerm (att,(CicNotationPt.Appl inner))::args)->
126         aux ~localize loc context 
127           (CicNotationPt.AttributedTerm (att,CicNotationPt.Appl (inner @ args)))
128     | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
129         let cic_args = List.map (aux ~localize loc context) args in
130         Disambiguate.resolve ~mk_choice ~env (Symbol (symb, i)) (`Args cic_args)
131     | CicNotationPt.Appl terms ->
132        NCic.Appl (List.map (aux ~localize loc context) terms)
133     | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
134         let cic_type = aux_option ~localize loc context `Type typ in
135         let cic_name = cic_name_of_name var  in
136         let cic_body = aux ~localize loc (cic_name :: context) body in
137         (match binder_kind with
138         | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
139         | `Pi
140         | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
141         | `Exists ->
142             Disambiguate.resolve ~env ~mk_choice (Symbol ("exists", 0))
143               (`Args [ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ]))
144     | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
145         let cic_term = aux ~localize loc context term in
146         let cic_outtype = aux_option ~localize loc context `Term outtype in
147         let do_branch ((_, _, args), term) =
148          let rec do_branch' context = function
149            | [] -> aux ~localize loc context term
150            | (name, typ) :: tl ->
151                let cic_name = cic_name_of_name name in
152                let cic_body = do_branch' (cic_name :: context) tl in
153                let typ =
154                  match typ with
155                  | None -> NCic.Implicit `Type
156                  | Some typ -> aux ~localize loc context typ
157                in
158                NCic.Lambda (cic_name, typ, cic_body)
159          in
160           do_branch' context args
161         in
162         if create_dummy_ids then
163          let branches =
164           List.map
165            (function
166                Ast.Wildcard,term -> ("wildcard",None,[]), term
167              | Ast.Pattern _,_ ->
168                 raise (DisambiguateTypes.Invalid_choice 
169                  (lazy (loc, "Syntax error: the left hand side of a "^
170                    "branch pattern must be \"_\"")))
171            ) branches
172          in
173          (*
174           NCic.MutCase (ref, cic_outtype, cic_term,
175             (List.map do_branch branches))
176           *) ignore branches; assert false (* patterns not implemented yet *)
177         else
178          let indtype_ref =
179           match indty_ident with
180           | Some (indty_ident, _) ->
181              (match Disambiguate.resolve ~env ~mk_choice 
182                 (Id indty_ident) (`Args []) with
183               | NCic.Const (NReference.Ref (_,NReference.Ind _) as r) -> r
184               | NCic.Implicit _ ->
185                  raise (Disambiguate.Try_again 
186                   (lazy "The type of the term to be matched is still unknown"))
187               | t ->
188                 raise (DisambiguateTypes.Invalid_choice 
189                   (lazy (loc,"The type of the term to be matched "^
190                           "is not (co)inductive: " ^ NCicPp.ppterm 
191                           ~metasenv:[] ~subst:[] ~context:[] t))))
192           | None ->
193               let rec fst_constructor =
194                 function
195                    (Ast.Pattern (head, _, _), _) :: _ -> head
196                  | (Ast.Wildcard, _) :: tl -> fst_constructor tl
197                  | [] -> raise (Invalid_choice (lazy (loc,"The type "^
198                      "of the term to be matched cannot be determined "^
199                      "because it is an inductive type without constructors "^
200                      "or because all patterns use wildcards")))
201               in
202 (*
203               DisambiguateTypes.Environment.iter
204                   (fun k v ->
205                       prerr_endline
206                         (DisambiguateTypes.string_of_domain_item k ^ " => " ^
207                         description_of_alias v)) env; 
208 *)
209               (match Disambiguate.resolve ~env ~mk_choice
210                 (Id (fst_constructor branches)) (`Args []) with
211               | NCic.Const (NReference.Ref (_,NReference.Con _) as r) -> 
212                    let b,_,_,_,_ = NCicEnvironment.get_checked_indtys r in
213                    NReference.mk_indty b r
214               | NCic.Implicit _ ->
215                  raise (Disambiguate.Try_again 
216                   (lazy "The type of the term to be matched is still unknown"))
217               | t ->
218                 raise (DisambiguateTypes.Invalid_choice 
219                   (lazy (loc, 
220                   "The type of the term to be matched is not (co)inductive: " 
221                   ^ NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t))))
222          in
223          let _,leftsno,itl,_,indtyp_no =
224           NCicEnvironment.get_checked_indtys indtype_ref in
225          let _,_,_,cl =
226           try
227            List.nth itl indtyp_no
228           with _ -> assert false in
229          let rec count_prod t =
230                  match NCicReduction.whd ~subst:[] [] t with
231                NCic.Prod (_, _, t) -> 1 + (count_prod t)
232              | _ -> 0 
233          in 
234          let rec sort branches cl =
235           match cl with
236              [] ->
237               let rec analyze unused unrecognized useless =
238                function
239                   [] ->
240                    if unrecognized != [] then
241                     raise (DisambiguateTypes.Invalid_choice
242                      (lazy
243                        (loc,"Unrecognized constructors: " ^
244                         String.concat " " unrecognized)))
245                    else if useless > 0 then
246                     raise (DisambiguateTypes.Invalid_choice
247                      (lazy
248                        (loc,"The last " ^ string_of_int useless ^
249                         "case" ^ if useless > 1 then "s are" else " is" ^
250                         " unused")))
251                    else
252                     []
253                 | (Ast.Wildcard,_)::tl when not unused ->
254                     analyze true unrecognized useless tl
255                 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
256                     analyze unused (head::unrecognized) useless tl
257                 | _::tl -> analyze unused unrecognized (useless + 1) tl
258               in
259                analyze false [] 0 branches
260            | (_,name,ty)::cltl ->
261               let rec find_and_remove =
262                function
263                   [] ->
264                    raise
265                     (DisambiguateTypes.Invalid_choice
266                      (lazy (loc, "Missing case: " ^ name)))
267                 | ((Ast.Wildcard, _) as branch :: _) as branches ->
268                     branch, branches
269                 | (Ast.Pattern (name',_,_),_) as branch :: tl
270                    when name = name' ->
271                     branch,tl
272                 | branch::tl ->
273                    let found,rest = find_and_remove tl in
274                     found, branch::rest
275               in
276                let branch,tl = find_and_remove branches in
277                match branch with
278                   Ast.Pattern (name,y,args),term ->
279                    if List.length args = count_prod ty - leftsno then
280                     ((name,y,args),term)::sort tl cltl
281                    else
282                     raise
283                      (DisambiguateTypes.Invalid_choice
284                       (lazy (loc,"Wrong number of arguments for " ^ name)))
285                 | Ast.Wildcard,term ->
286                    let rec mk_lambdas =
287                     function
288                        0 -> term
289                      | n ->
290                         CicNotationPt.Binder
291                          (`Lambda, (CicNotationPt.Ident ("_", None), None),
292                            mk_lambdas (n - 1))
293                    in
294                     (("wildcard",None,[]),
295                      mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
296          in
297           let branches = sort branches cl in
298            NCic.Match (indtype_ref, cic_outtype, cic_term,
299             (List.map do_branch branches))
300     | CicNotationPt.Cast (t1, t2) ->
301         let cic_t1 = aux ~localize loc context t1 in
302         let cic_t2 = aux ~localize loc context t2 in
303         NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
304     | CicNotationPt.LetIn ((name, typ), def, body) ->
305         let cic_def = aux ~localize loc context def in
306         let cic_name = cic_name_of_name name in
307         let cic_typ =
308           match typ with
309           | None -> NCic.Implicit `Type
310           | Some t -> aux ~localize loc context t
311         in
312         let cic_body = aux ~localize loc (cic_name :: context) body in
313         NCic.LetIn (cic_name, cic_typ, cic_def, cic_body)
314     | CicNotationPt.LetRec (_kind, _defs, _body) -> NCic.Implicit `Term
315     | CicNotationPt.Ident _
316     | CicNotationPt.Uri _
317     | CicNotationPt.NRef _ when is_path -> raise Disambiguate.PathNotWellFormed
318     | CicNotationPt.Ident (name, subst) ->
319        assert (subst = None);
320        (try
321              NCic.Rel (find_in_context name context)
322        with Not_found -> 
323          try NCic.Const (List.assoc name obj_context)
324          with Not_found ->
325            Disambiguate.resolve ~env ~mk_choice (Id name) (`Args []))
326     | CicNotationPt.Uri (uri, subst) ->
327        assert (subst = None);
328        (try
329          NCic.Const (OCic2NCic.reference_of_oxuri(UriManager.uri_of_string uri))
330         with NRef.IllFormedReference _ ->
331          CicNotationPt.fail loc "Ill formed reference")
332     | CicNotationPt.NRef nref -> NCic.Const nref
333     | CicNotationPt.Implicit `Vector -> NCic.Implicit `Vector
334     | CicNotationPt.Implicit `JustOne -> NCic.Implicit `Term
335     | CicNotationPt.UserInput -> NCic.Implicit `Hole
336     | CicNotationPt.Num (num, i) -> 
337         Disambiguate.resolve ~env ~mk_choice (Num i) (`Num_arg num)
338     | CicNotationPt.Meta (index, subst) ->
339         let cic_subst =
340          List.map
341           (function None -> assert false| Some t -> aux ~localize loc context t)
342           subst
343         in
344          NCic.Meta (index, (0, NCic.Ctx cic_subst))
345     | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
346     | CicNotationPt.Sort `Set -> NCic.Sort (NCic.Type
347        [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
348     | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
349        [false,NUri.uri_of_string "cic:/matita/pts/Type0.univ"])
350     | CicNotationPt.Sort (`NType s) -> NCic.Sort (NCic.Type
351        [false,NUri.uri_of_string ("cic:/matita/pts/Type" ^ s ^ ".univ")])
352     | CicNotationPt.Sort (`NCProp s) -> NCic.Sort (NCic.Type
353        [false,NUri.uri_of_string ("cic:/matita/pts/CProp" ^ s ^ ".univ")])
354     | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
355        [false,NUri.uri_of_string "cic:/matita/pts/CProp0.univ"])
356     | CicNotationPt.Symbol (symbol, instance) ->
357         Disambiguate.resolve ~env ~mk_choice 
358          (Symbol (symbol, instance)) (`Args [])
359     | CicNotationPt.Variable _
360     | CicNotationPt.Magic _
361     | CicNotationPt.Layout _
362     | CicNotationPt.Literal _ -> assert false (* god bless Bologna *)
363   and aux_option ~localize loc context annotation = function
364     | None -> NCic.Implicit annotation
365     | Some (CicNotationPt.AttributedTerm (`Loc loc, term)) ->
366         let res = aux_option ~localize loc context annotation (Some term) in
367         if localize then 
368           NCicUntrusted.NCicHash.add localization_tbl res loc;
369         res
370     | Some (CicNotationPt.AttributedTerm (_, term)) ->
371         aux_option ~localize loc context annotation (Some term)
372     | Some CicNotationPt.Implicit `JustOne -> NCic.Implicit annotation
373     | Some CicNotationPt.Implicit `Vector -> NCic.Implicit `Vector
374     | Some term -> aux ~localize loc context term
375   in
376    (fun ~context -> aux ~localize:true HExtlib.dummy_floc context),
377    (fun ~context -> aux_option ~localize:true HExtlib.dummy_floc context)
378 ;;
379
380 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
381      ~obj_context ~localization_tbl ~mk_choice
382 =
383   let context = List.map fst context in
384   fst 
385     (interpretate_term_and_interpretate_term_option 
386       ~obj_context ~mk_choice ~create_dummy_ids ~env ~uri ~is_path ~localization_tbl)
387     ~context ast
388 ;;
389
390 let interpretate_term_option 
391   ?(create_dummy_ids=false) ~context ~env ~uri ~is_path 
392   ~localization_tbl ~mk_choice ~obj_context
393 =
394   let context = List.map fst context in
395   snd 
396     (interpretate_term_and_interpretate_term_option 
397       ~obj_context ~mk_choice ~create_dummy_ids ~env ~uri ~is_path ~localization_tbl)
398     ~context 
399 ;;
400
401 let disambiguate_path path =
402   let localization_tbl = NCicUntrusted.NCicHash.create 23 in
403   fst
404     (interpretate_term_and_interpretate_term_option 
405     ~obj_context:[] ~mk_choice:(fun _ -> assert false)
406     ~create_dummy_ids:true ~env:DisambiguateTypes.Environment.empty
407     ~uri:None ~is_path:true ~localization_tbl) ~context:[] path
408 ;;
409
410 let new_flavour_of_flavour = function 
411   | `Definition -> `Definition
412   | `MutualDefinition -> `Definition 
413   | `Fact -> `Fact
414   | `Lemma -> `Lemma
415   | `Remark -> `Corollary
416   | `Theorem -> `Theorem
417   | `Variant -> `Corollary 
418   | `Axiom -> `Fact
419 ;;
420
421 let ncic_name_of_ident = function
422   | Ast.Ident (name, None) -> name
423   | _ -> assert false
424 ;;
425
426 let interpretate_obj 
427 (*      ?(create_dummy_ids=false)  *)
428      ~context ~env ~uri ~is_path obj ~localization_tbl ~mk_choice 
429 =
430  assert (context = []);
431  assert (is_path = false);
432  let interpretate_term ~obj_context =
433   interpretate_term ~mk_choice ~localization_tbl ~obj_context in
434  let interpretate_term_option ~obj_context =
435    interpretate_term_option ~mk_choice ~localization_tbl ~obj_context in
436  let uri = match uri with | None -> assert false | Some u -> u in
437  match obj with
438  | CicNotationPt.Theorem (flavour, name, ty, bo) ->
439      let ty' = 
440        interpretate_term 
441          ~obj_context:[] ~context:[] ~env ~uri:None ~is_path:false ty 
442      in
443      let height = (* XXX calculate *) 0 in
444      uri, height, [], [], 
445      (match bo,flavour with
446       | None,`Axiom -> 
447           let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
448           NCic.Constant ([],name,None,ty',attrs)
449       | Some _,`Axiom -> assert false
450       | None,_ ->
451           let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
452           NCic.Constant ([],name,Some (NCic.Implicit `Term),ty',attrs)
453       | Some bo,_ ->
454         (match bo with
455          | CicNotationPt.LetRec (kind, defs, _) ->
456              let inductive = kind = `Inductive in
457              let _,obj_context =
458                List.fold_left
459                  (fun (i,acc) (_,(name,_),_,k) -> 
460                   (i+1, 
461                     (ncic_name_of_ident name, NReference.reference_of_spec uri 
462                      (if inductive then NReference.Fix (i,k,0)
463                       else NReference.CoFix i)) :: acc))
464                  (0,[]) defs
465              in
466              let inductiveFuns =
467                List.map
468                  (fun (params, (name, typ), body, decr_idx) ->
469                    let add_binders kind t =
470                     List.fold_right
471                      (fun var t -> 
472                         CicNotationPt.Binder (kind, var, t)) params t
473                    in
474                    let cic_body =
475                      interpretate_term 
476                        ~obj_context ~context ~env ~uri:None ~is_path:false
477                        (add_binders `Lambda body) 
478                    in
479                    let cic_type =
480                      interpretate_term_option 
481                        ~obj_context:[]
482                        ~context ~env ~uri:None ~is_path:false `Type
483                        (HExtlib.map_option (add_binders `Pi) typ)
484                    in
485                    ([],ncic_name_of_ident name, decr_idx, cic_type, cic_body))
486                  defs
487              in
488              let attrs = `Provided, new_flavour_of_flavour flavour in
489              NCic.Fixpoint (inductive,inductiveFuns,attrs)
490          | bo -> 
491              let bo = 
492                interpretate_term 
493                 ~obj_context:[] ~context:[] ~env ~uri:None ~is_path:false bo
494              in
495              let attrs = `Provided, new_flavour_of_flavour flavour, `Regular in
496              NCic.Constant ([],name,Some bo,ty',attrs)))
497  | CicNotationPt.Inductive (params,tyl) ->
498     let context,params =
499      let context,res =
500       List.fold_left
501        (fun (context,res) (name,t) ->
502          let t =
503           match t with
504              None -> CicNotationPt.Implicit `JustOne
505            | Some t -> t in
506          let name = cic_name_of_name name in
507          let t =
508           interpretate_term ~obj_context:[] ~context ~env ~uri:None
509            ~is_path:false t
510          in
511           (name,NCic.Decl t)::context,(name,t)::res
512        ) ([],[]) params
513      in
514       context,List.rev res in
515     let add_params =
516      List.fold_right (fun (name,ty) t -> NCic.Prod (name,ty,t)) params in
517     let leftno = List.length params in
518     let _,inductive,_,_ = try List.hd tyl with Failure _ -> assert false in
519     let obj_context =
520      snd (
521       List.fold_left
522        (fun (i,res) (name,_,_,_) ->
523          let nref =
524           NReference.reference_of_spec uri (NReference.Ind (inductive,i,leftno))
525          in
526           i+1,(name,nref)::res)
527        (0,[]) tyl) in
528     let tyl =
529      List.map
530       (fun (name,_,ty,cl) ->
531         let ty' =
532          add_params
533          (interpretate_term ~obj_context:[] ~context ~env ~uri:None
534            ~is_path:false ty) in
535         let cl' =
536          List.map
537           (fun (name,ty) ->
538             let ty' =
539              add_params
540               (interpretate_term ~obj_context ~context ~env ~uri:None
541                 ~is_path:false ty) in
542             let relevance = [] in
543              relevance,name,ty'
544           ) cl in
545         let relevance = [] in
546          relevance,name,ty',cl'
547       ) tyl
548     in
549      let height = (* XXX calculate *) 0 in
550      let attrs = `Provided, `Regular in
551      uri, height, [], [], 
552      NCic.Inductive (inductive,leftno,tyl,attrs)
553  | CicNotationPt.Record (params,name,ty,fields) ->
554     let context,params =
555      let context,res =
556       List.fold_left
557        (fun (context,res) (name,t) ->
558          let t =
559           match t with
560              None -> CicNotationPt.Implicit `JustOne
561            | Some t -> t in
562          let name = cic_name_of_name name in
563          let t =
564           interpretate_term ~obj_context:[] ~context ~env ~uri:None
565            ~is_path:false t
566          in
567           (name,NCic.Decl t)::context,(name,t)::res
568        ) ([],[]) params
569      in
570       context,List.rev res in
571     let add_params =
572      List.fold_right (fun (name,ty) t -> NCic.Prod (name,ty,t)) params in
573     let leftno = List.length params in
574     let ty' =
575      add_params
576       (interpretate_term ~obj_context:[] ~context ~env ~uri:None
577         ~is_path:false ty) in
578     let nref =
579      NReference.reference_of_spec uri (NReference.Ind (true,0,leftno)) in
580     let obj_context = [name,nref] in
581     let fields' =
582      snd (
583       List.fold_left
584        (fun (context,res) (name,ty,_coercion,_arity) ->
585          let ty =
586           interpretate_term ~obj_context ~context ~env ~uri:None
587            ~is_path:false ty in
588          let context' = (name,NCic.Decl ty)::context in
589           context',(name,ty)::res
590        ) (context,[]) fields) in
591     let concl =
592      let mutind = NCic.Const nref in
593      if params = [] then mutind
594      else
595       NCic.Appl
596        (mutind::mk_rels (List.length params) (List.length fields)) in
597     let con =
598      List.fold_left (fun t (name,ty) -> NCic.Prod (name,ty,t)) concl fields' in
599     let con' = add_params con in
600     let relevance = [] in
601     let tyl = [relevance,name,ty',[relevance,"mk_" ^ name,con']] in
602     let field_names = List.map (fun (x,_,y,z) -> x,y,z) fields in
603      let height = (* XXX calculate *) 0 in
604      let attrs = `Provided, `Record field_names in
605      uri, height, [], [], 
606      NCic.Inductive (true,leftno,tyl,attrs)
607 ;;
608
609 let disambiguate_term ~context ~metasenv ~subst ~expty
610    ~mk_implicit ~description_of_alias ~mk_choice
611    ~aliases ~universe ~rdb ~lookup_in_library 
612    (text,prefix_len,term) 
613  =
614   let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
615    let res,b =
616     MultiPassDisambiguator.disambiguate_thing
617      ~freshen_thing:CicNotationUtil.freshen_term
618      ~context ~metasenv ~initial_ugraph:() ~aliases
619      ~mk_implicit ~description_of_alias
620      ~string_context_of_context:(List.map (fun (x,_) -> Some x))
621      ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
622      ~passes:(MultiPassDisambiguator.passes ())
623      ~lookup_in_library ~domain_of_thing:Disambiguate.domain_of_term
624      ~interpretate_thing:(interpretate_term ~obj_context:[] ~mk_choice (?create_dummy_ids:None))
625      ~refine_thing:(refine_term ~rdb) (text,prefix_len,term)
626      ~mk_localization_tbl ~expty ~subst
627    in
628     List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
629 ;;
630
631 let disambiguate_obj 
632    ~mk_implicit ~description_of_alias ~mk_choice
633    ~aliases ~universe ~rdb ~lookup_in_library ~uri
634    (text,prefix_len,obj) 
635  =
636   let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
637    let res,b =
638     MultiPassDisambiguator.disambiguate_thing
639      ~freshen_thing:CicNotationUtil.freshen_obj
640      ~context:[] ~metasenv:[] ~subst:[] ~initial_ugraph:() ~aliases
641      ~mk_implicit ~description_of_alias
642      ~string_context_of_context:(List.map (fun (x,_) -> Some x))
643      ~universe 
644      ~uri:(Some uri)
645      ~pp_thing:(CicNotationPp.pp_obj CicNotationPp.pp_term)
646      ~passes:(MultiPassDisambiguator.passes ())
647      ~lookup_in_library ~domain_of_thing:Disambiguate.domain_of_obj
648      ~interpretate_thing:(interpretate_obj ~mk_choice)
649      ~refine_thing:(refine_obj ~rdb) 
650      (text,prefix_len,obj)
651      ~mk_localization_tbl ~expty:None
652    in
653     List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
654 ;;
655 (*
656 let _ = 
657 let mk_type n = 
658   if n = 0 then
659      [false, NUri.uri_of_string ("cic:/matita/pts/Type.univ")]
660   else
661      [false, NUri.uri_of_string ("cic:/matita/pts/Type"^string_of_int n^".univ")]
662 in
663 let mk_cprop n = 
664   if n = 0 then 
665     [false, NUri.uri_of_string ("cic:/matita/pts/CProp.univ")]
666   else
667     [false, NUri.uri_of_string ("cic:/matita/pts/CProp"^string_of_int n^".univ")]
668 in
669          NCicEnvironment.add_constraint true (mk_type 0) (mk_type 1);
670          NCicEnvironment.add_constraint true (mk_cprop 0) (mk_cprop 1);
671          NCicEnvironment.add_constraint true (mk_cprop 0) (mk_type 1);
672          NCicEnvironment.add_constraint true (mk_type 0) (mk_cprop 1);
673          NCicEnvironment.add_constraint false (mk_cprop 0) (mk_type 0);
674          NCicEnvironment.add_constraint false (mk_type 0) (mk_cprop 0);
675
676          NCicEnvironment.add_constraint true (mk_type 1) (mk_type 2);
677          NCicEnvironment.add_constraint true (mk_cprop 1) (mk_cprop 2);
678          NCicEnvironment.add_constraint true (mk_cprop 1) (mk_type 2);
679          NCicEnvironment.add_constraint true (mk_type 1) (mk_cprop 2);
680          NCicEnvironment.add_constraint false (mk_cprop 1) (mk_type 1);
681          NCicEnvironment.add_constraint false (mk_type 1) (mk_cprop 1);
682
683          NCicEnvironment.add_constraint true (mk_type 2) (mk_type 3);
684          NCicEnvironment.add_constraint true (mk_cprop 2) (mk_cprop 3);
685          NCicEnvironment.add_constraint true (mk_cprop 2) (mk_type 3);
686          NCicEnvironment.add_constraint true (mk_type 2) (mk_cprop 3);
687          NCicEnvironment.add_constraint false (mk_cprop 2) (mk_type 2);
688          NCicEnvironment.add_constraint false (mk_type 2) (mk_cprop 2);
689
690          NCicEnvironment.add_constraint false (mk_cprop 3) (mk_type 3);
691          NCicEnvironment.add_constraint false (mk_type 3) (mk_cprop 3);
692
693 ;;
694 *)
695