Skip to content

Commit

Permalink
[Starlark] 'file_loader' use starlark error instead of anyhow
Browse files Browse the repository at this point in the history
Summary: Needed for anyhow->buck2_error migration in `buck2/app`

Test Plan: CI

Reviewed By: epilatow, JakobDegen

Differential Revision: D64018263

fbshipit-source-id: dbd8bf162d69a0eff761e08dbe5ea1cc283e4494
  • Loading branch information
Will-MingLun-Li authored and facebook-github-bot committed Nov 26, 2024
1 parent 95dad8a commit 0a45292
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 29 deletions.
41 changes: 20 additions & 21 deletions antlir/bzl/shape2/bzl2ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use anyhow::anyhow;
use anyhow::bail;
use anyhow::ensure;
use anyhow::Context;
use anyhow::Result;
use clap::Parser;
use derive_more::Deref;
use derive_more::Display;
Expand Down Expand Up @@ -72,7 +71,7 @@ fn bzl_globals() -> GlobalsBuilder {
fn eval_and_freeze_module(
deps: &Dependencies,
ast: AstModule,
) -> Result<(FrozenModule, SlotMap<TypeId, Arc<ir::Type>>)> {
) -> anyhow::Result<(FrozenModule, SlotMap<TypeId, Arc<ir::Type>>)> {
let module = Module::new();
let globals = bzl_globals().build();
let registry = TypeRegistryRefCell::default();
Expand Down Expand Up @@ -164,11 +163,11 @@ starlark_simple_value!(StarlarkType);
impl<'v> StarlarkValue<'v> for StarlarkType {}

trait TryToType {
fn try_to_type(&self, reg: &TypeRegistry) -> Result<Arc<ir::Type>>;
fn try_to_type(&self, reg: &TypeRegistry) -> anyhow::Result<Arc<ir::Type>>;
}

impl<'v> TryToType for Value<'v> {
fn try_to_type(&self, reg: &TypeRegistry) -> Result<Arc<ir::Type>> {
fn try_to_type(&self, reg: &TypeRegistry) -> anyhow::Result<Arc<ir::Type>> {
if let Some(tid) = self.downcast_ref::<TypeId>() {
reg.get(*tid).ok_or_else(|| anyhow!("{:?} not found", tid))
} else if let Some(ty) = self.downcast_ref::<StarlarkType>() {
Expand All @@ -188,11 +187,11 @@ impl<'v> TryToType for Value<'v> {
}

trait TryToField {
fn try_to_field(&self, reg: &TypeRegistry) -> Result<ir::Field>;
fn try_to_field(&self, reg: &TypeRegistry) -> anyhow::Result<ir::Field>;
}

impl<'v> TryToField for Value<'v> {
fn try_to_field(&self, reg: &TypeRegistry) -> Result<ir::Field> {
fn try_to_field(&self, reg: &TypeRegistry) -> anyhow::Result<ir::Field> {
if let Ok(ty) = self.try_to_type(reg) {
Ok(ir::Field {
ty,
Expand All @@ -216,7 +215,7 @@ starlark_simple_value!(StarlarkField);
#[starlark_value(type = "StarlarkField")]
impl<'v> StarlarkValue<'v> for StarlarkField {}

fn get_type_registry<'a>(eval: &'a Evaluator) -> Result<&'a TypeRegistryRefCell> {
fn get_type_registry<'a>(eval: &'a Evaluator) -> anyhow::Result<&'a TypeRegistryRefCell> {
let extra = eval
.extra
.context("extra should be TypeRegistry, but was not present")?;
Expand All @@ -243,7 +242,7 @@ fn shape(builder: &mut GlobalsBuilder) {
.into_iter()
.filter(|(key, _)| (*key != "__I_AM_TARGET__") && (*key != "__thrift_fields"))
.map(|(key, val)| val.try_to_field(&reg).map(|f| (key.into(), Arc::new(f))))
.collect::<Result<_>>()?;
.collect::<anyhow::Result<_>>()?;
let thrift_fields = __thrift
.map(|t| {
t.entries
Expand All @@ -256,7 +255,7 @@ fn shape(builder: &mut GlobalsBuilder) {
.clone();
Ok((k, (field_name, field)))
})
.collect::<Result<_>>()
.collect::<anyhow::Result<_>>()
})
.transpose()
.context(
Expand Down Expand Up @@ -290,7 +289,7 @@ fn shape(builder: &mut GlobalsBuilder) {
.map_err(starlark::Error::into_anyhow)
.context("while collecting enum variants")?
.map(|v| String::unpack_param(v).map(|s| s.into()))
.collect::<Result<_>>()?;
.collect::<anyhow::Result<_>>()?;
let enm = ir::Enum {
options,
docstring: None,
Expand Down Expand Up @@ -367,7 +366,7 @@ fn shape(builder: &mut GlobalsBuilder) {
v.try_to_type(&reg)
.with_context(|| format!("union item at {} is not a type", i))
})
.collect::<Result<_>>()?;
.collect::<anyhow::Result<_>>()?;
let thrift_types = match __thrift {
Some(t) => {
// Closure to convert the `anyhow` error to a `starlark::Error`
Expand Down Expand Up @@ -408,12 +407,11 @@ fn shape(builder: &mut GlobalsBuilder) {
struct Dependencies(BTreeMap<ir::Target, PathBuf>);

impl FileLoader for Dependencies {
fn load(&self, load: &str) -> Result<FrozenModule> {
fn load(&self, load: &str) -> starlark::Result<FrozenModule> {
// shape.bzl itself is an implicit dependency and comes with a native
// implementation
if load == "//antlir/bzl:shape.bzl" || load == "@antlir//antlir/bzl:shape.bzl" {
let ast = AstModule::parse("", "shape = shape_impl".to_string(), &Dialect::Standard)
.map_err(starlark::Error::into_anyhow)?;
let ast = AstModule::parse("", "shape = shape_impl".to_string(), &Dialect::Standard)?;
let module = Module::new();
{
let mut evaluator: Evaluator = Evaluator::new(&module);
Expand All @@ -422,14 +420,15 @@ impl FileLoader for Dependencies {
.eval_module(ast, &globals)
.map_err(starlark::Error::into_anyhow)?;
}
return module.freeze();
return Ok(module.freeze()?);
}
let load: ir::Target = load
.strip_suffix(".bzl")
.unwrap_or(load)
.try_into()
.with_context(|| format!("while parsing '{}'", load))?;
self.0
Ok(self
.0
.get(&load)
.with_context(|| {
format!(
Expand All @@ -442,11 +441,11 @@ impl FileLoader for Dependencies {
std::fs::File::open(p).with_context(|| format!("while loading {:?}", p))?;
serde_json::from_reader(&mut f).with_context(|| format!("while parsing {:?}", p))
})
.and_then(ir_to_module)
.and_then(ir_to_module)?)
}
}

fn ir_to_module(m: ir::Module) -> Result<FrozenModule> {
fn ir_to_module(m: ir::Module) -> anyhow::Result<FrozenModule> {
let module = Module::new();
for name in m.types.into_keys() {
let ty = StarlarkType(Arc::new(ir::Type::Foreign {
Expand All @@ -463,7 +462,7 @@ fn starlark_to_ir(
types: SlotMap<TypeId, Arc<ir::Type>>,
target: ir::Target,
deps: BTreeSet<ir::Target>,
) -> Result<ir::Module> {
) -> anyhow::Result<ir::Module> {
let named_types: BTreeMap<ir::TypeName, _> = f
.names()
// grab the Value that is assigned to this name from the starlark module (this is the TypeId)
Expand Down Expand Up @@ -494,7 +493,7 @@ fn starlark_to_ir(
};
Ok((name, ty))
})
.collect::<Result<_>>()?;
.collect::<anyhow::Result<_>>()?;

Ok(ir::Module {
name: target.basename().to_string(),
Expand All @@ -521,7 +520,7 @@ struct Opts {
out: PathBuf,
}

fn main() -> Result<()> {
fn main() -> anyhow::Result<()> {
let opts = Opts::parse();
let dialect = Dialect {
enable_load_reexport: false,
Expand Down
17 changes: 9 additions & 8 deletions antlir/bzl/starlark_unittest/src/starlark_unittest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ use std::collections::HashMap;
use std::path::PathBuf;

use anyhow::anyhow;
use anyhow::bail;
use anyhow::Context;
use anyhow::Result;
use clap::Parser;
use regex::Regex;
use sha2::Digest;
Expand All @@ -34,6 +32,7 @@ use starlark::syntax::Dialect;
use starlark::values::none::NoneType;
use starlark::values::OwnedFrozenValue;
use starlark::values::Value;
use starlark::StarlarkResultExt;
use test::test::ShouldPanic;
use test::test::TestDesc;
use test::test::TestDescAndFn;
Expand Down Expand Up @@ -201,7 +200,7 @@ impl TestModule {
.collect()
}

fn load(path: PathBuf, loader: &Loader) -> Result<Self> {
fn load(path: PathBuf, loader: &Loader) -> starlark::Result<Self> {
let name = path
.file_name()
.context("modules always have filenames")?
Expand Down Expand Up @@ -243,10 +242,12 @@ fn globals() -> Globals {
}

impl FileLoader for Loader {
fn load(&self, path: &str) -> Result<FrozenModule> {
fn load(&self, path: &str) -> starlark::Result<FrozenModule> {
let path = path.trim_start_matches('@');
if path.starts_with(':') {
bail!("relative loads not allowed: {path}")
return Err(starlark::Error::new_other(anyhow!(
"relative loads not allowed: {path}"
)));
}
let path = match path.starts_with("//") {
true => format!("{}{}", self.default_cell, path),
Expand All @@ -266,7 +267,7 @@ impl FileLoader for Loader {
eval.eval_module(ast, &globals())
.map_err(starlark::Error::into_anyhow)?;
}
module.freeze()
Ok(module.freeze()?)
}
}

Expand All @@ -281,7 +282,7 @@ struct Args {
test_args: Vec<String>,
}

fn main() -> Result<()> {
fn main() -> anyhow::Result<()> {
let args = Args::parse();

let loader = Loader {
Expand All @@ -291,7 +292,7 @@ fn main() -> Result<()> {

let mut modules = vec![];
for src in args.test {
let module = TestModule::load(src, &loader)?;
let module = TestModule::load(src, &loader).into_anyhow_result()?;
modules.push(module);
}

Expand Down

0 comments on commit 0a45292

Please sign in to comment.