More bail! usage

This commit is contained in:
Laurenz 2023-06-12 16:43:49 +02:00
parent 378ebe5f56
commit d3b4d7da9a
25 changed files with 50 additions and 42 deletions

View File

@ -21,7 +21,7 @@ use same_file::{is_same_file, Handle};
use siphasher::sip128::{Hasher128, SipHasher13}; use siphasher::sip128::{Hasher128, SipHasher13};
use std::cell::OnceCell; use std::cell::OnceCell;
use termcolor::{ColorChoice, StandardStream, WriteColor}; use termcolor::{ColorChoice, StandardStream, WriteColor};
use typst::diag::{FileError, FileResult, SourceError, StrResult}; use typst::diag::{bail, FileError, FileResult, SourceError, StrResult};
use typst::doc::Document; use typst::doc::Document;
use typst::eval::{Datetime, Library}; use typst::eval::{Datetime, Library};
use typst::font::{Font, FontBook, FontInfo, FontVariant}; use typst::font::{Font, FontBook, FontInfo, FontVariant};
@ -314,7 +314,7 @@ fn export(document: &Document, command: &CompileSettings) -> StrResult<()> {
let string = command.output.to_str().unwrap_or_default(); let string = command.output.to_str().unwrap_or_default();
let numbered = string.contains("{n}"); let numbered = string.contains("{n}");
if !numbered && document.pages.len() > 1 { if !numbered && document.pages.len() > 1 {
Err("cannot export multiple PNGs without `{n}` in output path")?; bail!("cannot export multiple PNGs without `{{n}}` in output path");
} }
// Find a number width that accommodates all pages. For instance, the // Find a number width that accommodates all pages. For instance, the

View File

@ -171,12 +171,12 @@ cast! {
Component, Component,
v: i64 => match v { v: i64 => match v {
0 ..= 255 => Self(v as u8), 0 ..= 255 => Self(v as u8),
_ => Err("number must be between 0 and 255")?, _ => bail!("number must be between 0 and 255"),
}, },
v: Ratio => if (0.0 ..= 1.0).contains(&v.get()) { v: Ratio => if (0.0 ..= 1.0).contains(&v.get()) {
Self((v.get() * 255.0).round() as u8) Self((v.get() * 255.0).round() as u8)
} else { } else {
Err("ratio must be between 0% and 100%")? bail!("ratio must be between 0% and 100%");
}, },
} }
@ -375,7 +375,7 @@ cast! {
v: Ratio => if (0.0 ..= 1.0).contains(&v.get()) { v: Ratio => if (0.0 ..= 1.0).contains(&v.get()) {
Self((v.get() * 255.0).round() as u8) Self((v.get() * 255.0).round() as u8)
} else { } else {
Err("ratio must be between 0% and 100%")? bail!("ratio must be between 0% and 100%");
}, },
} }
@ -437,7 +437,7 @@ cast! {
let mut iter = array.into_iter(); let mut iter = array.into_iter();
match (iter.next(), iter.next(), iter.next()) { match (iter.next(), iter.next(), iter.next()) {
(Some(a), Some(b), None) => Self(a.cast()?, b.cast()?), (Some(a), Some(b), None) => Self(a.cast()?, b.cast()?),
_ => Err("point array must contain exactly two entries")?, _ => bail!("point array must contain exactly two entries"),
} }
}, },
} }

View File

@ -105,11 +105,11 @@ cast! {
let mut chars = v.chars(); let mut chars = v.chars();
let first = chars.next().ok_or("delimiter must not be empty")?; let first = chars.next().ok_or("delimiter must not be empty")?;
if chars.next().is_some() { if chars.next().is_some() {
Err("delimiter must be a single character")? bail!("delimiter must be a single character");
} }
if !first.is_ascii() { if !first.is_ascii() {
Err("delimiter must be an ASCII character")? bail!("delimiter must be an ASCII character");
} }
Self(first) Self(first)

View File

@ -294,7 +294,7 @@ cast! {
let mut iter = array.into_iter(); let mut iter = array.into_iter();
let (number, body) = match (iter.next(), iter.next(), iter.next()) { let (number, body) = match (iter.next(), iter.next(), iter.next()) {
(Some(a), Some(b), None) => (a.cast()?, b.cast()?), (Some(a), Some(b), None) => (a.cast()?, b.cast()?),
_ => Err("array must contain exactly two entries")?, _ => bail!("array must contain exactly two entries"),
}; };
Self::new(body).with_number(number) Self::new(body).with_number(number)
}, },

View File

