ronantakizawa/codereview-bench huggingface dataset:
Repository: typst/typst
File: crates/typst-layout/src/math/frac.rs (Rust)

Code before:
    style_for_numerator,
};

const FRAC_AROUND: Em = Em::new(0.1);

/// Lays out a [`FracElem`].
#[typst_macros::time(name = "math.frac", span = elem.span())]
pub fn layout_frac(
    elem: &Packed<FracElem>,
    ctx: &mut MathContext,
    styles: StyleChain,
) -> SourceResult<()> {
    match elem.style.get(styles) {
        FracStyle::Skewed => {
            layout_skewed_frac(ctx, styles, &elem.num, &elem.denom, elem.span())
        }
        FracStyle::Horizontal => layout_horizontal_frac(
            ctx,
            styles,
            &elem.num,
            &elem.denom,
            elem.span(),
            elem.num_deparenthesized.as_option().unwrap_or(false),
            elem.denom_deparenthesized.as_option().unwrap_or(false),
        ),
        _ => layout_vertical_frac_like(
            ctx,
            styles,
            &elem.num,
            std::slice::from_ref(&elem.denom),
            false,
            elem.span(),
        ),
    }
}

/// Lays out a [`BinomElem`].
#[typst_macros::time(name = "math.binom", span = elem.span())]
pub fn layout_binom(
    elem: &Packed<BinomElem>,
    ctx: &mut MathContext,
    styles: StyleChain,
) -> SourceResult<()> {
    layout_vertical_frac_like(ctx, styles, &elem.upper, &elem.lower, true, elem.span())
}

