-
Notifications
You must be signed in to change notification settings - Fork 239
/
Copy pathFStarC.Parser.Dep.fst
2079 lines (1880 loc) · 78.2 KB
/
FStarC.Parser.Dep.fst
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
Copyright 2008-2014 Nikhil Swamy and Microsoft Research
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
(** This module provides an ocamldep-like tool for F*, invoked with [fstar --dep].
Unlike ocamldep, it outputs the transitive closure of the dependency graph
of a given file. The dependencies that are output are *compilation units*
(not module names).
*)
module FStarC.Parser.Dep
open FStar.Pervasives
open FStarC.Compiler.Effect //for ref, failwith etc
open FStarC.Compiler.List
open FStar open FStarC
open FStarC.Compiler
open FStarC.Parser
open FStarC.Parser.AST
open FStarC.Compiler.Util
open FStarC.Const
open FStar.String
open FStarC.Ident
open FStarC.Errors
open FStarC.Class.Show
module Const = FStarC.Parser.Const
module BU = FStarC.Compiler.Util
let dbg = Debug.get_toggle "Dep"
let dbg_CheckedFiles = Debug.get_toggle "CheckedFiles"
let profile f c = Profiling.profile f None c
(* Meant to write to a file as an out_channel. If an exception is raised,
the file is deleted. *)
let with_file_outchannel (fn : string) (k : out_channel -> 'a) : 'a =
let outc = BU.open_file_for_writing fn in
let r =
try k outc
with | e -> BU.close_out_channel outc; BU.delete_file fn; raise e
in
BU.close_out_channel outc;
r
(* In case the user passed [--verify_all], we record every single module name we
* found in the list of modules to be verified.
* In the [VerifyUserList] case, for every [--verify_module X], we check we
* indeed find a module [X].
* In the [VerifyFigureItOut] case, for every file that was on the command-line,
* we record its module name as one module to be verified.
*)
type verify_mode =
| VerifyAll
| VerifyUserList
| VerifyFigureItOut
type intf_and_impl = option string & option string
type files_for_module_name = smap intf_and_impl
let intf_and_impl_to_string ii =
match ii with
| None, None -> "<None>, <None>"
| Some intf, None -> intf
| None, Some impl -> impl
| Some intf, Some impl -> intf ^ ", " ^ impl
let files_for_module_name_to_string (m:files_for_module_name) =
BU.print_string "Printing the file system map {\n";
let str_opt_to_string sopt =
match sopt with
| None -> "<None>"
| Some s -> s in
smap_iter m (fun k v -> BU.print2 "%s:%s\n" k (intf_and_impl_to_string v));
BU.print_string "}\n"
type color = | White | Gray | Black
let check_and_strip_suffix (f: string): option string =
let suffixes = [ ".fsti"; ".fst"; ".fsi"; ".fs" ] in
let matches = List.map (fun ext ->
let lext = String.length ext in
let l = String.length f in
if l > lext && String.substring f (l - lext) lext = ext then
Some (String.substring f 0 (l - lext))
else
None
) suffixes in
match List.filter is_some matches with
| Some m :: _ ->
Some m
| _ ->
None
(* In public interface *)
let is_interface (f: string): bool =
String.get f (String.length f - 1) = 'i'
(* In public interface *)
let is_implementation f =
not (is_interface f)
let list_of_option = function Some x -> [x] | None -> []
let list_of_pair (intf, impl) =
list_of_option intf @ list_of_option impl
(* In public interface *)
let maybe_module_name_of_file f = check_and_strip_suffix (basename f)
let module_name_of_file f =
match maybe_module_name_of_file f with
| Some longname ->
longname
| None ->
raise_error0 Errors.Fatal_NotValidFStarFile (Util.format1 "Not a valid FStar file: '%s'" f)
(* In public interface *)
let lowercase_module_name f = String.lowercase (module_name_of_file f)
let namespace_of_module f =
let lid = FStarC.Ident.lid_of_path (FStarC.Ident.path_of_text f) Range.dummyRange in
match ns_of_lid lid with
| [] -> None
| ns -> Some (FStarC.Ident.lid_of_ids ns)
type file_name = string
type dependence =
| UseInterface of module_name
| PreferInterface of module_name
| UseImplementation of module_name
| FriendImplementation of module_name
let dep_to_string = function
| UseInterface f -> "UseInterface " ^ f
| PreferInterface f -> "PreferInterface " ^ f
| UseImplementation f -> "UseImplementation " ^ f
| FriendImplementation f -> "FriendImplementation " ^ f
instance showable_dependence : showable dependence = {
show = dep_to_string;
}
type dependences = list dependence
let empty_dependences = []
type dep_node = {
edges:dependences;
color:color
}
type dependence_graph = //maps file names to the modules it depends on
| Deps of smap dep_node //(dependences * color)>
(*
* AR: Parsing data for a file (also cached in the checked files)
* It is a summary of opens, includes, A.<id>, etc. in a module
* Earlier we used to store the dependences in the checked file,
* however that is an image of the file system, and so, when the checked
* files were used in a slightly different file system, there were strange errors
* see e.g. #1657 for a couple of cases
* Now we store the following summary and construct the dependences from the current
* file system
*)
type parsing_data_elt =
| P_begin_module of lident //begin_module
| P_open of bool & lident //record_open
| P_implicit_open_module_or_namespace of (open_kind & lid) //record_open_module_or_namespace
| P_dep of bool & lident //add_dep_on_module, bool=true iff it's a friend dependency
| P_alias of ident & lident //record_module_alias
| P_lid of lident //record_lid
| P_inline_for_extraction
type parsing_data =
| Mk_pd of list parsing_data_elt
let str_of_parsing_data_elt elt =
let str_of_open_kind = function
| Open_module -> "P_open_module"
| Open_namespace -> "P_open_namespace"
in
match elt with
| P_begin_module lid -> "P_begin_module (" ^ (string_of_lid lid) ^ ")"
| P_open (b, lid) -> "P_open (" ^ (string_of_bool b) ^ ", " ^ (string_of_lid lid) ^ ")"
| P_implicit_open_module_or_namespace (k, lid) -> "P_implicit_open_module_or_namespace (" ^ (str_of_open_kind k) ^ ", " ^ (string_of_lid lid) ^ ")"
| P_dep (b, lid) -> "P_dep (" ^ (string_of_lid lid) ^ ", " ^ (string_of_bool b) ^ ")"
| P_alias (id, lid) -> "P_alias (" ^ (string_of_id id) ^ ", " ^ (string_of_lid lid) ^ ")"
| P_lid lid -> "P_lid (" ^ (string_of_lid lid) ^ ")"
| P_inline_for_extraction -> "P_inline_for_extraction"
let str_of_parsing_data = function
| Mk_pd l ->
l |> List.fold_left (fun s elt -> s ^ "; " ^ (elt |> str_of_parsing_data_elt)) ""
let friends (p:parsing_data) : list lident =
let Mk_pd p = p in
List.collect
(function
| P_dep (true, l) -> [l]
| _ -> [])
p
let parsing_data_elt_eq (e1:parsing_data_elt) (e2:parsing_data_elt) =
match e1, e2 with
| P_begin_module l1, P_begin_module l2 -> lid_equals l1 l2
| P_open (b1, l1), P_open (b2, l2) -> b1 = b2 && lid_equals l1 l2
| P_implicit_open_module_or_namespace (k1, l1), P_implicit_open_module_or_namespace (k2, l2) ->
k1 = k2 && lid_equals l1 l2
| P_dep (b1, l1), P_dep (b2, l2) -> b1 = b2 && lid_equals l1 l2
| P_alias (i1, l1), P_alias (i2, l2) -> string_of_id i1 = string_of_id i2 && lid_equals l1 l2
| P_lid l1, P_lid l2 -> lid_equals l1 l2
| P_inline_for_extraction, P_inline_for_extraction -> true
| _, _ -> false
let empty_parsing_data = Mk_pd []
type deps = {
dep_graph:dependence_graph; //dependences of the entire project, not just those reachable from the command line
file_system_map:files_for_module_name; //an abstraction of the file system, keys are lowercase module names
cmd_line_files:list file_name; //all command-line files
all_files:list file_name; //all files
parse_results:smap parsing_data //map from filenames to parsing_data
//callers (Universal.fs) use this to get the parsing data for caching purposes
}
let deps_try_find (Deps m) k = BU.smap_try_find m k
let deps_add_dep (Deps m) k v =
BU.smap_add m k v
let deps_keys (Deps m) = BU.smap_keys m
let deps_empty () = Deps (BU.smap_create 41)
let mk_deps dg fs c a pr = {
dep_graph=dg;
file_system_map=fs;
cmd_line_files=c;
all_files=a;
parse_results=pr;
}
(* In public interface *)
let empty_deps = mk_deps (deps_empty ()) (BU.smap_create 0) [] [] (BU.smap_create 0)
let module_name_of_dep = function
| UseInterface m
| PreferInterface m
| UseImplementation m
| FriendImplementation m -> m
let resolve_module_name (file_system_map:files_for_module_name) (key:module_name)
: option module_name
= match BU.smap_try_find file_system_map key with
| Some (Some fn, _)
| Some (_, Some fn) -> Some (lowercase_module_name fn)
| _ -> None
let interface_of_internal (file_system_map:files_for_module_name) (key:module_name)
: option file_name =
match BU.smap_try_find file_system_map key with
| Some (Some iface, _) -> Some iface
| _ -> None
let implementation_of_internal (file_system_map:files_for_module_name) (key:module_name)
: option file_name =
match BU.smap_try_find file_system_map key with
| Some (_, Some impl) -> Some impl
| _ -> None
let interface_of deps key = interface_of_internal deps.file_system_map key
let implementation_of deps key = implementation_of_internal deps.file_system_map key
let has_interface (file_system_map:files_for_module_name) (key:module_name)
: bool =
Option.isSome (interface_of_internal file_system_map key)
let has_implementation (file_system_map:files_for_module_name) (key:module_name)
: bool =
Option.isSome (implementation_of_internal file_system_map key)
let interfaces_with_inlining deps m =
if Options.cmi()
then has_interface deps.file_system_map m
else false
(*
* Public interface
*)
let cache_file_name =
let checked_file_and_exists_flag fn =
let cache_fn =
let lax = Options.lax () in
if lax then fn ^".checked.lax"
else fn ^".checked"
in
let mname = fn |> module_name_of_file in
match Find.find_file (cache_fn |> Util.basename) with
| Some path ->
let expected_cache_file = Find.prepend_cache_dir cache_fn in
if Option.isSome (Options.dep()) //if we're in the dependence analysis
&& not (Options.should_be_already_cached mname) //and checked file is in the
&& (not (BU.file_exists expected_cache_file) //wrong spot ... complain
|| not (BU.paths_to_same_file path expected_cache_file))
then (
let open FStarC.Pprint in
let open FStarC.Errors.Msg in
log_issue0 FStarC.Errors.Warning_UnexpectedCheckedFile [
text "Did not expect module" ^/^ doc_of_string mname ^/^ text "to be already checked.";
prefix 2 1 (text "Found it in an unexpected location:")
(doc_of_string path) ^/^
prefix 2 1 (text "instead of")
(doc_of_string expected_cache_file);
]
);
(* This expression morally just returns [path], but prefers
* the path in [expected_cache_file] is possible to give
* preference to relative filenames. This is mostly since
* GNU make doesn't resolve paths in targets, so we try
* to keep target paths relative. See issue #1978. *)
if BU.file_exists expected_cache_file && BU.paths_to_same_file path expected_cache_file
then expected_cache_file
else path
| None ->
if !dbg_CheckedFiles then
BU.print1 "find_file(%s) returned None\n" (cache_fn |> Util.basename);
if mname |> Options.should_be_already_cached then
raise_error0 FStarC.Errors.Error_AlreadyCachedAssertionFailure [
text (BU.format1 "Expected %s to be already checked but could not find it." mname)
];
Find.prepend_cache_dir cache_fn
in
let memo = Util.smap_create 100 in
let memo f x =
match Util.smap_try_find memo x with
| Some res -> res
| None ->
let res = f x in
Util.smap_add memo x res;
res
in
memo checked_file_and_exists_flag
let parsing_data_of deps fn = BU.smap_try_find deps.parse_results fn |> must
let file_of_dep_aux
(use_checked_file:bool)
(file_system_map:files_for_module_name)
(all_cmd_line_files:list file_name)
(d:dependence)
: file_name =
let cmd_line_has_impl key =
all_cmd_line_files
|> BU.for_some (fun fn ->
is_implementation fn &&
key = lowercase_module_name fn)
in
let maybe_use_cache_of f = if use_checked_file then cache_file_name f else f in
match d with
| UseInterface key ->
//This key always resolves to an interface source file
(match interface_of_internal file_system_map key with
| None ->
assert false; //should be unreachable; see the only use of UseInterface in discover_one
raise_error0 Errors.Fatal_MissingInterface (BU.format1 "Expected an interface for module %s, but couldn't find one" key)
| Some f ->
f)
| PreferInterface key //key for module 'a'
when has_interface file_system_map key -> //so long as 'a.fsti' exists
if cmd_line_has_impl key //unless the cmd line contains 'a.fst'
&& Option.isNone (Options.dep()) //and we're not just doing a dependency scan using `--dep _`
then if Options.expose_interfaces()
then maybe_use_cache_of (Option.get (implementation_of_internal file_system_map key))
else raise_error0 Errors.Fatal_MissingExposeInterfacesOption [
text <| BU.format3 "You may have a cyclic dependence on module %s: use --dep full to confirm. \
Alternatively, invoking fstar with %s on the command line breaks \
the abstraction imposed by its interface %s."
key
(Option.get (implementation_of_internal file_system_map key))
(Option.get (interface_of_internal file_system_map key));
text "If you really want this behavior add the option '--expose_interfaces'.";
]
else maybe_use_cache_of (Option.get (interface_of_internal file_system_map key)) //we prefer to use 'a.fsti'
| PreferInterface key
| UseImplementation key
| FriendImplementation key ->
match implementation_of_internal file_system_map key with
| None ->
//if d is actually an edge in the dep_graph computed by discover
//then d is only present if either an interface or an implementation exist
//the previous case already established that the interface doesn't exist
// since if the implementation was on the command line, it must exist because of option validation
raise_error0 Errors.Fatal_MissingImplementation
(BU.format1 "Expected an implementation of module %s, but couldn't find one" key)
| Some f -> maybe_use_cache_of f
let file_of_dep = file_of_dep_aux false
let dependences_of (file_system_map:files_for_module_name)
(deps:dependence_graph)
(all_cmd_line_files:list file_name)
(fn:file_name)
: list file_name =
match deps_try_find deps fn with
| None -> empty_dependences
| Some ({edges=deps}) ->
List.map (file_of_dep file_system_map all_cmd_line_files) deps
|> List.filter (fun k -> k <> fn) (* skip current module, cf #451 *)
let print_graph (outc : out_channel) (fn : string) (graph:dependence_graph) =
if not (Options.silent ()) then begin
Util.print1 "A DOT-format graph has been dumped in the current directory as `%s`\n" fn;
Util.print1 "With GraphViz installed, try: fdp -Tpng -odep.png %s\n" fn;
Util.print1 "Hint: cat %s | grep -v _ | grep -v prims\n" fn
end;
let s =
"digraph {\n" ^
String.concat "\n" (List.collect
(fun k ->
let deps = (must (deps_try_find graph k)).edges in
let r s = replace_char s '.' '_' in
let print dep =
Util.format2 " \"%s\" -> \"%s\""
(r (lowercase_module_name k))
(r (module_name_of_dep dep))
in
List.map print deps)
(List.unique (deps_keys graph))) ^
"\n}\n"
in
fprint outc "%s" [s]
let safe_readdir_for_include (d:string) : list string =
try readdir d
with
| _ ->
let open FStarC.Pprint in
if false then
// fixme: only warn if given in --include, not for transitive fstar.include
// I'd say it's legit to fstar.include a .cache dir that may not exist yet.
log_issue0 Errors.Fatal_NotValidIncludeDirectory [
prefix 2 1 (text "Not a valid include directory:")
(doc_of_string d);
];
[]
(** Enumerate all F* files in include directories.
Return a list of pairs of long names and full paths. *)
(* In public interface *)
let build_inclusion_candidates_list (): list (string & string) =
let include_directories = Find.include_path () in
let include_directories = List.map normalize_file_path include_directories in
(* Note that [BatList.unique] keeps the last occurrence, that way one can
* always override the precedence order. *)
let include_directories = List.unique include_directories in
let cwd = normalize_file_path (getcwd ()) in
include_directories |> List.concatMap (fun d ->
let files = safe_readdir_for_include d in
files |> List.filter_map (fun f ->
let f = basename f in
check_and_strip_suffix f
|> Util.map_option (fun longname ->
let full_path = if d = cwd then f else join_paths d f in
(longname, full_path))
)
)
(** List the contents of all include directories, then build a map from long
names (e.g. a.b) to pairs of filenames (/path/to/A.B.fst). Long names are
all normalized to lowercase. The first component of the pair is the
interface (if any). The second component of the pair is the implementation
(if any). *)
let build_map (filenames: list string): files_for_module_name =
let map = smap_create 41 in
let add_entry key full_path =
match smap_try_find map key with
| Some (intf, impl) ->
if is_interface full_path then
smap_add map key (Some full_path, impl)
else
smap_add map key (intf, Some full_path)
| None ->
if is_interface full_path then
smap_add map key (Some full_path, None)
else
smap_add map key (None, Some full_path)
in
(* Add files from all include directories *)
List.iter (fun (longname, full_path) ->
add_entry (String.lowercase longname) full_path
) (build_inclusion_candidates_list ());
(* All the files we've been given on the command-line must be valid FStar files. *)
List.iter (fun f ->
add_entry (lowercase_module_name f) f
) filenames;
map
let string_of_lid (l: lident) (last: bool) =
let suffix = if last then [ (string_of_id (ident_of_lid l)) ] else [ ] in
let names = List.map (fun x -> (string_of_id x)) (ns_of_lid l) @ suffix in
String.concat "." names
(** All the components of a [lident] joined by "." (the last component of the
* lident is included iff [last = true]). *)
let lowercase_join_longident (l: lident) (last: bool) =
String.lowercase (string_of_lid l last)
let namespace_of_lid l =
String.concat "_" (List.map string_of_id (ns_of_lid l))
let check_module_declaration_against_filename (lid: lident) (filename: string): unit =
let k' = string_of_lid lid true in
if must (check_and_strip_suffix (basename filename)) <> k' then
log_issue lid Errors.Error_ModuleFileNameMismatch [
Errors.Msg.text (Util.format2 "The module declaration \"module %s\" \
found in file %s does not match its filename." (string_of_lid lid true) filename);
Errors.Msg.text "Dependencies will be incorrect and the module will not be verified.";
]
exception Exit
(* In public interface *)
let core_modules () =
[Basefiles.prims_basename () ;
Basefiles.pervasives_basename () ;
Basefiles.pervasives_native_basename ()]
|> List.map module_name_of_file
let implicit_ns_deps =
[ Const.fstar_ns_lid ]
let implicit_module_deps =
[ Const.prims_lid; Const.pervasives_lid ]
let hard_coded_dependencies full_filename =
let filename : string = basename full_filename in
let implicit_module_deps = List.map (fun l -> l, Open_module) implicit_module_deps in
let implicit_ns_deps = List.map (fun l -> l, Open_namespace) implicit_ns_deps in
(* The core libraries do not have any implicit dependencies *)
if List.mem (module_name_of_file filename) (core_modules ()) then []
else match namespace_of_module (module_name_of_file full_filename) with
| None -> implicit_ns_deps @ implicit_module_deps
(*
* AR: we open FStar, and then ns
* which means that enter_namespace will be called first for F*, and then for ns
* giving precedence to My.M over FStar.M
*)
| Some ns -> implicit_ns_deps @ implicit_module_deps @ [(ns, Open_namespace)]
let dep_subsumed_by d d' =
match d, d' with
| PreferInterface l', FriendImplementation l -> l=l'
| _ -> d = d'
(** For all items [i] in the map that start with [prefix], add an additional
entry where [i] stripped from [prefix] points to the same value. Returns a
boolean telling whether the map was modified.
If the open is an implicit open (as indicated by the flag),
and doing so shadows an existing entry, warn! *)
let enter_namespace
(original_map: files_for_module_name)
(working_map: files_for_module_name)
(sprefix: string)
(implicit_open:bool) : bool =
let found = BU.mk_ref false in
let sprefix = sprefix ^ "." in
let suffix_exists mopt =
match mopt with
| None -> false
| Some (intf, impl) -> is_some intf || is_some impl in
smap_iter original_map (fun k _ ->
if Util.starts_with k sprefix then
let suffix =
String.substring k (String.length sprefix) (String.length k - String.length sprefix)
in
begin
let suffix_filename = smap_try_find original_map suffix in
if implicit_open &&
suffix_exists suffix_filename
then let str = suffix_filename |> must |> intf_and_impl_to_string in
let open FStarC.Pprint in
log_issue0 Errors.Warning_UnexpectedFile [
flow (break_ 1) [
text "Implicitly opening namespace";
squotes (doc_of_string sprefix);
text "shadows module";
squotes (doc_of_string suffix);
text "in file";
dquotes (doc_of_string str) ^^ dot;
];
text "Rename" ^/^ dquotes (doc_of_string str) ^/^ text "to avoid conflicts.";
]
end;
let filename = must (smap_try_find original_map k) in
smap_add working_map suffix filename;
found := true
);
!found
(*
* Get parsing data for a file
* First see if the data in the checked file is good (using the provided callback)
* If it is, return that
*
* Else parse the file, walk its AST, return a list of FStar lowercased module names
it depends on
*)
let collect_one
(original_map: files_for_module_name)
(filename: string)
(get_parsing_data_from_cache:string -> option parsing_data)
: parsing_data &
list dependence & //direct dependence
bool & //has_inline_for_extraction
list dependence //additional roots
//that used to be part of parsing_data earlier
//removing it from the cache (#1657)
//this always returns a single element, remove the list?
=
(*
* Construct dependences from the parsing data
* This is common function for when the parsing data is read from the checked files
* or constructed after AST traversal of the module
*)
let from_parsing_data (pd:parsing_data) (original_map:files_for_module_name) (filename:string)
: list dependence &
bool &
list dependence
= let deps : ref (list dependence) = BU.mk_ref [] in
let has_inline_for_extraction = BU.mk_ref false in
let mo_roots =
let mname = lowercase_module_name filename in
if is_interface filename
&& has_implementation original_map mname
then [ UseImplementation mname ]
else []
in
let auto_open = hard_coded_dependencies filename |> List.map (fun (lid, k) ->
P_implicit_open_module_or_namespace (k, lid))
in
let working_map = smap_copy original_map in
let set_interface_inlining () =
if is_interface filename
then has_inline_for_extraction := true
in
let add_dep deps d =
if not (List.existsML (dep_subsumed_by d) !deps) then
deps := d :: !deps
in
let dep_edge module_name is_friend =
if is_friend then FriendImplementation module_name
else PreferInterface module_name
in
let add_dependence_edge original_or_working_map lid is_friend =
let key = lowercase_join_longident lid true in
match resolve_module_name original_or_working_map key with
| Some module_name ->
add_dep deps (dep_edge module_name is_friend);
true
| _ ->
false
in
let record_open_module let_open lid =
//use the original_map here
//since the working_map will resolve lid while accounting
//for already opened namespaces
//if let_open, then this is the form `UInt64.( ... )`
// where UInt64 can resolve to FStar.UInt64
// So, use the working map, accounting for opened namespaces
//Otherwise, this is the form `open UInt64`,
// where UInt64 must resolve to either
// a module or a namespace for F# compatibility
// So, use the original map, disregarding opened namespaces
if (let_open && add_dependence_edge working_map lid false)
|| (not let_open && add_dependence_edge original_map lid false)
then true
else begin
if let_open then
log_issue lid Errors.Warning_ModuleOrFileNotFoundWarning
(Util.format1 "Module not found: %s" (string_of_lid lid true));
false
end
in
let record_open_namespace lid (implicit_open:bool) =
let key = lowercase_join_longident lid true in
let r = enter_namespace original_map working_map key implicit_open in
if not r && not implicit_open then //suppress the warning for implicit opens
log_issue lid Errors.Warning_ModuleOrFileNotFoundWarning
(Util.format1 "No modules in namespace %s and no file with that name either" (string_of_lid lid true))
in
let record_open let_open lid =
if record_open_module let_open lid
then ()
else if not let_open //syntactically, this cannot be a namespace if let_open is true; so don't retry
then record_open_namespace lid false
in
let record_implicit_open_module_or_namespace (lid, kind) =
match kind with
| Open_namespace -> record_open_namespace lid true
| Open_module -> let _ = record_open_module false lid in ()
in
let record_module_alias ident lid =
let key = String.lowercase (string_of_id ident) in
let alias = lowercase_join_longident lid true in
// Only fully qualified module aliases are allowed.
match smap_try_find original_map alias with
| Some deps_of_aliased_module ->
smap_add working_map key deps_of_aliased_module;
add_dep deps (dep_edge (lowercase_join_longident lid true) false);
true
| None ->
log_issue lid Errors.Warning_ModuleOrFileNotFoundWarning
(Util.format1 "module not found in search path: %s" alias);
false
in
let add_dep_on_module (module_name : lid) (is_friend : bool) =
if add_dependence_edge working_map module_name is_friend
then ()
else if !dbg then
log_issue module_name Errors.Warning_UnboundModuleReference
(BU.format1 "Unbound module reference %s" (show module_name))
in
let record_lid lid =
(* Thanks to the new `?.` and `.(` syntaxes, `lid` is no longer a
module name itself, so only its namespace part is to be
recorded as a module dependency. *)
match ns_of_lid lid with
| [] -> ()
| ns ->
let module_name = Ident.lid_of_ids ns in
add_dep_on_module module_name false
in
let begin_module lid =
if List.length (ns_of_lid lid) > 0 then
ignore (enter_namespace original_map working_map (namespace_of_lid lid))
in
(*
* Iterate over the parsing data elements
*)
begin
match pd with
| Mk_pd l ->
(auto_open @ l) |> List.iter (fun elt ->
match elt with
| P_begin_module lid -> begin_module lid
| P_open (b, lid) -> record_open b lid
| P_implicit_open_module_or_namespace (k, lid) -> record_implicit_open_module_or_namespace (lid, k)
| P_dep (b, lid) -> add_dep_on_module lid b
| P_alias (id, lid) -> ignore (record_module_alias id lid)
| P_lid lid -> record_lid lid
| P_inline_for_extraction -> set_interface_inlining ())
end;
(*
* And then return the dependences
*)
!deps,
!has_inline_for_extraction,
mo_roots
in
let data_from_cache = filename |> get_parsing_data_from_cache in
if data_from_cache |> is_some then begin //we found the parsing data in the checked file
let deps, has_inline_for_extraction, mo_roots = from_parsing_data (data_from_cache |> must) original_map filename in
if !dbg then
BU.print2 "Reading the parsing data for %s from its checked file .. found [%s]\n" filename (show deps);
data_from_cache |> must,
deps, has_inline_for_extraction, mo_roots
end
else
//parse the file and traverse the AST to collect parsing data
let num_of_toplevelmods = BU.mk_ref 0 in
let pd : ref (list parsing_data_elt) = BU.mk_ref [] in
let add_to_parsing_data elt =
if not (List.existsML (fun e -> parsing_data_elt_eq e elt) !pd)
then pd := elt::!pd
in
let rec collect_module = function
| Module (lid, decls)
| Interface (lid, decls, _) ->
check_module_declaration_against_filename lid filename;
add_to_parsing_data (P_begin_module lid);
collect_decls decls
and collect_decls decls =
List.iter (fun x -> collect_decl x.d;
List.iter collect_term x.attrs;
match x.d with
| _ when List.contains Inline_for_extraction x.quals ->
add_to_parsing_data P_inline_for_extraction
| _ -> ()
) decls
and collect_decl d =
match d with
| Include (lid, _)
| Open (lid, _) ->
add_to_parsing_data (P_open (false, lid))
| Friend lid ->
add_to_parsing_data (P_dep (true, (lowercase_join_longident lid true |> Ident.lid_of_str)))
| ModuleAbbrev (ident, lid) ->
add_to_parsing_data (P_alias (ident, lid))
| TopLevelLet (_, patterms) ->
List.iter (fun (pat, t) -> collect_pattern pat; collect_term t) patterms
| Splice (_, _, t)
| Assume (_, t)
| SubEffect { lift_op = NonReifiableLift t }
| SubEffect { lift_op = LiftForFree t }
| Val (_, t) ->
collect_term t
| SubEffect { lift_op = ReifiableLift (t0, t1) } ->
collect_term t0;
collect_term t1
| Tycon (_, tc, ts) ->
begin
if tc then
add_to_parsing_data (P_lid Const.tcclass_lid);
List.iter collect_tycon ts
end
| Exception (_, t) ->
iter_opt t collect_term
| NewEffect ed
| LayeredEffect ed ->
collect_effect_decl ed
| Polymonadic_bind (_, _, _, t)
| Polymonadic_subcomp (_, _, t) -> collect_term t //collect deps from the effect lids?
| DeclToBeDesugared tbs ->
tbs.dep_scan
{ scan_term = collect_term;
scan_binder = collect_binder;
scan_pattern = collect_pattern;
add_lident = (fun lid -> add_to_parsing_data (P_lid lid));
add_open = (fun lid -> add_to_parsing_data (P_open (true, lid)))
}
tbs.blob
| UseLangDecls _
| Pragma _
| DeclSyntaxExtension _
| Unparseable ->
()
| TopLevelModule lid ->
incr num_of_toplevelmods;
if (!num_of_toplevelmods > 1) then
raise_error lid Errors.Fatal_OneModulePerFile
(Util.format1 "Automatic dependency analysis demands one module per file (module %s not supported)" (string_of_lid lid true))
and collect_tycon = function
| TyconAbstract (_, binders, k) ->
collect_binders binders;
iter_opt k collect_term
| TyconAbbrev (_, binders, k, t) ->
collect_binders binders;
iter_opt k collect_term;
collect_term t
| TyconRecord (_, binders, k, _, identterms) ->
collect_binders binders;
iter_opt k collect_term;
collect_tycon_record identterms
| TyconVariant (_, binders, k, identterms) ->
collect_binders binders;
iter_opt k collect_term;
List.iter ( function
| VpOfNotation t | VpArbitrary t -> collect_term t
| VpRecord (record, t) -> collect_tycon_record record;
iter_opt t collect_term
) (List.filter_map Mktuple3?._2 identterms)
and collect_tycon_record r =
List.iter (fun (_, aq, attrs, t) ->
collect_aqual aq;
attrs |> List.iter collect_term;
collect_term t) r
and collect_effect_decl = function
| DefineEffect (_, binders, t, decls) ->
collect_binders binders;
collect_term t;
collect_decls decls
| RedefineEffect (_, binders, t) ->
collect_binders binders;
collect_term t
and collect_binders binders =
List.iter collect_binder binders
and collect_binder b =
collect_aqual b.aqual;
b.battributes |> List.iter collect_term;
match b with
| { b = Annotated (_, t) }
| { b = TAnnotated (_, t) }
| { b = NoName t } -> collect_term t
| _ -> ()
and collect_aqual = function
| Some (Meta t) -> collect_term t
| Some TypeClassArg -> add_to_parsing_data (P_lid Const.tcresolve_lid)
| _ -> ()
and collect_term t =
collect_term' t.tm
and collect_constant = function
| Const_int (_, Some (Unsigned, Sizet)) ->
add_to_parsing_data (P_dep (false, ("fstar.sizeT" |> Ident.lid_of_str)))
| Const_int (_, Some (signedness, width)) ->
let u = match signedness with | Unsigned -> "u" | Signed -> "" in
let w = match width with | Int8 -> "8" | Int16 -> "16" | Int32 -> "32" | Int64 -> "64" in
add_to_parsing_data (P_dep (false, (Util.format2 "fstar.%sint%s" u w |> Ident.lid_of_str)))
| Const_char _ ->
add_to_parsing_data (P_dep (false, ("fstar.char" |> Ident.lid_of_str)))
| Const_range_of
| Const_set_range_of ->
add_to_parsing_data (P_dep (false, ("fstar.range" |> Ident.lid_of_str)))
| Const_real _ ->
add_to_parsing_data (P_dep (false, ("fstar.real" |> Ident.lid_of_str)))
| _ ->
()
and collect_term' = function
| Wild ->
()
| Const c ->
collect_constant c
| Op (_, ts) ->
List.iter collect_term ts
| Tvar _
| AST.Uvar _ ->
()
| Var lid
| AST.Projector (lid, _)
| AST.Discrim lid
| Name lid ->
add_to_parsing_data (P_lid lid)
| Construct (lid, termimps) ->
add_to_parsing_data (P_lid lid);
List.iter (fun (t, _) -> collect_term t) termimps
| Function (branches, _) ->
collect_branches branches
| Abs (pats, t) ->
collect_patterns pats;
collect_term t
| App (t1, t2, _) ->
collect_term t1;
collect_term t2
| Let (_, patterms, t) ->
List.iter (fun (attrs_opt, (pat, t)) ->
ignore (BU.map_opt attrs_opt (List.iter collect_term));
collect_pattern pat;
collect_term t)
patterms;
collect_term t
| LetOperator (lets, body) ->
List.iter (fun (ident, pat, def) ->
collect_pattern pat;
collect_term def
) lets;
collect_term body
| LetOpen (lid, t) ->
add_to_parsing_data (P_open (true, lid));
collect_term t
| LetOpenRecord (r, rty, e) ->
collect_term r;