@ -216,7 +216,7 @@ cast! {
v: Content => Self::Content(vec![v]), v: Content => Self::Content(vec![v]),
array: Array => { array: Array => {
if array.is_empty() { if array.is_empty() {
Err("array must contain at least one marker")?; bail!("array must contain at least one marker");
} }
Self::Content(array.into_iter().map(Value::display).collect()) Self::Content(array.into_iter().map(Value::display).collect())
}, },

View File

@ -595,7 +595,7 @@ cast! {
v: GenAlign => match v { v: GenAlign => match v {
GenAlign::Specific(Align::Left) => Self::Left, GenAlign::Specific(Align::Left) => Self::Left,
GenAlign::Specific(Align::Right) => Self::Right, GenAlign::Specific(Align::Right) => Self::Right,
_ => Err("must be `left` or `right`")?, _ => bail!("must be `left` or `right`"),
}, },
} }

View File

@ -158,7 +158,7 @@ cast! {
let mut iter = array.into_iter(); let mut iter = array.into_iter();
let (term, description) = match (iter.next(), iter.next(), iter.next()) { let (term, description) = match (iter.next(), iter.next(), iter.next()) {
(Some(a), Some(b), None) => (a.cast()?, b.cast()?), (Some(a), Some(b), None) => (a.cast()?, b.cast()?),
_ => Err("array must contain exactly two entries")?, _ => bail!("array must contain exactly two entries"),
}; };
Self::new(term, description) Self::new(term, description)
}, },

View File

@ -134,6 +134,6 @@ cast! {
v: char => Self::new(v), v: char => Self::new(v),
v: Content => match v.to::<TextElem>() { v: Content => match v.to::<TextElem>() {
Some(elem) => Value::Str(elem.text().into()).cast()?, Some(elem) => Value::Str(elem.text().into()).cast()?,
None => Err("expected text")?, None => bail!("expected text"),
}, },
} }

View File

@ -633,7 +633,7 @@ fn parse_bib(path_str: &str, src: &str) -> StrResult<Vec<hayagriva::Entry>> {
.map(|error| format_biblatex_error(path_str, src, error)) .map(|error| format_biblatex_error(path_str, src, error))
.unwrap_or_else(|| eco_format!("failed to parse {path_str}")) .unwrap_or_else(|| eco_format!("failed to parse {path_str}"))
}), }),
_ => Err("unknown bibliography format (must be .yml/.yaml or .bib)".into()), _ => bail!("unknown bibliography format (must be .yml/.yaml or .bib)"),
} }
} }

View File

@ -218,7 +218,7 @@ impl FromStr for NumberingPattern {
let suffix = pattern[handled..].into(); let suffix = pattern[handled..].into();
if pieces.is_empty() { if pieces.is_empty() {
Err("invalid numbering pattern")?; return Err("invalid numbering pattern");
} }
Ok(Self { pieces, suffix, trimmed: false }) Ok(Self { pieces, suffix, trimmed: false })

View File

@ -407,9 +407,8 @@ cast! {
/// == Setup /// == Setup
/// ``` /// ```
/// ///
/// To completely customize an entry's line, you can also build it from /// To completely customize an entry's line, you can also build it from scratch
/// scratch by accessing the `level`, `element`, `outline`, and `fill` /// by accessing the `level`, `element`, `body`, and `fill` fields on the entry.
/// fields on the entry.
/// ///
/// Display: Outline Entry /// Display: Outline Entry
/// Category: meta /// Category: meta

View File

@ -644,7 +644,7 @@ cast! {
self => self.0.into_value(), self => self.0.into_value(),
v: Smart<Dir> => { v: Smart<Dir> => {
if v.map_or(false, |dir| dir.axis() == Axis::Y) { if v.map_or(false, |dir| dir.axis() == Axis::Y) {
Err("text direction must be horizontal")?; bail!("text direction must be horizontal");
} }
Self(v) Self(v)
}, },
@ -703,7 +703,7 @@ cast! {
self => self.0.into_value(), self => self.0.into_value(),
v: i64 => match v { v: i64 => match v {
1 ..= 20 => Self::new(v as u8), 1 ..= 20 => Self::new(v as u8),
_ => Err("stylistic set must be between 1 and 20")?, _ => bail!("stylistic set must be between 1 and 20"),
}, },
} }

View File

@ -185,7 +185,7 @@ fn load(
"jpg" | "jpeg" => ImageFormat::Raster(RasterFormat::Jpg), "jpg" | "jpeg" => ImageFormat::Raster(RasterFormat::Jpg),
"gif" => ImageFormat::Raster(RasterFormat::Gif), "gif" => ImageFormat::Raster(RasterFormat::Gif),
"svg" | "svgz" => ImageFormat::Vector(VectorFormat::Svg), "svg" | "svgz" => ImageFormat::Vector(VectorFormat::Svg),
_ => return Err("unknown image format".into()), _ => bail!("unknown image format"),
}; };
Image::with_fonts(buffer, format, world, fallback_family, alt) Image::with_fonts(buffer, format, world, fallback_family, alt)
} }

