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

Add semantic highlighting #869

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
23 changes: 15 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ doctest = false
[dependencies]
anyhow = "1.0.69"
chrono = { version = "0.4.23", default-features = false, features = ["std"] }
clap = { version = "4.1.6", features = ["derive"] }
clap = { version = "4.1.8", features = ["derive"] }
crossbeam-channel = "0.5.6"
dashmap = "5.4.0"
dirs = "4.0.0"
Expand Down Expand Up @@ -69,6 +69,7 @@ thiserror = "1.0.38"
threadpool = "1.8.1"
titlecase = "2.2.1"
unicode-normalization = "0.1.22"
bitflags = "2.0.1"

[dependencies.salsa]
git = "https://github.com/salsa-rs/salsa"
Expand Down
22 changes: 22 additions & 0 deletions src/db/analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@ impl TheoremEnvironment {
}
}

#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct TexCitation {
pub key: String,
pub range: TextRange,
}

#[salsa::tracked]
pub struct GraphicsPath {
#[return_ref]
Expand All @@ -130,6 +136,9 @@ pub struct TexAnalysis {
#[return_ref]
pub links: Vec<TexLink>,

#[return_ref]
pub citations: Vec<TexCitation>,

#[return_ref]
pub labels: Vec<label::Name>,

Expand Down Expand Up @@ -162,6 +171,7 @@ impl TexAnalysis {
impl TexAnalysis {
pub(super) fn analyze(db: &dyn Db, root: &latex::SyntaxNode) -> Self {
let mut links = Vec::new();
let mut citations = Vec::new();
let mut labels = Vec::new();
let mut label_numbers = Vec::new();
let mut theorem_environments = Vec::new();
Expand All @@ -178,6 +188,17 @@ impl TexAnalysis {
NodeOrToken::Node(node) => {
TexLink::of_include(db, node.clone(), &mut links)
.or_else(|| TexLink::of_import(db, node.clone(), &mut links))
.or_else(|| {
let citation = latex::Citation::cast(node.clone())?;
for key in citation.key_list()?.keys() {
citations.push(TexCitation {
key: key.to_string(),
range: latex::small_range(&key),
});
}

Some(())
})
.or_else(|| label::Name::of_definition(db, node.clone(), &mut labels))
.or_else(|| label::Name::of_reference(db, node.clone(), &mut labels))
.or_else(|| label::Name::of_reference_range(db, node.clone(), &mut labels))
Expand Down Expand Up @@ -210,6 +231,7 @@ impl TexAnalysis {
Self::new(
db,
links,
citations,
labels,
label_numbers,
theorem_environments,
Expand Down
1 change: 1 addition & 0 deletions src/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ pub mod inlay_hint;
pub mod link;
pub mod reference;
pub mod rename;
pub mod semantic_tokens;
pub mod symbol;
pub mod workspace_command;
163 changes: 163 additions & 0 deletions src/features/semantic_tokens.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
mod citations;
mod label;
mod math_delimiter;

use bitflags::bitflags;
use lsp_types::{
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens,
SemanticTokensLegend, Url,
};
use rowan::{TextLen, TextRange};

use crate::{
db::{Document, Workspace},
util::{line_index::LineIndex, line_index_ext::LineIndexExt},
Db,
};

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
#[repr(u32)]
enum TokenKind {
GenericLabel = 0,
SectionLabel,
FloatLabel,
TheoremLabel,
EquationLabel,
EnumItemLabel,

GenericCitation,
ArticleCitation,
BookCitation,
CollectionCitation,
PartCitation,
ThesisCitation,

MathDelimiter,
}

bitflags! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
struct TokenModifiers: u32 {
const NONE = 0;
const UNDEFINED = 1;
const UNUSED = 2;
const DEPRECATED = 4;
}
}

pub fn legend() -> SemanticTokensLegend {
SemanticTokensLegend {
token_types: vec![
SemanticTokenType::new("genericLabel"),
SemanticTokenType::new("sectionLabel"),
SemanticTokenType::new("floatLabel"),
SemanticTokenType::new("theoremLabel"),
SemanticTokenType::new("equationLabel"),
SemanticTokenType::new("enumItemLabel"),
SemanticTokenType::new("genericCitation"),
SemanticTokenType::new("articleCitation"),
SemanticTokenType::new("bookCitation"),
SemanticTokenType::new("collectionCitation"),
SemanticTokenType::new("partCitation"),
SemanticTokenType::new("thesisCitation"),
SemanticTokenType::new("mathDelimiter"),
],
token_modifiers: vec![
SemanticTokenModifier::new("undefined"),
SemanticTokenModifier::new("unused"),
SemanticTokenModifier::new("deprecated"),
],
}
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
struct Token {
range: TextRange,
kind: TokenKind,
modifiers: TokenModifiers,
}

#[derive(Debug, Default)]
struct TokenBuilder {
tokens: Vec<Token>,
}

impl TokenBuilder {
pub fn push(&mut self, token: Token) {
log::info!("Adding sem token {token:#?}");
self.tokens.push(token);
}

pub fn finish(mut self, line_index: &LineIndex) -> SemanticTokens {
let mut data = Vec::new();

self.tokens.sort_by_key(|token| token.range.start());

let mut last_pos = Position::new(0, 0);
for token in self.tokens {
let range = line_index.line_col_lsp_range(token.range);
let length = range.end.character - range.start.character;
let token_type = token.kind as u32;
let token_modifiers_bitset = token.modifiers.bits();

if range.start.line > last_pos.line {
let delta_line = range.start.line - last_pos.line;
let delta_start = range.start.character;
data.push(SemanticToken {
delta_line,
delta_start,
length,
token_type,
token_modifiers_bitset,
});
} else {
let delta_line = 0;
let delta_start = range.start.character - last_pos.character;
data.push(SemanticToken {
delta_line,
delta_start,
length,
token_type,
token_modifiers_bitset,
});
}

last_pos = range.start;
}

SemanticTokens {
result_id: None,
data,
}
}
}

#[derive(Clone, Copy)]
struct Context<'db> {
db: &'db dyn Db,
document: Document,
viewport: TextRange,
}

pub fn find_all(db: &dyn Db, uri: &Url, viewport: Option<Range>) -> Option<SemanticTokens> {
let workspace = Workspace::get(db);
let document = workspace.lookup_uri(db, uri)?;
let viewport = viewport.map_or_else(
|| TextRange::new(0.into(), document.text(db).text_len()),
|range| document.line_index(db).offset_lsp_range(range),
);

let context = Context {
db,
document,
viewport,
};

let mut builder = TokenBuilder::default();

label::find(context, &mut builder);
citations::find(context, &mut builder);
math_delimiter::find(context, &mut builder);

Some(builder.finish(document.line_index(db)))
}
60 changes: 60 additions & 0 deletions src/features/semantic_tokens/citations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use rowan::ast::AstNode;

use crate::{
db::Workspace,
syntax::bibtex::{self, HasName, HasType},
util::lang_data::{BibtexEntryTypeCategory, LANGUAGE_DATA},
};

use super::{Context, Token, TokenBuilder, TokenKind, TokenModifiers};

pub(super) fn find(context: Context, builder: &mut TokenBuilder) -> Option<()> {
let db = context.db;
let analysis = context.document.parse(db).as_tex()?.analyze(db);
for citation in analysis
.citations(db)
.iter()
.filter(|citation| context.viewport.intersect(citation.range).is_some())
{
let entry = Workspace::get(db)
.related(db, context.document)
.iter()
.filter_map(|document| document.parse(db).as_bib())
.flat_map(|data| data.root(db).children())
.filter_map(bibtex::Entry::cast)
.find(|entry| {
entry
.name_token()
.map_or(false, |name| name.text() == &citation.key)
});

let modifiers = if entry.is_some() {
TokenModifiers::NONE
} else {
TokenModifiers::UNDEFINED
};

let kind = match entry
.and_then(|entry| entry.type_token())
.and_then(|token| LANGUAGE_DATA.find_entry_type(&token.text()[1..]))
.map(|doc| doc.category)
{
Some(BibtexEntryTypeCategory::String) => unreachable!(),
Some(BibtexEntryTypeCategory::Misc) => TokenKind::GenericCitation,
Some(BibtexEntryTypeCategory::Article) => TokenKind::ArticleCitation,
Some(BibtexEntryTypeCategory::Book) => TokenKind::BookCitation,
Some(BibtexEntryTypeCategory::Part) => TokenKind::PartCitation,
Some(BibtexEntryTypeCategory::Thesis) => TokenKind::ThesisCitation,
Some(BibtexEntryTypeCategory::Collection) => TokenKind::CollectionCitation,
None => TokenKind::GenericCitation,
};

builder.push(Token {
range: citation.range,
kind,
modifiers,
});
}

Some(())
}
Loading