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

Code before:
        match (x, y) {
            (Smart::Auto, Smart::Auto) => {
                bail!(self.span(), "x and y cannot both be auto")
            }
            (Smart::Custom(x), Smart::Custom(y)) => Ok(Axes::new(x, y)),
            (Smart::Auto, Smart::Custom(v)) | (Smart::Custom(v), Smart::Auto) => {
                Ok(Axes::splat(v))
            }
        }
    }
}

cast! {
    ScaleAmount,
    self => match self {
        ScaleAmount::Ratio(ratio) => ratio.into_value(),
        ScaleAmount::Length(length) => length.into_value(),
    },
    ratio: Ratio => ScaleAmount::Ratio(ratio),
    length: Length => ScaleAmount::Length(length),
}

/// Skews content without affecting the layout.
///
/// Skews an element in horizontal and/or vertical direction. The layout will
/// act as if the element was not skewed unless you specify `{reflow: true}`.
///
/// # Example
/// ```example
/// #skew(-12deg)[This is some fake italic text.]
/// ```
#[elem(Show)]
pub struct SkewElem {
    /// The horizontal skewing angle.
    ///
    /// ```example
    /// #skew(ax: 30deg)[Skewed]
    /// ```
    ///
    #[parse(args.named("ax")?.or(args.find()?))]
    #[default(Angle::zero())]
    pub ax: Angle,

    /// The vertical skewing angle.
    ///
    /// ```example
    /// #skew(ay: 30deg)[Skewed]
    /// ```
    ///
    #[parse(args.named("ay")?.or(args.find()?))]
    #[default(Angle::zero())]

Review comment (suggestion):
Aren't the first and third sentence somehwat contradictory? Since it will affect the layout if `reflow` is set to `true`.

Code after:
        match (x, y) {
            (Smart::Auto, Smart::Auto) => {
                bail!(self.span(), "x and y cannot both be auto")
            }
            (Smart::Custom(x), Smart::Custom(y)) => Ok(Axes::new(x, y)),
            (Smart::Auto, Smart::Custom(v)) | (Smart::Custom(v), Smart::Auto) => {
                Ok(Axes::splat(v))
            }
        }
    }
}

cast! {
    ScaleAmount,
    self => match self {
        ScaleAmount::Ratio(ratio) => ratio.into_value(),
        ScaleAmount::Length(length) => length.into_value(),
    },
    ratio: Ratio => ScaleAmount::Ratio(ratio),
    length: Length => ScaleAmount::Length(length),
}

/// Skews content.
///
/// Skews an element in horizontal and/or vertical direction. The layout will
/// act as if the element was not skewed unless you specify `{reflow: true}`.
///
/// # Example
/// ```example
/// #skew(ax: -12deg)[This is some fake italic text.]
/// ```
#[elem(Show)]
pub struct SkewElem {
    /// The horizontal skewing angle.
    ///
    /// ```example
    /// #skew(ax: 30deg)[Skewed]
    /// ```
    ///
    #[default(Angle::zero())]
    pub ax: Angle,

