move skill code to own file, change caching names/concept

This commit is contained in:
acereca 2023-04-12 22:48:36 +02:00
parent 1705b928ee
commit edee082587
3 changed files with 54 additions and 72 deletions

View File

@ -1,5 +1,8 @@
use dashmap::DashMap; use dashmap::DashMap;
use std::path::{Path, PathBuf}; use pest::error::Error;
use tower_lsp::lsp_types::CompletionItem;
use crate::{parse_global_symbols, parse_skill};
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
struct Position { struct Position {
@ -13,61 +16,45 @@ struct Range {
to: Position, to: Position,
} }
#[derive(PartialEq, Debug)]
struct CachedScope {
range: Range,
}
#[derive(PartialEq, Debug, Clone)]
pub struct CachedItems {
global_tokens: Vec<String>,
scopes: Vec<CachedScope>,
}
#[derive(Debug)] #[derive(Debug)]
pub struct DocumentCache { pub struct SymbolCache {
pub documents: DashMap<PathBuf, CachedItems>, pub symbols: DashMap<String, Vec<CompletionItem>>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct FileNotInCache; struct FileNotInCache;
impl DocumentCache { impl SymbolCache {
pub fn new() -> DocumentCache { pub fn new() -> SymbolCache {
DocumentCache { SymbolCache {
documents: DashMap::new(), symbols: DashMap::new(),
} }
} }
pub fn update_document(&self, path: PathBuf, items: CachedItems) { pub fn update(&self, path: &str) -> Vec<CompletionItem> {
self.documents.insert(path, items); let parsed = parse_skill(path);
for rule in parsed {
match parse_global_symbols(rule) {
Ok(_) => {}
Err(_) => {}
}
}
return self.symbols.get(path).unwrap().to_vec();
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::cache::{CachedItems, DocumentCache}; use crate::cache::SymbolCache;
use std::collections::HashMap; // use std::collections::HashMap;
use std::path::Path; // use std::path::Path;
#[test] #[test]
fn insert() { fn insert() {
let mut d = DocumentCache::new(Path::new("/example/workdir").to_path_buf()); let mut d = SymbolCache::new();
d.update_document( d.update();
Path::new("example_file.ext").to_path_buf(), // let mut comp = HashMap::new();
CachedItems { // comp.insert();
global_tokens: vec![], // assert_eq!(d.documents, comp)
scopes: vec![],
},
);
let mut comp = HashMap::new();
comp.insert(
Path::new("example_file.ext").to_path_buf(),
CachedItems {
global_tokens: vec![],
scopes: vec![],
},
);
assert_eq!(d.documents, comp)
} }
} }

View File

@ -1,17 +1,16 @@
mod cache; mod cache;
use cache::DocumentCache; use cache::SymbolCache;
mod skill;
use skill::{parse_global_symbols, parse_skill};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use std::fs;
use std::path::{Path, PathBuf};
use tower_lsp::jsonrpc::{Error, ErrorCode, Result}; use tower_lsp::jsonrpc::{Error, ErrorCode, Result};
use tower_lsp::lsp_types::notification::Notification; use tower_lsp::lsp_types::notification::Notification;
use tower_lsp::lsp_types::*; use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer, LspService, Server}; use tower_lsp::{Client, LanguageServer, LspService, Server};
use crate::pest::Parser;
extern crate glob; extern crate glob;
extern crate pest; extern crate pest;
#[macro_use] #[macro_use]
@ -20,13 +19,9 @@ extern crate pest_derive;
#[derive(Debug)] #[derive(Debug)]
struct Backend { struct Backend {
client: Client, client: Client,
cache: DocumentCache, cache: SymbolCache,
} }
#[derive(Parser)]
#[grammar = "./skill.pest"]
struct SkillParser;
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
struct CustomNotificationParams { struct CustomNotificationParams {
title: String, title: String,
@ -67,9 +62,11 @@ impl LanguageServer for Backend {
self.client self.client
.log_message(MessageType::INFO, format!("pattern used: {:?}", pattern)) .log_message(MessageType::INFO, format!("pattern used: {:?}", pattern))
.await; .await;
for entry in glob::glob(pattern.as_str()).expect("no file to cache in root_dir") { for entry in glob::glob(pattern.as_str()).expect("no file to cache in root_dir") {
match entry { match entry {
Ok(path) => { Ok(path) => {
self.cache.update(path.to_str().unwrap());
self.client self.client
.log_message(MessageType::INFO, format!("caching {:?}", path.display())) .log_message(MessageType::INFO, format!("caching {:?}", path.display()))
.await .await
@ -132,27 +129,12 @@ impl LanguageServer for Backend {
} }
async fn completion(&self, cparams: CompletionParams) -> Result<Option<CompletionResponse>> { async fn completion(&self, cparams: CompletionParams) -> Result<Option<CompletionResponse>> {
let doc = cparams.text_document_position.text_document.uri.path(); let symbols: Vec<CompletionItem> = self
// let line = cparams.text_document_position.position.line; .cache
// let character = cparams.text_document_position.position.character; .symbols
let content = fs::read_to_string(doc).expect("could not read"); .get_mut(&cparams.text_document_position.text_document.uri.to_string())
let file = SkillParser::parse(Rule::skill, &content) .unwrap()
.expect("unsuccessful parse") .to_vec();
.next()
.unwrap();
let mut symbols: Vec<CompletionItem> = vec![];
for record in file.into_inner() {
match record.as_rule() {
Rule::assign => symbols.push(CompletionItem {
label: record.into_inner().next().unwrap().as_str().to_string(),
kind: Some(CompletionItemKind::VARIABLE),
..Default::default()
}),
_ => {}
};
}
Ok(Some(CompletionResponse::Array(symbols))) Ok(Some(CompletionResponse::Array(symbols)))
} }
@ -166,7 +148,7 @@ async fn main() {
let (service, socket) = LspService::new(|client| Backend { let (service, socket) = LspService::new(|client| Backend {
client, client,
cache: DocumentCache::new(), cache: SymbolCache::new(),
}); });
Server::new(stdin, stdout, socket).serve(service).await; Server::new(stdin, stdout, socket).serve(service).await;
} }

13
src/skill.rs Normal file
View File

@ -0,0 +1,13 @@
use pest::error::Error;
use pest::iterators::Pair;
#[derive(Parser)]
#[grammar = "./skill.pest"]
pub struct SkillParser;
pub fn parse_skill(path: &str) -> Vec<Pair<Rule>> {
vec![]
}
pub fn parse_global_symbols(token: Pair<Rule>) -> Result<&str, Error<Rule>> {
Ok("")
}