ronantakizawa/codereview-bench huggingface dataset:
Repository: denoland/deno
File: runtime/ops/mod.rs (Rust)

Code before:
// Copyright 2018-2025 the Deno authors. MIT license.

pub mod bootstrap;
pub mod fs_events;
pub mod http;
pub mod permissions;
pub mod runtime;
pub mod tty;
pub mod web_worker;
pub mod worker_host;

use deno_core::OpState;

/// Helper for checking unstable features. Used for sync ops.
pub fn check_unstable(state: &OpState, feature: &str, api_name: &str) {
  state.feature_checker.check_or_exit(feature, api_name);
}

pub struct TestingFeaturesEnabled(pub bool);


Review comment (suggestion):
I'm wondering if we should bury `Arc` inside `FeatureChecker`. Seems like an implementation detail. Feel free to do it in a follow up

Code after:
// Copyright 2018-2025 the Deno authors. MIT license.

pub mod bootstrap;
pub mod fs_events;
pub mod http;
pub mod permissions;
pub mod runtime;
pub mod tty;
pub mod web_worker;
pub mod worker_host;

use std::sync::Arc;

use deno_core::OpState;
use deno_features::FeatureChecker;

/// Helper for checking unstable features. Used for sync ops.
pub fn check_unstable(state: &OpState, feature: &str, api_name: &str) {
  state
    .borrow::<Arc<FeatureChecker>>()
    .check_or_exit(feature, api_name);
}

pub struct TestingFeaturesEnabled(pub bool);
Repository: denoland/deno
File: resolvers/npm_cache/lib.rs (Rust)

Code before:
              .map(|n| n.to_string())
              .collect(),
          }
        }
      }
      CacheSetting::RespectHeaders => panic!("not supported"),
      CacheSetting::Use => NpmCacheSetting::Use,
    }
  }
  pub fn should_use_for_npm_package(&self, package_name: &str) -> bool {
    match self {
      NpmCacheSetting::ReloadAll => false,
      NpmCacheSetting::ReloadSome { npm_package_names } => {
        !npm_package_names.iter().any(|n| n == package_name)
      }
      _ => true,
    }
  }
}

/// Stores a single copy of npm packages in a cache.
#[derive(Debug)]
pub struct NpmCache<
  TSys: FsCreateDirAll
    + FsHardLink
    + FsMetadata
    + FsOpen
    + FsRead
    + FsReadDir
    + FsRemoveFile
    + FsRename
    + ThreadSleep
    + SystemRandom,
> {
  cache_dir: Arc<NpmCacheDir>,
  sys: TSys,
  cache_setting: NpmCacheSetting,
  npmrc: Arc<ResolvedNpmRc>,
  previously_reloaded_packages: Mutex<HashSet<PackageNv>>,
}

impl<
    TSys: FsCreateDirAll
      + FsHardLink
      + FsMetadata
      + FsOpen
      + FsRead
      + FsReadDir
      + FsRemoveFile
      + FsRename
      + ThreadSleep

Review comment (performance):
Wonder if we should add a macro to `sys_traits` to generate these aliases. Something like

```rust
macro_rules! sys_traits_alias {
    ($name : ident : $($t: path),* $(,)?) => {
      pub trait $name: $($t +)* { }
      
      impl<T: 'static> $name for T where
        T: $($t +)+
      {
      }
    };
}
```
used like
`sys_trait_alias!(NpmCacheSys: FsCanonicalize, FsCreateDirAll, ...)`

Code after:
        } else {
          NpmCacheSetting::ReloadSome {
            npm_package_names: values
              .iter()
              .filter_map(|v| v.strip_prefix("npm:"))
              .map(|n| n.to_string())
              .collect(),
          }
        }
      }
      CacheSetting::RespectHeaders => panic!("not supported"),
      CacheSetting::Use => NpmCacheSetting::Use,
    }
  }
  pub fn should_use_for_npm_package(&self, package_name: &str) -> bool {
    match self {
      NpmCacheSetting::ReloadAll => false,
      NpmCacheSetting::ReloadSome { npm_package_names } => {
        !npm_package_names.iter().any(|n| n == package_name)
      }
      _ => true,
    }
  }
}

