Skip to content

Commit

Permalink
refactor: cargo clippy parser, resolver and tools crates
Browse files Browse the repository at this point in the history
Signed-off-by: peefy <[email protected]>
  • Loading branch information
Peefy committed Aug 23, 2024
1 parent 0b2a81e commit 1f03a77
Show file tree
Hide file tree
Showing 21 changed files with 63 additions and 200 deletions.
1 change: 1 addition & 0 deletions kclvm/Cargo.lock

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

1 change: 1 addition & 0 deletions kclvm/parser/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ num-bigint = "0.4"
regex = "1.7.0"
anyhow = "1.0"
indexmap = "1.0"
parking_lot = "0.12.3"

kclvm-lexer = {path = "../lexer"}
kclvm-ast = {path = "../ast"}
Expand Down
12 changes: 6 additions & 6 deletions kclvm/parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ impl Loader {
.map(|path| format!("- {}\n", path.to_string_lossy()))
.collect::<String>();

self.sess.1.borrow_mut().add_error(
self.sess.1.write().add_error(
ErrorKind::RecursiveLoad,
&[Message {
range: (Position::dummy_pos(), Position::dummy_pos()),
Expand All @@ -423,7 +423,7 @@ impl Loader {

Ok(LoadProgramResult {
program,
errors: self.sess.1.borrow().diagnostics.clone(),
errors: self.sess.1.read().diagnostics.clone(),
paths,
})
}
Expand Down Expand Up @@ -452,7 +452,7 @@ impl Loader {

// 3. Internal and external packages cannot be duplicated
if is_external.is_some() && is_internal.is_some() {
self.sess.1.borrow_mut().add_error(
self.sess.1.write().add_error(
ErrorKind::CannotFindModule,
&[Message {
range: Into::<Range>::into(pos),
Expand All @@ -472,7 +472,7 @@ impl Loader {
match is_internal.or(is_external) {
Some(pkg_info) => Ok(Some(pkg_info)),
None => {
self.sess.1.borrow_mut().add_error(
self.sess.1.write().add_error(
ErrorKind::CannotFindModule,
&[Message {
range: Into::<Range>::into(pos),
Expand All @@ -494,7 +494,7 @@ impl Loader {
),
);
}
self.sess.1.borrow_mut().add_suggestions(suggestions);
self.sess.1.write().add_suggestions(suggestions);
Ok(None)
}
}
Expand Down Expand Up @@ -574,7 +574,7 @@ impl Loader {
// plugin pkgs
if self.is_plugin_pkg(pkgpath.as_str()) {
if !self.opts.load_plugins {
self.sess.1.borrow_mut().add_error(
self.sess.1.write().add_error(
ErrorKind::CannotFindModule,
&[Message {
range: Into::<Range>::into(pos),
Expand Down
15 changes: 8 additions & 7 deletions kclvm/parser/src/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,21 @@ use indexmap::IndexSet;
use kclvm_ast::token::Token;
use kclvm_error::{Diagnostic, Handler, ParseError, ParseErrorMessage};
use kclvm_span::{BytePos, Loc, Span};
use std::{cell::RefCell, sync::Arc};
use parking_lot::RwLock;
use std::sync::Arc;

pub type ParseSessionRef = Arc<ParseSession>;

/// ParseSession represents the data associated with a parse session such as the
/// source map and the error handler.
#[derive(Default, Clone)]
pub struct ParseSession(pub Arc<Session>, pub RefCell<Handler>);
#[derive(Default)]
pub struct ParseSession(pub Arc<Session>, pub RwLock<Handler>);

impl ParseSession {
/// New a parse session with the global session.
#[inline]
pub fn with_session(sess: Arc<Session>) -> Self {
Self(sess, RefCell::new(Handler::default()))
Self(sess, RwLock::new(Handler::default()))
}

/// Lookup char pos from span.
Expand Down Expand Up @@ -96,7 +97,7 @@ impl ParseSession {
fn add_parse_err(&self, err: ParseError) {
let add_error = || -> Result<()> {
self.0.add_err(err.clone().into_diag(&self.0)?)?;
self.1.borrow_mut().add_diagnostic(err.into_diag(&self.0)?);
self.1.write().add_diagnostic(err.into_diag(&self.0)?);
Ok(())
};
if let Err(err) = add_error() {
Expand All @@ -110,13 +111,13 @@ impl ParseSession {
/// Append diagnostics into the parse session.
pub fn append_diagnostic(&self, diagnostics: IndexSet<Diagnostic>) -> &Self {
for diagnostic in diagnostics {
self.1.borrow_mut().add_diagnostic(diagnostic);
self.1.write().add_diagnostic(diagnostic);
}
self
}

/// Classify diagnostics into errors and warnings.
pub fn classification(&self) -> (IndexSet<Diagnostic>, IndexSet<Diagnostic>) {
self.1.borrow().classification()
self.1.read().classification()
}
}
2 changes: 1 addition & 1 deletion kclvm/runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ fn emit_compile_diag_to_string(
scope: &ProgramScope,
include_warnings: bool,
) -> Result<()> {
let mut res_str = sess.1.borrow_mut().emit_to_string()?;
let mut res_str = sess.1.write().emit_to_string()?;
let sema_err = scope.emit_diagnostics_to_string(sess.0.clone(), include_warnings);
if let Err(err) = &sema_err {
#[cfg(not(target_os = "windows"))]
Expand Down
108 changes: 9 additions & 99 deletions kclvm/sema/src/advanced_resolver/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::{
SymbolHintKind, SymbolRef, SymbolSemanticInfo, UnresolvedSymbol, ValueSymbol,
},
},
ty::{self, Type, TypeKind, SCHEMA_MEMBER_FUNCTIONS},
ty::{Parameter, Type, TypeKind, SCHEMA_MEMBER_FUNCTIONS},
};

use super::AdvancedResolver;
Expand Down Expand Up @@ -686,11 +686,11 @@ impl<'ctx> MutSelfTypedResultWalker<'ctx> for AdvancedResolver<'ctx> {
.get_scopes_mut()
.set_owner_to_scope(*cur_scope, owner);
}
self.do_arguments_symbol_resolve_with_hint_schema(
self.do_arguments_symbol_resolve_with_hint(
&call_expr.args,
&call_expr.keywords,
&schema_ty.func.params,
true,
schema_ty,
)?;

self.leave_scope();
Expand All @@ -711,11 +711,11 @@ impl<'ctx> MutSelfTypedResultWalker<'ctx> for AdvancedResolver<'ctx> {
.set_owner_to_scope(*cur_scope, owner);
}

self.do_arguments_symbol_resolve_with_hint_func(
self.do_arguments_symbol_resolve_with_hint(
&call_expr.args,
&call_expr.keywords,
&func_ty.params,
true,
&func_ty,
)?;
self.leave_scope();
}
Expand Down Expand Up @@ -1786,107 +1786,17 @@ impl<'ctx> AdvancedResolver<'ctx> {
Ok(())
}

pub fn do_arguments_symbol_resolve_with_hint_func(
pub fn do_arguments_symbol_resolve_with_hint(
&mut self,
args: &'ctx [ast::NodeRef<ast::Expr>],
kwargs: &'ctx [ast::NodeRef<ast::Keyword>],
params: &[Parameter],
with_hint: bool,
func_ty: &ty::FunctionType,
) -> anyhow::Result<()> {
if func_ty.params.is_empty() {
if params.is_empty() {
self.do_arguments_symbol_resolve(args, kwargs)?;
} else {
for (arg, param) in args.iter().zip(func_ty.params.iter()) {
self.expr(arg)?;

if with_hint {
let symbol_data = self.gs.get_symbols_mut();
let id = match &arg.node {
ast::Expr::Identifier(id) => id.names.last().unwrap().id.clone(),
_ => arg.id.clone(),
};
if let Some(arg_ref) = symbol_data
.symbols_info
.node_symbol_map
.get(&self.ctx.get_node_key(&id))
{
match arg_ref.get_kind() {
crate::core::symbol::SymbolKind::Expression => {
if let Some(expr) = symbol_data.exprs.get_mut(arg_ref.get_id()) {
expr.hint = Some(SymbolHint {
pos: arg.get_pos(),
kind: SymbolHintKind::VarHint(param.name.clone()),
});
}
}
crate::core::symbol::SymbolKind::Unresolved => {
let mut has_hint = false;
if let Some(unresolved) =
symbol_data.unresolved.get(arg_ref.get_id())
{
if let Some(def) = unresolved.def {
if let Some(def) = symbol_data.get_symbol(def) {
if def.get_name() != param.name {
has_hint = true;
}
}
}
}
if has_hint {
if let Some(unresolved) =
symbol_data.unresolved.get_mut(arg_ref.get_id())
{
unresolved.hint = Some(SymbolHint {
kind: SymbolHintKind::VarHint(param.name.clone()),
pos: arg.get_pos(),
});
}
}
}
_ => {}
}
}
}
}

for kw in kwargs.iter() {
if let Some(value) = &kw.node.value {
self.expr(value)?;
}
let (start_pos, end_pos): Range = kw.node.arg.get_span_pos();
let value = self.gs.get_symbols_mut().alloc_value_symbol(
ValueSymbol::new(kw.node.arg.node.get_name(), start_pos, end_pos, None, false),
self.ctx.get_node_key(&kw.id),
self.ctx.current_pkgpath.clone().unwrap(),
);

if let Some(value) = self.gs.get_symbols_mut().values.get_mut(value.get_id()) {
value.sema_info = SymbolSemanticInfo {
ty: self
.ctx
.node_ty_map
.borrow()
.get(&self.ctx.get_node_key(&kw.id))
.map(|ty| ty.clone()),
doc: None,
};
}
}
}
Ok(())
}

pub fn do_arguments_symbol_resolve_with_hint_schema(
&mut self,
args: &'ctx [ast::NodeRef<ast::Expr>],
kwargs: &'ctx [ast::NodeRef<ast::Keyword>],
with_hint: bool,
schema_ty: &ty::SchemaType,
) -> anyhow::Result<()> {
if schema_ty.func.params.is_empty() {
self.do_arguments_symbol_resolve(args, kwargs)?;
} else {
for (arg, param) in args.iter().zip(schema_ty.func.params.iter()) {
for (arg, param) in args.iter().zip(params.iter()) {
self.expr(arg)?;

if with_hint {
Expand Down
4 changes: 2 additions & 2 deletions kclvm/tools/benches/benchmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl fmt::Display for StopWatchSpan {
/// Utility for writing benchmark tests.
///
/// If you need to benchmark the entire test, you can directly add the macro `#[bench_test]` like this:
/// ```
/// ```no_check
/// #[test]
/// #[bench_test]
/// fn benchmark_foo() {
Expand All @@ -76,7 +76,7 @@ impl fmt::Display for StopWatchSpan {
/// If you need to skip some preparation stages and only test some parts of test, you can use the `bench()` method.
/// A benchmark test looks like this:
///
/// ```
/// ```no_check
/// #[test]
/// fn benchmark_foo() {
/// let data = bench_fixture::some_fixture();
Expand Down
3 changes: 1 addition & 2 deletions kclvm/tools/src/LSP/src/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ fn completion_import_stmt(
if let Some(node) = program.pos_to_stmt(line_start_pos) {
if let Stmt::Import(_) = node.node {
completions.extend(completion_import_builtin_pkg());
completions.extend(completion_import_internal_pkg(&program, &line_start_pos));
completions.extend(completion_import_internal_pkg(program, line_start_pos));
completions.extend(completion_import_external_pkg(metadata));
}
}
Expand Down Expand Up @@ -558,7 +558,6 @@ fn completion_import_external_pkg(metadata: Option<Metadata>) -> IndexSet<KCLCom
Some(metadata) => metadata
.packages
.keys()
.into_iter()
.map(|name| KCLCompletionItem {
label: name.to_string(),
detail: None,
Expand Down
4 changes: 2 additions & 2 deletions kclvm/tools/src/LSP/src/inlay_hints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@ pub fn inlay_hints(file: &str, gs: &GlobalState) -> Option<Vec<InlayHint>> {

#[inline]
fn generate_inlay_hint(hint: &SymbolHint) -> KCLInlayHint {
let (part, position) = get_hint_label(&hint);
let (part, position) = get_hint_label(hint);
KCLInlayHint { position, part }
}

#[inline]
fn into_lsp_inlay_hint(hint: &KCLInlayHint) -> InlayHint {
InlayHint {
position: hint.position.clone(),
position: hint.position,
label: lsp_types::InlayHintLabel::LabelParts(vec![hint.part.clone()]),
kind: None,
text_edits: None,
Expand Down
10 changes: 4 additions & 6 deletions kclvm/tools/src/LSP/src/signature_help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ pub fn signature_help(
gs: &GlobalState,
trigger_character: Option<String>,
) -> Option<SignatureHelp> {
if trigger_character.is_none() {
return None;
}
trigger_character.as_ref()?;
match trigger_character.unwrap().as_str() {
// func<cursor>
"(" => {
Expand All @@ -32,7 +30,7 @@ pub fn signature_help(
.get_sema_info()
.doc
.clone()
.and_then(|s| Some(lsp_types::Documentation::String(s)));
.map(lsp_types::Documentation::String);

return Some(SignatureHelp {
signatures: vec![SignatureInformation {
Expand Down Expand Up @@ -68,7 +66,7 @@ pub fn signature_help(
.get_sema_info()
.doc
.clone()
.and_then(|s| Some(lsp_types::Documentation::String(s)));
.map(lsp_types::Documentation::String);

// highlight parameter's index
// if None, it will highlight first param(maybe default)
Expand All @@ -90,7 +88,7 @@ pub fn signature_help(
.collect();
let mut index: usize = 0;
for (i, symbol) in actually_symbol.iter().enumerate() {
let s = gs.get_symbols().get_symbol(symbol.clone()).unwrap();
let s = gs.get_symbols().get_symbol(*symbol).unwrap();
let start = s.get_range().0;
if pos.less_equal(&start) {
index = i;
Expand Down
4 changes: 1 addition & 3 deletions kclvm/tools/src/LSP/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,7 @@ impl LanguageServerState {

{
let mut db = snapshot.db.write();
if !db.contains_key(&file.file_id) {
db.insert(file.file_id, None);
}
db.entry(file.file_id).or_insert(None);
}
let (diags, compile_res) = compile_with_params(Params {
file: filename.clone(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@

[dependencies]
k8s = { oci = "oci://ghcr.io/kcl-lang/k8s", tag = "1.28" }

Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,3 @@ version = "0.0.4"

[dependencies]
konfig = { git = "https://github.com/awesome-kusion/konfig.git", tag = "v0.0.1" }

Loading

0 comments on commit 1f03a77

Please sign in to comment.