rust/crates/ide/src/syntax_highlighting/format.rs

67 lines
1.9 KiB
Rust
Raw Normal View History

2020-10-13 17:56:41 -05:00
//! Syntax highlighting for format macro strings.
use syntax::{
ast::{self, FormatSpecifier, HasFormatSpecifier},
2021-01-10 02:57:17 -06:00
AstNode, AstToken, TextRange,
2020-10-13 17:56:41 -05:00
};
2021-01-10 02:57:17 -06:00
use crate::{syntax_highlighting::highlights::Highlights, HlRange, HlTag, SymbolKind};
2021-01-10 02:57:17 -06:00
pub(super) fn highlight_format_string(
stack: &mut Highlights,
string: &ast::String,
range: TextRange,
) {
if is_format_string(string).is_none() {
return;
}
2020-10-13 17:56:41 -05:00
2021-01-10 02:57:17 -06:00
string.lex_format_specifier(|piece_range, kind| {
if let Some(highlight) = highlight_format_specifier(kind) {
stack.add(HlRange {
range: piece_range + range.start(),
highlight: highlight.into(),
binding_hash: None,
});
}
});
2020-10-13 17:56:41 -05:00
}
2021-01-10 02:57:17 -06:00
fn is_format_string(string: &ast::String) -> Option<()> {
let parent = string.syntax().parent();
let name = parent.parent().and_then(ast::MacroCall::cast)?.path()?.segment()?.name_ref()?;
2021-01-19 16:56:11 -06:00
if !matches!(name.text(), "format_args" | "format_args_nl") {
2021-01-10 02:57:17 -06:00
return None;
2020-10-13 17:56:41 -05:00
}
2021-01-10 02:57:17 -06:00
let first_literal = parent
.children_with_tokens()
.filter_map(|it| it.as_token().cloned().and_then(ast::String::cast))
.next()?;
if &first_literal != string {
return None;
2020-10-13 17:56:41 -05:00
}
2021-01-10 02:57:17 -06:00
Some(())
2020-10-13 17:56:41 -05:00
}
2021-01-09 05:44:01 -06:00
fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HlTag> {
2020-10-13 17:56:41 -05:00
Some(match kind {
FormatSpecifier::Open
| FormatSpecifier::Close
| FormatSpecifier::Colon
| FormatSpecifier::Fill
| FormatSpecifier::Align
| FormatSpecifier::Sign
| FormatSpecifier::NumberSign
| FormatSpecifier::DollarSign
| FormatSpecifier::Dot
| FormatSpecifier::Asterisk
2021-01-09 05:44:01 -06:00
| FormatSpecifier::QuestionMark => HlTag::FormatSpecifier,
2021-01-10 02:57:17 -06:00
2021-01-09 05:44:01 -06:00
FormatSpecifier::Integer | FormatSpecifier::Zero => HlTag::NumericLiteral,
2021-01-10 02:57:17 -06:00
2021-01-09 05:44:01 -06:00
FormatSpecifier::Identifier => HlTag::Symbol(SymbolKind::Local),
2020-10-13 17:56:41 -05:00
})
}