pub trait NpmCacheSys:
  FsCanonicalize
  + FsCreateDirAll
  + FsHardLink
  + FsMetadata
  + FsOpen
  + FsRead
  + FsReadDir
  + FsRemoveDirAll
  + FsRemoveFile
  + FsRename
  + ThreadSleep
  + SystemRandom
  + Send
  + Sync
  + Clone
  + 'static
{
}

impl<T> NpmCacheSys for T where
  T: FsCanonicalize
    + FsCreateDirAll
    + FsHardLink
    + FsMetadata
    + FsOpen
Repository: denoland/deno
File: resolvers/npm_cache/tarball_extract.rs (Rust)

Code before:
  FailedCreatingDir {
    path: PathBuf,
    #[source]
    source: std::io::Error,
  },
  #[class(generic)]
  #[error("Failed canonicalizing '{}'", path.display())]
  FailedCanonicalizing {
    path: PathBuf,
    #[source]
    source: std::io::Error,
  },
  #[class(generic)]
  #[error("Failed opening '{}'", path.display())]
  FailedOpening {
    path: PathBuf,
    #[source]
    source: std::io::Error,
  },
  #[class(generic)]
  #[error("Failed writing '{}'", path.display())]
  FailedWriting {
    path: PathBuf,
    #[source]
    source: std::io::Error,
  },
  #[class(generic)]
  #[error(
    "Extracted directory '{0}' of npm tarball was not in output directory."
  )]
  NotInOutputDirectory(PathBuf),
}

fn extract_tarball(
  sys: &(impl FsCanonicalize + FsCreateDirAll + FsOpen + FsRemoveFile),
  data: &[u8],
  output_folder: &Path,
) -> Result<(), ExtractTarballError> {
  sys.fs_create_dir_all(output_folder).map_err(|source| {
    ExtractTarballError::FailedCreatingDir {
      path: output_folder.to_path_buf(),
      source,
    }
  })?;
  let output_folder = sys.fs_canonicalize(output_folder).map_err(|source| {
    ExtractTarballError::FailedCanonicalizing {
      path: output_folder.to_path_buf(),
      source,
    }
  })?;
  let tar = GzDecoder::new(data);

Review comment (bug):
Kind of feel like we should just have a generic IO error type with a context and what kind of operation failed. Might be good for deno_error.

Code after:
    match self {
      IoErrorOperation::Creating => write!(f, "creating"),
      IoErrorOperation::Canonicalizing => write!(f, "canonicalizing"),
    }
  }
}

#[derive(Debug, thiserror::Error, deno_error::JsError)]
#[class(generic)]
#[error("Failed {} '{}'", operation, path.display())]
pub struct IoWithPathError {
  pub path: PathBuf,
  pub operation: IoErrorOperation,
  #[source]
  pub source: std::io::Error,
}

#[derive(Debug, thiserror::Error, deno_error::JsError)]
pub enum ExtractTarballError {
  #[class(inherit)]
  #[error(transparent)]
  Io(#[from] std::io::Error),
  #[class(inherit)]
  #[error(transparent)]
  IoWithPath(#[from] IoWithPathError),
  #[class(generic)]
  #[error(
    "Extracted directory '{0}' of npm tarball was not in output directory."
  )]
  NotInOutputDirectory(PathBuf),
}

fn extract_tarball(
  sys: &(impl FsCanonicalize + FsCreateDirAll + FsOpen + FsRemoveFile),
  data: &[u8],
  output_folder: &Path,
) -> Result<(), ExtractTarballError> {
  sys
    .fs_create_dir_all(output_folder)
    .map_err(|source| IoWithPathError {
      path: output_folder.to_path_buf(),
      operation: IoErrorOperation::Creating,
      source,
    })?;
  let output_folder =
    sys
      .fs_canonicalize(output_folder)
      .map_err(|source| IoWithPathError {
        path: output_folder.to_path_buf(),
        operation: IoErrorOperation::Canonicalizing,
        source,
Repository: denoland/deno
File: cli/lsp/testing/execution.rs (Rust)

Code before:
            filter.exclude.insert(test.id.clone(), test.clone());
          }
        }
      } else {
        // the entire test module is excluded
        queue.remove(&url);
      }
    }
  }

  queue.retain(|s| !tests.get(s).unwrap().0.is_empty());

  (queue, filters)
}

