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#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
13#[serde(rename_all = "kebab-case")]
14pub enum HighlightKind {
15    Keyword,
16    String,
17    Comment,
18    Number,
19    Type,
20    Function,
21    Macro,
22    Attribute,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
26#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
27pub struct Highlight {
28    pub span: Span,
29    pub kind: HighlightKind,
30}
31
32/// "Nodes of kind `node` (under a parent of kind `under`, if given) are
33/// `kind`." A matched node is coloured whole; nothing under it is visited.
34///
35/// Keywords need no rule: any anonymous node made of letters (`fn`, `pub`,
36/// `import`) is one.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct HighlightRule {
39    pub node: &'static str,
40    pub under: Option<&'static str>,
41    pub kind: HighlightKind,
42}
43
44impl HighlightRule {
45    pub const fn new(node: &'static str, kind: HighlightKind) -> Self {
46        Self {
47            node,
48            under: None,
49            kind,
50        }
51    }
52
53    pub const fn under(mut self, parent: &'static str) -> Self {
54        self.under = Some(parent);
55        self
56    }
57}