Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
use std::sync::Arc;

use emmylua_parser::{
LuaAstNode, LuaAstToken, LuaDocDescriptionOwner, LuaDocFieldKey, LuaDocTagField,
LuaDocTagOperator, LuaDocType, NumberResult, VisibilityKind,
};

use crate::{
AnalyzeError, AsyncState, DiagnosticCode, LuaFunctionType, LuaMemberFeature, LuaMemberId,
LuaSignatureId, LuaTypeCache, OperatorFunction, TypeOps,
AnalyzeError, DiagnosticCode, LuaMemberFeature, LuaMemberId, LuaSignatureId, LuaTypeCache,
OperatorFunction, TypeOps,
compilation::analyzer::doc::preprocess_description,
db_index::{
LuaMember, LuaMemberKey, LuaMemberOwner, LuaOperator, LuaOperatorMetaMethod,
Expand Down Expand Up @@ -99,19 +97,10 @@ pub fn analyze_field(analyzer: &mut DocAnalyzer, tag: LuaDocTagField) -> Option<
LuaOperatorMetaMethod::Index,
file_id,
range,
OperatorFunction::Func(Arc::new(LuaFunctionType::new(
AsyncState::None,
false,
false,
vec![
(
"self".to_string(),
Some(LuaType::Ref(current_type_id.clone())),
),
("key".to_string(), Some(key_type_ref.clone())),
],
field_type.clone(),
))),
OperatorFunction::BinOp {
param: key_type_ref.clone(),
ret: field_type.clone(),
},
);
analyzer
.get_db()
Expand Down Expand Up @@ -169,46 +158,58 @@ pub fn analyze_operator(analyzer: &mut DocAnalyzer, tag: LuaDocTagOperator) -> O
let current_type_id = analyzer.current_type_id.clone()?;
let name_token = tag.get_name_token()?;
let op_kind = LuaOperatorMetaMethod::from_operator_name(name_token.get_name_text())?;
let mut operands: Vec<(String, Option<LuaType>)> = tag
let params: Vec<LuaType> = tag
.get_param_list()
.map(|list| {
list.get_types()
.enumerate()
.map(|(i, doc_type)| {
(
format!("arg{}", i),
Some(infer_type(&mut analyzer.type_context, doc_type)),
)
})
.map(|doc_type| infer_type(&mut analyzer.type_context, doc_type))
.collect()
})
.unwrap_or_default();

let self_name = if op_kind == LuaOperatorMetaMethod::Call {
"@call_self"
} else {
"self"
};
operands.insert(0, (self_name.to_string(), Some(LuaType::SelfInfer)));

let return_type = if let Some(return_type) = tag.get_return_type() {
infer_type(&mut analyzer.type_context, return_type)
} else {
LuaType::Unknown
};

let func = match op_kind {
LuaOperatorMetaMethod::Unm
| LuaOperatorMetaMethod::BNot
| LuaOperatorMetaMethod::Len
| LuaOperatorMetaMethod::Pairs => OperatorFunction::UnOp { ret: return_type },
LuaOperatorMetaMethod::Add
| LuaOperatorMetaMethod::Sub
| LuaOperatorMetaMethod::Mul
| LuaOperatorMetaMethod::Div
| LuaOperatorMetaMethod::Mod
| LuaOperatorMetaMethod::Pow
| LuaOperatorMetaMethod::IDiv
| LuaOperatorMetaMethod::BAnd
| LuaOperatorMetaMethod::BOr
| LuaOperatorMetaMethod::BXor
| LuaOperatorMetaMethod::Shl
| LuaOperatorMetaMethod::Shr
| LuaOperatorMetaMethod::Concat
| LuaOperatorMetaMethod::Eq
| LuaOperatorMetaMethod::Lt
| LuaOperatorMetaMethod::Le
| LuaOperatorMetaMethod::Index => OperatorFunction::BinOp {
param: params.into_iter().next().unwrap_or(LuaType::Any),
ret: return_type,
},
LuaOperatorMetaMethod::Call => OperatorFunction::Call {
params,
ret: return_type,
},
};

let operator = LuaOperator::new(
current_type_id.into(),
op_kind,
analyzer.file_id,
name_token.get_range(),
OperatorFunction::Func(Arc::new(LuaFunctionType::new(
AsyncState::None,
false,
false,
operands,
return_type,
))),
func,
);

analyzer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ pub fn analyze_overload(analyzer: &mut DocAnalyzer, tag: LuaDocTagOverload) -> O
LuaOperatorMetaMethod::Call,
analyzer.file_id,
tag.get_range(),
OperatorFunction::Func(func.clone()),
OperatorFunction::Overload(func),
);
analyzer
.get_db()
Expand Down
122 changes: 80 additions & 42 deletions crates/emmylua_code_analysis/src/db_index/operators/lua_operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::sync::Arc;
use rowan::{TextRange, TextSize};

use crate::{
DbIndex, FileId, InFiled, InferFailReason, LuaConstructorReturnMode, LuaFunctionType,
LuaSignature, LuaSignatureId, SignatureReturnStatus,
AsyncState, DbIndex, FileId, InFiled, InferFailReason, LuaConstructorReturnMode,
LuaFunctionType, LuaSignature, LuaSignatureId, SignatureReturnStatus,
db_index::{LuaType, LuaTypeDeclId},
};

