package lambdapi

All checked builds pass
  1. Overview
  2. Docs
Proof assistant for the λΠ-calculus modulo rewriting

Install

dune-project
 Dependency

Authors

Maintainers

Sources

lambdapi-4.0.0.tbz
sha256=0e2e73e0ea0c674f1263bf85ed3453ed3d6084d38eea29974a03ba9e382d29d7
sha512=2831db57fcd09206687a92fc9ee7d363e87bcec5167949e9c8161d41c63d5887b9f3556bfd63a7a9a0c12e5a5dc61a397baf4f496ebdb2a2fce122142c05e7a1

doc/src/lambdapi.tool/indexing.ml.html

Source file indexing.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
open Core open Term
open Common open Pos
open Timed

let index_version = "v.1.0.0"

let lsp_input = Stdlib.ref ("","")

type sym_name = Common.Path.t * string

let string_of_path x = Format.asprintf "%a" Common.Path.pp x
let string_of_sym_name (p,n) = string_of_path p ^ "." ^ n

let is_path_prefix patt p =
 Lplib.String.is_prefix patt (string_of_path p)

let re_matches_sym_name re sym_name =
 try
  ignore (Str.search_forward re (string_of_sym_name sym_name) 0) ;
  true
 with Not_found -> false

let (@) = Lplib.List.(@)

let name_of_sym s = (s.sym_path, s.sym_name)

let dump_to ~filename i =
 let ch = open_out_bin filename in
 output_string ch index_version;
 Marshal.to_channel ch i [] ;
 close_out ch

(* discrimination tree *)
(* substitution trees would be best *)

(* - all variables are indexed equally, ignoring the name
   - let-ins are expanded when indexed, but not when computing subterms
     to index
   - patterns (e.g. $x.[t1 .. tn]) are indexed as HOLES, ignoring the
     arguments t1 .. tn
   - we consider t1 ... tn as subterms when computing the subterms to index
   - flexible terms, i.e. applyed HOLES (i.e. applied patterns $x.[t1 .. tn])
     are not indexed as subterms
   - when computing the subterms to index, when entering a product the
     bound variable is replaced with a pattern to simulate modus-ponens
     e.g. "pi x : T. x + x"  has as subterm "$x + $x"
*)

module Index = struct

type 'a index =
 | Leaf of 'a list
 | Choice of 'a node list

and 'a node =
 | IHOLE of 'a index
 | IRigid of rigid * 'a index

and rigid =
 | IVar
 | IKind
 | IType
 | ISymb of sym_name
 | IAppl
 | IAbst
 | IProd

type 'a db = 'a list Lplib.Extra.StrMap.t * 'a index

let empty : 'a db =  Lplib.Extra.StrMap.empty, Choice []

let rec node_of_stack t s v =
 match unfold t with
 | Kind -> IRigid(IKind, index_of_stack s v)
 | Type -> IRigid(IType, index_of_stack s v)
 | Vari _ -> IRigid(IVar, index_of_stack s v)
 | Symb sym  -> IRigid(ISymb (name_of_sym sym), index_of_stack s v)
 | Appl(t1,t2) -> IRigid(IAppl, index_of_stack (t1::t2::s) v)
 | Abst(t1,bind) ->
    let _, t2 = unbind bind in
    IRigid(IAbst, index_of_stack (t1::t2::s) v)
 | Prod(t1,bind) ->
    let _, t2 = unbind bind in
    IRigid(IProd, index_of_stack (t1::t2::s) v)
 | Patt (_var,_varname,_args) ->
    IHOLE (index_of_stack s v)
 | LLet (_typ, bod, bind) ->
    (* Let-ins are expanded during indexing *)
    node_of_stack (subst bind bod) s v
 | Meta _ -> assert false
 | Plac _ ->
    (* this may happen in a rewriting rule that uses a _ in the r.h.s.
       that is NOT instantiated; the rule is meant to open a proof
       obligation.

       Tentative implementation: a placeholder is seen as a variable *)
    IRigid(IVar, index_of_stack s v)
 | Wild -> assert false (* used only by tactics and reduction *)
 | TRef _  -> assert false (* destroyed by unfold *)
 | Bvar _ -> assert false

and index_of_stack stack v =
 match stack with
 | [] -> Leaf [v]
 | t::s -> Choice [node_of_stack t s v]

exception NoMatch

(* match a rigid with a term, either raising NoMatch or returning the
   (ordered) list of immediate subterms of the term *)