/// Layout a vertical fraction or binomial.
fn layout_vertical_frac_like(
    ctx: &mut MathContext,
    styles: StyleChain,
    num: &Content,

Review comment (suggestion):
```suggestion
        FracStyle::Vertical => layout_vertical_frac_like(
```
I think its clearer to give this explicitly, otherwise it could seem like there are more variants being matched.

Code after:
use super::{
    DELIM_SHORT_FALL, FrameFragment, MathContext, style_for_denominator,
    style_for_numerator,
};

const FRAC_AROUND: Em = Em::new(0.1);

/// Lays out a [`FracElem`].
#[typst_macros::time(name = "math.frac", span = elem.span())]
pub fn layout_frac(
    elem: &Packed<FracElem>,
    ctx: &mut MathContext,
    styles: StyleChain,
) -> SourceResult<()> {
    match elem.style.get(styles) {
        FracStyle::Skewed => {
            layout_skewed_frac(ctx, styles, &elem.num, &elem.denom, elem.span())
        }
        FracStyle::Horizontal => layout_horizontal_frac(
            ctx,
            styles,
            &elem.num,
            &elem.denom,
            elem.span(),
            elem.num_deparenthesized.get(styles),
            elem.denom_deparenthesized.get(styles),
        ),
        FracStyle::Vertical => layout_vertical_frac_like(
            ctx,
            styles,
            &elem.num,
            std::slice::from_ref(&elem.denom),
            false,
            elem.span(),
        ),
    }
}

/// Lays out a [`BinomElem`].
#[typst_macros::time(name = "math.binom", span = elem.span())]
pub fn layout_binom(
    elem: &Packed<BinomElem>,
    ctx: &mut MathContext,
    styles: StyleChain,
) -> SourceResult<()> {
    layout_vertical_frac_like(ctx, styles, &elem.upper, &elem.lower, true, elem.span())
}

/// Layout a vertical fraction or binomial.
fn layout_vertical_frac_like(
    ctx: &mut MathContext,
Repository: typst/typst
File: crates/typst-layout/src/math/frac.rs (Rust)

Code before:

use super::{
    DELIM_SHORT_FALL, FrameFragment, GlyphFragment, MathContext, style_for_denominator,
    style_for_numerator,
};

const FRAC_AROUND: Em = Em::new(0.1);

/// Lays out a [`FracElem`].
#[typst_macros::time(name = "math.frac", span = elem.span())]
pub fn layout_frac(
    elem: &Packed<FracElem>,
    ctx: &mut MathContext,
    styles: StyleChain,
) -> SourceResult<()> {
    match elem.style.get(styles) {
        FracStyle::Skewed => {
            layout_skewed_frac(ctx, styles, &elem.num, &elem.denom, elem.span())
        }
        FracStyle::Horizontal => layout_horizontal_frac(
            ctx,
            styles,
            &elem.num,
            &elem.denom,
            elem.span(),
            elem.num_deparenthesized.as_option().unwrap_or(false),
            elem.denom_deparenthesized.as_option().unwrap_or(false),
        ),
        _ => layout_vertical_frac_like(
            ctx,
            styles,
            &elem.num,
            std::slice::from_ref(&elem.denom),
            false,
            elem.span(),
        ),
    }
}

/// Lays out a [`BinomElem`].
#[typst_macros::time(name = "math.binom", span = elem.span())]
pub fn layout_binom(
    elem: &Packed<BinomElem>,
    ctx: &mut MathContext,
    styles: StyleChain,
) -> SourceResult<()> {
    layout_vertical_frac_like(ctx, styles, &elem.upper, &elem.lower, true, elem.span())
}

/// Layout a vertical fraction or binomial.
fn layout_vertical_frac_like(

Review comment (suggestion):
```suggestion
            elem.num_deparenthesized.get(styles),
```
This'll make use of the default set in the FracElem definition. Similar for denom below.

Code after:
use typst_library::visualize::{FixedStroke, Geometry};
use typst_syntax::Span;

use super::{
    DELIM_SHORT_FALL, FrameFragment, MathContext, style_for_denominator,
    style_for_numerator,
};

const FRAC_AROUND: Em = Em::new(0.1);

/// Lays out a [`FracElem`].
#[typst_macros::time(name = "math.frac", span = elem.span())]
pub fn layout_frac(
    elem: &Packed<FracElem>,
    ctx: &mut MathContext,
    styles: StyleChain,
) -> SourceResult<()> {
    match elem.style.get(styles) {
        FracStyle::Skewed => {
            layout_skewed_frac(ctx, styles, &elem.num, &elem.denom, elem.span())
        }
        FracStyle::Horizontal => layout_horizontal_frac(
            ctx,
            styles,
            &elem.num,
            &elem.denom,
            elem.span(),
            elem.num_deparenthesized.get(styles),
            elem.denom_deparenthesized.get(styles),
        ),
        FracStyle::Vertical => layout_vertical_frac_like(
            ctx,
            styles,
            &elem.num,
            std::slice::from_ref(&elem.denom),
            false,
            elem.span(),
        ),
    }
}

/// Lays out a [`BinomElem`].
#[typst_macros::time(name = "math.binom", span = elem.span())]
pub fn layout_binom(
    elem: &Packed<BinomElem>,
    ctx: &mut MathContext,
    styles: StyleChain,
) -> SourceResult<()> {
    layout_vertical_frac_like(ctx, styles, &elem.upper, &elem.lower, true, elem.span())
}
Repository: typst/typst
File: crates/typst-library/src/math/frac.rs (Rust)

Code before:
use typst_syntax::Spanned;

use crate::diag::bail;
use crate::foundations::{Cast, Content, Value, elem};
use crate::math::Mathy;

/// Fraction style
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum FracStyle {
    Vertical,
    Skewed,
    Horizontal,
}

/// A mathematical fraction.
///
/// # Example
/// ```example
/// $ 1/2 < (x+1)/2 $
/// $ ((x+1)) / 2 = frac(a, b) $
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: Use a slash to turn neighbouring
/// expressions into a fraction. Multiple atoms can be grouped into a single
/// expression using round grouping parentheses. Such parentheses are removed
/// from the output, but you can nest multiple to force them.
#[elem(title = "Fraction", Mathy)]
pub struct FracElem {
    /// The fraction's numerator.
    #[required]
    pub num: Content,

    /// The fraction's denominator.
    #[required]
    pub denom: Content,

    /// The style of the fraction.
    /// - `"vertical"`: stacked numerator and denominator with a bar.

Review comment (bug):
```suggestion
/// Fraction style
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum FracStyle {
    /// Stacked numerator and denominator with a bar.
    #[default]
    Vertical,
    /// Numerator and denominator separated by a slash.
    Skewed,
    /// Numerator and denominator placed inline and parentheses are not absorbed.
    Horizontal,
}

```
Adding the docs here should make sure it ends up like https://typst.app/docs/reference/model/ref/#parameters-form in the docs.

Code after:
use typst_syntax::Spanned;

use crate::diag::bail;
use crate::foundations::{Cast, Content, Value, elem};
use crate::math::Mathy;

/// A mathematical fraction.
///
/// # Example
/// ```example
/// $ 1/2 < (x+1)/2 $
/// $ ((x+1)) / 2 = frac(a, b) $
/// ```
///
/// # Syntax
/// This function also has dedicated syntax: Use a slash to turn neighbouring
/// expressions into a fraction. Multiple atoms can be grouped into a single
/// expression using round grouping parentheses. Such parentheses are removed
/// from the output, but you can nest multiple to force them.
#[elem(title = "Fraction", Mathy)]
pub struct FracElem {
    /// The fraction's numerator.
    #[required]
    pub num: Content,

    /// The fraction's denominator.
    #[required]
    pub denom: Content,

    /// How the fraction shoud be laid out.
    ///
    /// ```example
    /// #set math.frac(style: "skewed")
    /// $ a / b $
    /// $ frac(x, y, style: "vertical") $
    /// ```
    #[default(FracStyle::Vertical)]
    pub style: FracStyle,
Repository: typst/typst
File: crates/typst-library/src/math/frac.rs (Rust)

Code before:
    pub style: FracStyle,

    /// Whether the numerator was originally surrounded by parentheses
    /// that were stripped by the parser.
    #[internal]
    #[parse(None)]
    #[default(false)]
    pub num_deparenthesized: bool,

    /// Whether the denominator was originally surrounded by parentheses
    /// that were stripped by the parser.
    #[internal]
    #[parse(None)]
    #[default(false)]
    pub denom_deparenthesized: bool,
}

/// Fraction style
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum FracStyle {
    /// Stacked numerator and denominator with a bar.
    #[default]
    Vertical,
    /// Numerator and denominator separated by a slash.
    Skewed,
    /// Numerator and denominator placed inline and parentheses are not absorbed
    Horizontal,
}

/// A binomial expression.
///
/// # Example
/// ```example
/// $ binom(n, k) $
/// $ binom(n, k_1, k_2, k_3, ..., k_m) $
/// ```
#[elem(title = "Binomial", Mathy)]
pub struct BinomElem {
    /// The binomial's upper index.
    #[required]
    pub upper: Content,

    /// The binomial's lower index.
    #[required]
    #[variadic]
    #[parse(
        let values = args.all::<Spanned<Value>>()?;
        if values.is_empty() {
            // Prevents one element binomials
            bail!(args.span, "missing argument: lower");
        }

Review comment (suggestion):
```suggestion
    /// Numerator and denominator placed inline and parentheses are not absorbed.
```

Code after:
    pub style: FracStyle,

    /// Whether the numerator was originally surrounded by parentheses
    /// that were stripped by the parser.
    #[internal]
    #[parse(None)]
    #[default(false)]
    pub num_deparenthesized: bool,

    /// Whether the denominator was originally surrounded by parentheses
    /// that were stripped by the parser.
    #[internal]
    #[parse(None)]
    #[default(false)]
    pub denom_deparenthesized: bool,
}

/// Fraction style
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)]
pub enum FracStyle {
    /// Stacked numerator and denominator with a bar.
    #[default]
    Vertical,
    /// Numerator and denominator separated by a slash.
    Skewed,
    /// Numerator and denominator placed inline and parentheses are not
    /// absorbed.
    Horizontal,
}

/// A binomial expression.
///
/// # Example
/// ```example
/// $ binom(n, k) $
/// $ binom(n, k_1, k_2, k_3, ..., k_m) $
/// ```
#[elem(title = "Binomial", Mathy)]
pub struct BinomElem {
    /// The binomial's upper index.
    #[required]
    pub upper: Content,

    /// The binomial's lower index.
    #[required]
    #[variadic]
    #[parse(
        let values = args.all::<Spanned<Value>>()?;
        if values.is_empty() {
            // Prevents one element binomials
            bail!(args.span, "missing argument: lower");
Repository: typst/typst
File: crates/typst-library/src/layout/grid/mod.rs (Rust)

Code before:
    ///
    /// #grid(
    ///   stroke: 0.5pt,
    ///   ..placeholder
    /// )
    ///
    /// #grid(
    ///   stroke: (y: 0.8pt + gray),
    ///   ..placeholder
    /// )
    /// #grid(
    ///   columns: (1em, 2em) * 2,
    ///   stroke: (blue, none),
    ///   ..placeholder
    /// )
    ///
    /// #grid(
    ///   stroke: (x, y) => if x == 0 { (right: green) },
    ///   ..placeholder
    /// )
    ///
    /// #grid(
    ///   stroke: (x, y) => if x >= 1 { (left: purple) },
    ///   ..placeholder
    /// )
    /// ```
    ///
    /// ```example
    /// // If there is a gutter, then result of `stroke` will be
    /// // different from that of `hline` and `vline`.
    /// >>> #set grid(inset: 3pt, align: center + horizon)
    /// #set grid(
    ///   columns: 2,
    ///   row-gutter: 5pt,
    /// )
    ///
    /// #grid(
    ///   stroke: (x, y) => if x == 0 { (right: green) },
    ///   [A], [B],
    ///   [C], [D],
    /// )
    ///
    /// #grid(
    ///   [A], grid.vline(stroke: green), [B],
    ///   [C], [D],
    /// )
    /// ```
    ///
    /// ```example
    /// #set page(height: 13em, width: 26em)
    ///

Review comment (suggestion):
<img width="219" height="682" alt="Image" src="https://github.com/user-attachments/assets/f88c5234-9001-4605-b1c5-33c1c5ac902e" />

Code after:
    /// - use an array of strokes corresponding to each column
    /// - use a function that maps a cell's position to its stroke
    ///
    /// See the [styling section](#styling) above for more details.
    ///
    /// ```example
    /// #set page(width: 420pt)
    /// #set text(number-type: "old-style")
    /// #show grid.cell.where(y: 0): set text(size: 1.3em)
    ///
    /// #grid(
    ///   columns: (1fr, 2fr, 2fr),
    ///   row-gutter: 1.5em,
    ///   inset: (left: 0.5em),
    ///   stroke: (x, y) => if x > 0 { (left: 0.5pt + gray) },
    ///   align: horizon,
    ///
    ///   [Winter \ 2007 \ Season],
    ///   [Aaron Copland \ *The Tender Land* \ January 2007],
    ///   [Eric Satie \ *Gymnopedie 1, 2* \ February 2007],
    ///
    ///   [],
    ///   [Jan 12 \ *Middlebury College \ Center for the Arts* \ 20:00],
    ///   [Feb 2 \ *Johnson State College Dibden Center for the Arts* \ 19:30],
    ///
    ///   [],
    ///   [Skip a week \ #text(0.8em)[_Prepare your exams!_]],
    ///   [Feb 9 \ *Castleton State College \ Fine Arts Center* \ 19:30],
    ///
    ///   [],
    ///   [Jan 26, 27 \ *Lyndon State College Alexander Twilight Theater* \ 20:00],
    ///   [
    ///     Feb 17 --- #smallcaps[Anniversary] \
    ///     *Middlebury College \ Center for the Arts* \
    ///     19:00 #text(0.7em)[(for a special guest)]
    ///   ],
    /// )
    /// ```
    ///
    /// ```example
    /// #set page(height: 13em, width: 26em)
    ///
    /// #let cv(..jobs) = grid(
    ///   columns: 2,
    ///   inset: 5pt,
    ///   stroke: (x, y) => if x == 0 and y > 0 {
    ///     (right: (
    ///       paint: luma(180),
    ///       thickness: 1.5pt,
    ///       dash: "dotted"
    ///     ))
Repository: typst/typst
File: crates/typst-library/src/foundations/calc.rs (Rust)

Code before:
}

/// Calculates the hyperbolic tangent of a hyperbolic angle.
///
/// ```example
/// #calc.tanh(0) \
/// #calc.tanh(1.5)
/// ```
#[func(title = "Hyperbolic Tangent")]
pub fn tanh(
    /// The hyperbolic angle whose hyperbolic tangent to calculate.
    value: f64,
) -> f64 {
    value.tanh()
}

/// Calculates the inverse hyperbolic sine of a number.
///
/// ```example
/// #calc.asinh(0) \
/// #calc.asinh(1)
/// ```
#[func(title = "Inverse Hyperbolic Sine")]
pub fn asinh(
    /// The number whose inverse hyperbolic sine to calculate.
    value: Num,
) -> f64 {
    value.float().asinh()
}

/// Calculates the inverse hyperbolic cosine of a number.
///
/// ```example
/// #calc.acosh(1) \
/// #calc.acosh(2.5)
/// ```
#[func(title = "Inverse Hyperbolic Cosine")]
pub fn acosh(
    /// The number whose inverse hyperbolic cosine to calculate. Must be greater than or equal to 1.
    value: Spanned<Num>,
) -> SourceResult<f64> {
    let val = value.v.float();
    if val < 1.0 {
        bail!(value.span, "value must be greater than or equal to 1");
    }
    Ok(val.acosh())
}

/// Calculates the inverse hyperbolic tangent of a number.
///
/// ```example

Review comment (suggestion):
`Num` can be `f64` everywhere here since we call `value.float()` directly and ints auto-ast to floats on a language level.

Code after:
    value: f64,
) -> f64 {
    libm::cosh(value)
}

/// Calculates the hyperbolic tangent of a hyperbolic angle.
///
/// ```example
/// #calc.tanh(0) \
/// #calc.tanh(1.5)
/// ```
#[func(title = "Hyperbolic Tangent")]
pub fn tanh(
    /// The hyperbolic angle whose hyperbolic tangent to calculate.
    value: f64,
) -> f64 {
    libm::tanh(value)
}

/// Calculates the inverse hyperbolic sine of a number.
///
/// ```example
/// #calc.asinh(0) \
/// #calc.asinh(1)
/// ```
#[func(title = "Inverse Hyperbolic Sine")]
pub fn asinh(
    /// The number whose inverse hyperbolic sine to calculate.
    value: f64,
) -> f64 {
    libm::asinh(value)
}

/// Calculates the inverse hyperbolic cosine of a number.
///
/// ```example
/// #calc.acosh(1) \
/// #calc.acosh(2.5)
/// ```
#[func(title = "Inverse Hyperbolic Cosine")]
pub fn acosh(
    /// The number whose inverse hyperbolic cosine to calculate. Must be greater
    /// than or equal to 1.
    value: Spanned<f64>,
) -> SourceResult<f64> {
    let val = value.v;
    if val < 1.0 {
        bail!(value.span, "value must be greater than or equal to 1");
    }
    Ok(libm::acosh(val))
}
Repository: typst/typst
File: crates/typst-syntax/src/node.rs (Rust)

Code before:
    /// you may need to use [`get()`](Self::get) instead in some situations.
    fn deref(&self) -> &Self::Target {
        self.get()
    }
}

impl Debug for LinkedNode<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.node.fmt(f)
    }
}