View File

@ -205,7 +205,7 @@ cast! {
(Some(a), Some(b), Some(c), None) => { (Some(a), Some(b), Some(c), None) => {
AllControlPoints(a.cast()?, b.cast()?, c.cast()?) AllControlPoints(a.cast()?, b.cast()?, c.cast()?)
}, },
_ => Err("path vertex must have 1, 2, or 3 points")?, _ => bail!("path vertex must have 1, 2, or 3 points"),
} }
}, },
} }

View File

@ -13,6 +13,15 @@ use crate::syntax::{ErrorPos, Span, Spanned};
use crate::World; use crate::World;
/// Early-return with a [`StrResult`] or [`SourceResult`]. /// Early-return with a [`StrResult`] or [`SourceResult`].
///
/// If called with just a string and format args, returns with a
/// `StrResult`. If called with a span, a string and format args, returns
/// a `SourceResult`.
///
/// ```
/// bail!("bailing with a {}", "string result");
/// bail!(span, "bailing with a {}", "source result");
/// ```
#[macro_export] #[macro_export]
#[doc(hidden)] #[doc(hidden)]
macro_rules! __bail { macro_rules! __bail {

View File

@ -256,7 +256,7 @@ impl<'a> Vm<'a> {
} }
} }
Err("cannot access file system from here".into()) bail!("cannot access file system from here")
} }
} }

View File

@ -6,7 +6,7 @@ use std::fmt::Debug;
use ecow::eco_format; use ecow::eco_format;
use super::{format_str, Regex, Value}; use super::{format_str, Regex, Value};
use crate::diag::StrResult; use crate::diag::{bail, StrResult};
use crate::geom::{Axes, Axis, GenAlign, Length, Numeric, PartialStroke, Rel, Smart}; use crate::geom::{Axes, Axis, GenAlign, Length, Numeric, PartialStroke, Rel, Smart};
use Value::*; use Value::*;
@ -219,7 +219,7 @@ pub fn mul(lhs: Value, rhs: Value) -> StrResult<Value> {
/// Compute the quotient of two values. /// Compute the quotient of two values.
pub fn div(lhs: Value, rhs: Value) -> StrResult<Value> { pub fn div(lhs: Value, rhs: Value) -> StrResult<Value> {
if is_zero(&rhs) { if is_zero(&rhs) {
Err("cannot divide by zero")?; bail!("cannot divide by zero");
} }
Ok(match (lhs, rhs) { Ok(match (lhs, rhs) {

View File

@ -5,7 +5,7 @@ use std::hash::Hash;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use super::{IntoValue, Library, Value}; use super::{IntoValue, Library, Value};
use crate::diag::StrResult; use crate::diag::{bail, StrResult};
/// A stack of scopes. /// A stack of scopes.
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
@ -171,7 +171,7 @@ impl Slot {
match self.kind { match self.kind {
Kind::Normal => Ok(&mut self.value), Kind::Normal => Ok(&mut self.value),
Kind::Captured => { Kind::Captured => {
Err("variables from outside the function are read-only and cannot be modified")? bail!("variables from outside the function are read-only and cannot be modified")
} }
} }
} }

View File

@ -7,7 +7,7 @@ use ecow::EcoString;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use super::{cast, dict, Args, Array, Dict, Func, IntoValue, Value, Vm}; use super::{cast, dict, Args, Array, Dict, Func, IntoValue, Value, Vm};
use crate::diag::{At, SourceResult, StrResult}; use crate::diag::{bail, At, SourceResult, StrResult};
use crate::geom::GenAlign; use crate::geom::GenAlign;
/// Create a new [`Str`] from a format string. /// Create a new [`Str`] from a format string.
@ -507,7 +507,7 @@ cast! {
let mut chars = string.chars(); let mut chars = string.chars();
match (chars.next(), chars.next()) { match (chars.next(), chars.next()) {
(Some(c), None) => c, (Some(c), None) => c,
_ => Err("expected exactly one character")?, _ => bail!("expected exactly one character"),
} }
}, },
} }
@ -600,7 +600,7 @@ cast! {
align: GenAlign => match align { align: GenAlign => match align {
GenAlign::Start => Self::Start, GenAlign::Start => Self::Start,
GenAlign::End => Self::End, GenAlign::End => Self::End,
_ => Err("expected either `start` or `end`")?, _ => bail!("expected either `start` or `end`"),
}, },
} }

View File

@ -5,7 +5,7 @@ use std::sync::Arc;
use ecow::EcoString; use ecow::EcoString;
use crate::diag::StrResult; use crate::diag::{bail, StrResult};
/// A symbol, possibly with variants. /// A symbol, possibly with variants.
#[derive(Clone, Eq, PartialEq, Hash)] #[derive(Clone, Eq, PartialEq, Hash)]
@ -72,7 +72,7 @@ impl Symbol {
} }
} }
Err("unknown symbol modifier".into()) bail!("unknown symbol modifier")
} }
/// The characters that are covered by this symbol. /// The characters that are covered by this symbol.

