profmt 0.1.0

A fast, deterministic, configurable Protocol Buffers formatter built on tree-sitter
Documentation
//! Comments, identifiers, strings and option values.

use std::borrow::Cow;

use tree_sitter::Node;

use super::{Formatter, Walk};
use crate::doc::{HARD, SOFT, SPACE};
use crate::options::{CommentSpacing, QuoteStyle};

impl<'a> Formatter<'a> {
    /// Prints a comment that starts its own line.
    pub fn own_line_comment(&mut self, node: Node<'_>) {
        self.comment(node);
    }

    /// Prints a comment at the end of the current line. A line comment
    /// forces the enclosing groups to break so nothing follows it.
    pub fn trailing_comment(&mut self, node: Node<'_>) {
        let text = self.comment_text(node);
        let range = node.byte_range();
        self.b.line_suffix(|b| {
            b.text(" ");
            match text {
                Cow::Borrowed(text) => b.source(range.start, range.start + text.len()),
                Cow::Owned(text) => b.text(&text),
            }
        });
        if self.is_line_comment(node) {
            self.b.break_parent();
        }
    }

    /// Prints a comment found between the tokens of a statement.
    pub fn inline_comment(&mut self, node: Node<'_>) {
        if self.is_line_comment(node) {
            self.trailing_comment(node);
        } else {
            self.b.text(" ");
            self.comment(node);
            self.b.text(" ");
        }
    }

    fn is_line_comment(&self, node: Node<'_>) -> bool {
        self.source[node.byte_range()].starts_with(b"//")
    }

    fn comment(&mut self, node: Node<'_>) {
        let text = self.comment_text(node);
        let range = node.byte_range();
        match text {
            Cow::Borrowed(text) if text.contains('\n') => {
                self.block_comment(range.start, text, node.start_position().column)
            }
            Cow::Borrowed(text) => self.b.source(range.start, range.start + text.len()),
            Cow::Owned(text) => self.b.text(&text),
        }
    }

    /// Prints a block comment spanning several lines. Each later line loses
    /// up to `column` characters of leading whitespace — the indentation the
    /// comment had in the source — and gains the current indentation, so a
    /// column of `*` stays aligned under the opening `/*`.
    fn block_comment(&mut self, start: usize, text: &str, column: usize) {
        let mut offset = start;
        for (index, line) in text.split('\n').enumerate() {
            if index > 0 {
                self.b.line(HARD);
            }
            let line = line.strip_suffix('\r').unwrap_or(line);
            let trimmed = if index == 0 {
                line
            } else {
                let indentation = line
                    .bytes()
                    .take(column)
                    .take_while(|byte| matches!(byte, b' ' | b'\t'))
                    .count();
                &line[indentation..]
            };
            let line_start = offset + (line.len() - trimmed.len());
            self.b.source(line_start, line_start + trimmed.len());
            offset += line.len() + 1;
        }
    }