/// An iterator over the children of a linked node.
pub struct LinkedChildren<'a> {
    parent: Rc<LinkedNode<'a>>,
    iter: std::slice::Iter<'a, SyntaxNode>,
    index: usize,
    front: usize,
    back: usize,
}

impl<'a> Iterator for LinkedChildren<'a> {
    type Item = LinkedNode<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let node = self.iter.next()?;
        let item = LinkedNode {
            node,
            parent: Some(self.parent.clone()),
            index: self.index,
            offset: self.front,
        };
        self.index += 1;
        self.front += node.len();
        Some(item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl DoubleEndedIterator for LinkedChildren<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let node = self.iter.next_back()?;
        self.back -= node.len();
        Some(LinkedNode {
            node,
            parent: Some(self.parent.clone()),
            index: self.index + self.iter.len(),
            offset: self.back,

Review comment (suggestion):
The use of the question mark operator here and in `next_back` is nice.

Code after:
        while let Some(next) = node.next_sibling() {
            if let Some(leaf) = next.leftmost_leaf() {
                return Some(leaf);
            }
            node = next;
        }
        self.parent()?.next_leaf()
    }
}

impl Deref for LinkedNode<'_> {
    type Target = SyntaxNode;

    /// Dereference to a syntax node. Note that this shortens the lifetime, so
    /// you may need to use [`get()`](Self::get) instead in some situations.
    fn deref(&self) -> &Self::Target {
        self.get()
    }
}

impl Debug for LinkedNode<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.node.fmt(f)
    }
}