    /// The vertical skewing angle.
    ///
    /// ```example
    /// #skew(ay: 30deg)[Skewed]
    /// ```
    ///
    #[default(Angle::zero())]
    pub ay: Angle,
Repository: typst/typst
File: crates/typst/src/foundations/args.rs (Rust)

Code before:
use std::fmt::{self, Debug, Formatter};

use ecow::{eco_format, eco_vec, EcoString, EcoVec};
use typst_macros::cast;

use crate::diag::{bail, error, At, SourceDiagnostic, SourceResult, StrResult};
use crate::foundations::{
    func, repr, scope, ty, Array, Dict, FromValue, IntoValue, Repr, Str, Value,
};
use crate::syntax::{Span, Spanned};

/// Captured arguments to a function.
///
/// # Argument Sinks
/// Like built-in functions, custom functions can also take a variable number of
/// arguments. You can specify an _argument sink_ which collects all excess
/// arguments as `..sink`. The resulting `sink` value is of the `arguments`
/// type. It exposes methods to access the positional and named arguments.
///
/// ```example
/// #let format(title, ..authors) = {
///   let by = authors
///     .pos()
///     .join(", ", last: " and ")
///
///   [*#title* \ _Written by #by;_]
/// }
///
/// #format("ArtosFlow", "Jane", "Joe")

Review comment (refactor):
please move this into the `crate::foundations` import

Code after:
use std::fmt::{self, Debug, Formatter};

use ecow::{eco_format, eco_vec, EcoString, EcoVec};

use crate::diag::{bail, error, At, SourceDiagnostic, SourceResult, StrResult};
use crate::foundations::{
    cast, func, repr, scope, ty, Array, Dict, FromValue, IntoValue, Repr, Str, Value,
};
use crate::syntax::{Span, Spanned};

/// Captured arguments to a function.
///
/// # Argument Sinks
/// Like built-in functions, custom functions can also take a variable number of
/// arguments. You can specify an _argument sink_ which collects all excess
/// arguments as `..sink`. The resulting `sink` value is of the `arguments`
/// type. It exposes methods to access the positional and named arguments.
///
/// ```example
/// #let format(title, ..authors) = {
///   let by = authors
///     .pos()
///     .join(", ", last: " and ")
///
///   [*#title* \ _Written by #by;_]
/// }
///
/// #format("ArtosFlow", "Jane", "Joe")
/// ```
Repository: typst/typst
File: crates/typst-syntax/src/parser.rs (Rust)

Code before:
        node.hint("destructuring patterns must be wrapped in parentheses");
        if p.at_set(set::PATTERN) {
            pattern(p, false, &mut seen, None);
        }
    }

    p.expect(SyntaxKind::In);
    code_expr(p);
    block(p);
    p.wrap(m, SyntaxKind::ForLoop);
}

/// Parses a module import: `import "utils.typ": a, b, c`.
fn module_import(p: &mut Parser) {
    let m = p.marker();
    p.assert(SyntaxKind::Import);
    code_expr(p);
    if p.eat_if(SyntaxKind::As) {
        // Allow renaming a full module import.
        // If items are included, both the full module and the items are
        // imported at the same time.
        p.expect(SyntaxKind::Ident);
    }

    if p.eat_if(SyntaxKind::Colon) {
        if p.current() == SyntaxKind::LeftParen {
            let m1 = p.marker();
            p.enter_newline_mode(NewlineMode::Continue);
            p.expect(SyntaxKind::LeftParen);

            import_items(p);

            p.expect_closing_delimiter(m1, SyntaxKind::RightParen);
            p.exit_newline_mode();
        } else if !p.eat_if(SyntaxKind::Star) {
            import_items(p);
        }
    }

    p.wrap(m, SyntaxKind::ModuleImport);
}

/// Parses items to import from a module: `a, b, c`.
fn import_items(p: &mut Parser) {
    let m = p.marker();
    while !p.current().is_terminator() {
        let item_marker = p.marker();
        if !p.eat_if(SyntaxKind::Ident) {
            p.unexpected();
        }


Review comment (suggestion):
```suggestion
        if p.at(SyntaxKind::LeftParen) {
```

Code after:
        node.hint("destructuring patterns must be wrapped in parentheses");
        if p.at_set(set::PATTERN) {
            pattern(p, false, &mut seen, None);
        }
    }

    p.expect(SyntaxKind::In);
    code_expr(p);
    block(p);
    p.wrap(m, SyntaxKind::ForLoop);
}

/// Parses a module import: `import "utils.typ": a, b, c`.
fn module_import(p: &mut Parser) {
    let m = p.marker();
    p.assert(SyntaxKind::Import);
    code_expr(p);
    if p.eat_if(SyntaxKind::As) {
        // Allow renaming a full module import.
        // If items are included, both the full module and the items are
        // imported at the same time.
        p.expect(SyntaxKind::Ident);
    }

    if p.eat_if(SyntaxKind::Colon) {
        if p.at(SyntaxKind::LeftParen) {
            let m1 = p.marker();
            p.enter_newline_mode(NewlineMode::Continue);
            p.assert(SyntaxKind::LeftParen);

            import_items(p);

            p.expect_closing_delimiter(m1, SyntaxKind::RightParen);
            p.exit_newline_mode();
        } else if !p.eat_if(SyntaxKind::Star) {
            import_items(p);
        }
    }

    p.wrap(m, SyntaxKind::ModuleImport);
}

