Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Highlight in prqlc #4755

Merged
merged 10 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions prqlc/prqlc/src/cli/highlight.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
use color_eyre::owo_colors::OwoColorize;
use prqlc::{
lr::{TokenKind, Tokens},
pr::Literal,
};

/// Highlight PRQL code printed to the terminal.
pub fn highlight(tokens: &Tokens) -> String {
let mut output = String::new();
let mut last = 0;

for token in &tokens.0 {
let diff = token.span.start - last;
last = token.span.end;
output.push_str(&" ".repeat(diff));
vanillajonathan marked this conversation as resolved.
Show resolved Hide resolved

match &token.kind {
TokenKind::NewLine => output.push('\n'),
TokenKind::Ident(ident) => {
if is_transform(ident) {
output.push_str(&ident.green().to_string())
} else {
output.push_str(&ident.to_string())
}
}
TokenKind::Keyword(keyword) => output.push_str(&keyword.blue().to_string()),
TokenKind::Literal(literal) => output.push_str(&match literal {
Literal::Null => literal.green().bold().to_string(),
Literal::Integer(_) => literal.green().to_string(),
Literal::Float(_) => literal.green().to_string(),
Literal::Boolean(_) => literal.green().bold().to_string(),
Literal::String(_) => literal.yellow().to_string(),
_ => literal.to_string(),
}),
TokenKind::Param(param) => output.push_str(&param.purple().to_string()),
TokenKind::Range {
bind_left: _,
bind_right: _,
} => output.push_str(".."),
TokenKind::Interpolation(_, _) => output.push_str(&format!("{}", token.kind.yellow())),
TokenKind::Control(char) => output.push(*char),
TokenKind::ArrowThin
| TokenKind::ArrowFat
| TokenKind::Eq
| TokenKind::Ne
| TokenKind::Gte
| TokenKind::Lte
| TokenKind::RegexSearch => output.push_str(&format!("{}", token.kind)),
TokenKind::And | TokenKind::Or => {
output.push_str(&format!("{}", token.kind).purple().to_string())
}
TokenKind::Coalesce | TokenKind::DivInt | TokenKind::Pow | TokenKind::Annotate => {
output.push_str(&format!("{}", token.kind))
}
TokenKind::Comment(comment) => output.push_str(
&format!("#{comment}")
.truecolor(95, 135, 135)
.italic()
.to_string(),
),
TokenKind::DocComment(comment) => output.push_str(
&format!("#!{comment}")
.truecolor(95, 135, 135)
.italic()
.to_string(),
),
TokenKind::LineWrap(_) => todo!(),
max-sixty marked this conversation as resolved.
Show resolved Hide resolved
TokenKind::Start => {}
}
}

output
}

fn is_transform(ident: &str) -> bool {
vanillajonathan marked this conversation as resolved.
Show resolved Hide resolved
match ident {
"from" => true,
"derive" | "select" | "filter" | "sort" | "join" | "take" | "group" | "aggregate"
| "window" | "lopo" => true,
vanillajonathan marked this conversation as resolved.
Show resolved Hide resolved
_ => false,
}
}

#[cfg(test)]
mod tests {
use std::process::Command;

use insta_cmd::assert_cmd_snapshot;
use insta_cmd::get_cargo_bin;

#[test]
fn highlight() {
let input = r"
foo

";

assert_cmd_snapshot!(prqlc_command().args(["experimental", "highlight"]).pass_stdin(input), @r###"
success: true
exit_code: 0
----- stdout -----

foo


----- stderr -----
"###);
}

fn prqlc_command() -> Command {
max-sixty marked this conversation as resolved.
Show resolved Hide resolved
max-sixty marked this conversation as resolved.
Show resolved Hide resolved
let mut cmd = Command::new(get_cargo_bin("prqlc"));
normalize_prqlc(&mut cmd);

Check warning on line 112 in prqlc/prqlc/src/cli/highlight.rs

View workflow job for this annotation

GitHub Actions / test-rust (wasm32-unknown-unknown, ubuntu-latest, default) / test-rust

Diff in /home/runner/work/prql/prql/prqlc/prqlc/src/cli/highlight.rs
cmd
}

fn normalize_prqlc(cmd: &mut Command) -> &mut Command {
cmd
// We set `CLICOLOR_FORCE` in CI to force color output, but we don't want `prqlc` to
// output color for our snapshot tests. And it seems to override the
// `--color=never` flag.
.env_remove("CLICOLOR_FORCE")
.env("NO_COLOR", "1")
.args(["--color=never"])
// We don't want the tests to be affected by the user's `RUST_BACKTRACE` setting.
.env_remove("RUST_BACKTRACE")
.env_remove("RUST_LOG")
}
}
16 changes: 16 additions & 0 deletions prqlc/prqlc/src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![cfg(not(target_family = "wasm"))]

mod docs_generator;
mod highlight;
mod jinja;
mod watch;

Expand Down Expand Up @@ -222,6 +223,10 @@ pub enum ExperimentalCommand {
/// Generate Markdown documentation
#[command(name = "doc")]
GenerateDocs(IoArgs),

/// Syntax highlight
#[command(name = "highlight")]
Highlight(IoArgs),
}

#[derive(clap::Args, Default, Debug, Clone)]
Expand Down Expand Up @@ -435,6 +440,15 @@ impl Command {

docs_generator::generate_markdown_docs(module_ref.stmts).into_bytes()
}
Command::Experimental(ExperimentalCommand::Highlight(_)) => {
let s = sources.sources.values().exactly_one().or_else(|_| {
// TODO: allow multiple sources
bail!("Currently `highlight` only works with a single source, but found multiple sources")
})?;
let tokens = prql_to_tokens(s)?;

highlight::highlight(&tokens).into_bytes()
}
Command::Compile {
signature_comment,
format,
Expand Down Expand Up @@ -483,6 +497,7 @@ impl Command {
io_args
}
Experimental(ExperimentalCommand::GenerateDocs(io_args)) => io_args,
Experimental(ExperimentalCommand::Highlight(io_args)) => io_args,
_ => unreachable!(),
};
let input = &mut io_args.input;
Expand Down Expand Up @@ -518,6 +533,7 @@ impl Command {
io_args.output.clone()
}
Experimental(ExperimentalCommand::GenerateDocs(io_args)) => io_args.output.clone(),
Experimental(ExperimentalCommand::Highlight(io_args)) => io_args.output.clone(),
_ => unreachable!(),
};
output.write_all(data)
Expand Down
Loading