/// An iterator over the children of a linked node.
pub struct LinkedChildren<'a> {
    /// The parent whose children we're iterating.
    parent: Rc<LinkedNode<'a>>,
    /// The underlying syntax nodes and their indices.
    iter: std::iter::Enumerate<std::slice::Iter<'a, SyntaxNode>>,
    /// The byte offset of the next child's start.
    front: usize,
    /// The byte offset after the final child.
    back: usize,
}

impl<'a> Iterator for LinkedChildren<'a> {
    type Item = LinkedNode<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let (index, node) = self.iter.next()?;
        let offset = self.front;
        self.front += node.len();
        Some(LinkedNode {
            node,
            parent: Some(self.parent.clone()),
            index,
            offset,
        })
Repository: typst/typst
File: crates/typst-eval/src/binding.rs (Rust)

Code before:
use ecow::eco_format;
use rustc_hash::FxHashSet;
use typst_library::diag::{At, SourceDiagnostic, SourceResult, bail, error};
use typst_library::foundations::{Array, Dict, Value};
use typst_syntax::ast::{self, AstNode};

use crate::{Access, Eval, Vm};
use typst_library::diag::HintedString;

/// Provide a hint if the callee is a shadowed standard library function.
pub(crate) fn hint_if_shadowed_std(
    vm: &mut Vm,
    callee: &ast::Expr,
    mut err: HintedString,
) -> HintedString {
    if let ast::Expr::Ident(ident) = callee {
        let ident = ident.get();
        if vm.scopes.check_std_shadowed(ident) {
            err.hint(eco_format!(
                "use `std.{ident}` to access the shadowed standard library function",
            ));
        }
    }
    err
}

impl Eval for ast::LetBinding<'_> {
    type Output = Value;