fn failure_to_test_message(
  test_uri: lsp::Uri,
  failure: &TestFailure,
) -> lsp_custom::TestMessage {
  let message = lsp::MarkupContent {
    kind: lsp::MarkupKind::PlainText,
    value: failure
      .format(&TestFailureFormatOptions::default())
      .to_string(),
  };
  let location = failure.error_location().map(|v| {
    let pos = lsp::Position {
      line: v.line_number,
      // TODO: The column number might be wrong if Unicode is involved
      character: v.column_number,
    };
    lsp::Location {
      // TODO: Or is there a good way of converting the v.file_name to a URI?
      uri: test_uri,
      range: lsp::Range::new(pos, pos),
    }
  });
  lsp_custom::TestMessage {
    message,
    expected_output: None,
    actual_output: None,
    location,
  }
}

#[derive(Debug, Clone, Default, PartialEq)]
struct LspTestFilter {
  include: Option<HashMap<String, TestDefinition>>,
  exclude: HashMap<String, TestDefinition>,
}


Review comment (suggestion):
Okay, I tested this. Surprisingly enough, the column number seems to be correct.

I ran a test, and then clicked on the indicator. It placed my cursor at the correct column, and visually points there.

![image](https://github.com/user-attachments/assets/f26b4b0b-a091-4d61-b3b7-e5069aff6fb0)


Code after:
            filter.exclude.insert(test.id.clone(), test.clone());
          }
        }
      } else {
        // the entire test module is excluded
        queue.remove(&url);
      }
    }
  }

  queue.retain(|s| !tests.get(s).unwrap().0.is_empty());

  (queue, filters)
}

fn failure_to_test_message(failure: &TestFailure) -> lsp_custom::TestMessage {
  let message = lsp::MarkupContent {
    kind: lsp::MarkupKind::PlainText,
    value: failure
      .format(&TestFailureFormatOptions::default())
      .to_string(),
  };
  let location = failure.error_location().and_then(|v| {
    let pos = lsp::Position {
      line: v.line_number,
      character: v.column_number,
    };
    // Does not have to match the test URI
    // since one can write `Deno.test(importedFunction)`
    let uri = uri_parse_unencoded(&v.file_name).ok()?;
    Some(lsp::Location {
      uri,
      range: lsp::Range::new(pos, pos),
    })
  });
  lsp_custom::TestMessage {
    message,
    expected_output: None,
    actual_output: None,
    location,
  }
}

#[derive(Debug, Clone, Default, PartialEq)]
struct LspTestFilter {
  include: Option<HashMap<String, TestDefinition>>,
  exclude: HashMap<String, TestDefinition>,
}

impl LspTestFilter {
  fn as_ids(&self, test_module: &TestModule) -> Vec<String> {
Repository: denoland/deno
File: cli/tools/jupyter/install.rs (Rust)

Code before:
    log::warn!(
      "ℹ️ Deno kernel is not yet installed, run `{}` to set it up",
      install_cmd
    );
    Ok(())
  }
}

fn install_icon(
  dir_path: &Path,
  filename: &str,
  icon_data: &[u8],
) -> Result<(), AnyError> {
  let path = dir_path.join(filename);
  let mut file = std::fs::File::create(path)?;
  file.write_all(icon_data)?;
  Ok(())
}

