Skip to main content

vvv_core/highlight/
mod.rs

1//! Syntax colouring as data. A grammar declares which node kinds are
2//! strings, comments, types and so on ([`HighlightRule`]); a language returns
3//! [`Highlight`] spans for a text; a display decides the colours.
4
5use serde::{Deserialize, Serialize};
6
7use crate::text::Span;
8
9/// The classes a display distinguishes. Coarse on purpose: enough to read
10/// code, not enough to argue about.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(rename_all = "kebab-case")]
13pub enum HighlightKind {
14    Keyword,
15    String,
16    Comment,
17    Number,
18    Type,
19    Function,
20    Macro,
21    Attribute,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Highlight {
26    pub span: Span,
27    pub kind: HighlightKind,
28}
29
30/// "Nodes of kind `node` (under a parent of kind `under`, if given) are
31/// `kind`." A matched node is coloured whole; nothing under it is visited.
32///
33/// Keywords need no rule: any anonymous node made of letters (`fn`, `pub`,
34/// `import`) is one.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct HighlightRule {
37    pub node: &'static str,
38    pub under: Option<&'static str>,
39    pub kind: HighlightKind,
40}
41
42impl HighlightRule {
43    pub const fn new(node: &'static str, kind: HighlightKind) -> Self {
44        Self {
45            node,
46            under: None,
47            kind,
48        }
49    }
50
51    pub const fn under(mut self, parent: &'static str) -> Self {
52        self.under = Some(parent);
53        self
54    }
55}