-
Notifications
You must be signed in to change notification settings - Fork 92
/
cache.rs
1544 lines (1409 loc) · 61 KB
/
cache.rs
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
//! Source cache.
use crate::error::{Error, ImportError, ParseError, ParseErrors, TypecheckError};
use crate::eval::cache::Cache as EvalCache;
use crate::eval::Closure;
#[cfg(feature = "nix-experimental")]
use crate::nix_ffi;
use crate::parser::{lexer::Lexer, ErrorTolerantParser};
use crate::position::TermPos;
use crate::program::FieldPath;
use crate::stdlib::{self as nickel_stdlib, StdlibModule};
use crate::term::array::Array;
use crate::term::record::{Field, RecordData};
use crate::term::{RichTerm, SharedTerm, Term};
use crate::transform::import_resolution;
use crate::typ::UnboundTypeVariableError;
use crate::typecheck::{self, type_check, Wildcards};
use crate::{eval, parser, transform};
use codespan::{FileId, Files};
use io::Read;
use serde::Deserialize;
use std::collections::hash_map;
use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::result::Result;
use std::time::SystemTime;
use void::Void;
/// Supported input formats.
#[derive(Default, Clone, Copy, Eq, Debug, PartialEq)]
pub enum InputFormat {
#[default]
Nickel,
Json,
Yaml,
Toml,
#[cfg(feature = "nix-experimental")]
Nix,
Raw,
}
impl InputFormat {
/// Returns an [InputFormat] based on the file extension of a path.
pub fn from_path(path: &Path) -> Option<InputFormat> {
match path.extension().and_then(OsStr::to_str) {
Some("ncl") => Some(InputFormat::Nickel),
Some("json") => Some(InputFormat::Json),
Some("yaml") | Some("yml") => Some(InputFormat::Yaml),
Some("toml") => Some(InputFormat::Toml),
#[cfg(feature = "nix-experimental")]
Some("nix") => Some(InputFormat::Nix),
Some("txt") => Some(InputFormat::Raw),
_ => None,
}
}
}
/// File and terms cache.
///
/// Manage a file database, which stores a set of sources (the original source code as string) and
/// the corresponding parsed terms. The storage comprises three elements:
///
/// - The file database, holding the string content of sources indexed by unique `FileId`
/// identifiers.
/// - The name-id table, associating source names for standalone inputs, or paths and timestamps
/// for files, to `FileId`s.
/// - The term cache, holding parsed terms indexed by `FileId`s.
///
/// Terms possibly undergo typechecking and program transformation. The state of each entry (that
/// is, the operations that have been performed on this term) is stored in an [EntryState].
#[derive(Debug, Clone)]
pub struct Cache {
/// The content of the program sources plus imports.
files: Files<String>,
file_paths: HashMap<FileId, SourcePath>,
/// The name-id table, holding file ids stored in the database indexed by source names.
file_ids: HashMap<SourcePath, NameIdEntry>,
/// Map containing for each FileId a list of files they import (directly).
imports: HashMap<FileId, HashSet<FileId>>,
/// Map containing for each FileId a list of files importing them (directly).
rev_imports: HashMap<FileId, HashSet<FileId>>,
/// The table storing parsed terms corresponding to the entries of the file database.
terms: HashMap<FileId, TermEntry>,
/// The list of ids corresponding to the stdlib modules
stdlib_ids: Option<HashMap<StdlibModule, FileId>>,
/// The inferred type of wildcards for each `FileId`.
wildcards: HashMap<FileId, Wildcards>,
/// Whether processing should try to continue even in case of errors. Needed by the NLS.
error_tolerance: ErrorTolerance,
import_paths: Vec<PathBuf>,
#[cfg(debug_assertions)]
/// Skip loading the stdlib, used for debugging purpose
pub skip_stdlib: bool,
}
/// The error tolerance mode used by the parser. The NLS needs to try to
/// continue even in case of errors.
#[derive(Debug, Clone)]
pub enum ErrorTolerance {
Tolerant,
Strict,
}
/// The different environments maintained during the REPL session for evaluation and typechecking.
#[derive(Debug, Clone)]
pub struct Envs {
/// The eval environment.
pub eval_env: eval::Environment,
/// The typing context.
pub type_ctxt: typecheck::Context,
}
impl Envs {
pub fn new() -> Self {
Envs {
eval_env: eval::Environment::new(),
type_ctxt: typecheck::Context::new(),
}
}
}
impl Default for Envs {
fn default() -> Self {
Self::new()
}
}
/// An entry in the term cache. Stores the parsed term together with some metadata and state.
#[derive(Debug, Clone, PartialEq)]
pub struct TermEntry {
pub term: RichTerm,
pub state: EntryState,
/// Any non fatal parse errors.
pub parse_errs: ParseErrors,
}
/// Inputs can be read from the filesystem or from in-memory buffers (which come, e.g., from
/// the REPL, the standard library, or the language server).
///
/// Inputs read from the filesystem get auto-refreshed: if we try to access them again and
/// the on-disk file has changed, we read it again. Inputs read from in-memory buffers
/// are not auto-refreshed. If an in-memory buffer has a path that also exists in the
/// filesystem, we will not even check that file to see if it has changed.
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
enum SourceKind {
Filesystem(SystemTime),
Memory,
}
/// Cache keys for sources.
///
/// A source can be either a snippet input by the user, in which case it is only identified by its
/// name in the name-id table, and a unique `FileId`. On the other hand, different versions of the
/// same file can coexist during the same session of the REPL. For this reason, an entry of the
/// name-id table of a file also stores the *modified at* timestamp, such that if a file is
/// imported or loaded again and has been modified in between, the entry is invalidated, the
/// content is loaded again and a new `FileId` is generated.
///
/// Note that in that case, invalidation just means that the `FileId` of a previous version is not
/// accessible anymore in the name-id table. However, terms that contain non evaluated imports or
/// source locations referring to previous version are still able access the corresponding source
/// or term which are kept respectively in `files` and `cache` by using the corresponding `FileId`.
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
pub struct NameIdEntry {
id: FileId,
source: SourceKind,
}
/// The state of an entry of the term cache.
///
/// # Imports
///
/// Usually, when applying a procedure to an entry (typechecking, transformation, ...), we process
/// all of its transitive imports as well. We start by processing the entry, updating the state to
/// `XXXing` (ex: `Typechecking`) upon success. Only when all the imports have been successfully
/// processed, the state is updated to `XXXed` (ex: `Typechecked`).
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
pub enum EntryState {
/// The term have just been parsed.
Parsed,
/// The imports of the entry have been resolved, and the imports of its (transitive) imports are
/// being resolved.
ImportsResolving,
/// The imports of the entry and its transitive dependencies has been resolved.
ImportsResolved,
/// The entry have been typechecked, and its (transitive) imports are being typechecked.
Typechecking,
/// The entry and its transitive imports have been typechecked.
Typechecked,
/// The entry have been transformed, and its (transitive) imports are being transformed.
Transforming,
/// The entry and its transitive imports have been transformed.
Transformed,
}
pub enum EntryOrigin {}
/// The result of a cache operation, such as parsing, typechecking, etc. which can either have
/// performed actual work, or have done nothing if the corresponding entry was already at a later
/// stage.
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
pub enum CacheOp<T> {
Done(T),
Cached(T),
}
impl<T> CacheOp<T> {
pub fn inner(self: CacheOp<T>) -> T {
match self {
CacheOp::Done(t) | CacheOp::Cached(t) => t,
}
}
}
/// Wrapper around other errors to indicate that typechecking or applying program transformations
/// failed because the source has not been parsed yet.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum CacheError<E> {
Error(E),
NotParsed,
}
impl<E> From<E> for CacheError<E> {
fn from(e: E) -> Self {
CacheError::Error(e)
}
}
impl<E> CacheError<E> {
#[track_caller]
pub fn unwrap_error(self, msg: &str) -> E {
match self {
CacheError::Error(err) => err,
CacheError::NotParsed => panic!("{}", msg),
}
}
}
/// Input data usually comes from files on the file system, but there are also
/// lots of cases where we want to synthesize other kinds of inputs.
///
/// Note that a `SourcePath` does not uniquely identify a cached input:
/// - Some functions (like [`Cache::add_file`]) add a new cached input unconditionally.
/// - [`Cache::get_or_add_file`] will add a new cached input at the same `SourcePath` if
/// the file on disk was updated.
///
/// The equality checking of `SourcePath` only affects [`Cache::replace_string`], which
/// overwrites any previous cached input with the same `SourcePath`.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum SourcePath {
/// A file at the given path.
///
/// Note that this does not need to be a real file on the filesystem: it could still
/// be loaded from memory by, e.g, [`Cache::add_string`].
///
/// This is the only `SourcePath` variant that can be resolved as the target
/// of an import statement.
Path(PathBuf),
/// A subrange of a file at the given path.
///
/// This is used by nls to analyze small parts of files that don't fully parse. The
/// original file path is preserved, because it's needed for resolving imports.
Snippet(PathBuf),
Std(StdlibModule),
Query,
ReplInput(usize),
ReplTypecheck,
ReplQuery,
CliFieldAssignment,
Override(FieldPath),
Generated(String),
}
impl<'a> TryFrom<&'a SourcePath> for &'a OsStr {
type Error = ();
fn try_from(value: &'a SourcePath) -> Result<Self, Self::Error> {
match value {
SourcePath::Path(p) | SourcePath::Snippet(p) => Ok(p.as_os_str()),
_ => Err(()),
}
}
}
// [`Files`] needs to have an OsString for each file, so we synthesize names even for
// sources that don't have them. They don't need to be unique; they're just used for
// diagnostics.
impl From<SourcePath> for OsString {
fn from(source_path: SourcePath) -> Self {
match source_path {
SourcePath::Path(p) | SourcePath::Snippet(p) => p.into(),
SourcePath::Std(StdlibModule::Std) => "<stdlib/std.ncl>".into(),
SourcePath::Std(StdlibModule::Internals) => "<stdlib/internals.ncl>".into(),
SourcePath::Query => "<query>".into(),
SourcePath::ReplInput(idx) => format!("<repl-input-{idx}>").into(),
SourcePath::ReplTypecheck => "<repl-typecheck>".into(),
SourcePath::ReplQuery => "<repl-query>".into(),
SourcePath::CliFieldAssignment => "<cli-assignment>".into(),
SourcePath::Override(path) => format!("<override {path}>",).into(),
SourcePath::Generated(description) => format!("<generated {}>", description).into(),
}
}
}
/// Return status indicating if an import has been resolved from a file (first encounter), or was
/// retrieved from the cache.
///
/// See [ImportResolver::resolve].
#[derive(Debug, PartialEq, Eq)]
pub enum ResolvedTerm {
FromFile {
path: PathBuf, /* the loaded path */
},
FromCache,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum SourceState {
UpToDate(FileId),
/// The source is stale because it came from a file on disk that has since been updated.
/// The data is the timestamp of the new version of the file.
Stale(SystemTime),
}
impl Cache {
pub fn new(error_tolerance: ErrorTolerance) -> Self {
Cache {
files: Files::new(),
file_ids: HashMap::new(),
file_paths: HashMap::new(),
terms: HashMap::new(),
wildcards: HashMap::new(),
imports: HashMap::new(),
rev_imports: HashMap::new(),
stdlib_ids: None,
error_tolerance,
import_paths: Vec::new(),
#[cfg(debug_assertions)]
skip_stdlib: false,
}
}
pub fn add_import_paths<P>(&mut self, paths: impl Iterator<Item = P>)
where
PathBuf: From<P>,
{
self.import_paths.extend(paths.map(PathBuf::from));
}
/// Same as [Self::add_file], but assume that the path is already normalized, and take the
/// timestamp as a parameter.
fn add_file_(&mut self, path: PathBuf, timestamp: SystemTime) -> io::Result<FileId> {
let contents = std::fs::read_to_string(&path)?;
let file_id = self.files.add(&path, contents);
self.file_paths
.insert(file_id, SourcePath::Path(path.clone()));
self.file_ids.insert(
SourcePath::Path(path),
NameIdEntry {
id: file_id,
source: SourceKind::Filesystem(timestamp),
},
);
Ok(file_id)
}
/// Load a file from the filesystem and add it to the name-id table.
///
/// Uses the normalized path and the *modified at* timestamp as the name-id table entry.
/// Overrides any existing entry with the same name.
pub fn add_file(&mut self, path: impl Into<OsString>) -> io::Result<FileId> {
let path = path.into();
let timestamp = timestamp(&path)?;
let normalized = normalize_path(&path)?;
self.add_file_(normalized, timestamp)
}
/// Try to retrieve the id of a file from the cache.
///
/// If it was not in cache, try to read it from the filesystem and add it as a new entry.
pub fn get_or_add_file(&mut self, path: impl Into<OsString>) -> io::Result<CacheOp<FileId>> {
let path = path.into();
let normalized = normalize_path(&path)?;
match self.id_or_new_timestamp_of(path.as_ref())? {
SourceState::UpToDate(id) => Ok(CacheOp::Cached(id)),
SourceState::Stale(timestamp) => {
self.add_file_(normalized, timestamp).map(CacheOp::Done)
}
}
}
/// Load a source and add it to the name-id table.
///
/// Do not check if a source with the same name already exists: if it is the
/// case, this one will override the old entry in the name-id table.
pub fn add_source<T>(&mut self, source_name: SourcePath, mut source: T) -> io::Result<FileId>
where
T: Read,
{
let mut buffer = String::new();
source.read_to_string(&mut buffer)?;
Ok(self.add_string(source_name, buffer))
}
pub fn source(&self, id: FileId) -> &str {
self.files.source(id)
}
/// Load a new source as a string and add it to the name-id table.
///
/// Do not check if a source with the same name already exists: if it is the case, this one
/// will override the old entry in the name-id table but the old `FileId` will remain valid.
pub fn add_string(&mut self, source_name: SourcePath, s: String) -> FileId {
let id = self.files.add(source_name.clone(), s);
self.file_paths.insert(id, source_name.clone());
self.file_ids.insert(
source_name,
NameIdEntry {
id,
source: SourceKind::Memory,
},
);
id
}
/// Load a new source as a string, replacing any existing source with the same name.
///
/// If there was a previous source with the same name, its `FileId` is reused and the
/// cached term is deleted.
///
/// Used to store intermediate short-lived generated snippets that needs to have a
/// corresponding `FileId`, such as when querying or reporting errors.
pub fn replace_string(&mut self, source_name: SourcePath, s: String) -> FileId {
if let Some(file_id) = self.id_of(&source_name) {
self.files.update(file_id, s);
self.terms.remove(&file_id);
file_id
} else {
let file_id = self.files.add(source_name.clone(), s);
self.file_paths.insert(file_id, source_name.clone());
self.file_ids.insert(
source_name,
NameIdEntry {
id: file_id,
source: SourceKind::Memory,
},
);
file_id
}
}
/// Parse a source and populate the corresponding entry in the cache, or do nothing if the
/// entry has already been parsed. This function is error tolerant: parts of the source which
/// result in parse errors are parsed as [`crate::term::Term::ParseError`] and the
/// corresponding error messages are collected and returned.
///
/// The `Err` part of the result corresponds to non-recoverable errors.
fn parse_lax(&mut self, file_id: FileId) -> Result<CacheOp<ParseErrors>, ParseError> {
if let Some(TermEntry { parse_errs, .. }) = self.terms.get(&file_id) {
Ok(CacheOp::Cached(parse_errs.clone()))
} else {
let (term, parse_errs) = self.parse_nocache(file_id)?;
self.terms.insert(
file_id,
TermEntry {
term,
state: EntryState::Parsed,
parse_errs: parse_errs.clone(),
},
);
Ok(CacheOp::Done(parse_errs))
}
}
/// Parse a source and populate the corresponding entry in the cache, or do
/// nothing if the entry has already been parsed. This function is error
/// tolerant if `self.error_tolerant` is `true`.
pub fn parse(&mut self, file_id: FileId) -> Result<CacheOp<ParseErrors>, ParseErrors> {
let result = self.parse_lax(file_id);
match self.error_tolerance {
ErrorTolerance::Tolerant => result.map_err(|err| err.into()),
ErrorTolerance::Strict => match result? {
CacheOp::Done(e) | CacheOp::Cached(e) if !e.no_errors() => Err(e),
CacheOp::Done(_) => Ok(CacheOp::Done(ParseErrors::none())),
CacheOp::Cached(_) => Ok(CacheOp::Cached(ParseErrors::none())),
},
}
}
/// Parse a source and populate the corresponding entry in the cache, or do
/// nothing if the entry has already been parsed. Support multiple formats.
/// This function is always error tolerant, independently from `self.error_tolerant`.
fn parse_multi_lax(
&mut self,
file_id: FileId,
format: InputFormat,
) -> Result<CacheOp<ParseErrors>, ParseError> {
if let Some(TermEntry { parse_errs, .. }) = self.terms.get(&file_id) {
Ok(CacheOp::Cached(parse_errs.clone()))
} else {
let (term, parse_errs) = self.parse_nocache_multi(file_id, format)?;
self.terms.insert(
file_id,
TermEntry {
term,
state: EntryState::Parsed,
parse_errs: parse_errs.clone(),
},
);
Ok(CacheOp::Done(parse_errs))
}
}
/// Parse a source and populate the corresponding entry in the cache, or do
/// nothing if the entry has already been parsed. Support multiple formats.
/// This function is error tolerant if `self.error_tolerant` is `true`.
pub fn parse_multi(
&mut self,
file_id: FileId,
format: InputFormat,
) -> Result<CacheOp<ParseErrors>, ParseErrors> {
let result = self.parse_multi_lax(file_id, format);
match self.error_tolerance {
ErrorTolerance::Tolerant => result.map_err(|err| err.into()),
ErrorTolerance::Strict => match result? {
CacheOp::Done(e) | CacheOp::Cached(e) if !e.no_errors() => Err(e),
CacheOp::Done(_) => Ok(CacheOp::Done(ParseErrors::none())),
CacheOp::Cached(_) => Ok(CacheOp::Cached(ParseErrors::none())),
},
}
}
/// Parse a source without querying nor populating the cache.
pub fn parse_nocache(&self, file_id: FileId) -> Result<(RichTerm, ParseErrors), ParseError> {
self.parse_nocache_multi(file_id, InputFormat::default())
}
/// Parse a source without querying nor populating the cache. Support multiple formats.
pub fn parse_nocache_multi(
&self,
file_id: FileId,
format: InputFormat,
) -> Result<(RichTerm, ParseErrors), ParseError> {
let attach_pos = |t: RichTerm| -> RichTerm {
let pos: TermPos =
crate::position::RawSpan::from_codespan(file_id, self.files.source_span(file_id))
.into();
t.with_pos(pos)
};
let buf = self.files.source(file_id);
match format {
InputFormat::Nickel => {
let (t, parse_errs) =
// TODO: Should this really be parse_term if self.error_tolerant = false?
parser::grammar::TermParser::new().parse_tolerant(file_id, Lexer::new(buf))?;
Ok((t, parse_errs))
}
InputFormat::Json => serde_json::from_str(self.files.source(file_id))
.map(|t| (attach_pos(t), ParseErrors::default()))
.map_err(|err| ParseError::from_serde_json(err, file_id, &self.files)),
InputFormat::Yaml => {
// YAML files can contain multiple documents. If there is only
// one we transparently deserialize it. If there are multiple,
// we deserialize the file as an array.
let de = serde_yaml::Deserializer::from_str(self.files.source(file_id));
let mut terms = de
.map(|de| {
RichTerm::deserialize(de)
.map(attach_pos)
.map_err(|err| (ParseError::from_serde_yaml(err, file_id)))
})
.collect::<Result<Vec<_>, _>>()?;
if terms.is_empty() {
unreachable!(
"serde always produces at least one document, \
the empty string turns into `null`"
)
} else if terms.len() == 1 {
Ok((
terms.pop().expect("we just checked the length"),
ParseErrors::default(),
))
} else {
Ok((
attach_pos(
Term::Array(
Array::new(Rc::from(terms.into_boxed_slice())),
Default::default(),
)
.into(),
),
ParseErrors::default(),
))
}
}
InputFormat::Toml => toml::from_str(self.files.source(file_id))
.map(|t| (attach_pos(t), ParseErrors::default()))
.map_err(|err| (ParseError::from_toml(err, file_id))),
#[cfg(feature = "nix-experimental")]
InputFormat::Nix => {
let json = nix_ffi::eval_to_json(self.files.source(file_id))
.map_err(|e| ParseError::from_nix(e.what(), file_id))?;
serde_json::from_str(&json)
.map(|t| (attach_pos(t), ParseErrors::default()))
.map_err(|err| ParseError::from_serde_json(err, file_id, &self.files))
}
InputFormat::Raw => Ok((
attach_pos(Term::Str(self.files.source(file_id).into()).into()),
ParseErrors::default(),
)),
}
}
/// Typecheck an entry of the cache and update its state accordingly, or do nothing if the
/// entry has already been typechecked. Require that the corresponding source has been parsed.
/// If the source contains imports, recursively typecheck on the imports too.
pub fn typecheck(
&mut self,
file_id: FileId,
initial_ctxt: &typecheck::Context,
) -> Result<CacheOp<()>, CacheError<TypecheckError>> {
match self.terms.get(&file_id) {
Some(TermEntry { state, .. }) if *state >= EntryState::Typechecked => {
Ok(CacheOp::Cached(()))
}
Some(TermEntry { term, state, .. }) if *state >= EntryState::Parsed => {
if *state < EntryState::Typechecking {
let wildcards = type_check(term, initial_ctxt.clone(), self)?;
self.update_state(file_id, EntryState::Typechecking);
self.wildcards.insert(file_id, wildcards);
if let Some(imports) = self.imports.get(&file_id).cloned() {
for f in imports.into_iter() {
self.typecheck(f, initial_ctxt)?;
}
}
self.update_state(file_id, EntryState::Typechecked);
}
// The else case correponds to `EntryState::Typechecking`. There is nothing to do:
// cf (grep for) [transitory_entry_state]
Ok(CacheOp::Done(()))
}
_ => Err(CacheError::NotParsed),
}
}
/// Apply program transformations to an entry of the cache, and update its state accordingly,
/// or do nothing if the entry has already been transformed. Require that the corresponding
/// source has been parsed.
/// If the source contains imports, recursively perform transformations on the imports too.
pub fn transform(
&mut self,
file_id: FileId,
) -> Result<CacheOp<()>, CacheError<UnboundTypeVariableError>> {
match self.entry_state(file_id) {
Some(state) if state >= EntryState::Transformed => Ok(CacheOp::Cached(())),
Some(state) if state >= EntryState::Parsed => {
if state < EntryState::Transforming {
let cached_term = self.terms.remove(&file_id).unwrap();
let term =
transform::transform(cached_term.term, self.wildcards.get(&file_id))?;
self.terms.insert(
file_id,
TermEntry {
term,
state: EntryState::Transforming,
..cached_term
},
);
if let Some(imports) = self.imports.get(&file_id).cloned() {
for f in imports.into_iter() {
self.transform(f)?;
}
}
self.update_state(file_id, EntryState::Transformed);
}
Ok(CacheOp::Done(()))
}
_ => Err(CacheError::NotParsed),
}
}
/// Apply program transformations to all the fields of a record.
///
/// Used to transform stdlib modules and other records loaded in the environment, when using
/// e.g. the `load` command of the REPL. If one just uses [Self::transform], the share normal
/// form transformation would add let bindings to a record entry `{ ... }`, turning it into
/// `let %0 = ... in ... in { ... }`. But stdlib entries are required to be syntactically
/// records.
///
/// Note that this requirement may be relaxed in the future by e.g. evaluating stdlib entries
/// before adding their fields to the initial environment.
///
/// # Preconditions
///
/// - the entry must syntactically be a record (`Record` or `RecRecord`). Otherwise, this
/// function panics
pub fn transform_inner(
&mut self,
file_id: FileId,
) -> Result<CacheOp<()>, CacheError<UnboundTypeVariableError>> {
match self.entry_state(file_id) {
Some(state) if state >= EntryState::Transformed => Ok(CacheOp::Cached(())),
Some(_) => {
let TermEntry {
mut term,
state,
parse_errs,
} = self.terms.remove(&file_id).unwrap();
let wildcards = self.wildcards.get(&file_id);
if state < EntryState::Transforming {
match SharedTerm::make_mut(&mut term.term) {
Term::Record(RecordData { ref mut fields, .. }) => {
let map_res: Result<_, UnboundTypeVariableError> =
std::mem::take(fields)
.into_iter()
.map(|(id, field)| {
Ok((
id,
field.try_map_value(|v| {
transform::transform(v, wildcards)
})?,
))
})
.collect();
*fields = map_res.map_err(CacheError::Error)?;
}
Term::RecRecord(ref mut record, ref mut dyn_fields, ..) => {
let map_res: Result<_, UnboundTypeVariableError> =
std::mem::take(&mut record.fields)
.into_iter()
.map(|(id, field)| {
Ok((
id,
field.try_map_value(|v| {
transform::transform(v, wildcards)
})?,
))
})
.collect();
let dyn_fields_res: Result<_, UnboundTypeVariableError> =
std::mem::take(dyn_fields)
.into_iter()
.map(|(id_t, mut field)| {
let value = field
.value
.take()
.map(|v| transform::transform(v, wildcards))
.transpose()?;
Ok((
transform::transform(id_t, wildcards)?,
Field { value, ..field },
))
})
.collect();
record.fields = map_res.map_err(CacheError::Error)?;
*dyn_fields = dyn_fields_res.map_err(CacheError::Error)?;
}
_ => panic!("cache::transform_inner(): not a record"),
}
self.terms.insert(
file_id,
TermEntry {
term,
state: EntryState::Transforming,
parse_errs,
},
);
if let Some(imports) = self.imports.get(&file_id).cloned() {
for f in imports.into_iter() {
self.transform(f).map_err(|_| CacheError::NotParsed)?;
}
}
self.update_state(file_id, EntryState::Transformed);
}
Ok(CacheOp::Done(()))
}
None => Err(CacheError::NotParsed),
}
}
/// Resolve every imports of an entry of the cache, and update its state accordingly, or do
/// nothing if the imports of the entry have already been resolved. Require that the
/// corresponding source has been parsed.
///
/// If resolved imports contain imports themselves, resolve them recursively. Returns a tuple
/// of vectors, where the first component is the imports that were transitively resolved, and
/// the second component is the errors it encountered while resolving imports in `file_id`,
/// respectively. Imports that were already resolved before are not included in the first
/// component: this return value is currently used by the LSP to re-run code analysis on new
/// files/modified files.
///
/// The resolved imports are ordered by a pre-order depth-first-search. In
/// particular, earlier elements in the returned list might import later
/// elements but -- unless there are cyclic imports -- later elements do not
/// import earlier elements.
///
/// It only accumulates errors if the cache is in error tolerant mode, otherwise it returns an
/// `Err(..)` containing a `CacheError`.
#[allow(clippy::type_complexity)]
pub fn resolve_imports(
&mut self,
file_id: FileId,
) -> Result<CacheOp<(Vec<FileId>, Vec<ImportError>)>, CacheError<ImportError>> {
match self.entry_state(file_id) {
Some(EntryState::Parsed) => {
let TermEntry { term, .. } = self.terms.get(&file_id).unwrap();
let term = term.clone();
let import_resolution::tolerant::ResolveResult {
transformed_term,
resolved_ids: pending,
import_errors,
} = match self.error_tolerance {
ErrorTolerance::Tolerant => {
import_resolution::tolerant::resolve_imports(term, self)
}
ErrorTolerance::Strict => {
import_resolution::strict::resolve_imports(term, self)?.into()
}
};
// unwrap!(): we called `unwrap()` at the beginning of the enclosing if branch
// on the result of `self.terms.get(&file_id)`. We only made recursive calls to
// `resolve_imports` in between, which don't remove anything from `self.terms`.
let cached_term = self.terms.get_mut(&file_id).unwrap();
cached_term.term = transformed_term;
cached_term.state = EntryState::ImportsResolving;
let mut done = Vec::new();
// Transitively resolve the imports, and accumulate the ids of the resolved
// files along the way.
for id in pending {
if let CacheOp::Done((mut done_local, _)) = self.resolve_imports(id)? {
done.push(id);
done.append(&mut done_local)
}
}
self.update_state(file_id, EntryState::ImportsResolved);
Ok(CacheOp::Done((done, import_errors)))
}
// [transitory_entry_state]:
//
// This case is triggered by a cyclic import. The entry is already
// being treated by an ongoing call to `resolve_import` higher up in
// the call chain, so we don't do anything here.
//
// Note that in some cases, this intermediate state can be observed by an
// external caller: if a first call to `resolve_imports` fails in the middle of
// resolving the transitive imports, the end state of the entry is
// `ImportsResolving`. Subsequent calls to `resolve_imports` will succeed, but
// won't change the state to `EntryState::ImportsResolved` (and for a good
// reason: we wouldn't even know what are the pending imports to resolve). The
// Nickel pipeline should however fail if `resolve_imports` failed at some
// point, anyway.
Some(EntryState::ImportsResolving) => Ok(CacheOp::Done((Vec::new(), Vec::new()))),
// >= EntryState::ImportsResolved
Some(
EntryState::ImportsResolved
| EntryState::Typechecking
| EntryState::Typechecked
| EntryState::Transforming
| EntryState::Transformed,
) => Ok(CacheOp::Cached((Vec::new(), Vec::new()))),
None => Err(CacheError::NotParsed),
}
}
/// Prepare a source for evaluation: parse it, resolve the imports,
/// typecheck it and apply program transformations,
/// if it was not already done.
pub fn prepare(
&mut self,
file_id: FileId,
initial_ctxt: &typecheck::Context,
) -> Result<CacheOp<()>, Error> {
let mut result = CacheOp::Cached(());
if let CacheOp::Done(_) = self.parse(file_id)? {
result = CacheOp::Done(());
}
let import_res = self.resolve_imports(file_id).map_err(|cache_err| {
cache_err.unwrap_error(
"cache::prepare(): expected source to be parsed before imports resolutions",
)
})?;
if let CacheOp::Done(..) = import_res {
result = CacheOp::Done(());
}
let typecheck_res = self.typecheck(file_id, initial_ctxt).map_err(|cache_err| {
cache_err
.unwrap_error("cache::prepare(): expected source to be parsed before typechecking")
})?;
if typecheck_res == CacheOp::Done(()) {
result = CacheOp::Done(());
};
let transform_res = self.transform(file_id).map_err(|cache_err| {
Error::ParseErrors(
cache_err
.unwrap_error(
"cache::prepare(): expected source to be parsed before transformations",
)
.into(),
)
})?;
if transform_res == CacheOp::Done(()) {
result = CacheOp::Done(());
};
Ok(result)
}
/// Same as [Self::prepare], but do not use nor populate the cache. Used for inputs which are
/// known to not be reused.
///
/// In this case, the caller has to process the imports themselves as needed:
/// - typechecking
/// - resolve imports performed inside these imports.
/// - apply program transformations.
pub fn prepare_nocache(
&mut self,
file_id: FileId,
initial_ctxt: &typecheck::Context,
) -> Result<(RichTerm, Vec<FileId>), Error> {
let (term, errs) = self.parse_nocache(file_id)?;
if !errs.no_errors() {
return Err(Error::ParseErrors(errs));
}
let import_resolution::strict::ResolveResult {
transformed_term: term,
resolved_ids: pending,
} = import_resolution::strict::resolve_imports(term, self)?;
let wildcards = type_check(&term, initial_ctxt.clone(), self)?;
let term = transform::transform(term, Some(&wildcards))
.map_err(|err| Error::ParseErrors(err.into()))?;
Ok((term, pending))
}
/// Retrieve the name of a source given an id.
pub fn name(&self, file_id: FileId) -> &OsStr {
self.files.name(file_id)
}
/// Retrieve the id of a source given a name.
///
/// Note that files added via [Self::add_file] are indexed by their full normalized path (cf
/// [normalize_path]).
pub fn id_of(&self, name: &SourcePath) -> Option<FileId> {
match name {
SourcePath::Path(p) => match self.id_or_new_timestamp_of(p).ok()? {
SourceState::UpToDate(id) => Some(id),
SourceState::Stale(_) => None,
},
name => Some(self.file_ids.get(name)?.id),
}
}
/// Try to retrieve the id of a cached source.
///
/// Only returns `Ok` if the source is up-to-date; if the source is stale, returns
/// either the new timestamp of the up-to-date file or the error we encountered when
/// trying to read it (which most likely means there was no such file).
///
/// The main point of this awkward signature is to minimize I/O operations: if we accessed
/// the timestamp, keep it around.
fn id_or_new_timestamp_of(&self, name: &Path) -> io::Result<SourceState> {
match self.file_ids.get(&SourcePath::Path(name.to_owned())) {
None => Ok(SourceState::Stale(timestamp(name)?)),