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