use ast_grep_core::language::Language;
use ast_grep_language::{LanguageExt, SupportLang};
use std::{
collections::{BTreeSet, HashSet},
ops::Range,
};
const COMMENT_ALIASES: &[(SupportLang, &[&str])] = &[
(SupportLang::Rust, &["line_comment", "block_comment"]),
(SupportLang::TypeScript, &["comment"]),
(SupportLang::Tsx, &["comment"]),
(SupportLang::JavaScript, &["comment"]),
(SupportLang::Python, &["comment"]),
(SupportLang::Go, &["comment"]),
(SupportLang::Swift, &["comment", "multiline_comment"]),
];
const STRING_ALIASES: &[(SupportLang, &[&str])] = &[
(SupportLang::Rust, &["string_literal", "raw_string_literal"]),
(SupportLang::TypeScript, &["string", "template_string"]),
(SupportLang::Tsx, &["string", "template_string"]),
(SupportLang::JavaScript, &["string", "template_string"]),
(SupportLang::Python, &["string"]),
(
SupportLang::Go,
&["interpreted_string_literal", "raw_string_literal"],
),
(
SupportLang::Swift,
&["line_string_literal", "multi_line_string_literal"],
),
];
pub fn validate(within: &[String], languages: &HashSet<SupportLang>) -> Result<(), String> {
for requested in within {
let known = languages
.iter()
.any(|language| resolve_one(*language, requested).is_some());
if !known {
return Err(format!("unknown node kind `{requested}`"));
}
}
Ok(())
}
#[must_use]
pub fn spans(language: SupportLang, text: &str, within: &[String]) -> Vec<Range<usize>> {
let kinds: BTreeSet<String> = within
.iter()
.filter_map(|requested| resolve_one(language, requested))
.flatten()
.collect();
if kinds.is_empty() {
return Vec::new();
}
let tree = language.ast_grep(text);
tree.root()
.dfs()
.filter(|node| kinds.contains(node.kind().as_ref()))
.map(|node| node.range())
.collect()
}
fn resolve_one(language: SupportLang, requested: &str) -> Option<Vec<String>> {
match requested {
"comment" => lookup(COMMENT_ALIASES, language),
"string" => lookup(STRING_ALIASES, language),
raw => (language.kind_to_id(raw) != 0).then(|| vec![raw.to_string()]),
}
}
fn lookup(table: &[(SupportLang, &[&str])], language: SupportLang) -> Option<Vec<String>> {
table
.iter()
.find(|(lang, _)| *lang == language)
.map(|(_, kinds)| kinds.iter().map(|kind| (*kind).to_string()).collect())
}