//! Semantic tokens: every meaningful token of a file, classified from the //! real parse and from name resolution. Editors color code with them, so //! `io.println` shows `io` as a module and `println` as a function, and a //! parameter looks different from a local or a constructor. //! //! Lexical classes (keywords, literals, comments, operators) come from the //! syntax tree. An identifier gets the class of what it refers to: the //! innermost resolved name containing it. Within a qualified name, the //! segments before the name are modules. Identifiers that nothing //! resolves fall back on their syntactic position. use std::collections::HashSet; use louise_hir::body::{Body, Expr, LocalId, Pat, PatId, Stmt}; use louise_hir::{DefId, DefKind, Hir, TypeRef}; use louise_span::{FileId, TextRange}; use louise_syntax::{SyntaxKind, SyntaxNode, SyntaxToken}; use super::nav::{signature_types, visit_type_refs}; use crate::{Analysis, Db}; /// What a token is. The names follow the LSP's standard token types. #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] pub enum TokenClass { Namespace, Type, Interface, TypeParameter, Parameter, Variable, Property, EnumMember, Function, Method, Keyword, Comment, String, Number, Operator, Decorator, } impl TokenClass { /// Every class, in the order of the LSP legend. pub const ALL: [TokenClass; 16] = [ TokenClass::Namespace, TokenClass::Type, TokenClass::Interface, TokenClass::TypeParameter, TokenClass::Parameter, TokenClass::Variable, TokenClass::Property, TokenClass::EnumMember, TokenClass::Function, TokenClass::Method, TokenClass::Keyword, TokenClass::Comment, TokenClass::String, TokenClass::Number, TokenClass::Operator, TokenClass::Decorator, ]; /// The LSP token type name. pub fn lsp_name(self) -> &'static str { match self { TokenClass::Namespace => "namespace", TokenClass::Type => "type", TokenClass::Interface => "interface", TokenClass::TypeParameter => "typeParameter", TokenClass::Parameter => "parameter", TokenClass::Variable => "variable", TokenClass::Property => "property", TokenClass::EnumMember => "enumMember", TokenClass::Function => "function", TokenClass::Method => "method", TokenClass::Keyword => "keyword", TokenClass::Comment => "comment", TokenClass::String => "string", TokenClass::Number => "number", TokenClass::Operator => "operator", TokenClass::Decorator => "decorator", } } } /// Modifier bits, in the order of [`MODIFIERS`]. pub const DECLARATION: u32 = 1; pub const DOCUMENTATION: u32 = 1 << 1; pub const DEFAULT_LIBRARY: u32 = 1 << 2; /// The LSP modifier names, by bit. pub const MODIFIERS: [&str; 3] = ["declaration", "documentation", "defaultLibrary"]; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct SemanticToken { pub range: TextRange, pub class: TokenClass, pub modifiers: u32, } /// The semantic tokens of `file`, in order. pub fn semantic_tokens(db: &Db, analysis: &Analysis, file: FileId) -> Vec { let Some(parse) = db.parse(file) else { return Vec::new(); }; let names = resolved_names(analysis, db, file); let mut out = Vec::new(); for element in parse.syntax().descendants_with_tokens() { let Some(token) = element.into_token() else { continue; }; if let Some(t) = classify(&token, &names) { out.push(t); } } out } /// A resolved name: its range in the file, and what the name it contains /// is. struct Resolved { range: TextRange, /// The identifier text that is the name itself (the segments before it /// are modules); `None` when the range is exactly one identifier. name: Option, class: TokenClass, modifiers: u32, } fn def_class(hir: &Hir, def: DefId) -> TokenClass { match &hir.def(def).kind { DefKind::Fn(f) => match f.owner.map(|o| &hir.def(o).kind) { Some(DefKind::Trait(_) | DefKind::Impl(_)) => TokenClass::Method, _ => TokenClass::Function, }, DefKind::Op(_) => TokenClass::Method, DefKind::Ctor(_) => TokenClass::EnumMember, DefKind::Trait(_) | DefKind::Effect(_) | DefKind::EffectAlias(_) => TokenClass::Interface, DefKind::Type(_) | DefKind::AssocType(_) => TokenClass::Type, _ => TokenClass::Variable, } } fn resolved_names(analysis: &Analysis, db: &Db, file: FileId) -> Vec { let hir = &analysis.hir; let sources = db.sources(); let library = |def: DefId| { let f = hir.modules[hir.def(def).module].file; if sources.get(f).path().starts_with('<') { DEFAULT_LIBRARY } else { 0 } }; let mut out = Vec::new(); let reference = |range: TextRange, def: DefId, out: &mut Vec| { out.push(Resolved { range, name: Some(hir.def(def).name.clone()), class: def_class(hir, def), modifiers: library(def), }); }; for (id, def) in hir.defs.iter() { if hir.modules[def.module].file != file { continue; } if !def.name.is_empty() && !matches!(def.kind, DefKind::Impl(_)) { out.push(Resolved { range: def.span.range, name: None, class: def_class(hir, id), modifiers: DECLARATION, }); } for tref in signature_types(&def.kind) { visit_type_refs(tref, &mut |range, target| { reference(range, target, &mut out) }); visit_type_vars(tref, &mut |range| { out.push(Resolved { range, name: None, class: TokenClass::TypeParameter, modifiers: 0, }) }); } let DefKind::Fn(f) = &def.kind else { continue }; let Some(body) = &f.body else { continue }; let params = parameter_locals(body); let local_class = |l: LocalId| { if params.contains(&l) { TokenClass::Parameter } else { TokenClass::Variable } }; for (l, local) in body.locals.iter().filter(|(_, local)| !local.synthetic) { out.push(Resolved { range: local.span, name: None, class: local_class(l), modifiers: DECLARATION, }); } for (e, expr) in body.exprs.iter() { let range = body.expr_span(e); match expr { Expr::Def(d) => reference(range, *d, &mut out), Expr::Local(l) if !body.locals[*l].synthetic => out.push(Resolved { range, name: Some(body.locals[*l].name.clone()), class: local_class(*l), modifiers: 0, }), Expr::Lambda { params, ret, .. } => { for tref in params .iter() .filter_map(|p| p.ty.as_ref()) .chain(ret.iter()) { visit_type_refs(tref, &mut |r, d| reference(r, d, &mut out)); } } Expr::Block { stmts, .. } => { for stmt in stmts { if let Stmt::Let { ty: Some(tref), .. } = stmt { visit_type_refs(tref, &mut |r, d| reference(r, d, &mut out)); } } } _ => {} } } for (p, pat) in body.pats.iter() { if let Pat::Ctor { def: c, .. } = pat { reference(body.pat_span(p), *c, &mut out); } } } out } /// Locals bound by the parameters of the function and of its lambdas. fn parameter_locals(body: &Body) -> HashSet { let mut out = HashSet::new(); let mut pats: Vec = body.params.clone(); for (_, expr) in body.exprs.iter() { if let Expr::Lambda { params, .. } = expr { pats.extend(params.iter().map(|p| p.pat)); } } while let Some(p) = pats.pop() { match &body.pats[p] { Pat::Bind(l) => { out.insert(*l); } Pat::As { pat, local } => { out.insert(*local); pats.push(*pat); } Pat::Ctor { args, .. } => pats.extend(args.iter().map(|a| a.pat)), Pat::Tuple(elems) | Pat::Or(elems) => pats.extend(elems.iter().copied()), Pat::List { elems, rest } => { pats.extend(elems.iter().copied()); if let Some(Some(l)) = rest { out.insert(*l); } } Pat::Missing | Pat::Wild | Pat::Lit { .. } => {} } } out } fn visit_type_vars(tref: &TypeRef, f: &mut impl FnMut(TextRange)) { match tref { TypeRef::Var { name, args, span } => { // `f`: the variable is the name, before its arguments. let len = louise_span::TextSize::of(name.as_str()).min(span.len()); f(TextRange::at(span.start(), len)); args.iter().for_each(|a| visit_type_vars(a, f)); } TypeRef::Def { args, .. } => args.iter().for_each(|a| visit_type_vars(a, f)), TypeRef::Fn { params, ret, effects, .. } => { params.iter().for_each(|p| visit_type_vars(&p.ty, f)); visit_type_vars(ret, f); if let Some(row) = effects { row.labels.iter().for_each(|l| visit_type_vars(l, f)); if let Some(t) = &row.tail { visit_type_vars(t, f); } } } TypeRef::Tuple { elems, .. } => elems.iter().for_each(|e| visit_type_vars(e, f)), TypeRef::Row { row, .. } => { row.labels.iter().for_each(|l| visit_type_vars(l, f)); if let Some(t) = &row.tail { visit_type_vars(t, f); } } TypeRef::Error { .. } => {} } } fn classify(token: &SyntaxToken, names: &[Resolved]) -> Option { use SyntaxKind::*; let kind = token.kind(); let range = token.text_range(); let plain = |class| { Some(SemanticToken { range, class, modifiers: 0, }) }; if kind.is_keyword() { return plain(TokenClass::Keyword); } match kind { COMMENT => plain(TokenClass::Comment), DOC_COMMENT => Some(SemanticToken { range, class: TokenClass::Comment, modifiers: DOCUMENTATION, }), STRING | HTML_STRING | STRING_START | STRING_TEXT | STRING_END => plain(TokenClass::String), TEMPLATE | TEMPLATE_START | TEMPLATE_TEXT | TEMPLATE_END => plain(TokenClass::String), INT | FLOAT => plain(TokenClass::Number), ARROW | L_ARROW | EQ | NEQ | LT | GT | LTEQ | GTEQ | LT_GT | PLUS | MINUS | STAR | SLASH | PERCENT | BANG | PIPE | PIPE_GT => plain(TokenClass::Operator), AT => plain(TokenClass::Decorator), HTML_NAME => { let parent = token.parent()?; let class = match parent.kind() { HTML_ATTR => TokenClass::Property, _ if is_component(token.text()) => TokenClass::Function, _ => TokenClass::Type, }; plain(class) } IDENT => ident(token, names), _ => None, } } /// An Uppercase or dotted tag calls a function (ADR 0009). fn is_component(tag: &str) -> bool { tag.starts_with(|c: char| c.is_ascii_uppercase()) || tag.contains('.') } fn ident(token: &SyntaxToken, names: &[Resolved]) -> Option { let range = token.text_range(); // The innermost resolved name containing the identifier. let best = names .iter() .filter(|r| r.range.contains_range(range)) .min_by_key(|r| r.range.len()); if let Some(r) = best { let is_name = match &r.name { None => true, Some(name) => token.text() == name || r.range == range, }; if is_name { return Some(SemanticToken { range, class: r.class, modifiers: r.modifiers, }); } // A qualifier before the name: `io` in `io.println`. if name_follows(token, r) { return Some(SemanticToken { range, class: TokenClass::Namespace, modifiers: 0, }); } } syntactic(token) } /// Whether the resolved name's identifier comes after `token` in its /// range (so `token` qualifies it). fn name_follows(token: &SyntaxToken, r: &Resolved) -> bool { let Some(name) = &r.name else { return false }; let mut next = token.next_token(); while let Some(t) = next { if !r.range.contains_range(t.text_range()) { return false; } if t.kind() == SyntaxKind::IDENT && t.text() == name { return true; } next = t.next_token(); } false } /// A class from where the identifier sits, when nothing resolved it. fn syntactic(token: &SyntaxToken) -> Option { use SyntaxKind::*; let parent: SyntaxNode = token.parent()?; let upper = token.text().starts_with(|c: char| c.is_ascii_uppercase()); let class = match parent.kind() { IMPORT_PATH => TokenClass::Namespace, ATTR => TokenClass::Decorator, LABEL => TokenClass::Parameter, HANDLER_CLAUSE => TokenClass::Method, _ => match parent.parent().map(|g| g.kind()) { Some(FIELD_EXPR) => TokenClass::Property, Some(FIELD) => TokenClass::Property, Some(LABEL) => TokenClass::Parameter, Some(IMPORT_ITEM) if upper => TokenClass::Type, Some(IMPORT_ITEM) => TokenClass::Function, Some(IMPORT_PATH) => TokenClass::Namespace, Some(ATTR) => TokenClass::Decorator, _ if upper => TokenClass::Type, _ => return None, }, }; Some(SemanticToken { range: token.text_range(), class, modifiers: 0, }) } /// Classes of the tokens of a file, by text (for tests). #[cfg(test)] pub fn token_classes( db: &Db, analysis: &Analysis, file: FileId, ) -> std::collections::HashMap> { let text = db.sources().get(file).text().clone(); let mut out: std::collections::HashMap> = Default::default(); for t in semantic_tokens(db, analysis, file) { let s = text[usize::from(t.range.start())..usize::from(t.range.end())].to_owned(); out.entry(s).or_default().push(t.class); } out } #[cfg(test)] mod tests { use super::TokenClass as C; use super::*; #[test] fn classifies_names_by_what_they_are() { let mut db = Db::new(); let src = r#"import std/io /// Shapes. pub type Shape { Circle(radius: Int) } effect log { fn log :: message: String -> () } fn area :: s: Shape -> Int / { log "area" match s { Circle(r) -> r * r } } pub fn main :: -> () / { let total = handle { area Circle(radius: 2) } with { log m -> io.println m } io.println (show total) } fn page :: xs: List -> Html {
    {"items"}
} "#; let file = db.add_module("main", "main.lse", src.into()); let analysis = db.analyze(); let classes = token_classes(&db, &analysis, file); let has = |text: &str, class: C| classes.get(text).is_some_and(|cs| cs.contains(&class)); assert!(has("io", C::Namespace), "{classes:?}"); assert!(has("println", C::Function)); assert!(has("Shape", C::Type)); assert!(has("Circle", C::EnumMember)); assert!(has("log", C::Interface), "the effect"); assert!(has("log", C::Method), "the operation"); assert!(has("area", C::Function)); assert!(has("s", C::Parameter)); assert!(has("total", C::Variable)); assert!(has("r", C::Variable)); assert!(has("radius", C::Parameter), "a label"); assert!(has("a", C::TypeParameter)); assert!(has("fn", C::Keyword)); assert!(has("\"area\"", C::String)); assert!(has("2", C::Number)); assert!(has("ul", C::Type), "an HTML tag"); assert!(has("class", C::Property), "an HTML attribute"); assert!(has("/// Shapes.", C::Comment)); assert!(has("->", C::Operator)); } }