about summary refs log tree commit diff
path: root/tvix/eval/src/builtins/impure.rs
blob: d91f703a6ab7c15cf090acbadbdf23a3d27bb0bd (plain) (blame)
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
use builtin_macros::builtins;
use std::{
    collections::BTreeMap,
    env, io,
    rc::{Rc, Weak},
    time::{SystemTime, UNIX_EPOCH},
};

use crate::{
    compiler::GlobalsMap,
    errors::ErrorKind,
    observer::NoOpObserver,
    spans::LightSpan,
    value::{Builtin, BuiltinArgument, NixAttrs, Thunk},
    vm::VM,
    SourceCode, Value,
};

#[builtins]
mod impure_builtins {
    use super::*;
    use crate::builtins::coerce_value_to_path;

    #[builtin("getEnv")]
    fn builtin_get_env(_: &mut VM, var: Value) -> Result<Value, ErrorKind> {
        Ok(env::var(var.to_str()?).unwrap_or_else(|_| "".into()).into())
    }

    #[builtin("pathExists")]
    fn builtin_path_exists(vm: &mut VM, s: Value) -> Result<Value, ErrorKind> {
        let path = coerce_value_to_path(&s, vm)?;
        vm.io().path_exists(path).map(Value::Bool)
    }

    #[builtin("readDir")]
    fn builtin_read_dir(vm: &mut VM, path: Value) -> Result<Value, ErrorKind> {
        let path = coerce_value_to_path(&path, vm)?;
        let mk_err = |err: io::Error| ErrorKind::IO {
            path: Some(path.clone()),
            error: Rc::new(err),
        };

        let res = path.read_dir().map_err(mk_err)?.into_iter().flat_map(
            |entry| -> Result<(String, &str), ErrorKind> {
                let entry = entry.map_err(mk_err)?;
                let file_type = entry
                    .metadata()
                    .map_err(|err| ErrorKind::IO {
                        path: Some(entry.path()),
                        error: Rc::new(err),
                    })?
                    .file_type();
                let val = if file_type.is_dir() {
                    "directory"
                } else if file_type.is_file() {
                    "regular"
                } else if file_type.is_symlink() {
                    "symlink"
                } else {
                    "unknown"
                };
                Ok((entry.file_name().to_string_lossy().to_string(), val))
            },
        );
        Ok(Value::attrs(NixAttrs::from_iter(res)))
    }

    #[builtin("readFile")]
    fn builtin_read_file(vm: &mut VM, path: Value) -> Result<Value, ErrorKind> {
        let path = coerce_value_to_path(&path, vm)?;
        vm.io()
            .read_to_string(path)
            .map(|s| Value::String(s.into()))
    }
}

/// Return all impure builtins, that is all builtins which may perform I/O
/// outside of the VM and so cannot be used in all contexts (e.g. WASM).
pub(super) fn builtins() -> BTreeMap<&'static str, Value> {
    let mut map: BTreeMap<&'static str, Value> = impure_builtins::builtins()
        .into_iter()
        .map(|b| (b.name(), Value::Builtin(b)))
        .collect();

    // currentTime pins the time at which evaluation was started
    {
        let seconds = match SystemTime::now().duration_since(UNIX_EPOCH) {
            Ok(dur) => dur.as_secs() as i64,

            // This case is hit if the system time is *before* epoch.
            Err(err) => -(err.duration().as_secs() as i64),
        };

        map.insert("currentTime", Value::Integer(seconds));
    }

    map
}

/// Constructs and inserts the `import` builtin. This builtin is special in that
/// it needs to capture the [crate::SourceCode] structure to correctly track
/// source code locations while invoking a compiler.
// TODO: need to be able to pass through a CompilationObserver, too.
pub fn builtins_import(globals: &Weak<GlobalsMap>, source: SourceCode) -> Builtin {
    // This (very cheap, once-per-compiler-startup) clone exists
    // solely in order to keep the borrow checker happy.  It
    // resolves the tension between the requirements of
    // Rc::new_cyclic() and Builtin::new()
    let globals = globals.clone();

    Builtin::new(
        "import",
        &[BuiltinArgument {
            strict: true,
            name: "path",
        }],
        None,
        move |mut args: Vec<Value>, vm: &mut VM| {
            let mut path = super::coerce_value_to_path(&args.pop().unwrap(), vm)?;
            if path.is_dir() {
                path.push("default.nix");
            }

            let current_span = vm.current_span();

            if let Some(cached) = vm.import_cache.get(&path) {
                return Ok(cached.clone());
            }

            let contents = vm.io().read_to_string(path.clone())?;

            let parsed = rnix::ast::Root::parse(&contents);
            let errors = parsed.errors();

            let file = source.add_file(path.to_string_lossy().to_string(), contents);

            if !errors.is_empty() {
                return Err(ErrorKind::ImportParseError {
                    path,
                    file,
                    errors: errors.to_vec(),
                });
            }

            let result = crate::compiler::compile(
                &parsed.tree().expr().unwrap(),
                Some(path.clone()),
                file,
                // The VM must ensure that a strong reference to the
                // globals outlives any self-references (which are
                // weak) embedded within the globals.  If the
                // expect() below panics, it means that did not
                // happen.
                globals
                    .upgrade()
                    .expect("globals dropped while still in use"),
                &mut NoOpObserver::default(),
            )
            .map_err(|err| ErrorKind::ImportCompilerError {
                path: path.clone(),
                errors: vec![err],
            })?;

            if !result.errors.is_empty() {
                return Err(ErrorKind::ImportCompilerError {
                    path,
                    errors: result.errors,
                });
            }

            // Compilation succeeded, we can construct a thunk from whatever it spat
            // out and return that.
            let res = Value::Thunk(Thunk::new_suspended(
                result.lambda,
                LightSpan::new_actual(current_span),
            ));

            vm.import_cache.insert(path, res.clone());

            for warning in result.warnings {
                vm.push_warning(warning);
            }

            Ok(res)
        },
    )
}