pub fn install(
  maybe_name: Option<&str>,
  maybe_display_name: Option<&str>,
  force: bool,
) -> Result<(), AnyError> {
  let user_data_dir = if let Ok(env_var) = std::env::var(TEST_ENV_VAR_NAME) {
    PathBuf::from(env_var)
  } else {
    jupyter_runtime::dirs::user_data_dir()?
  };

  let kernel_name = maybe_name.unwrap_or("deno");
  let kernel_spec_dir_path = user_data_dir.join("kernels").join(kernel_name);
  let kernel_spec_path = kernel_spec_dir_path.join("kernel.json");

  std::fs::create_dir_all(&kernel_spec_dir_path).with_context(|| {
    format!(
      "Failed to create kernel directory at {}",
      kernel_spec_dir_path.display()
    )
  })?;

  if kernel_spec_path.exists() && !force {
    bail!(
      "Deno kernel already exists at {}, run again with `--force` to overwrite it",
      kernel_spec_dir_path.display()
    );
  }

  let display_name = maybe_display_name.unwrap_or("Deno");
  let current_exe_path = current_exe()
    .context("Failed to get current executable path")?

Review comment (refactor):
```suggestion
  let user_data_dir = if let Some(env_var) = std::env::var_os(TEST_ENV_VAR_NAME) {
    PathBuf::from(env_var)
```

Deja-vu. Should this code be extracted out to a reusable function?

Code after:
    if let Some(name) = maybe_name {
      install_cmd.push_str(" --name ");
      install_cmd.push_str(name);
    }
    log::warn!(
      "ℹ️ Deno kernel is not yet installed, run `{}` to set it up",
      install_cmd
    );
    Ok(())
  }
}

fn install_icon(
  dir_path: &Path,
  filename: &str,
  icon_data: &[u8],
) -> Result<(), AnyError> {
  let path = dir_path.join(filename);
  let mut file = std::fs::File::create(path)?;
  file.write_all(icon_data)?;
  Ok(())
}

pub fn install(
  maybe_name: Option<&str>,
  maybe_display_name: Option<&str>,
  force: bool,
) -> Result<(), AnyError> {
  let user_data_dir = get_user_data_dir()?;

  let kernel_name = maybe_name.unwrap_or("deno");
  let kernel_spec_dir_path = user_data_dir.join("kernels").join(kernel_name);
  let kernel_spec_path = kernel_spec_dir_path.join("kernel.json");

  std::fs::create_dir_all(&kernel_spec_dir_path).with_context(|| {
    format!(
      "Failed to create kernel directory at {}",
      kernel_spec_dir_path.display()
    )
  })?;

  if kernel_spec_path.exists() && !force {
    bail!(
      "Deno kernel already exists at {}, run again with `--force` to overwrite it",
      kernel_spec_dir_path.display()
    );
  }

  let display_name = maybe_display_name.unwrap_or("Deno");
  let current_exe_path = current_exe()
    .context("Failed to get current executable path")?
Repository: denoland/deno
File: ext/webgpu/byow.rs (Rust)

Code before:
  #[nofast]
  fn present(&self, scope: &mut v8::HandleScope) -> Result<(), JsErrorBox> {
    let Some(context) = self.context.try_unwrap(scope) else {
      return Err(JsErrorBox::type_error("getContext was never called"));
    };

    context.present().map_err(JsErrorBox::from_err)
  }

  #[fast]
  fn resize(
    &self,
    width: u32,
    height: u32,
    scope: &mut v8::HandleScope,
  ) -> Result<(), JsErrorBox> {
    self.width.replace(width);
    self.height.replace(height);

    let Some(context) = self.context.try_unwrap(scope) else {
      return Ok(());
    };

    context
      .resize_configure(width, height)
      .map_err(JsErrorBox::from_err)
  }
}

struct UnsafeWindowSurfaceOptions {
  system: UnsafeWindowSurfaceSystem,
  window_handle: *const c_void,
  display_handle: *const c_void,
  width: u32,
  height: u32,
}

#[derive(Eq, PartialEq)]
enum UnsafeWindowSurfaceSystem {
  Cocoa,
  Win32,
  X11,
  Wayland,
}