Expand All @@ -21,8 +21,25 @@ pub struct LuaOperator {

#[derive(Debug, Clone)]
pub enum OperatorFunction {
Func(Arc<LuaFunctionType>),
// One explicit parameter: `@operator add(T): R`, `@operator sub(T): R`, or `@field [K] V`.
BinOp {
param: LuaType,
ret: LuaType,
},
// Unary declarations such as `@operator unm: R` or `@operator len: R`.
UnOp {
ret: LuaType,
},
// `@operator call(...)`.
Call {
params: Vec<LuaType>,
ret: LuaType,
},
// `@overload fun(...)`.
Overload(Arc<LuaFunctionType>),
// Runtime metatable closures like `__add = function(...)` or `__call = function(...)`.
Signature(LuaSignatureId),
// Synthesized call operator for default class constructors.
DefaultClassCtor {
id: LuaSignatureId,
strip_self: bool,
Expand Down Expand Up @@ -57,14 +74,7 @@ impl LuaOperator {

pub fn get_operand(&self, db: &DbIndex) -> LuaType {
match &self.func {
OperatorFunction::Func(func) => {
let params = func.get_params();
if params.len() >= 2 {
return params[1].1.clone().unwrap_or(LuaType::Any);
}

LuaType::Any
}
OperatorFunction::BinOp { param, .. } => param.clone(),
OperatorFunction::Signature(signature) => {
let signature = db.get_signature_index().get(signature);
if let Some(signature) = signature {
Expand All @@ -76,14 +86,19 @@ impl LuaOperator {

LuaType::Any
}
// 只有 .field 才有`operand`, call 不会有这个
OperatorFunction::DefaultClassCtor { .. } => LuaType::Unknown,
OperatorFunction::Overload(_)
| OperatorFunction::UnOp { .. }
| OperatorFunction::Call { .. }
| OperatorFunction::DefaultClassCtor { .. } => LuaType::Unknown,
}
}

pub fn get_result(&self, db: &DbIndex) -> Result<LuaType, InferFailReason> {
match &self.func {
OperatorFunction::Func(func) => Ok(func.get_ret().clone()),
OperatorFunction::BinOp { ret, .. }
| OperatorFunction::UnOp { ret }
| OperatorFunction::Call { ret, .. } => Ok(ret.clone()),
OperatorFunction::Overload(func) => Ok(func.get_ret().clone()),
OperatorFunction::Signature(signature_id) => {
let signature = db.get_signature_index().get(signature_id);
if let Some(signature) = signature {
Expand Down Expand Up @@ -115,40 +130,63 @@ impl LuaOperator {

pub fn get_operator_func(&self, db: &DbIndex) -> LuaType {
match &self.func {
OperatorFunction::Func(func) => {
if self.op == LuaOperatorMetaMethod::Call {
LuaType::DocFunction(func.to_call_operator_func_type())
} else {
LuaType::DocFunction(func.clone())
}
OperatorFunction::BinOp { param, ret } => LuaFunctionType::new(
AsyncState::None,
false,
false,
vec![
("self".to_string(), Some(LuaType::SelfInfer)),
("arg0".to_string(), Some(param.clone())),
],
ret.clone(),
)
.into(),
OperatorFunction::UnOp { ret } => LuaFunctionType::new(
AsyncState::None,
false,
false,
vec![("self".to_string(), Some(LuaType::SelfInfer))],
ret.clone(),
)
.into(),
OperatorFunction::Call { params, ret } => {
let is_variadic = params.last().is_some_and(LuaType::is_variadic);
let last_param_idx = params.len().saturating_sub(1);
let params = params
.iter()
.enumerate()
.map(|(i, param)| {
let name = if is_variadic && i == last_param_idx {
"...".to_string()
} else {
format!("arg{}", i)
};
(name, Some(param.clone()))
})
.collect();

LuaFunctionType::new(AsyncState::None, false, is_variadic, params, ret.clone())
.into()
}
OperatorFunction::Overload(func) => {
LuaType::DocFunction(func.to_call_operator_func_type())
}
OperatorFunction::Signature(signature) => LuaType::Signature(*signature),
OperatorFunction::DefaultClassCtor {
id,
strip_self,
return_mode,
} => {
if let Some(signature) = db.get_signature_index().get(id) {
let params = signature.get_type_params();
let is_colon_define = if *strip_self {
false
} else {
signature.is_colon_define
};
let return_type = get_constructor_return_type(signature, return_mode);

let func_type = LuaFunctionType::new(
signature.async_state,
is_colon_define,
signature.is_vararg,
params,
return_type,
);
return LuaType::DocFunction(Arc::new(func_type));
}

LuaType::Signature(*id)
}
} => match db.get_signature_index().get(id) {
Some(signature) => LuaFunctionType::new(
signature.async_state,
!*strip_self && signature.is_colon_define,
signature.is_vararg,
signature.get_type_params(),
get_constructor_return_type(signature, return_mode),
)
.into(),
None => LuaType::Signature(*id),
},
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,24 @@ mod test {
));
}

#[test]
fn test_variadic_call_operator() {
let mut ws = VirtualWorkspace::new();
let source = r#"
---@class Callable
---@operator call(string...): string

---@type Callable
local callable

callable("a", "b")
callable("a", 1)
"#;

assert!(ws.has_no_diagnostic(DiagnosticCode::RedundantParameter, source));
assert!(!ws.has_no_diagnostic(DiagnosticCode::ParamTypeMismatch, source));
}

#[test]
fn test_issue_360() {
let mut ws = VirtualWorkspace::new();
Expand Down
Loading