    fn eval(self, vm: &mut Vm) -> SourceResult<Self::Output> {
        let value = match self.init() {
            Some(expr) => expr.eval(vm)?,
            None => Value::None,
        };
        if vm.flow.is_some() {
            return Ok(Value::None);

Review comment (suggestion):
I think at the bottom of `vm.rs` would be a better place.

Code after:
use ecow::eco_format;
use rustc_hash::FxHashSet;
use typst_library::diag::{At, SourceDiagnostic, SourceResult, bail, error};
use typst_library::foundations::{Array, Dict, Value};
use typst_syntax::ast::{self, AstNode};

use crate::{Access, Eval, Vm};

impl Eval for ast::LetBinding<'_> {
    type Output = Value;

    fn eval(self, vm: &mut Vm) -> SourceResult<Self::Output> {
        let value = match self.init() {
            Some(expr) => expr.eval(vm)?,
            None => Value::None,
        };
        if vm.flow.is_some() {
            return Ok(Value::None);
        }

        match self.kind() {
            ast::LetBindingKind::Normal(pattern) => destructure(vm, pattern, value)?,
            ast::LetBindingKind::Closure(ident) => vm.define(ident, value),
        }

        Ok(Value::None)
    }
}

impl Eval for ast::DestructAssignment<'_> {
    type Output = Value;

    fn eval(self, vm: &mut Vm) -> SourceResult<Self::Output> {
        let value = self.value().eval(vm)?;
        destructure_impl(vm, self.pattern(), value, &mut |vm, expr, value| {
            let location = expr.access(vm)?;