/// Parses items to import from a module: `a, b, c`.
fn import_items(p: &mut Parser) {
    let m = p.marker();
    while !p.current().is_terminator() {
        let item_marker = p.marker();
        if !p.eat_if(SyntaxKind::Ident) {
            p.unexpected();
        }
Repository: typst/typst
File: crates/typst-syntax/src/parser.rs (Rust)

Code before:
        }
    }

    p.expect(SyntaxKind::In);
    code_expr(p);
    block(p);
    p.wrap(m, SyntaxKind::ForLoop);
}

/// Parses a module import: `import "utils.typ": a, b, c`.
fn module_import(p: &mut Parser) {
    let m = p.marker();
    p.assert(SyntaxKind::Import);
    code_expr(p);
    if p.eat_if(SyntaxKind::As) {
        // Allow renaming a full module import.
        // If items are included, both the full module and the items are
        // imported at the same time.
        p.expect(SyntaxKind::Ident);
    }

    if p.eat_if(SyntaxKind::Colon) {
        if p.current() == SyntaxKind::LeftParen {
            let m1 = p.marker();
            p.enter_newline_mode(NewlineMode::Continue);
            p.expect(SyntaxKind::LeftParen);

            import_items(p);

            p.expect_closing_delimiter(m1, SyntaxKind::RightParen);
            p.exit_newline_mode();
        } else if !p.eat_if(SyntaxKind::Star) {
            import_items(p);
        }
    }

    p.wrap(m, SyntaxKind::ModuleImport);
}

/// Parses items to import from a module: `a, b, c`.
fn import_items(p: &mut Parser) {
    let m = p.marker();
    while !p.current().is_terminator() {
        let item_marker = p.marker();
        if !p.eat_if(SyntaxKind::Ident) {
            p.unexpected();
        }

        // Nested import path: `a.b.c`
        while p.eat_if(SyntaxKind::Dot) {
            p.expect(SyntaxKind::Ident);

Review comment (suggestion):
```suggestion
            p.assert(SyntaxKind::LeftParen);
```

Code after:
        }
    }

    p.expect(SyntaxKind::In);
    code_expr(p);
    block(p);
    p.wrap(m, SyntaxKind::ForLoop);
}

/// Parses a module import: `import "utils.typ": a, b, c`.
fn module_import(p: &mut Parser) {
    let m = p.marker();
    p.assert(SyntaxKind::Import);
    code_expr(p);
    if p.eat_if(SyntaxKind::As) {
        // Allow renaming a full module import.
        // If items are included, both the full module and the items are
        // imported at the same time.
        p.expect(SyntaxKind::Ident);
    }

    if p.eat_if(SyntaxKind::Colon) {
        if p.at(SyntaxKind::LeftParen) {
            let m1 = p.marker();
            p.enter_newline_mode(NewlineMode::Continue);
            p.assert(SyntaxKind::LeftParen);

            import_items(p);

            p.expect_closing_delimiter(m1, SyntaxKind::RightParen);
            p.exit_newline_mode();
        } else if !p.eat_if(SyntaxKind::Star) {
            import_items(p);
        }
    }

    p.wrap(m, SyntaxKind::ModuleImport);
}

