profmt 0.1.0

A fast, deterministic, configurable Protocol Buffers formatter built on tree-sitter
Documentation
//! The statements that open a file — `syntax`, `package`, imports and file
//! options — and the optional reordering of that header.

use tree_sitter::Node;

use super::{Blank, Entry, Formatter, Item, Walk};
use crate::doc::SPACE;
use crate::options::{HeaderOrder, ImportOrder, OptionValueLayout};

impl Formatter<'_> {
    pub fn syntax(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        walk.expect(self, "syntax");
        walk.expect(self, "=");
        self.b.text("syntax = ");
        let version = walk.next(self).expect("syntax version");
        self.source_node(version);
        walk.expect(self, ";");
        self.b.text(";");
        walk.finish(self);
    }

    pub fn edition(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        walk.expect(self, "edition");
        walk.expect(self, "=");
        self.b.text("edition = ");
        let year = walk.expect(self, "string");
        self.string(year);
        walk.expect(self, ";");
        self.b.text(";");
        walk.finish(self);
    }

    pub fn import(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        walk.expect(self, "import");
        self.b.text("import ");
        if let Some(modifier) = walk.accept_any(self, &["weak", "public", "option"]) {
            self.source_node(modifier);
            self.b.text(" ");
        }
        let path = walk.expect(self, "string");
        self.string(path);
        walk.expect(self, ";");
        self.b.text(";");
        walk.finish(self);
    }

    pub fn package(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        walk.expect(self, "package");
        self.b.text("package ");
        let name = walk.expect(self, "full_ident");
        self.compact(name);
        walk.expect(self, ";");
        self.b.text(";");
        walk.finish(self);
    }

    /// `option name = value;`.
    pub fn option(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        walk.expect(self, "option");
        self.b.open_group();
        self.b.text("option ");
        self.option_name(&mut walk);
        walk.expect(self, "=");
        self.b.text(" =");
        let value = walk.expect(self, "constant");
        let literal = value.child(0).is_some_and(|child| child.kind() == "block_lit");
        match self.options.option_value_layout {
            OptionValueLayout::NewLine if !literal => {
                self.b.open_indent();
                self.b.line(SPACE);
                self.constant(value);
                self.b.close_indent();
            }
            OptionValueLayout::NewLine | OptionValueLayout::SingleLine => {
                self.b.text(" ");
                self.constant(value);
            }
        }
        self.b.close_group();
        walk.expect(self, ";");
        self.b.text(";");
        walk.finish(self);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Section {
    Preamble,
    Syntax,
    Package,
    Imports,
    Options,
}

/// A header statement with the comments that lead into it and the trailing
/// comments and stray semicolons that follow it.
struct Unit<'t> {
    section: Section,
    /// Position among the header's units in the source.
    source_index: usize,
    items: Vec<Item<'t>>,
}

const DEFINITIONS: &[&str] = &["message", "enum", "extend", "service"];