    /// The comment as printed: trailing whitespace removed, and the space
    /// after `//` normalised when configured. Borrowed text is a prefix of
    /// the source comment.
    fn comment_text(&self, node: Node<'_>) -> Cow<'a, str> {
        let text = self.text_of(node).trim_end_matches([' ', '\t', '\r']);
        if self.options.comment_spacing == CommentSpacing::Normalized
            && let Some(body) = text.strip_prefix("//")
            && let Some(first) = body.chars().next()
            && !matches!(first, ' ' | '\t' | '/' | '!')
        {
            return Cow::Owned(format!("// {body}"));
        }
        Cow::Borrowed(text)
    }

    /// Prints a node's tokens with no whitespace between them: dotted names,
    /// type references, option names.
    pub fn compact(&mut self, node: Node<'_>) {
        if node.child_count() == 0 {
            self.source_node(node);
            return;
        }
        let mut walk = Walk::new(node);
        while let Some(child) = walk.next(self) {
            self.compact(child);
        }
    }

    /// Prints an option name up to, but not including, its `=`.
    pub fn option_name(&mut self, walk: &mut Walk<'_>) {
        while walk.peek().is_some_and(|kind| kind != "=") {
            let part = walk.next(self).expect("peeked");
            self.compact(part);
        }
    }

    /// Prints `name = value` for a statement option, field option or enum
    /// value option, consuming the rest of `walk` up to the value.
    pub fn option_assignment(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        self.option_name(&mut walk);
        walk.expect(self, "=");
        self.b.text(" = ");
        let value = walk.expect(self, "constant");
        self.constant(value);
        walk.finish(self);
    }

    pub fn constant(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        while let Some(child) = walk.next(self) {
            match child.kind() {
                "string" => self.string(child),
                "block_lit" => self.block_literal(child),
                "full_ident" => self.compact(child),
                _ => self.source_node(child),
            }
        }
    }

    /// Prints a string literal, converting each quoted piece to the preferred
    /// delimiter where that changes no bytes of the value. Adjacent pieces
    /// are separated by one space.
    pub fn string(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        let mut open: Option<Node<'_>> = None;
        let mut first = true;
        while let Some(child) = walk.next(self) {
            if !matches!(child.kind(), "\"" | "'") {
                continue;
            }
            match open.take() {
                None => open = Some(child),
                Some(opening) => {
                    if !first {
                        self.b.text(" ");
                    }
                    first = false;
                    self.quoted(opening.start_byte(), child.end_byte());
                }
            }
        }
    }

    /// Prints the quoted literal at `start..end`, switching delimiters when
    /// the body contains no quote or backslash.
    pub fn quoted(&mut self, start: usize, end: usize) {
        let body = &self.source[start + 1..end - 1];
        let target = match self.options.quote_style {
            QuoteStyle::Preserve => None,
            QuoteStyle::Single => Some("'"),
            QuoteStyle::Double => Some("\""),
        };
        match target {
            Some(quote)
                if quote.as_bytes()[0] != self.source[start]
                    && !body.iter().any(|byte| matches!(byte, b'"' | b'\'' | b'\\')) =>
            {
                self.b.text(quote);
                self.b.source(start + 1, end - 1);
                self.b.text(quote);
            }
            _ => self.b.source(start, end),
        }
    }

    /// Prints a text-format message literal: `{ key: value, nested { ... } }`.
    fn block_literal(&mut self, node: Node<'_>) {
        let mut walk = Walk::new(node);
        walk.expect(self, "{");
        if walk.peek() == Some("}") {
            self.b.text("{}");
            walk.expect(self, "}");
            walk.finish(self);
            return;
        }
        self.b.open_group();
        self.b.text("{");
        self.b.open_indent();
        while walk.peek().is_some_and(|kind| kind != "}") {
            self.b.line(SPACE);
            match walk.peek() {
                Some("[") => {
                    walk.expect(self, "[");
                    self.b.text("[");
                    let name = walk.expect(self, "full_ident");
                    self.compact(name);
                    walk.expect(self, "]");
                    self.b.text("]");
                }
                _ => {
                    let key = walk.expect(self, "identifier");
                    self.source_node(key);
                }
            }
            if walk.accept(self, ":").is_some() {
                self.b.text(":");
            }
            self.b.text(" ");
            match walk.peek() {
                Some("[") => self.constant_list(&mut walk),
                _ => {
                    let value = walk.expect(self, "constant");
                    self.constant(value);
                }
            }
            if let Some(separator) = walk.accept_any(self, &[",", ";"]) {
                self.source_node(separator);
            }
        }
        self.b.close_indent();
        self.b.line(SPACE);
        self.b.text("}");
        self.b.close_group();
        walk.expect(self, "}");
        walk.finish(self);
    }

    /// Prints `[a, b, c]` inside a text-format literal.
    fn constant_list(&mut self, walk: &mut Walk<'_>) {
        walk.expect(self, "[");
        self.b.open_group();
        self.b.text("[");
        self.b.open_indent();
        let mut first = true;
        while let Some(kind) = walk.peek()
            && kind != "]"
        {
            if kind == "," {
                walk.expect(self, ",");
                self.b.text(",");
                continue;
            }
            self.b.line(if first { SOFT } else { SPACE });
            first = false;
            let value = walk.expect(self, "constant");
            self.constant(value);
        }
        self.b.close_indent();
        self.b.line(SOFT);
        self.b.text("]");
        self.b.close_group();
        walk.expect(self, "]");
    }
}