/// Parses items to import from a module: `a, b, c`.
fn import_items(p: &mut Parser) {
    let m = p.marker();
    while !p.current().is_terminator() {
        let item_marker = p.marker();
        if !p.eat_if(SyntaxKind::Ident) {
            p.unexpected();
        }

        // Nested import path: `a.b.c`
        while p.eat_if(SyntaxKind::Dot) {
            p.expect(SyntaxKind::Ident);
Repository: typst/typst
File: crates/typst/src/visualize/image/mod.rs (Rust)

Code before:
use crate::visualize::Path;
use crate::World;

/// A raster or vector graphic.
///
/// Supported formats are PNG, JPEG, GIF and SVG.
///
/// _Note:_ Work on SVG export is ongoing and there might be visual inaccuracies
/// in the resulting PDF. Make sure to double-check embedded SVG images. If you
/// have an issue, also feel free to report it on [GitHub][gh-svg].
///
/// # Example
/// ```example
/// #figure(
///   image("molecular.jpg", width: 80%),
///   caption: [
///     A step in the molecular testing
///     pipeline of our lab.
///   ],
/// )
/// ```
///
/// [gh-svg]: https://github.com/typst/typst/issues?q=is%3Aopen+is%3Aissue+label%3Asvg
#[elem(scope, Show, LocalName, Figurable)]
pub struct ImageElem {
    /// Path to an image file, relative to the input file by default; if starting with `/`, it's relative to the `--root` path.
    #[required]
    #[parse(
        let Spanned { v: path, span } =
            args.expect::<Spanned<EcoString>>("path to image file")?;
        let id = span.resolve_path(&path).at(span)?;
        let data = engine.world.file(id).at(span)?;
        path
    )]
    #[borrowed]
    pub path: EcoString,

    /// The raw file data.
    #[internal]
    #[required]
    #[parse(Readable::Bytes(data))]
    pub data: Readable,

    /// The image's format. Detected automatically by default.
    pub format: Smart<ImageFormat>,

    /// The width of the image.
    pub width: Smart<Rel<Length>>,

    /// The height of the image.
    pub height: Smart<Rel<Length>>,

Review comment (suggestion):
For non-CLI users, they would not know what `--root` is. :confused: 

Code after:
use crate::visualize::Path;
use crate::World;

/// A raster or vector graphic.
///
/// Supported formats are PNG, JPEG, GIF and SVG.
///
/// _Note:_ Work on SVG export is ongoing and there might be visual inaccuracies
/// in the resulting PDF. Make sure to double-check embedded SVG images. If you
/// have an issue, also feel free to report it on [GitHub][gh-svg].
///
/// # Example
/// ```example
/// #figure(
///   image("molecular.jpg", width: 80%),
///   caption: [
///     A step in the molecular testing
///     pipeline of our lab.
///   ],
/// )
/// ```
///
/// [gh-svg]: https://github.com/typst/typst/issues?q=is%3Aopen+is%3Aissue+label%3Asvg
#[elem(scope, Show, LocalName, Figurable)]
pub struct ImageElem {
    /// Path to an image file
    ///
    /// For more details, see the [Paths section]($syntax/#paths).
    #[required]
    #[parse(
        let Spanned { v: path, span } =
            args.expect::<Spanned<EcoString>>("path to image file")?;
        let id = span.resolve_path(&path).at(span)?;
        let data = engine.world.file(id).at(span)?;
        path
    )]
    #[borrowed]
    pub path: EcoString,

    /// The raw file data.
    #[internal]
    #[required]
    #[parse(Readable::Bytes(data))]
    pub data: Readable,

    /// The image's format. Detected automatically by default.
    pub format: Smart<ImageFormat>,

    /// The width of the image.
    pub width: Smart<Rel<Length>>,
Repository: typst/typst
File: crates/typst/src/visualize/image/mod.rs (Rust)

Code before:

use std::ffi::OsStr;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;

use comemo::Tracked;
use ecow::EcoString;

use crate::diag::{bail, At, SourceResult, StrResult};
use crate::engine::Engine;
use crate::foundations::{
    cast, elem, func, scope, Bytes, Cast, Content, NativeElement, Packed, Show, Smart,
    StyleChain,
};
use crate::introspection::Locator;
use crate::layout::{
    Abs, Axes, BlockElem, FixedAlignment, Frame, FrameItem, Length, Point, Region, Rel,
    Size,
};
use crate::loading::Readable;
use crate::model::Figurable;
use crate::syntax::{Span, Spanned};
use crate::text::{families, LocalName};
use crate::utils::LazyHash;
use crate::visualize::Path;
use crate::warning;
use crate::World;

/// A raster or vector graphic.
///
/// Supported formats are PNG, JPEG, GIF and SVG.
///
/// _Note:_ Work on SVG export is ongoing and there might be visual inaccuracies
/// in the resulting PDF. Make sure to double-check embedded SVG images. If you
/// have an issue, also feel free to report it on [GitHub][gh-svg].
///
/// # Example
/// ```example
/// #figure(
///   image("molecular.jpg", width: 80%),
///   caption: [
///     A step in the molecular testing
///     pipeline of our lab.
///   ],
/// )
/// ```
///
/// [gh-svg]: https://github.com/typst/typst/issues?q=is%3Aopen+is%3Aissue+label%3Asvg
#[elem(scope, Show, LocalName, Figurable)]
pub struct ImageElem {
    /// Path to an image file.

Review comment (suggestion):
not sure why this even works, but it should be imported from `crate::diag`

Code after:

use std::ffi::OsStr;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;

use comemo::Tracked;
use ecow::EcoString;

use crate::diag::{bail, warning, At, SourceResult, StrResult};
use crate::engine::Engine;
use crate::foundations::{
    cast, elem, func, scope, Bytes, Cast, Content, NativeElement, Packed, Show, Smart,
    StyleChain,
};
use crate::introspection::Locator;
use crate::layout::{
    Abs, Axes, BlockElem, FixedAlignment, Frame, FrameItem, Length, Point, Region, Rel,
    Size,
};
use crate::loading::Readable;
use crate::model::Figurable;
use crate::syntax::{Span, Spanned};
use crate::text::{families, LocalName};
use crate::utils::LazyHash;
use crate::visualize::Path;
use crate::World;

/// A raster or vector graphic.
///
/// Supported formats are PNG, JPEG, GIF and SVG.
///
/// _Note:_ Work on SVG export is ongoing and there might be visual inaccuracies
/// in the resulting PDF. Make sure to double-check embedded SVG images. If you
/// have an issue, also feel free to report it on [GitHub][gh-svg].
///
/// # Example
/// ```example
/// #figure(
///   image("molecular.jpg", width: 80%),
///   caption: [
///     A step in the molecular testing
///     pipeline of our lab.
///   ],
/// )
/// ```
///
/// [gh-svg]: https://github.com/typst/typst/issues?q=is%3Aopen+is%3Aissue+label%3Asvg
#[elem(scope, Show, LocalName, Figurable)]
pub struct ImageElem {
    /// Path to an image file.
    #[required]
Repository: typst/typst
File: crates/typst-syntax/src/lexer.rs (Rust)

Code before:

use crate::{SyntaxError, SyntaxKind};

/// Splits up a string of source code into tokens.
#[derive(Clone)]
pub(super) struct Lexer<'s> {
    /// The underlying scanner.
    s: Scanner<'s>,
    /// The mode the lexer is in. This determines which kinds of tokens it
    /// produces.
    mode: LexMode,
    /// Whether the last token contained a newline.
    newline: bool,
    /// The state held by raw line lexing.
    raw: Vec<(SyntaxKind, usize)>,
    /// An error for the last token.
    error: Option<SyntaxError>,
}

/// What kind of tokens to emit.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(super) enum LexMode {
    /// Text and markup.
    Markup,
    /// Math atoms, operators, etc.
    Math,
    /// An argument in a math function.
    MathArg,
    /// Function argument list in math.
    MathArgs,
    /// Keywords, literals and operators.
    Code,
    /// The contents of a raw block.
    Raw,
}

impl<'s> Lexer<'s> {
    /// Create a new lexer with the given mode and a prefix to offset column
    /// calculations.
    pub fn new(text: &'s str, mode: LexMode) -> Self {
        Self {
            s: Scanner::new(text),
            mode,
            newline: false,
            error: None,
            raw: Vec::new(),
        }
    }

    /// Get the current lexing mode.
    pub fn mode(&self) -> LexMode {

Review comment (suggestion):
Following your comment in the PR description, I do think it would be ideal to use #4364's work on returning a SyntaxNode instead of creating new modes if possible. But we'll have to wait and see how that PR progresses.

Code after:

use crate::{SyntaxError, SyntaxKind, SyntaxNode};

/// An iterator over a source code string which returns tokens.
#[derive(Clone)]
pub(super) struct Lexer<'s> {
    /// The scanner: contains the underlying string and location as a "cursor".
    s: Scanner<'s>,
    /// The mode the lexer is in. This determines which kinds of tokens it
    /// produces.
    mode: LexMode,
    /// Whether the last token contained a newline.
    newline: bool,
    /// An error for the last token.
    error: Option<SyntaxError>,
}

/// What kind of tokens to emit.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(super) enum LexMode {
    /// Text and markup.
    Markup,
    /// Math atoms, operators, etc.
    Math,
    /// Keywords, literals and operators.
    Code,
}

impl<'s> Lexer<'s> {
    /// Create a new lexer with the given mode and a prefix to offset column
    /// calculations.
    pub fn new(text: &'s str, mode: LexMode) -> Self {
        Self {
            s: Scanner::new(text),
            mode,
            newline: false,
            error: None,
        }
    }

    /// Get the current lexing mode.
    pub fn mode(&self) -> LexMode {
        self.mode
    }

    /// Change the lexing mode.
    pub fn set_mode(&mut self, mode: LexMode) {
        self.mode = mode;
    }

    /// The index in the string at which the last token ends and next token
Repository: typst/typst
File: crates/typst/src/math/stretch.rs (Rust)

Code before:
    }
}