/// Arranges a file's items into entries, rewriting the header when the
/// header or import order is configured. Statements after the first
/// definition are never moved.
pub fn arrange<'t>(f: &Formatter<'_>, items: Vec<Item<'t>>) -> Vec<Entry<'t>> {
    let rewrite = f.options.header_order != HeaderOrder::Preserve || f.options.import_order != ImportOrder::Preserve;
    if !rewrite {
        return items.into_iter().map(source_entry).collect();
    }
    let end = items
        .iter()
        .position(|item| matches!(item, Item::Statement(node) if DEFINITIONS.contains(&node.kind())))
        .unwrap_or(items.len());
    let (region, rest) = items.split_at(end);

    let mut units: Vec<Unit<'t>> = Vec::new();
    let mut pending: Vec<Item<'t>> = Vec::new();
    for &item in region {
        match item {
            Item::Statement(node) => {
                pending.push(item);
                units.push(Unit {
                    section: section_of(node),
                    source_index: units.len(),
                    items: std::mem::take(&mut pending),
                });
            }
            Item::Trailing(_) | Item::Empty(_) if pending.is_empty() && !units.is_empty() => {
                units.last_mut().expect("checked").items.push(item);
            }
            _ => pending.push(item),
        }
    }
    // Comments after the last header statement lead into the first
    // definition.
    let mut rest: Vec<Item<'t>> = pending.into_iter().chain(rest.iter().copied()).collect();
    let region_empty = units.is_empty();

    // Comments at the top of the file separated from the first statement by
    // a blank line are a preamble that stays first.
    if let Some(first) = units.first_mut() {
        let split = detach_preamble(&first.items);
        if split > 0 {
            let preamble = first.items.drain(..split).collect();
            units.insert(
                0,
                Unit {
                    section: Section::Preamble,
                    source_index: 0,
                    items: preamble,
                },
            );
            for unit in units.iter_mut().skip(1) {
                unit.source_index += 1;
            }
        }
    }

    let order: Vec<Section> = match f.options.header_order {
        HeaderOrder::PackageFirst => vec![
            Section::Preamble,
            Section::Syntax,
            Section::Package,
            Section::Imports,
            Section::Options,
        ],
        HeaderOrder::ImportsFirst => vec![
            Section::Preamble,
            Section::Syntax,
            Section::Imports,
            Section::Package,
            Section::Options,
        ],
        HeaderOrder::Preserve => {
            let mut order = Vec::new();
            for unit in &units {
                if !order.contains(&unit.section) {
                    order.push(unit.section);
                }
            }
            order
        }
    };
    units.sort_by_key(|unit| order.iter().position(|section| *section == unit.section));
    if f.options.import_order == ImportOrder::Sorted {
        let start = units.iter().position(|unit| unit.section == Section::Imports);
        if let Some(start) = start {
            let end = start
                + units[start..]
                    .iter()
                    .take_while(|unit| unit.section == Section::Imports)
                    .count();
            units[start..end].sort_by_key(|unit| import_path(f, unit));
        }
    }

    let mut entries = Vec::with_capacity(items_len(&units) + rest.len());
    let mut previous: Option<(Section, usize)> = None;
    for unit in &units {
        let blank = match previous {
            None => Blank::Exactly(0),
            Some((section, _)) if section != unit.section => Blank::Exactly(1),
            Some(_) if unit.section == Section::Imports && f.options.import_order == ImportOrder::Sorted => {
                Blank::Exactly(0)
            }
            Some((_, source_index)) if source_index + 1 == unit.source_index => Blank::Source,
            Some(_) => Blank::Exactly(0),
        };
        let mut unit_items = unit.items.iter().copied();
        if let Some(first) = unit_items.next() {
            entries.push(Entry { item: first, blank });
        }
        entries.extend(unit_items.map(source_entry));
        previous = Some((unit.section, unit.source_index));
    }
    if !region_empty && let Some(first) = rest.first_mut() {
        entries.push(Entry {
            item: *first,
            blank: Blank::Exactly(1),
        });
        rest.remove(0);
    }
    entries.extend(rest.into_iter().map(source_entry));
    entries
}

fn source_entry(item: Item<'_>) -> Entry<'_> {
    Entry {
        item,
        blank: Blank::Source,
    }
}

fn items_len(units: &[Unit<'_>]) -> usize {
    units.iter().map(|unit| unit.items.len()).sum()
}

fn section_of(node: Node<'_>) -> Section {
    match node.kind() {
        "syntax" | "edition" => Section::Syntax,
        "package" => Section::Package,
        "import" => Section::Imports,
        "option" => Section::Options,
        other => unreachable!("`{other}` is not a header statement"),
    }
}

/// How many leading items of the first unit are separated from its statement
/// by a blank line, and so form the file preamble.
fn detach_preamble(items: &[Item<'_>]) -> usize {
    let statement = items
        .iter()
        .position(|item| matches!(item, Item::Statement(_)))
        .expect("a unit has a statement");
    let mut next_row = items[statement].node().start_position().row;
    let mut attached_from = statement;
    for (index, item) in items[..statement].iter().enumerate().rev() {
        if let Item::Trailing(_) = item {
            continue;
        }
        if item.node().end_position().row + 1 < next_row {
            break;
        }
        attached_from = index;
        next_row = item.node().start_position().row;
    }
    attached_from
}

fn import_path<'a>(f: &Formatter<'a>, unit: &Unit<'_>) -> &'a str {
    let import = unit
        .items
        .iter()
        .find_map(|item| match item {
            Item::Statement(node) => Some(*node),
            _ => None,
        })
        .expect("an import unit has a statement");
    let mut cursor = import.walk();
    let path = import
        .named_children(&mut cursor)
        .find(|child| child.kind() == "string")
        .expect("an import has a path");
    f.text_of(path).trim_matches(['"', '\''])
}