refactor(tvix/eval) s/NixPath/NixSearchPath/

Since NixString is the Rust type for nix strings, people might
mistake NixPath for the Rust type of nix paths, which it is not.
Let's call it NixSearchPath instead.

Signed-off-by: Adam Joseph <adam@westernsemico.com>
Change-Id: Ib2ea155c4b27cb90d6180a04ea7b951d86607373
Reviewed-on: https://cl.tvl.fyi/c/depot/+/6927
Reviewed-by: kanepyork <rikingcoding@gmail.com>
Tested-by: BuildkiteCI
Reviewed-by: tazjin <tazjin@tvl.su>
This commit is contained in:
Adam Joseph 2022-10-10 11:43:51 -07:00
parent 04fccd89a5
commit 32ac7d6c6d
5 changed files with 49 additions and 46 deletions

View file

@ -3,7 +3,7 @@ use std::{cell::RefCell, path::PathBuf, rc::Rc};
use crate::{ use crate::{
builtins::global_builtins, builtins::global_builtins,
errors::{Error, ErrorKind, EvalResult}, errors::{Error, ErrorKind, EvalResult},
nix_path::NixPath, nix_search_path::NixSearchPath,
observer::{DisassemblingObserver, NoOpObserver, TracingObserver}, observer::{DisassemblingObserver, NoOpObserver, TracingObserver},
value::Value, value::Value,
SourceCode, SourceCode,
@ -27,7 +27,7 @@ pub struct Options {
/// A colon-separated list of directories to use to resolve `<...>`-style paths /// A colon-separated list of directories to use to resolve `<...>`-style paths
#[cfg_attr(feature = "repl", clap(long, short = 'I', env = "NIX_PATH"))] #[cfg_attr(feature = "repl", clap(long, short = 'I', env = "NIX_PATH"))]
nix_path: Option<NixPath>, nix_search_path: Option<NixSearchPath>,
} }
pub fn interpret(code: &str, location: Option<PathBuf>, options: Options) -> EvalResult<Value> { pub fn interpret(code: &str, location: Option<PathBuf>, options: Options) -> EvalResult<Value> {
@ -111,13 +111,13 @@ pub fn interpret(code: &str, location: Option<PathBuf>, options: Options) -> Eva
let result = if options.trace_runtime { let result = if options.trace_runtime {
crate::vm::run_lambda( crate::vm::run_lambda(
options.nix_path.unwrap_or_default(), options.nix_search_path.unwrap_or_default(),
&mut TracingObserver::new(std::io::stderr()), &mut TracingObserver::new(std::io::stderr()),
result.lambda, result.lambda,
) )
} else { } else {
crate::vm::run_lambda( crate::vm::run_lambda(
options.nix_path.unwrap_or_default(), options.nix_search_path.unwrap_or_default(),
&mut NoOpObserver::default(), &mut NoOpObserver::default(),
result.lambda, result.lambda,
) )

View file

@ -12,7 +12,7 @@ mod value;
mod vm; mod vm;
mod warnings; mod warnings;
mod nix_path; mod nix_search_path;
#[cfg(test)] #[cfg(test)]
mod properties; mod properties;
#[cfg(test)] #[cfg(test)]

View file

@ -6,11 +6,11 @@ use std::str::FromStr;
use crate::errors::ErrorKind; use crate::errors::ErrorKind;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
enum NixPathEntry { enum NixSearchPathEntry {
/// Resolve subdirectories of this path within `<...>` brackets. This /// Resolve subdirectories of this path within `<...>` brackets. This
/// corresponds to bare paths within the `NIX_PATH` environment variable /// corresponds to bare paths within the `NIX_PATH` environment variable
/// ///
/// For example, with `NixPathEntry::Path("/example")` and the following /// For example, with `NixSearchPathEntry::Path("/example")` and the following
/// directory structure: /// directory structure:
/// ///
/// ```notrust /// ```notrust
@ -27,7 +27,7 @@ enum NixPathEntry {
/// Resolve paths starting with `prefix` as subdirectories of `path`. This /// Resolve paths starting with `prefix` as subdirectories of `path`. This
/// corresponds to `prefix=path` within the `NIX_PATH` environment variable. /// corresponds to `prefix=path` within the `NIX_PATH` environment variable.
/// ///
/// For example, with `NixPathEntry::Prefix { prefix: "prefix", path: /// For example, with `NixSearchPathEntry::Prefix { prefix: "prefix", path:
/// "/example" }` and the following directory structure: /// "/example" }` and the following directory structure:
/// ///
/// ```notrust /// ```notrust
@ -42,7 +42,7 @@ enum NixPathEntry {
Prefix { prefix: PathBuf, path: PathBuf }, Prefix { prefix: PathBuf, path: PathBuf },
} }
impl NixPathEntry { impl NixSearchPathEntry {
fn resolve(&self, lookup_path: &Path) -> io::Result<Option<PathBuf>> { fn resolve(&self, lookup_path: &Path) -> io::Result<Option<PathBuf>> {
let resolve_in = let resolve_in =
|parent: &Path, lookup_path: &Path| match parent.join(lookup_path).canonicalize() { |parent: &Path, lookup_path: &Path| match parent.join(lookup_path).canonicalize() {
@ -52,8 +52,8 @@ impl NixPathEntry {
}; };
match self { match self {
NixPathEntry::Path(p) => resolve_in(p, lookup_path), NixSearchPathEntry::Path(p) => resolve_in(p, lookup_path),
NixPathEntry::Prefix { prefix, path } => { NixSearchPathEntry::Prefix { prefix, path } => {
if let Ok(child_path) = lookup_path.strip_prefix(prefix) { if let Ok(child_path) = lookup_path.strip_prefix(prefix) {
resolve_in(path, child_path) resolve_in(path, child_path)
} else { } else {
@ -64,7 +64,7 @@ impl NixPathEntry {
} }
} }
impl FromStr for NixPathEntry { impl FromStr for NixSearchPathEntry {
type Err = Infallible; type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
@ -83,14 +83,14 @@ impl FromStr for NixPathEntry {
/// ///
/// This struct can be constructed by parsing a string using the [`FromStr`] /// This struct can be constructed by parsing a string using the [`FromStr`]
/// impl, or via [`str::parse`]. Nix `<...>` paths can then be resolved using /// impl, or via [`str::parse`]. Nix `<...>` paths can then be resolved using
/// [`NixPath::resolve`]. /// [`NixSearchPath::resolve`].
#[derive(Default, Debug, Clone, PartialEq, Eq)] #[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct NixPath { pub struct NixSearchPath {
entries: Vec<NixPathEntry>, entries: Vec<NixSearchPathEntry>,
} }
impl NixPath { impl NixSearchPath {
/// Attempt to resolve the given `path` within this [`NixPath`] using the /// Attempt to resolve the given `path` within this [`NixSearchPath`] using the
/// path resolution rules for `<...>`-style paths /// path resolution rules for `<...>`-style paths
#[allow(dead_code)] // TODO(grfn) #[allow(dead_code)] // TODO(grfn)
pub fn resolve<P>(&self, path: P) -> Result<PathBuf, ErrorKind> pub fn resolve<P>(&self, path: P) -> Result<PathBuf, ErrorKind>
@ -110,7 +110,7 @@ impl NixPath {
} }
} }
impl FromStr for NixPath { impl FromStr for NixSearchPath {
type Err = Infallible; type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
@ -118,7 +118,7 @@ impl FromStr for NixPath {
.split(':') .split(':')
.map(|s| s.parse()) .map(|s| s.parse())
.collect::<Result<Vec<_>, _>>()?; .collect::<Result<Vec<_>, _>>()?;
Ok(NixPath { entries }) Ok(NixSearchPath { entries })
} }
} }
@ -132,11 +132,11 @@ mod tests {
#[test] #[test]
fn bare_paths() { fn bare_paths() {
assert_eq!( assert_eq!(
NixPath::from_str("/foo/bar:/baz").unwrap(), NixSearchPath::from_str("/foo/bar:/baz").unwrap(),
NixPath { NixSearchPath {
entries: vec![ entries: vec![
NixPathEntry::Path("/foo/bar".into()), NixSearchPathEntry::Path("/foo/bar".into()),
NixPathEntry::Path("/baz".into()) NixSearchPathEntry::Path("/baz".into())
], ],
} }
); );
@ -145,14 +145,14 @@ mod tests {
#[test] #[test]
fn mixed_prefix_and_paths() { fn mixed_prefix_and_paths() {
assert_eq!( assert_eq!(
NixPath::from_str("nixpkgs=/my/nixpkgs:/etc/nixos").unwrap(), NixSearchPath::from_str("nixpkgs=/my/nixpkgs:/etc/nixos").unwrap(),
NixPath { NixSearchPath {
entries: vec![ entries: vec![
NixPathEntry::Prefix { NixSearchPathEntry::Prefix {
prefix: "nixpkgs".into(), prefix: "nixpkgs".into(),
path: "/my/nixpkgs".into() path: "/my/nixpkgs".into()
}, },
NixPathEntry::Path("/etc/nixos".into()) NixSearchPathEntry::Path("/etc/nixos".into())
], ],
} }
); );
@ -168,15 +168,15 @@ mod tests {
#[test] #[test]
fn simple_dir() { fn simple_dir() {
let nix_path = NixPath::from_str("./.").unwrap(); let nix_search_path = NixSearchPath::from_str("./.").unwrap();
let res = nix_path.resolve("src").unwrap(); let res = nix_search_path.resolve("src").unwrap();
assert_eq!(res, current_dir().unwrap().join("src").clean()); assert_eq!(res, current_dir().unwrap().join("src").clean());
} }
#[test] #[test]
fn failed_resolution() { fn failed_resolution() {
let nix_path = NixPath::from_str("./.").unwrap(); let nix_search_path = NixSearchPath::from_str("./.").unwrap();
let err = nix_path.resolve("nope").unwrap_err(); let err = nix_search_path.resolve("nope").unwrap_err();
assert!( assert!(
matches!(err, ErrorKind::PathResolution(..)), matches!(err, ErrorKind::PathResolution(..)),
"err = {err:?}" "err = {err:?}"
@ -185,22 +185,22 @@ mod tests {
#[test] #[test]
fn second_in_path() { fn second_in_path() {
let nix_path = NixPath::from_str("./.:/").unwrap(); let nix_search_path = NixSearchPath::from_str("./.:/").unwrap();
let res = nix_path.resolve("bin").unwrap(); let res = nix_search_path.resolve("bin").unwrap();
assert_eq!(res, Path::new("/bin")); assert_eq!(res, Path::new("/bin"));
} }
#[test] #[test]
fn prefix() { fn prefix() {
let nix_path = NixPath::from_str("/:tvix=.").unwrap(); let nix_search_path = NixSearchPath::from_str("/:tvix=.").unwrap();
let res = nix_path.resolve("tvix/src").unwrap(); let res = nix_search_path.resolve("tvix/src").unwrap();
assert_eq!(res, current_dir().unwrap().join("src").clean()); assert_eq!(res, current_dir().unwrap().join("src").clean());
} }
#[test] #[test]
fn matching_prefix() { fn matching_prefix() {
let nix_path = NixPath::from_str("/:tvix=.").unwrap(); let nix_search_path = NixSearchPath::from_str("/:tvix=.").unwrap();
let res = nix_path.resolve("tvix").unwrap(); let res = nix_search_path.resolve("tvix").unwrap();
assert_eq!(res, current_dir().unwrap().clean()); assert_eq!(res, current_dir().unwrap().clean());
} }
} }

View file

@ -113,9 +113,9 @@ pub enum OpCode {
OpCoerceToString, OpCoerceToString,
// Paths // Paths
/// Attempt to resolve the Value on the stack using the configured [`NixPath`][] /// Attempt to resolve the Value on the stack using the configured [`NixSearchPath`][]
/// ///
/// [`NixPath`]: crate::nix_path::NixPath /// [`NixSearchPath`]: crate::nix_search_path::NixSearchPath
OpFindFile, OpFindFile,
// Type assertion operators // Type assertion operators

View file

@ -8,7 +8,7 @@ use path_clean::PathClean;
use crate::{ use crate::{
chunk::Chunk, chunk::Chunk,
errors::{Error, ErrorKind, EvalResult}, errors::{Error, ErrorKind, EvalResult},
nix_path::NixPath, nix_search_path::NixSearchPath,
observer::RuntimeObserver, observer::RuntimeObserver,
opcode::{CodeIdx, Count, JumpOffset, OpCode, StackIdx, UpvalueIdx}, opcode::{CodeIdx, Count, JumpOffset, OpCode, StackIdx, UpvalueIdx},
upvalues::{UpvalueCarrier, Upvalues}, upvalues::{UpvalueCarrier, Upvalues},
@ -50,7 +50,7 @@ pub struct VM<'o> {
/// Runtime warnings collected during evaluation. /// Runtime warnings collected during evaluation.
warnings: Vec<EvalWarning>, warnings: Vec<EvalWarning>,
nix_path: NixPath, nix_search_path: NixSearchPath,
observer: &'o mut dyn RuntimeObserver, observer: &'o mut dyn RuntimeObserver,
} }
@ -142,9 +142,9 @@ macro_rules! cmp_op {
} }
impl<'o> VM<'o> { impl<'o> VM<'o> {
pub fn new(nix_path: NixPath, observer: &'o mut dyn RuntimeObserver) -> Self { pub fn new(nix_search_path: NixSearchPath, observer: &'o mut dyn RuntimeObserver) -> Self {
Self { Self {
nix_path, nix_search_path,
observer, observer,
frames: vec![], frames: vec![],
stack: vec![], stack: vec![],
@ -518,7 +518,10 @@ impl<'o> VM<'o> {
OpCode::OpFindFile => { OpCode::OpFindFile => {
let path = self.pop().to_str().map_err(|e| self.error(e))?; let path = self.pop().to_str().map_err(|e| self.error(e))?;
let resolved = self.nix_path.resolve(path).map_err(|e| self.error(e))?; let resolved = self
.nix_search_path
.resolve(path)
.map_err(|e| self.error(e))?;
self.push(resolved.into()); self.push(resolved.into());
} }
@ -887,11 +890,11 @@ fn unwrap_or_clone_rc<T: Clone>(rc: Rc<T>) -> T {
} }
pub fn run_lambda( pub fn run_lambda(
nix_path: NixPath, nix_search_path: NixSearchPath,
observer: &mut dyn RuntimeObserver, observer: &mut dyn RuntimeObserver,
lambda: Rc<Lambda>, lambda: Rc<Lambda>,
) -> EvalResult<RuntimeResult> { ) -> EvalResult<RuntimeResult> {
let mut vm = VM::new(nix_path, observer); let mut vm = VM::new(nix_search_path, observer);
vm.enter_frame(lambda, Upvalues::with_capacity(0), 0)?; vm.enter_frame(lambda, Upvalues::with_capacity(0), 0)?;
let value = vm.pop(); let value = vm.pop();
vm.force_for_output(&value)?; vm.force_for_output(&value)?;