/// Attempts to stretch the given fragment by/to the amount given in stretch.
pub(super) fn stretch_fragment(
    ctx: &mut MathContext,
    styles: StyleChain,
    fragment: &mut MathFragment,
    axis: Option<Axis>,
    relative_to: Option<Abs>,
    stretch: Smart<Rel<Length>>,
    short_fall: Abs,
) {
    let glyph = match fragment {
        MathFragment::Glyph(glyph) => glyph.clone(),
        MathFragment::Variant(variant) => {
            GlyphFragment::new(ctx, styles, variant.c, variant.span)
        }
        _ => return,
    };

    let axis = if let Some(stretch_axis) = axis.or_else(|| stretch_axis(ctx, &glyph)) {
        stretch_axis
    } else {
        return;
    };

    let relative_to_size = relative_to.unwrap_or_else(|| fragment.size().get(axis));

    let mut variant = stretch_glyph(
        ctx,
        glyph,
        stretch
            .unwrap_or(Rel::one())
            .resolve(styles)
            .relative_to(relative_to_size),
        short_fall,
        axis,
    );

    if axis == Axis::Y {
        variant.align_on_axis(ctx, delimiter_alignment(variant.c));
    }

    *fragment = MathFragment::Variant(variant);
}

pub(super) fn delimiter_alignment(delimiter: char) -> VAlignment {
    match delimiter {
        '\u{231c}' | '\u{231d}' => VAlignment::Top,
        '\u{231e}' | '\u{231f}' => VAlignment::Bottom,

Review comment (suggestion):
```suggestion
    let Some(axis) = axis.or_else(|| stretch_axis(ctx, &glyph)) else {
        return;
    };
```

Code after:
    }
}