View File

@ -216,7 +216,7 @@ cast! {
self => self.0.into_value(), self => self.0.into_value(),
align: GenAlign => { align: GenAlign => {
if align.axis() != Axis::X { if align.axis() != Axis::X {
Err("alignment must be horizontal")?; bail!("alignment must be horizontal");
} }
Self(align) Self(align)
}, },
@ -232,7 +232,7 @@ cast! {
self => self.0.into_value(), self => self.0.into_value(),
align: GenAlign => { align: GenAlign => {
if align.axis() != Axis::Y { if align.axis() != Axis::Y {
Err("alignment must be vertical")?; bail!("alignment must be vertical");
} }
Self(align) Self(align)
}, },

View File

@ -280,7 +280,7 @@ cast! {
let mut iter = array.into_iter(); let mut iter = array.into_iter();
match (iter.next(), iter.next(), iter.next()) { match (iter.next(), iter.next(), iter.next()) {
(Some(a), Some(b), None) => Axes::new(a.cast()?, b.cast()?), (Some(a), Some(b), None) => Axes::new(a.cast()?, b.cast()?),
_ => Err("point array must contain exactly two entries")?, _ => bail!("point array must contain exactly two entries"),
} }
}, },
} }

View File

@ -61,7 +61,7 @@ use std::hash::{Hash, Hasher};
use std::iter::Sum; use std::iter::Sum;
use std::ops::*; use std::ops::*;
use crate::diag::StrResult; use crate::diag::{bail, StrResult};
use crate::eval::{array, cast, Array, Dict, Value}; use crate::eval::{array, cast, Array, Dict, Value};
use crate::model::{Fold, Resolve, StyleChain}; use crate::model::{Fold, Resolve, StyleChain};

View File

@ -9,7 +9,7 @@ use ecow::EcoVec;
use indexmap::IndexMap; use indexmap::IndexMap;
use super::{Content, Selector}; use super::{Content, Selector};
use crate::diag::StrResult; use crate::diag::{bail, StrResult};
use crate::doc::{Frame, FrameItem, Meta, Position}; use crate::doc::{Frame, FrameItem, Meta, Position};
use crate::eval::{cast, Value}; use crate::eval::{cast, Value};
use crate::geom::{Point, Transform}; use crate::geom::{Point, Transform};
@ -313,7 +313,7 @@ impl Introspector {
let mut found = None; let mut found = None;
for elem in self.all().filter(|elem| elem.label() == Some(label)) { for elem in self.all().filter(|elem| elem.label() == Some(label)) {
if found.is_some() { if found.is_some() {
return Err("label occurs multiple times in the document".into()); bail!("label occurs multiple times in the document");
} }
found = Some(elem.clone()); found = Some(elem.clone());
} }

View File

@ -5,7 +5,7 @@ use std::sync::Arc;
use ecow::{eco_format, EcoString, EcoVec}; use ecow::{eco_format, EcoString, EcoVec};
use super::{Content, ElemFunc, Label, Location}; use super::{Content, ElemFunc, Label, Location};
use crate::diag::StrResult; use crate::diag::{bail, StrResult};
use crate::eval::{ use crate::eval::{
cast, CastInfo, Dict, FromValue, Func, IntoValue, Reflect, Regex, Value, cast, CastInfo, Dict, FromValue, Func, IntoValue, Reflect, Regex, Value,
}; };
@ -201,8 +201,8 @@ impl FromValue for LocatableSelector {
} }
Selector::Location(_) => {} Selector::Location(_) => {}
Selector::Label(_) => {} Selector::Label(_) => {}
Selector::Regex(_) => Err("text is not locatable")?, Selector::Regex(_) => bail!("text is not locatable"),
Selector::Can(_) => Err("capability is not locatable")?, Selector::Can(_) => bail!("capability is not locatable"),
Selector::Or(list) | Selector::And(list) => { Selector::Or(list) | Selector::And(list) => {
for selector in list { for selector in list {
validate(selector)?; validate(selector)?;
@ -279,7 +279,7 @@ impl FromValue for ShowableSelector {
| Selector::Can(_) | Selector::Can(_)
| Selector::Before { .. } | Selector::Before { .. }
| Selector::After { .. } => { | Selector::After { .. } => {
Err("this selector cannot be used with show")? bail!("this selector cannot be used with show")
} }
} }
Ok(()) Ok(())