let rec match_rigid r term =
 match r, unfold term with
 | IKind, Kind -> []
 | IType, Type -> []
 | IVar, Vari _ -> []
 | ISymb n, Symb sym  when n = name_of_sym sym -> []
 | IAppl, Appl(t1,t2) -> [t1;t2]
 | IAbst, Abst(t1,bind) -> let _, t2 = unbind bind in [t1;t2]
 | IProd, Prod(t1,bind) -> let _, t2 = unbind bind in [t1;t2]
 | _, LLet (_typ, bod, bind) -> match_rigid r (subst bind bod)
 | IVar, Plac _ ->
    (* this may happen in a rewriting rule that uses a _ in the r.h.s.
       that is NOT instantiated; the rule is meant to open a proof
       obligation.

       Tentative implementation: a placeholder is seen as a variable *)
    []
 | _, (Meta _ | Wild | TRef _) -> assert false
 | _, _ -> raise NoMatch

(* match anything with a flexible term *)
let rec match_flexible =
 function
    IHOLE i -> [i]
  | IRigid(r,i) ->
     match r with
      | IVar
      | IKind
      | IType
      | ISymb _ -> [i]
      | IAppl
      | IAbst
      | IProd ->
          List.concat (List.map match_flexible_index (match_flexible_index i))

and match_flexible_index =
 function
    Leaf _ -> assert false (* ill-typed term *)
  | Choice nodes ->
     List.concat (List.map match_flexible nodes)

let rec insert_index index stack v =
 match index,stack with
 | Leaf vs, [] -> Leaf(v::vs)
 | Choice l, t::s ->
    let rec aux =
     function
     | [] -> [node_of_stack t s v]
     | n::nl ->
       try
        insert_node n t s v :: nl
       with
        NoMatch -> n :: aux nl
    in Choice(aux l)
 | _, _ -> assert false (* ill-typed term *)

and insert_node node term s v =
 match node,term with
 (* Patterns are holes, holes are patterns *)
 | IHOLE i, Patt _ -> IHOLE (insert_index i s v)
 | IRigid(r,i), t ->
    let s' = match_rigid r t in
    IRigid(r,insert_index i (s'@s) v)
 | _, _ -> raise NoMatch

let insert (namemap,index) term v =
 namemap, insert_index index [term] v

let insert_name (namemap,index) name v =
 let vs =
  match Lplib.Extra.StrMap.find_opt name namemap with
     None -> []
   | Some l -> l in
 Lplib.Extra.StrMap.add name (v::vs) namemap, index

let rec remove_index ~what =
 function
  | Leaf l ->
     let l' = List.filter what l in
     (match l' with
       | [] -> Choice []
       | _::_ -> Leaf l')
  | Choice l ->
     Choice (List.filter_map (remove_node ~what) l)

and remove_node ~what =
 function
  | IHOLE i ->
     (match remove_index ~what i with
       | Choice [] -> None
       | i' -> Some (IHOLE i'))
  | IRigid (r,i) ->
     (match remove_index ~what i with
       | Choice [] -> None
       | i' -> Some (IRigid (r,i')))

let remove_from_name_index ~what i =
 Lplib.Extra.StrMap.filter_map
  (fun _ l ->
    let f x = if what x then Some x else None in
    match List.filter_map f l with
     | [] -> None
     | l' -> Some l') i

let remove ~what (dbname, index) =
 remove_from_name_index ~what dbname, remove_index ~what index

let rec search_index ~generalize index stack =
 match index,stack with
 | Leaf vs, [] -> vs
 | Choice l, t::s ->
    List.fold_right
     (fun n res -> search_node ~generalize n t s @ res) l []
 | _, _ -> assert false (* ill-typed term *)

and search_node ~generalize node term s =
 match node,term with
 | _, Patt _ ->
     List.concat
      (List.map
        (fun i -> search_index ~generalize i s) (match_flexible node))
 | IHOLE i, _ when generalize -> search_index ~generalize i s
 | IHOLE i, t -> search_node ~generalize (IRigid(IVar,i)) t s
 | IRigid(r,i), t ->
     match match_rigid r t with
     | s' -> search_index ~generalize i (s'@s)
     | exception NoMatch -> []

(* when [~generalize] is false, all holes in the index are matched
   only by variables, i.e. the pattern is not matched up to generalization *)
let search ~generalize (_,index) term =
 search_index ~generalize index [term]

let locate_name (namemap,_) name =
  match Lplib.Extra.StrMap.find_opt name namemap with None -> [] | Some l -> l

end