/// Attempts to stretch the given fragment by/to the amount given in stretch.
pub(super) fn stretch_fragment(
    ctx: &mut MathContext,
    styles: StyleChain,
    fragment: &mut MathFragment,
    axis: Option<Axis>,
    relative_to: Option<Abs>,
    stretch: Smart<Rel<Length>>,
    short_fall: Abs,
) {
    let glyph = match fragment {
        MathFragment::Glyph(glyph) => glyph.clone(),
        MathFragment::Variant(variant) => {
            GlyphFragment::new(ctx, styles, variant.c, variant.span)
        }
        _ => return,
    };

    let Some(axis) = axis.or_else(|| stretch_axis(ctx, &glyph)) else {
        return;
    };

    let relative_to_size = relative_to.unwrap_or_else(|| fragment.size().get(axis));

    let mut variant = stretch_glyph(
        ctx,
        glyph,
        stretch
            .unwrap_or(Rel::one())
            .resolve(styles)
            .relative_to(relative_to_size),
        short_fall,
        axis,
    );

    if axis == Axis::Y {
        variant.align_on_axis(ctx, delimiter_alignment(variant.c));
    }

    *fragment = MathFragment::Variant(variant);
}

pub(super) fn delimiter_alignment(delimiter: char) -> VAlignment {
    match delimiter {
        '\u{231c}' | '\u{231d}' => VAlignment::Top,
        '\u{231e}' | '\u{231f}' => VAlignment::Bottom,
        _ => VAlignment::Horizon,
    }