impl<'a> FromV8<'a> for UnsafeWindowSurfaceOptions {
  type Error = JsErrorBox;

  fn from_v8(
    scope: &mut v8::HandleScope<'a>,
    value: Local<'a, Value>,

Review comment (suggestion):
```suggestion
    context.resize_configure(width, height)
```
unecessary map_err since resize_configure returns a JsErrorBox

Code after:
  #[nofast]
  fn present(&self, scope: &mut v8::HandleScope) -> Result<(), JsErrorBox> {
    let Some(context) = self.context.try_unwrap(scope) else {
      return Err(JsErrorBox::type_error("getContext was never called"));
    };

    context.present().map_err(JsErrorBox::from_err)
  }

  #[fast]
  fn resize(&self, width: u32, height: u32, scope: &mut v8::HandleScope) {
    self.width.replace(width);
    self.height.replace(height);

    let Some(context) = self.context.try_unwrap(scope) else {
      return;
    };

    context.resize_configure(width, height);
  }
}

struct UnsafeWindowSurfaceOptions {
  system: UnsafeWindowSurfaceSystem,
  window_handle: *const c_void,
  display_handle: *const c_void,
  width: u32,
  height: u32,
}

#[derive(Eq, PartialEq)]
enum UnsafeWindowSurfaceSystem {
  Cocoa,
  Win32,
  X11,
  Wayland,
}

impl<'a> FromV8<'a> for UnsafeWindowSurfaceOptions {
  type Error = JsErrorBox;

  fn from_v8(
    scope: &mut v8::HandleScope<'a>,
    value: Local<'a, Value>,
  ) -> Result<Self, Self::Error> {
    let obj = value
      .try_cast::<v8::Object>()
      .map_err(|_| JsErrorBox::type_error("is not an object"))?;

    let key = v8::String::new(scope, "system").unwrap();
    let val = obj
Repository: denoland/deno
File: resolvers/node/resolution.rs (Rust)

Code before:
    subpath: &str,
    package_subpath: &str,
    maybe_referrer: Option<&UrlOrPathRef>,
    resolution_mode: ResolutionMode,
    pattern: bool,
    internal: bool,
    conditions: &[&str],
    resolution_kind: NodeResolutionKind,
  ) -> Result<Option<MaybeTypesResolvedUrl>, PackageTargetResolveError> {
    let result = self.resolve_package_target_inner(
      package_json_path,
      target,
      subpath,
      package_subpath,
      maybe_referrer,
      resolution_mode,
      pattern,
      internal,
      conditions,
      resolution_kind,
    );
    match result {
      Ok(maybe_resolved) => Ok(maybe_resolved),
      Err(err) => {
        if resolution_kind.is_types()
          && errors::get_code(&err)
            == NodeJsErrorCode::ERR_TYPES_NOT_FOUND.as_str()
          && conditions != TYPES_ONLY_CONDITIONS
        {
          // try resolving with just "types" conditions for when someone misconfigures
          // and puts the "types" condition in the wrong place
          if let Ok(Some(resolved)) = self.resolve_package_target_inner(
            package_json_path,
            target,
            subpath,
            package_subpath,
            maybe_referrer,
            resolution_mode,
            pattern,
            internal,
            TYPES_ONLY_CONDITIONS,
            resolution_kind,
          ) {
            return Ok(Some(resolved));
          }
        }

        Err(err)
      }
    }
  }

Review comment (suggestion):
I'm being particular about this because I was working on removing allocations from node resolution. I think maybe we shouldn't remove the `err.code()` method.

Code after:
    package_subpath: &str,
    maybe_referrer: Option<&UrlOrPathRef>,
    resolution_mode: ResolutionMode,
    pattern: bool,
    internal: bool,
    conditions: &[&str],
    resolution_kind: NodeResolutionKind,
  ) -> Result<Option<MaybeTypesResolvedUrl>, PackageTargetResolveError> {
    let result = self.resolve_package_target_inner(
      package_json_path,
      target,
      subpath,
      package_subpath,
      maybe_referrer,
      resolution_mode,
      pattern,
      internal,
      conditions,
      resolution_kind,
    );
    match result {
      Ok(maybe_resolved) => Ok(maybe_resolved),
      Err(err) => {
        if resolution_kind.is_types()
          && err.code() == NodeJsErrorCode::ERR_TYPES_NOT_FOUND
          && conditions != TYPES_ONLY_CONDITIONS
        {
          // try resolving with just "types" conditions for when someone misconfigures
          // and puts the "types" condition in the wrong place
          if let Ok(Some(resolved)) = self.resolve_package_target_inner(
            package_json_path,
            target,
            subpath,
            package_subpath,
            maybe_referrer,
            resolution_mode,
            pattern,
            internal,
            TYPES_ONLY_CONDITIONS,
            resolution_kind,
          ) {
            return Ok(Some(resolved));
          }
        }

        Err(err)
      }
    }
  }

