datafusion_cli/
highlighter.rs

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