]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_disambiguation/nDisambiguate.ml
f4213bc3086b0c83603d1389b92ffe455c70eb44
[helm.git] / helm / software / components / ng_disambiguation / nDisambiguate.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 _ = ();;
23
24 let cic_name_of_name = function
25   | Ast.Ident (n, None) ->  n
26   | _ -> assert false
27 ;;
28
29 let refine_term metasenv subst context uri term _ ~localization_tbl =
30   assert (uri=None);
31   debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" 
32     (NCicPp.ppterm ~metasenv ~subst ~context term)));
33   try
34     let localise t = 
35       try NCicUntrusted.NCicHash.find localization_tbl t
36       with Not_found -> assert false
37     in
38     let metasenv, subst, term, _ = 
39       NCicRefiner.typeof metasenv subst context term None ~localise 
40     in
41      Disambiguate.Ok (term, metasenv, subst, ())
42   with
43   | NCicRefiner.Uncertain loc_msg ->
44       debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^ 
45         NCicPp.ppterm ~metasenv ~subst ~context term)) ;
46       Disambiguate.Uncertain loc_msg
47   | NCicRefiner.RefineFailure loc_msg ->
48       debug_print (lazy (sprintf "PRUNED:\nterm%s\nmessage:%s"
49         (NCicPp.ppterm ~metasenv ~subst ~context term) (snd(Lazy.force loc_msg))));
50       Disambiguate.Ko loc_msg
51 ;;
52
53 let resolve (env: NCic.term codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
54         ignore (env,item,num,args);
55   try
56     snd (Environment.find item env) env num args
57   with Not_found -> 
58     failwith ("Domain item not found: " ^ 
59       (DisambiguateTypes.string_of_domain_item item))
60
61   (* TODO move it to Cic *)
62 let find_in_context name context =
63   let rec aux acc = function
64     | [] -> raise Not_found
65     | hd :: _ when hd = name -> acc
66     | _ :: tl ->  aux (acc + 1) tl
67   in
68   aux 1 context
69
70 let interpretate_term 
71   ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast ~localization_tbl
72 =
73   (* create_dummy_ids shouldbe used only for interpretating patterns *)
74   assert (uri = None);
75
76   let rec aux ~localize loc context = function
77     | CicNotationPt.AttributedTerm (`Loc loc, term) ->
78         let res = aux ~localize loc context term in
79          if localize then NCicUntrusted.NCicHash.add localization_tbl res loc;
80          res
81     | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
82     | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
83         let cic_args = List.map (aux ~localize loc context) args in
84         resolve env (Symbol (symb, i)) ~args:cic_args ()
85     | CicNotationPt.Appl terms ->
86        NCic.Appl (List.map (aux ~localize loc context) terms)
87     | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
88         let cic_type = aux_option ~localize loc context `Type typ in
89         let cic_name = cic_name_of_name var  in
90         let cic_body = aux ~localize loc (cic_name :: context) body in
91         (match binder_kind with
92         | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
93         | `Pi
94         | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
95         | `Exists ->
96             resolve env (Symbol ("exists", 0))
97               ~args:[ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ] ())
98     | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
99         let cic_term = aux ~localize loc context term in
100         let cic_outtype = aux_option ~localize loc context `Term outtype in
101         let do_branch ((_, _, args), term) =
102          let rec do_branch' context = function
103            | [] -> aux ~localize loc context term
104            | (name, typ) :: tl ->
105                let cic_name = cic_name_of_name name in
106                let cic_body = do_branch' (cic_name :: context) tl in
107                let typ =
108                  match typ with
109                  | None -> NCic.Implicit `Type
110                  | Some typ -> aux ~localize loc context typ
111                in
112                NCic.Lambda (cic_name, typ, cic_body)
113          in
114           do_branch' context args
115         in
116         if create_dummy_ids then
117          let branches =
118           List.map
119            (function
120                Ast.Wildcard,term -> ("wildcard",None,[]), term
121              | Ast.Pattern _,_ ->
122                 raise (DisambiguateTypes.Invalid_choice 
123                  (lazy (loc, "Syntax error: the left hand side of a "^
124                    "branch pattern must be \"_\"")))
125            ) branches
126          in
127          (*
128           NCic.MutCase (ref, cic_outtype, cic_term,
129             (List.map do_branch branches))
130           *) ignore branches; assert false (* patterns not implemented yet *)
131         else
132          let indtype_ref =
133           match indty_ident with
134           | Some (indty_ident, _) ->
135              (match resolve env (Id indty_ident) () with
136               | NCic.Const r -> r
137               | NCic.Implicit _ ->
138                  raise (Disambiguate.Try_again 
139                   (lazy "The type of the term to be matched is still unknown"))
140               | _ ->
141                 raise (DisambiguateTypes.Invalid_choice 
142                   (lazy (loc,"The type of the term to be matched "^
143                           "is not (co)inductive!"))))
144           | None ->
145               let rec fst_constructor =
146                 function
147                    (Ast.Pattern (head, _, _), _) :: _ -> head
148                  | (Ast.Wildcard, _) :: tl -> fst_constructor tl
149                  | [] -> raise (Invalid_choice (lazy (loc,"The type "^
150                      "of the term to be matched cannot be determined "^
151                      "because it is an inductive type without constructors "^
152                      "or because all patterns use wildcards")))
153               in
154               (match resolve env (Id (fst_constructor branches)) () with
155               | NCic.Const r -> r
156               | NCic.Implicit _ ->
157                  raise (Disambiguate.Try_again 
158                   (lazy "The type of the term to be matched is still unknown"))
159               | _ ->
160                 raise (DisambiguateTypes.Invalid_choice 
161                   (lazy (loc, 
162                   "The type of the term to be matched is not (co)inductive!"))))
163          in
164          let _,leftsno,itl,_,indtyp_no =
165           NCicEnvironment.get_checked_indtys indtype_ref in
166          let _,_,_,cl =
167           try
168            List.nth itl indtyp_no
169           with _ -> assert false in
170          let rec count_prod t =
171            match NCicReduction.whd [] t with
172                NCic.Prod (_, _, t) -> 1 + (count_prod t)
173              | _ -> 0 
174          in 
175          let rec sort branches cl =
176           match cl with
177              [] ->
178               let rec analyze unused unrecognized useless =
179                function
180                   [] ->
181                    if unrecognized != [] then
182                     raise (DisambiguateTypes.Invalid_choice
183                      (lazy
184                        (loc,"Unrecognized constructors: " ^
185                         String.concat " " unrecognized)))
186                    else if useless > 0 then
187                     raise (DisambiguateTypes.Invalid_choice
188                      (lazy
189                        (loc,"The last " ^ string_of_int useless ^
190                         "case" ^ if useless > 1 then "s are" else " is" ^
191                         " unused")))
192                    else
193                     []
194                 | (Ast.Wildcard,_)::tl when not unused ->
195                     analyze true unrecognized useless tl
196                 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
197                     analyze unused (head::unrecognized) useless tl
198                 | _::tl -> analyze unused unrecognized (useless + 1) tl
199               in
200                analyze false [] 0 branches
201            | (_,name,ty)::cltl ->
202               let rec find_and_remove =
203                function
204                   [] ->
205                    raise
206                     (DisambiguateTypes.Invalid_choice
207                      (lazy (loc, "Missing case: " ^ name)))
208                 | ((Ast.Wildcard, _) as branch :: _) as branches ->
209                     branch, branches
210                 | (Ast.Pattern (name',_,_),_) as branch :: tl
211                    when name = name' ->
212                     branch,tl
213                 | branch::tl ->
214                    let found,rest = find_and_remove tl in
215                     found, branch::rest
216               in
217                let branch,tl = find_and_remove branches in
218                match branch with
219                   Ast.Pattern (name,y,args),term ->
220                    if List.length args = count_prod ty - leftsno then
221                     ((name,y,args),term)::sort tl cltl
222                    else
223                     raise
224                      (DisambiguateTypes.Invalid_choice
225                       (lazy (loc,"Wrong number of arguments for " ^ name)))
226                 | Ast.Wildcard,term ->
227                    let rec mk_lambdas =
228                     function
229                        0 -> term
230                      | n ->
231                         CicNotationPt.Binder
232                          (`Lambda, (CicNotationPt.Ident ("_", None), None),
233                            mk_lambdas (n - 1))
234                    in
235                     (("wildcard",None,[]),
236                      mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
237          in
238           let branches = sort branches cl in
239            NCic.Match (indtype_ref, cic_outtype, cic_term,
240             (List.map do_branch branches))
241     | CicNotationPt.Cast (t1, t2) ->
242         let cic_t1 = aux ~localize loc context t1 in
243         let cic_t2 = aux ~localize loc context t2 in
244         NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
245     | CicNotationPt.LetIn ((name, typ), def, body) ->
246         let cic_def = aux ~localize loc context def in
247         let cic_name = cic_name_of_name name in
248         let cic_typ =
249           match typ with
250           | None -> NCic.Implicit `Type
251           | Some t -> aux ~localize loc context t
252         in
253         let cic_body = aux ~localize loc (cic_name :: context) body in
254         NCic.LetIn (cic_name, cic_def, cic_typ, cic_body)
255     | CicNotationPt.LetRec (_kind, _defs, _body) ->
256        assert false (*
257         let context' =
258           List.fold_left
259             (fun acc (_, (name, _), _, _) ->
260               cic_name_of_name name :: acc)
261             context defs
262         in
263         let cic_body =
264          let unlocalized_body = aux ~localize:false loc context' body in
265          match unlocalized_body with
266             NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
267           | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
268              (try
269                let l' =
270                 List.map
271                  (function t ->
272                    let t',subst,metasenv =
273                     CicMetaSubst.delift_rels [] [] (List.length defs) t
274                    in
275                     assert (subst=[]);
276                     assert (metasenv=[]);
277                     t') l
278                in
279                 (* We can avoid the LetIn. But maybe we need to recompute l'
280                    so that it is localized *)
281                 if localize then
282                  match body with
283                     CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
284                      (* since we avoid the letin, the context has no
285                       * recfuns in it *)
286                      let l' = List.map (aux ~localize loc context) l in
287                       `AvoidLetIn (n,l')
288                   | _ -> assert false
289                 else
290                  `AvoidLetIn (n,l')
291               with
292                CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
293                 if localize then
294                  `AddLetIn (aux ~localize loc context' body)
295                 else
296                  `AddLetIn unlocalized_body)
297           | _ ->
298              if localize then
299               `AddLetIn (aux ~localize loc context' body)
300              else
301               `AddLetIn unlocalized_body
302         in
303         let inductiveFuns =
304           List.map
305             (fun (params, (name, typ), body, decr_idx) ->
306               let add_binders kind t =
307                List.fold_right
308                 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
309               in
310               let cic_body =
311                aux ~localize loc context' (add_binders `Lambda body) in
312               let cic_type =
313                aux_option ~localize loc context (Some `Type)
314                 (HExtlib.map_option (add_binders `Pi) typ) in
315               let name =
316                 match cic_name_of_name name with
317                 | NCic.Anonymous ->
318                     CicNotationPt.fail loc
319                       "Recursive functions cannot be anonymous"
320                 | NCic.Name name -> name
321               in
322               (name, decr_idx, cic_type, cic_body))
323             defs
324         in
325         let fix_or_cofix n =
326          match kind with
327             `Inductive -> NCic.Fix (n,inductiveFuns)
328           | `CoInductive ->
329               let coinductiveFuns =
330                 List.map
331                  (fun (name, _, typ, body) -> name, typ, body)
332                  inductiveFuns
333               in
334                NCic.CoFix (n,coinductiveFuns)
335         in
336          let counter = ref ~-1 in
337          let build_term _ (var,_,ty,_) t =
338           incr counter;
339           NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
340          in
341           (match cic_body with
342               `AvoidLetInNoAppl n ->
343                 let n' = List.length inductiveFuns - n in
344                  fix_or_cofix n'
345             | `AvoidLetIn (n,l) ->
346                 let n' = List.length inductiveFuns - n in
347                  NCic.Appl (fix_or_cofix n'::l)
348             | `AddLetIn cic_body ->         
349                 List.fold_right (build_term inductiveFuns) inductiveFuns
350                  cic_body)
351 *)
352     | CicNotationPt.Ident _
353     | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
354     | CicNotationPt.Ident (name, subst) ->
355        assert (subst = None);
356        (try
357          NCic.Rel (find_in_context name context)
358        with Not_found -> resolve env (Id name) ())
359     | CicNotationPt.Uri (name, subst) ->
360        assert (subst = None);
361        (try
362          NCic.Const (NRef.reference_of_string name)
363         with NRef.IllFormedReference _ ->
364          CicNotationPt.fail loc "Ill formed reference")
365     | CicNotationPt.Implicit -> NCic.Implicit `Term
366     | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
367 patterns not implemented *)
368     | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
369     | CicNotationPt.Meta (index, subst) ->
370         let cic_subst =
371          List.map
372           (function None -> assert false| Some t -> aux ~localize loc context t)
373           subst
374         in
375          NCic.Meta (index, (0, NCic.Ctx cic_subst))
376     | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
377     | CicNotationPt.Sort `Set -> assert false
378     | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
379        [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
380     | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
381        [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
382     | CicNotationPt.Symbol (symbol, instance) ->
383         resolve env (Symbol (symbol, instance)) ()
384     | _ -> assert false (* god bless Bologna *)
385   and aux_option ~localize loc context annotation = function
386     | None -> NCic.Implicit annotation
387     | Some term -> aux ~localize loc context term
388   in
389    aux ~localize:true HExtlib.dummy_floc context ast
390
391 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
392      ~localization_tbl
393 =
394   let context = List.map fst context in
395   interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
396 ~localization_tbl
397 ;;
398
399 let domain_of_term ~context = 
400   let context = List.map (fun name,_ -> Cic.Name name) context in
401   Disambiguate.domain_of_ast_term ~context
402 ;; 
403
404 module Make (C : DisambiguateTypes.Callbacks) = struct 
405  module Disambiguator = Disambiguate.Make(C)
406
407  let disambiguate_term ?(fresh_instances=false) ~context ~metasenv ~subst
408     ~aliases ~universe ~lookup_in_library ?goal
409     (text,prefix_len,term) 
410   =
411    let term =
412      if fresh_instances then CicNotationUtil.freshen_term term else term
413    in
414    let localization_tbl = NCicUntrusted.NCicHash.create 503 in
415    let hint =
416     match goal with
417        None -> (fun _ y -> y),(fun x -> x)
418      | Some n ->
419         (fun metasenv y ->
420           let _,_,ty = NCicUtils.lookup_meta n metasenv in
421            NCic.LetIn ("_",ty,y,NCic.Rel 1)),
422         (function  
423          | Disambiguate.Ok (t,m,s,ug) ->
424              (match t with
425              | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
426              | _ -> assert false)
427          | k -> k)
428    in
429     let res,b =
430      Disambiguator.disambiguate_thing
431       ~context ~metasenv ~initial_ugraph:() ~aliases
432       ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
433       ~mk_implicit:(function None -> NCic.Implicit `Term 
434                     | Some `Closed -> NCic.Implicit `Closed)
435       ~lookup_in_library ~domain_of_thing:domain_of_term
436       ~interpretate_thing:(interpretate_term (?create_dummy_ids:None))
437       ~refine_thing:refine_term (text,prefix_len,term)
438       ~localization_tbl ~hint ~subst
439     in
440      List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
441  ;;
442   
443 end