|
| 1 | +use emmylua_parser::{LuaAst, LuaAstNode, LuaCallExpr}; |
| 2 | + |
| 3 | +use crate::{humanize_type, DiagnosticCode, LuaType, SemanticModel}; |
| 4 | + |
| 5 | +use super::DiagnosticContext; |
| 6 | + |
| 7 | +pub const CODES: &[DiagnosticCode] = &[DiagnosticCode::ParamTypeNotMatch]; |
| 8 | + |
| 9 | +/// a simple implementation of param type check, later we will do better |
| 10 | +pub fn check(context: &mut DiagnosticContext, semantic_model: &mut SemanticModel) -> Option<()> { |
| 11 | + let root = semantic_model.get_root().clone(); |
| 12 | + for node in root.descendants::<LuaAst>() { |
| 13 | + match node { |
| 14 | + LuaAst::LuaCallExpr(call_expr) => { |
| 15 | + check_call_expr(context, semantic_model, call_expr); |
| 16 | + } |
| 17 | + _ => {} |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + Some(()) |
| 22 | +} |
| 23 | + |
| 24 | +fn check_call_expr( |
| 25 | + context: &mut DiagnosticContext, |
| 26 | + semantic_model: &mut SemanticModel, |
| 27 | + call_expr: LuaCallExpr, |
| 28 | +) -> Option<()> { |
| 29 | + let func = semantic_model.infer_call_expr_func(call_expr.clone(), None)?; |
| 30 | + let params = func.get_params(); |
| 31 | + let args = call_expr.get_args_list()?.get_args().collect::<Vec<_>>(); |
| 32 | + for (idx, param) in params.iter().enumerate() { |
| 33 | + if idx >= args.len() { |
| 34 | + break; |
| 35 | + } |
| 36 | + |
| 37 | + if param.0 == "..." { |
| 38 | + } else { |
| 39 | + if param.1.is_none() { |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + let param_type = param.1.clone().unwrap(); |
| 44 | + let arg = &args[idx]; |
| 45 | + let expr_type = semantic_model |
| 46 | + .infer_expr(arg.clone()) |
| 47 | + .unwrap_or(LuaType::Any); |
| 48 | + if !semantic_model.check_type_compact(¶m_type, &expr_type) { |
| 49 | + let db = semantic_model.get_db(); |
| 50 | + context.add_diagnostic( |
| 51 | + DiagnosticCode::ParamTypeNotMatch, |
| 52 | + arg.get_range(), |
| 53 | + format!( |
| 54 | + "expected {} but founded {}", |
| 55 | + humanize_type(db, ¶m_type), |
| 56 | + humanize_type(db, &expr_type) |
| 57 | + ), |
| 58 | + None, |
| 59 | + ); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + Some(()) |
| 65 | +} |
0 commit comments