Skip to main content

datafusion_cli/
highlighter.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! The syntax highlighter.
6
7use std::fmt::Write as _;
8use std::{
9    borrow::Cow::{self, Borrowed},
10    fmt::Display,
11};
12
13use datafusion::sql::sqlparser::{
14    dialect::{Dialect, GenericDialect, dialect_from_str},
15    keywords::Keyword,
16    tokenizer::{Token, Tokenizer},
17};
18use datafusion_common::config;
19use rustyline::highlight::{CmdKind, Highlighter};
20
21/// The syntax highlighter.
22#[derive(Debug)]
23pub struct SyntaxHighlighter {
24    dialect: Box<dyn Dialect>,
25}
26
27impl SyntaxHighlighter {
28    pub fn new(dialect: &config::Dialect) -> Self {
29        let dialect =
30            dialect_from_str(dialect).unwrap_or_else(|| Box::new(GenericDialect {}));
31        Self { dialect }
32    }
33}
34
35pub struct NoSyntaxHighlighter {}
36
37impl Highlighter for NoSyntaxHighlighter {}
38
39impl Highlighter for SyntaxHighlighter {
40    fn highlight<'l>(&self, line: &'l str, _: usize) -> Cow<'l, str> {
41        let mut out_line = String::new();
42
43        // `with_unescape(false)` since we want to rebuild the original string.
44        let mut tokenizer =
45            Tokenizer::new(self.dialect.as_ref(), line).with_unescape(false);
46        let tokens = tokenizer.tokenize();
47        match tokens {
48            Ok(tokens) => {
49                for token in tokens.iter() {
50                    match token {
51                        Token::Word(w) if w.keyword != Keyword::NoKeyword => {
52                            out_line.push_str(&Color::red(token));
53                        }
54                        Token::SingleQuotedString(_) => {
55                            out_line.push_str(&Color::green(token));
56                        }
57                        other => {
58                            write!(out_line, "{other}").ok();
59                        }
60                    }
61                }
62                out_line.into()
63            }
64            Err(_) => Borrowed(line),
65        }
66    }
67
68    fn highlight_char(&self, line: &str, _pos: usize, _cmd: CmdKind) -> bool {
69        !line.is_empty()
70    }
71}
72
73/// Convenient utility to return strings with [ANSI color](https://gist.github.com/JBlond/2fea43a3049b38287e5e9cefc87b2124).
74pub(crate) struct Color {}
75
76impl Color {
77    pub(crate) fn green(s: impl Display) -> String {
78        format!("\x1b[92m{s}\x1b[0m")
79    }
80
81    pub(crate) fn red(s: impl Display) -> String {
82        format!("\x1b[91m{s}\x1b[0m")
83    }
84
85    pub(crate) fn gray(s: impl Display) -> String {
86        format!("\x1b[90m{s}\x1b[0m")
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::SyntaxHighlighter;
93    use super::config::Dialect;
94    use rustyline::highlight::Highlighter;
95
96    #[test]
97    fn highlighter_valid() {
98        let s = "SElect col_a from tab_1;";
99        let highlighter = SyntaxHighlighter::new(&Dialect::Generic);
100        let out = highlighter.highlight(s, s.len());
101        assert_eq!(
102            "\u{1b}[91mSElect\u{1b}[0m col_a \u{1b}[91mfrom\u{1b}[0m tab_1;",
103            out
104        );
105    }
106
107    #[test]
108    fn highlighter_valid_with_new_line() {
109        let s = "SElect col_a from tab_1\n WHERE col_b = 'なにか';";
110        let highlighter = SyntaxHighlighter::new(&Dialect::Generic);
111        let out = highlighter.highlight(s, s.len());
112        assert_eq!(
113            "\u{1b}[91mSElect\u{1b}[0m col_a \u{1b}[91mfrom\u{1b}[0m tab_1\n \u{1b}[91mWHERE\u{1b}[0m col_b = \u{1b}[92m'なにか'\u{1b}[0m;",
114            out
115        );
116    }
117
118    #[test]
119    fn highlighter_invalid() {
120        let s = "SElect col_a from tab_1 WHERE col_b = ';";
121        let highlighter = SyntaxHighlighter::new(&Dialect::Generic);
122        let out = highlighter.highlight(s, s.len());
123        assert_eq!("SElect col_a from tab_1 WHERE col_b = ';", out);
124    }
125}