#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
//! Pretty printer for non-overlapping code spans.
//!
//! This crate aids you in creating output like the following,
//! both for the terminal (ANSI) as well as for the web (HTML):
//!
//!
//!
//!
//! ╭─[fac.lisp]
//! │
//! 1 │ (defunfactorial (n) (if (zerop n) 1
//! ┆ ────┬────▲
//! ┆ │ │
//! ┆ ╰───────────────────────── this function ...
//! ┆ ╭──────────────────────╯
//! 2 │ │ (* n (factorial (1- n)))))
//! ┆ │▲┬
//! ┆ │││
//! ┆ ╰─────────────────────────────────┴─── ... is defined by this
//! ┆ │
//! ┆ ╰─ (and here is EOF)
//! ──╯
//!
//!
//! This example has been created with `cargo run --example example -- --html`.
//! To see its console output, run `cargo run --example example`.
//!
//! # Usage
//!
//! Suppose that we have a source file and a list of byte ranges that we want to annotate.
//! For example:
//!
//! ~~~
//! let src = r#"if true { 42 } else { "42" }"#;
//! let labels = [
//! (8..14, "this is of type Nat"),
//! (20..28, "this is of type String"),
//! ];
//! ~~~
//!
//! First, we have to create a [`LineIndex`].
//! This splits the source into lines, so that further functions can
//! quickly find in which line a byte is situated.
//!
//! ~~~
//! use codesnake::LineIndex;
//! # let src = r#"if true { 42 } else { "42" }"#;
//! let idx = LineIndex::new(src);
//! ~~~
//!
//! Next, we create a code [`Block`] from our index and the [`Label`]s:
//!
//! ~~~
//! use codesnake::{Block, Label};
//! # use codesnake::LineIndex;
//! # let src = r#"if true { 42 } else { "42" }"#;
//! # let idx = LineIndex::new(src);
//! # let labels = [(8..14, "this is of type Nat")];
//! let block = Block::new(&idx, labels.map(|(range, text)| Label::<_, _, ()>::new(range).with_text(text))).unwrap();
//! ~~~
//!
//! This will fail if your labels refer to bytes outside the range of your source.
//!
//! Finally, we can print our code block:
//!
//! ~~~
//! use codesnake::CodeWidth;
//! # use codesnake::{Block, Label};
//! # use codesnake::LineIndex;
//! # let src = r#"if true { 42 } else { "42" }"#;
//! # let idx = LineIndex::new(src);
//! # let labels = [(8..14, "this is of type Nat")];
//! # let block = Block::new(&idx, labels.map(|(range, text)| Label::<_, _, ()>::new(range).with_text(text))).unwrap();
//! let block = block.map_code(|c| CodeWidth::new(c, c.len()));
//! // yield " ╭─[main.rs]"
//! println!("{}{}", block.prologue(), "[main.rs]");
//! print!("{block}");
//! // yield "──╯"
//! println!("{}", block.epilogue());
//! ~~~
//!
//! # Colors
//!
//! To color the output on a terminal, you can use a crate like [`yansi`](https://docs.rs/yansi).
//! This allows you to color labels as follows:
//!
//! ~~~
//! use codesnake::{Block, CodeWidth, Label, LineIndex};
//! use yansi::{Color, Paint};
//! # let src = r#"if true { 42 } else { "42" }"#;
//! # let idx = LineIndex::new(src);
//! # let range = 8..14;
//! let label = Label::<_, &str, _>::new(range).with_style(Color::Red);
//! # let block = Block::new(&idx, [label]).unwrap().map_code(|c| CodeWidth::new(c, c.len()));
//! let block = block.with_paint(|f, style, code| {
//! if *style == Color::default() {
//! write!(f, "{code}")
//! } else {
//! write!(f, "{}", code.fg(*style))
//! }
//! });
//! assert_eq!(block.to_string(), "1 │ if true \u{1b}[31m{ 42 }\u{1b}[0m else { \"42\" }\n");
//! ~~~
//!
//! For HTML, you can use something like:
//!
//! ~~~
//! use codesnake::{Block, CodeWidth, Label, LineIndex};
//! # let src = r#"if true { 42 } else { "42" }"#;
//! # let idx = LineIndex::new(src);
//! # let range = 8..14;
//! let label = Label::<_, &str, _>::new(range).with_style("color:red");
//! # let block = Block::new(&idx, [label]).unwrap().map_code(|c| CodeWidth::new(c, c.len()));
//! let block = block.with_paint(|f, style, code| {
//! if style.is_empty() {
//! write!(f, "{code}")
//! } else {
//! write!(f, "{code}")
//! }
//! });
//! assert_eq!(block.to_string(), "1 │ if true { 42 } else { \"42\" }\n");
//! ~~~
extern crate alloc;
use alloc::vec::Vec;
use core::fmt::{self, Display, Formatter};
use core::ops::Range;
/// Associate byte offsets with line numbers.
///
/// If `idx = LineIndex::new(s)` and `idx.0[n] = (offset, line)`, then
/// the `n`-th line of `s` starts at `offset` in `s` and equals `line`.
pub struct LineIndex<'a>(Vec<(usize, &'a str)>);
impl<'a> LineIndex<'a> {
/// Create a new index.
#[must_use]
pub fn new(s: &'a str) -> Self {
// indices of '\n' characters
let newlines: Vec<_> = s
.char_indices()
.filter_map(|(i, c)| (c == '\n').then_some(i))
.collect();
// indices of line starts and ends
let starts = core::iter::once(0).chain(newlines.iter().map(|i| *i + 1));
let ends = newlines.iter().copied().chain(core::iter::once(s.len()));
let lines = starts.zip(ends).map(|(start, end)| (start, &s[start..end]));
Self(lines.collect())
}
fn get(&self, offset: usize) -> Option> {
use core::cmp::Ordering;
let line_no = self.0.binary_search_by(|(line_start, line)| {
if *line_start > offset {
Ordering::Greater
} else if line_start + line.len() < offset {
Ordering::Less
} else {
Ordering::Equal
}
});
let line_no = line_no.ok()?;
let (line_start, line) = self.0[line_no];
Some(IndexEntry {
line_no,
line,
bytes: offset - line_start,
})
}
}
struct IndexEntry<'a> {
line: &'a str,
line_no: usize,
/// offset of position relative to start of line
bytes: usize,
}
/// Functions that determine what to print below labels.
struct Fns {
/// display line for label without text
snake: Option fmt::Result>,
/// display line for label with text
text: fn(&mut Formatter, usize, usize) -> fmt::Result,
}
impl LabelKind {
fn has_snake(&self) -> bool {
match self {
Self::None => false,
Self::Snake | Self::Text(_) => true,
}
}
fn text(self) -> Option {
match self {
Self::None | Self::Snake => None,
Self::Text(t) => Some(t),
}
}
}
/// Code label with text and style.
pub struct Label {
code: C,
kind: LabelKind,
style: S,
}
impl Label, T, S> {
/// Create a new label.
///
/// If the range start equals the range end,
/// an arrow is drawn at the range start.
/// This can be useful to indicate errors that occur at the end of the input.
#[must_use]
pub fn new(code: Range) -> Self {
Self {
code,
kind: LabelKind::None,
style: S::default(),
}
}
}
impl Label {
/// Create a snake label with text.
#[must_use]
pub fn with_text(self, text: T) -> Self {
let kind = LabelKind::Text(text);
Self { kind, ..self }
}
/// Create a snake label without text.
#[must_use]
pub fn with_snake(self) -> Self {
let kind = LabelKind::Snake;
Self { kind, ..self }
}
/// Use a custom style for drawing the label's snake.
#[must_use]
pub fn with_style(self, style: S) -> Self {
Self { style, ..self }
}
}
/// Piece of code together with its display width.
pub struct CodeWidth {
code: C,
width: usize,
}
impl CodeWidth {
/// Create a new piece of code with associated display width.
pub fn new(code: C, width: usize) -> Self {
CodeWidth { code, width }
}
/// Width to the left and right of the center (excluding the center itself).
fn left_right(&self) -> (usize, usize) {
let left = self.width / 2;
let right = self.width.saturating_sub(left + 1);
(left, right)
}
}
impl Display for CodeWidth {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.code.fmt(f)
}
}
type Paint = fn(&mut Formatter, &S, &dyn Display) -> fmt::Result;
fn styled<'a, S>(paint: Paint, style: &'a S, x: &'a impl Display) -> impl Display + 'a {
from_fn(move |f| paint(f, style, x))
}
struct FromFn(F);
fn from_fn fmt::Result>(f: F) -> FromFn {
FromFn(f)
}
impl fmt::Result> Display for FromFn {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
(self.0)(f)
}
}
enum LabelKind {
None,
Snake,
Text(T),
}
/// Sequence of lines, containing code `C`, (label) text `T`, and style `S`.
pub struct Block {
lines: Vec