  #[allow(clippy::too_many_arguments)]
Repository: denoland/deno
File: runtime/permissions/lib.rs (Rust)

Code before:
  InvalidIpv6(String),
  #[error("invalid host: '{0}'")]
  InvalidHost(String),
  #[error("invalid empty host: '{0}'")]
  InvalidEmptyHost(String),
  #[error("invalid host '{host}': {error}")]
  Fqdn {
    #[source]
    error: fqdn::Error,
    host: String,
  },
}

impl Host {
  fn parse_for_query(s: &str) -> Result<Self, HostParseError> {
    Self::parse_inner(s, false)
  }

  #[cfg(test)]
  fn parse_for_list(s: &str) -> Result<Self, HostParseError> {
    Self::parse_inner(s, true)
  }

  fn parse_inner(
    s: &str,
    allow_subdomain_wildcard: bool,
  ) -> Result<Self, HostParseError> {
    if s.starts_with('[') && s.ends_with(']') {
      let ip = s[1..s.len() - 1]
        .parse::<Ipv6Addr>()
        .map_err(|_| HostParseError::InvalidIpv6(s.to_string()))?;
      return Ok(Host::Ip(IpAddr::V6(ip)));
    }
    let (without_trailing_dot, has_trailing_dot) =
      s.strip_suffix('.').map_or((s, false), |s| (s, true));
    if let Ok(ip) = without_trailing_dot.parse::<IpAddr>() {
      if has_trailing_dot {
        return Err(HostParseError::InvalidHost(
          without_trailing_dot.to_string(),
        ));
      }
      Ok(Host::Ip(ip))
    } else {
      let lower = if s.chars().all(|c| c.is_ascii_lowercase()) {
        Cow::Borrowed(s)
      } else {
        Cow::Owned(s.to_ascii_lowercase())
      };
      let mut host_or_suffix = lower.as_ref();
      let mut has_subdomain_wildcard = false;
      if allow_subdomain_wildcard {

Review comment (bug):
Please use an enum here as these booleans are easy to mistake:
```
#[derive(Default, Debug)]
enum SubdomainWildcardSupport {
  Enabled,
  #[default]
  Disabled
}
```

Code after:
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub enum Host {
  Fqdn(FQDN),
  FqdnWithSubdomainWildcard(FQDN),
  Ip(IpAddr),
  Vsock(u32),
}

#[derive(Debug, thiserror::Error, deno_error::JsError)]
#[class(uri)]
pub enum HostParseError {
  #[error("invalid IPv6 address: '{0}'")]
  InvalidIpv6(String),
  #[error("invalid host: '{0}'")]
  InvalidHost(String),
  #[error("invalid empty host: '{0}'")]
  InvalidEmptyHost(String),
  #[error("invalid host '{host}': {error}")]
  Fqdn {
    #[source]
    error: fqdn::Error,
    host: String,
  },
}

impl Host {
  fn parse_for_query(s: &str) -> Result<Self, HostParseError> {
    Self::parse_inner(s, SubdomainWildcards::Disabled)
  }

  #[cfg(test)]
  fn parse_for_list(s: &str) -> Result<Self, HostParseError> {
    Self::parse_inner(s, SubdomainWildcards::Enabled)
  }

  fn parse_inner(
    s: &str,
    subdomain_wildcards: SubdomainWildcards,
  ) -> Result<Self, HostParseError> {
    if s.starts_with('[') && s.ends_with(']') {
      let ip = s[1..s.len() - 1]
        .parse::<Ipv6Addr>()
        .map_err(|_| HostParseError::InvalidIpv6(s.to_string()))?;
      return Ok(Host::Ip(IpAddr::V6(ip)));
    }
    let (without_trailing_dot, has_trailing_dot) =
      s.strip_suffix('.').map_or((s, false), |s| (s, true));
    if let Ok(ip) = without_trailing_dot.parse::<IpAddr>() {
      if has_trailing_dot {
        return Err(HostParseError::InvalidHost(
          without_trailing_dot.to_string(),
Repository: denoland/deno
File: runtime/permissions/lib.rs (Rust)

Code before:
    }

    fn parse_write_descriptor(
      &self,
      text: &str,
    ) -> Result<WriteDescriptor, PathResolveError> {
      Ok(WriteDescriptor(self.join_path_with_root(text)))
    }

    fn parse_net_descriptor(
      &self,
      text: &str,
    ) -> Result<NetDescriptor, NetDescriptorParseError> {
      NetDescriptor::parse(text)
    }

    fn parse_import_descriptor(
      &self,
      text: &str,
    ) -> Result<ImportDescriptor, NetDescriptorParseError> {
      ImportDescriptor::parse(text)
    }

    fn parse_env_descriptor(
      &self,
      text: &str,
    ) -> Result<EnvDescriptor, EnvDescriptorParseError> {
      Ok(EnvDescriptor::new(text))
    }

    fn parse_sys_descriptor(
      &self,
      text: &str,
    ) -> Result<SysDescriptor, SysDescriptorParseError> {
      SysDescriptor::parse(text.to_string())
    }

    fn parse_allow_run_descriptor(
      &self,
      text: &str,
    ) -> Result<AllowRunDescriptorParseResult, RunDescriptorParseError> {
      Ok(AllowRunDescriptorParseResult::Descriptor(
        AllowRunDescriptor(self.join_path_with_root(text)),
      ))
    }

    fn parse_deny_run_descriptor(
      &self,
      text: &str,
    ) -> Result<DenyRunDescriptor, PathResolveError> {
      if text.contains("/") {

Review comment (security):
One tiny thing, is considering this is permissions, I wonder if we should use a different type for query like `NetQuery` instead of `NetDescriptor` so there's a bit more protection in not accidentally mixing them up? I'm not sure it makes sense. Just a thought.

Code after:
  fn parse_allow_run_descriptor(
    &self,
    text: &str,
  ) -> Result<AllowRunDescriptorParseResult, RunDescriptorParseError>;

  fn parse_deny_run_descriptor(
    &self,
    text: &str,
  ) -> Result<DenyRunDescriptor, PathResolveError>;

  fn parse_ffi_descriptor(
    &self,
    text: &str,
  ) -> Result<FfiDescriptor, PathResolveError>;

  // queries

  fn parse_path_query(
    &self,
    path: &str,
  ) -> Result<PathQueryDescriptor, PathResolveError>;

  fn parse_net_query(
    &self,
    text: &str,
  ) -> Result<NetDescriptor, NetDescriptorParseError>;

  fn parse_run_query(
    &self,
    requested: &str,
  ) -> Result<RunQueryDescriptor, RunDescriptorParseError>;
}

static IS_STANDALONE: AtomicFlag = AtomicFlag::lowered();

pub fn mark_standalone() {
  IS_STANDALONE.raise();
}

pub fn is_standalone() -> bool {
  IS_STANDALONE.is_raised()
}

#[cfg(test)]
mod tests {
  use std::net::Ipv4Addr;

  use fqdn::fqdn;
  use prompter::tests::*;
  use serde_json::json;