module DB = struct
 (* fix codomain type *)

 type side = Parsing.Syntax.side = Lhs | Rhs

 type relation = Parsing.Syntax.relation = Exact | Inside

 type 'relation where = 'relation Parsing.Syntax.where =
  | Spine of 'relation
  | Conclusion of 'relation
  | Hypothesis of 'relation

 type position =
  | Name
  | Type of relation where
  | Xhs  of relation * side

 type item = sym_name * Common.Pos.pos option
 (* the "name" in the sym_name of rules is just the printed position of
    the rule; the associated position is never None *)

 let pp_side fmt =
  function
   | Lhs -> Lplib.Base.out fmt "lhs"
   | Rhs -> Lplib.Base.out fmt "rhs"

 let pp_relation fmt =
  function
    | Exact -> Lplib.Base.out fmt "as the exact"
    | Inside -> Lplib.Base.out fmt "inside the"

 let pp_where fmt =
  function
   | Spine ins -> Lplib.Base.out fmt "%a spine of" pp_relation ins
   | Hypothesis ins -> Lplib.Base.out fmt "%a hypothesis of" pp_relation ins
   | Conclusion ins -> Lplib.Base.out fmt "%a conclusion of" pp_relation ins

 module ItemSet =
  struct
   include Map.Make(struct type t = item let compare = compare end)

   let of_list l =
    List.fold_left
     (fun m (k,v) ->
       update k
        (function
          | None -> Some v
          | Some l -> Some (v@l))
        m) empty l
  end

 module Sym_nameMap =
   Map.Make(struct type t = sym_name let compare = compare end)

 type answer = ((*generalized:*)bool * term * position) list

 (* disk persistence *)

 let default_dbfile = ".LPSearch.db"

 let the_dbpath : string Stdlib.ref =
   Stdlib.ref
     (match Sys.getenv_opt "HOME" with
      | Some s -> Filename.concat s default_dbfile
      | None -> default_dbfile)

 let rwpaths = Stdlib.ref []

 let restore_from ~filename =
  if Sys.file_exists filename then
    begin
      let ch = open_in_bin filename in
      let buffer = Bytes.create (String.length index_version) in
      really_input ch buffer 0 (String.length index_version);
      if Bytes.unsafe_to_string buffer <> index_version then
        Error.fatal_no_pos
          "Wrong index file version. Please (re)move or regenerate \"%s\"."
          filename;
      let i = Marshal.from_channel ch in
      close_in ch ;
      i
    end
  else
    begin
      Common.Error.wrn None "Index file \"%s\" not found (will be created)."
        filename;
      Sym_nameMap.empty, Index.empty
    end

 let restore_from_disk() = restore_from ~filename:Stdlib.(!the_dbpath)

 (* The persistent database.
 Please increment the value of [index_version] in the header of this file
 whenever the structure of db changes to prevent SIGSEGV to occur *)
 let db :
  ((string * string * int * int) Sym_nameMap.t *
   (item * position list) Index.db) Lazy.t ref =
   ref (lazy (restore_from_disk ()))

 let preserving_index f x =
   let saved_db = !db in
   let res = f x in
   db := saved_db ;
   res

 let empty () = db := lazy (Sym_nameMap.empty,Index.empty)

 let insert k v =
   let sidx,idx = Lazy.force !db in
   let db' = sidx, Index.insert idx k v in
   db := lazy db'

 let insert_name k v =
   let sidx,idx = Lazy.force !db in
   let db' = sidx, Index.insert_name idx k v in
   db := lazy db'

 let remove path =
   let sidx,idx = Lazy.force !db in
   let keep sym_path = not (is_path_prefix path sym_path) in
   let idx =
     Index.remove
      ~what:(fun (((sym_path,_),_),_) -> keep sym_path ) idx in
   let sidx =
    Sym_nameMap.filter (fun (sym_path,_) _ -> keep sym_path) sidx in
   db := lazy (sidx,idx)

 let set_of_list ~generalize k l =
  (* rev_map is used because it is tail recursive *)
  ItemSet.of_list
   (List.rev_map
     (fun (i,pos) ->
       i, List.map (fun x -> generalize,k,x) pos) l)

 let search ~generalize k =
  set_of_list ~generalize k
   (Index.search ~generalize (snd (Lazy.force !db)) k)

 let dump () =
  dump_to ~filename:Stdlib.(!the_dbpath) (Lazy.force !db)

 let locate_name name =
  let k = Term.mk_Wild (* dummy, unused *) in
  set_of_list ~generalize:false k
   (Index.locate_name (snd (Lazy.force !db)) name)

 let parse_source_map filename =
  let sidx,idx = Lazy.force !db in
  let sidx = ref sidx in
  let ch = open_in filename in
  (try
   while true do
     let line = input_line ch in
     match String.split_on_char ' ' line with
      | [fname; start_line; end_line; sourceid; lpid] ->
          let rec sym_name_of =
           function
             | [] -> assert false
             | [name] -> [],name
             | hd::tl -> let path,name = sym_name_of tl in hd::path,name in
          let lpid = sym_name_of (String.split_on_char '.' lpid) in
          let start_line = int_of_string start_line in
          let end_line = int_of_string end_line in
          sidx :=
           Sym_nameMap.add lpid (sourceid,fname,start_line,end_line) !sidx
      | _ ->
         raise
          (Common.Error.Fatal
            (None,"wrong file format for source map file", ""))
   done
  with
   | Failure _ as exn ->
      close_in ch;
      raise
       (Common.Error.Fatal(None,"wrong file format for source map file: " ^
         Printexc.to_string exn, ""))
   | End_of_file -> close_in ch) ;
  db := lazy (!sidx,idx)

 type ho_pp = { run : 'a. 'a Lplib.Base.pp -> 'a Lplib.Base.pp }

 let identity_escaper : ho_pp =
  { run = fun x -> x }

 let html_escaper : ho_pp =
  { run  = fun pp fmt x ->
     let res = Dream.html_escape (Format.asprintf "%a" pp x) in
     Format.pp_print_string fmt res
  }

 let source_infos_of_sym_name sym_name =
  match Sym_nameMap.find_opt sym_name (fst (Lazy.force !db)) with
   | None -> None, None
   | Some (sourceid, fname, start_line, end_line) ->
      let start_col = 0 in
      let end_col = -1 in (* to the end of line *)
      (* FIX ME *)
      let start_offset, end_offset = 0, 0 in
      Some sourceid,
       Some { fname=Some fname; start_line; start_col; end_line;
              end_col; start_offset; end_offset }

 let generic_pp_of_position_list ~escaper ~sep =
  Lplib.List.pp
   (fun ppf position ->
     Print.no_qualif (fun () ->
     match position with
      | _,_,Name ->
         Lplib.Base.out ppf "Name"
      | generalize,term,Type where ->
         Lplib.Base.out ppf "%a occurs %s%a the type"
          (escaper.run Print.term) term
          (if generalize then "generalized " else "")
          pp_where where
      | generalize,term,Xhs (relation,side) ->
         Lplib.Base.out ppf "%a occurs %s %a %a"
          (escaper.run Print.term) term
          (if generalize then "generalized" else "")
          pp_relation relation pp_side side))
   sep

 (* given a filename/URI it returns the stream of lines
    and a function to close the resources *)
 let parse_file fname =
  if String.starts_with ~prefix:"file://" fname then
   (assert (fst Stdlib.(!lsp_input) = fname) ;
   let text = snd Stdlib.(!lsp_input) in
   let lines = ref (String.split_on_char '\n' text) in
   (fun () ->
     match !lines with
      | [] -> raise End_of_file
      | he::tl -> lines := tl ; he),
   (fun () -> ()))
  else
   let ch = open_in fname in
   (fun () -> input_line ch), (fun () -> close_in ch)

 let generic_pp_of_item_list ~escape ~escaper ~separator ~sep ~delimiters
  ~lis:(lisb,lise) ~pres:(preb,pree)
  ~bold:(boldb,bolde) ~code:(codeb,codee) ?(colorizer=Lplib.Extra.default)
  fmt l =
  if l = [] then
   Lplib.Base.out fmt "Nothing found"
  else
    Lplib.List.pp (fun ppf (((p,n) as sym_name,pos),(positions : answer)) ->
      let sourceid,sourcepos = source_infos_of_sym_name sym_name in
      (* let n_pp = (Lplib.Color.red "%s") n in *)
      Lplib.Base.out ppf
      ("%s%a.%s"
      ^^
      (colorizer "%s")
      ^^ "%s@%s%s%a%s%s%s%a%s%s%a%s%s%a%s%s%s%s@.")
      lisb (escaper.run Path.pp) p boldb n bolde
      (popt_to_string ~print_dirname:false pos)
      separator (generic_pp_of_position_list ~escaper ~sep) positions
      separator preb codeb
      (Common.Pos.print_file_contents ~parse_file ~escape ~delimiters
      ~complain_if_location_unknown:true) pos
      separator
      codee
      (fun ppf opt ->
        match opt with
        | None -> Lplib.Base.string ppf ""
        | Some sourceid ->
          Lplib.Base.string ppf ("Translated to " ^ sourceid)) sourceid
      codeb
          separator
          (Common.Pos.print_file_contents ~parse_file ~escape ~delimiters
          ~complain_if_location_unknown:false) sourcepos
          codee pree lise separator)
    "" fmt l

 let html_of_item_list =
  generic_pp_of_item_list ~escape:Dream.html_escape ~escaper:html_escaper
   ~separator:"<br>\n" ~sep:" and<br>\n" ~delimiters:("<p>","</p>")
   ~lis:("<li>","</li>") ~pres:("<pre>","</pre>") ~bold:("<b>","</b>")
   ~code:("<code>","</code>") ~colorizer: Lplib.Extra.default

 let pp_item_list fmt l =
  generic_pp_of_item_list ~escape:(fun x -> x) ~escaper:identity_escaper
   ~separator:"\n" ~sep:" and\n" ~delimiters:("","")
   ~lis:("* ","") ~pres:("","")
   ~bold:("","")
    ~code:("","")
    ~colorizer:
      (if Stdlib.(!Common.Console.lsp_mod) || Unix.isatty Unix.stdout then
        Lplib.Color.red
      else
        Lplib.Extra.default)
    fmt l

 let pp_results_list fmt l = pp_item_list fmt l

 let html_of_results_list from fmt l =
  Lplib.Base.out fmt "<ol start=\"%d\">%a</ol>" from html_of_item_list l

end

exception Overloaded of string * DB.answer DB.ItemSet.t

let normalize_fun = ref (fun _ -> assert false)

let mk_bogus_sym mp name pos =
 Core.Term.create_sym mp Core.Term.Public Core.Term.Defin Core.Term.Sequen
  false (Common.Pos.make pos name) None Core.Term.mk_Type []

let elim_duplicates_up_to_normalization res =
 let resl = DB.ItemSet.bindings res in
 let norm =
  List.map
   (fun ((((mp,name),sympos),l) as inp) ->
     let s = mk_bogus_sym mp name sympos in
     match !normalize_fun (Core.Term.mk_Symb s) with
     | Symb {sym_path ; sym_name ; _} ->
        (((sym_path,sym_name),sympos), l)
     | _ -> inp) resl in
 let res = List.sort (fun ((x,_),_) ((y,_),_) -> compare x y) norm in
 let res =
  let rec uniq =
   function
    | [] | [_] as l -> l
    | ((x,_),_)::(((y,_),_)::_ as l) when x=y -> uniq l
    | i::l -> i::uniq l in
   uniq res in
 DB.ItemSet.of_list res

let find_sym ~prt ~prv sig_state ({elt=(mp,name); pos} as s) =
 try
  Core.Sig_state.find_sym ~prt ~prv sig_state s
 with
  Common.Error.Fatal _ ->
   let pos,mp,name =
    match mp with
      [] ->
       let res_orig = DB.locate_name name in
       let res = elim_duplicates_up_to_normalization res_orig in
       if DB.ItemSet.cardinal res > 1 then
         raise (Overloaded (name,res_orig)) ;
       (match DB.ItemSet.choose_opt res with
         | None -> Common.Error.fatal pos "Unknown symbol %s." name
         | Some (((mp,name),sympos),[_,_,DB.Name]) -> sympos,mp,name
         | Some _ -> assert false) (* locate only returns DB.Name*)
    | _::_ -> None,mp,name
   in
    mk_bogus_sym mp name pos

module QNameMap =
 Map.Make(struct type t = sym_name let compare = Stdlib.compare end)

let no_implicits_in_term t =
 let res = ref true in
 Core.LibTerm.iter
  (function
    | Plac _ -> res := false
    | Wild | TRef _ -> assert false
    | _ -> ()) t ;
 !res

let check_rule : Parsing.Syntax.p_rule -> sym_rule = fun pr ->
 let ss = Core.Sig_state.dummy in
 let (_,r) as sr = Parsing.Scope.scope_rule ~find_sym false ss pr in
 if no_implicits_in_term r.rhs then sr
 else
  Common.Error.fatal pr.pos
   "The rule has implicit terms in the right-hand-side: %a"
   (Parsing.Pretty.rule "") pr

let load_meta_rules () =
 let rules = ref [] in
 List.iter (fun rwpath ->
  let cmdstream = Parsing.Parser.Lp.parse_file rwpath in
  Stream.iter
   (fun {elt ; _ } ->
     match elt with
       Parsing.Syntax.P_rules r -> rules := List.rev_append r !rules
     | _ -> ())
   cmdstream) Stdlib.(!DB.rwpaths) ;
 let rules = List.rev !rules in
 let handle_rule map r =
   let (s,r) = check_rule r in
   let h = function Some rs -> Some(r::rs) | None -> Some[r] in
   SymMap.update s h map in
 let map = List.fold_left handle_rule SymMap.empty rules in
 SymMap.iter Tree.set_dtree map;
 SymMap.fold
  (fun sym _rs map' ->
    QNameMap.add (name_of_sym sym) (Timed.(!(sym.sym_dtree))) map')
  map QNameMap.empty

let meta_rules = lazy (load_meta_rules ())

let force_meta_rules_loading () = ignore (Lazy.force meta_rules)

let normalize typ =
 let dtree sym =
  try QNameMap.find (name_of_sym sym) (Lazy.force meta_rules)
  with Not_found -> Core.Tree_type.empty_dtree in
 Core.Eval.snf ~dtree ~tags:[NoExpand] [] typ

let _ = normalize_fun := normalize

let search_pterm ~generalize ~mok ss env pterm =
 let env =
  ("V#",(new_var "V#",Term.mk_Type,None))::env in
 Dream.log "QUERY before scoping: %a@." Parsing.Pretty.term pterm ;
 let query =
  Parsing.Scope.scope_search_pattern ~find_sym ~mok ss env pterm in
 Dream.log "QUERY before normalize: %a" Core.Print.term query ;
 let query = normalize query in
 Dream.log "QUERY to be executed: %a" Core.Print.term query ;
 DB.search ~generalize query

let rec is_flexible t =
 match Core.Term.unfold t with
  | Patt _ -> true
  | Appl(t,_) -> is_flexible t
  | LLet(_,_,b) -> let _, t = unbind b in is_flexible t
  | Vari _ | Type | Kind | Symb _ | Prod _ | Abst _ -> false
  | Plac _ ->
     (* this may happen in a rewriting rule that uses a _ in the r.h.s.
        that is NOT instantiated; the rule is meant to open a proof
        obligation

       Tentative implementation: a placeholder is seen as a variable *)
     false
  | Meta _ | Wild | TRef _ | Bvar _ -> assert false

let enter =
 DB.(function
  | Hypothesis _ -> Hypothesis Inside
  | Spine _
  | Conclusion _ -> Conclusion Inside)

let enter_pi_source =
 DB.(function
  | Spine _ -> Hypothesis Exact
  | Hypothesis _ -> Hypothesis Inside
  | Conclusion _ -> Conclusion Inside)

let enter_pi_target ~is_prod =
 DB.(function
  | Spine _ when is_prod -> Spine Inside
  | Spine _ -> Conclusion Exact
  | Hypothesis _ -> Hypothesis Inside
  | Conclusion _ -> Conclusion Inside)

let subterms_to_index ~is_spine t =
 let rec aux ~where t =
  let t = Core.Term.unfold t in
  [where,t] @
  match t with
  | Bvar _
  | Vari _
  | Type
  | Kind
  | Plac _
  | Symb _ -> []
  | Abst(t,b) ->
     let _, t2 = unbind b in
     aux ~where:(enter where) t @ aux ~where:(enter where) t2
  | Prod(t,b) ->
     (match where with
       | Spine _ ->
          let t2 = subst b (Core.Term.mk_Patt (None,"dummy",[||])) in
          aux ~where:(enter_pi_source where) t @
           aux ~where:(enter_pi_target ~is_prod:(Core.Term.is_prod t2) where)
            t2
       | _ ->
         let _, t2 = unbind b in
         aux ~where:(enter_pi_source where) t @
          aux ~where:(enter_pi_target ~is_prod:false where) t2)
  | Appl(t1,t2) ->
     aux ~where:(enter where) t1 @ aux ~where:(enter where) t2
  | Patt (_var,_varname,args) ->
     List.concat (List.map (aux ~where:(enter where)) (Array.to_list args))
  | LLet (t1,t2,b) ->
     (* we do not expand the let-in when indexing subterms *)
     let _, t3 = unbind b in
     aux ~where:(enter where) t1 @ aux ~where:(enter where) t2 @
      aux ~where:(enter where) t3
  | Meta _ | Wild | TRef _ -> assert false
 in aux ~where:(if is_spine then Spine Exact else Conclusion Exact) t

let insert_rigid t v =
 if not (is_flexible t) then begin
  DB.insert t v
  (* assert (List.mem v (DB.search t)); *)
 end

let index_term_and_subterms ~is_spine t item =
 let tn = normalize t in
 (*
 let pp_item ppf (((p,n),_ ), _) =
   Lplib.Base.out ppf "%a.%s" Path.pp p n in
 Format.printf "%a :(%a) REWRITTEN TO (%a)@."
  pp_item (item (DB.Conclusion DB.Exact))
  Core.Print.term t Core.Print.term tn ;
 *)
 let cmp (where1,t1) (where2,t2) =
  let res = compare where1 where2 in
  if res = 0 then Core.Term.cmp t1 t2 else res in
 let subterms =
  List.sort_uniq cmp (subterms_to_index ~is_spine tn) in
 List.iter (fun (where,s) -> insert_rigid s (item where)) subterms

let index_rule ~path sym ({Core.Term.lhs=lhsargs ; rule_pos ; _} as rule) =
 let rule_pos =
   match rule_pos with
    | None -> assert false (* this probably may happen, but it is BAD!
                              I leave the assert false to detect when it
                              happens and let the team decide what to do *)
    | Some pos -> pos in
 let lhs = Core.Term.add_args (Core.Term.mk_Symb sym) lhsargs in
 let rhs = rule.rhs in
 let get_relation = function | DB.Conclusion r -> r | _ -> assert false in
 let rule_name = (path,Common.Pos.to_string ~print_fname:false rule_pos) in
 index_term_and_subterms ~is_spine:false lhs
  (fun where -> ((rule_name,Some rule_pos),[Xhs(get_relation where,Lhs)])) ;
 index_term_and_subterms ~is_spine:false rhs
  (fun where -> ((rule_name,Some rule_pos),[Xhs(get_relation where,Rhs)]))

let _ =
 Stdlib.(Core.Sign.add_rules_callback :=
   fun ~path sym rules -> List.iter (index_rule ~path sym) rules)

let index_sym ~path sym =
 let qname = name_of_sym sym in
 (* Name *)
 if List.exists (fun ((sn,_),_) -> sn=qname)
     (DB.ItemSet.bindings (DB.locate_name (snd qname)))
  then
   raise
    (Common.Error.Fatal
      (None,string_of_sym_name qname ^ " already indexed", ""));
 DB.insert_name (snd qname) ((qname,sym.sym_decl_pos),[Name]) ;
 (* Type + InType *)
 let typ = Timed.(!(sym.Core.Term.sym_type)) in
 index_term_and_subterms ~is_spine:true typ
  (fun where -> ((qname,sym.sym_decl_pos),[Type where])) ;
 (* InBody??? sym.sym_def : term option ref
    but all the subterms are too much; collect only the constants? *)
 (* Rules *)
 List.iter (index_rule ~path sym) Timed.(!(sym.Core.Term.sym_rules))

let _ = Stdlib.(Core.Sign.add_symbol_callback := index_sym)

let index_sign sign =
 (*Console.set_flag "print_domains" true ;
 Console.set_flag "print_implicits" true ;
 Common.Logger.set_debug true "e" ;*)
 let syms = Timed.(!(sign.Core.Sign.sign_symbols)) in
 let deps = Timed.(!(sign.Core.Sign.sign_deps)) in
 let path = sign.Core.Sign.sign_path in
 Lplib.Extra.StrMap.iter (fun _ sym -> index_sym ~path sym) syms ;
 Common.Path.Map.iter
  (fun p d ->
    Lplib.Extra.StrMap.iter
     (fun name sd ->
       let sym = Core.Sign.find_qualified p name in
       List.iter (index_rule ~path sym) sd.Sign.rules)
     d.Sign.dep_symbols)
  deps

let deindex_path path = DB.remove path

(* let's flatten the interface *)
include DB

module QueryLanguage = struct

 open Parsing.Syntax

 let match_opt p x =
  match p,x with
  | None, _ -> true
  | Some x', x -> x=x'

 let match_where p x =
  match p with
  | None -> true
  | Some p ->
     match p,x with
      | Spine insp, Spine ins
      | Conclusion insp, Conclusion ins
      | Hypothesis insp, Hypothesis ins -> match_opt insp ins
      | _, _ -> false

 let filter_constr constr _ positions =
  Option.map (fun x -> [x])
   (match constr with
    | QType wherep ->
       List.find_opt
        (function
          | _,_,Type where -> match_where wherep where
          | _ -> false) positions
    | QXhs (insp,sidep) ->
       List.find_opt
        (function
          | _,_,Xhs (ins,side) -> match_opt insp ins && match_opt sidep side
          | _ -> false) positions)

 let answer_base_query ~mok ss env =
  function
   | QName s -> locate_name s
   | QSearch (patt,generalize,constr) ->
      let res = search_pterm ~generalize ~mok ss env patt in
      (match constr with
        | None -> res
        | Some constr -> ItemSet.filter_map (filter_constr constr) res)

 let perform_op =
  function
   | Intersect ->
       ItemSet.merge
        (fun _ positions1 positions2 ->
          match positions1, positions2 with
           | Some l1, Some l2 -> Some (l1@l2)
           | _,_ -> None)
   | Union ->
       ItemSet.union
        (fun _ positions1 positions2 -> Some (positions1 @ positions2))

 let filter set f =
  let g ((p',_ as name),_) _ =
   match f with
    | Path p -> is_path_prefix p p'
    | RegExp s -> let re = Str.regexp s in re_matches_sym_name re name in
  ItemSet.filter g set

 let answer_query ~mok ss env =
  let rec aux =
   function
    | QBase bq -> answer_base_query ~mok ss env bq
    | QOp (q1,op,q2) -> perform_op op (aux q1) (aux q2)
    | QFilter (q,f) -> filter (aux q) f
  in
   aux

end

(* let's flatten the interface *)
include QueryLanguage

module UserLevelQueries = struct

 let search_cmd_gen ss ~from ~how_many
  ~(fail:Pos.popt option -> ?err_desc:string -> string -> string)
  ~pp_results ~tag:(hb,he) fmt q =
  try
   let mok _ = None in
  (* Let's do the parsing here to capture the exceptions here *)
   let q = Lazy.force q in
   let items = ItemSet.bindings (answer_query ~mok ss [] q) in
   let resultsno = List.length items in
   let _,items = Lplib.List.cut items from in
   let items,_ = Lplib.List.cut items how_many in
   Lplib.Base.out fmt "%sNumber of results: %d%s@.%a@."
    hb resultsno he pp_results items
  with
   | Stream.Failure ->
      Lplib.Base.out fmt "%s"
       (fail None (Format.asprintf "Syntax error: a query was expected@."))
   | Common.Error.Fatal (pos, msg, _) ->
      Lplib.Base.out fmt "%s" (fail pos (Format.asprintf "Error: %s@." msg))
   | Overloaded(name,res) ->
      Lplib.Base.out fmt "%s" (fail None (Format.asprintf
       "Overloaded symbol %s. Please rewrite the query replacing %s \
        with a fully qualified identifier among the following:@."
        name name)
        ~err_desc:(Format.asprintf "%a@." pp_results (ItemSet.bindings res))
        )
   | Stack_overflow ->
      Lplib.Base.out fmt "%s" (fail None
       (Format.asprintf
         "Error: too many results. Please refine your query.@." ))
   | exn ->
      Lplib.Base.out fmt "%s"
       (fail None (Format.asprintf "Error: %s@." (Printexc.to_string exn)))

  let search_cmd_txt_query ss fmt q =
  search_cmd_gen ss ~from:0 ~how_many:999999
   ~fail:(fun pos ?err_desc x ->
          Common.Error.fatal_optional_position pos ?err_desc "%s" x)
   ~pp_results:pp_results_list ~tag:("", "") fmt (lazy q)

  let search_cmd_gen_string ss ~from ~how_many ~fail ~pp_results ~tag fmt s =
    search_cmd_gen ss ~from ~how_many ~fail ~pp_results ~tag fmt
     (* Let's do the parsing later to capture the exceptions later *)
     (lazy
      (Parsing.Parser.Lp.parse_search_string ~allow_rocq_syntax:true
        ~alone:true (lexing_opt None) s))

 (** [transform_ascii_to_unicode s] replaces all the occurences of ["->"] and
     ["forall"] with ["→"] and ["Π"] in the search query [s] *)
  let transform_ascii_to_unicode : string -> string =
    let arrow = Str.regexp_string " -> "
    and forall = Str.regexp "\\bforall\\b" in
    fun s -> Str.global_replace forall "Π" (Str.global_replace arrow " → " s)

  (* unit tests *)
  let _ =
    assert (transform_ascii_to_unicode "a -> b" = "a → b");
    assert (transform_ascii_to_unicode " forall x, y" = " Π x, y");
    assert (transform_ascii_to_unicode "forall x, y" = "Π x, y");
    assert (transform_ascii_to_unicode "forall.x, y" = "Π.x, y");
    assert (transform_ascii_to_unicode "((forall x, y" = "((Π x, y")

 let search_cmd_html ss ~from ~how_many fmt s =
   search_cmd_gen_string ss ~from ~how_many
      ~fail:(fun pos ?err_desc x -> "<font color=\"red\">" ^ x ^ "</font>"
          ^ (match pos with None -> "" | Some p -> popt_to_string p)
          ^ Option.value err_desc ~default:"")
      ~pp_results:(html_of_results_list from)
      ~tag:("<h1>","</h1")
      fmt
      s

 let search_cmd_txt ss (fmt:Format.formatter) s =
    let s = transform_ascii_to_unicode s in
    search_cmd_gen_string ss ~from:0 ~how_many:999999
      ~fail:(fun pos ?err_desc x ->
          Common.Error.fatal_optional_position pos ?err_desc "%s" x)
      ~pp_results:pp_results_list ~tag:("", "") fmt s

end

(* let's flatten the interface *)
include UserLevelQueries