fix: __new__ method definition bug

This commit is contained in:
Shunsuke Shibayama 2023-06-08 12:32:46 +09:00
parent ef30a05708
commit 1cbe2de706
2 changed files with 32 additions and 23 deletions

View file

@ -1288,9 +1288,7 @@ impl Context {
2,
self.level,
);
if ERG_MODE {
self.gen_class_new_method(&gen, &mut ctx)?;
}
self.gen_class_new_method(&gen, &mut ctx)?;
self.register_gen_mono_type(ident, gen, ctx, Const)
} else {
let params = gen
@ -1307,9 +1305,7 @@ impl Context {
2,
self.level,
);
if ERG_MODE {
self.gen_class_new_method(&gen, &mut ctx)?;
}
self.gen_class_new_method(&gen, &mut ctx)?;
self.register_gen_poly_type(ident, gen, ctx, Const)
}
}
@ -1558,16 +1554,31 @@ impl Context {
} else {
func0(gen.typ().clone())
};
methods.register_fixed_auto_impl(
"__new__",
new_t.clone(),
Immutable,
Visibility::BUILTIN_PRIVATE,
Some("__call__".into()),
)?;
// 必要なら、ユーザーが独自に上書きする
// users can override this if necessary
methods.register_auto_impl("new", new_t, Immutable, Visibility::BUILTIN_PUBLIC, None)?;
if ERG_MODE {
methods.register_fixed_auto_impl(
"__new__",
new_t.clone(),
Immutable,
Visibility::BUILTIN_PRIVATE,
Some("__call__".into()),
)?;
// users can override this if necessary
methods.register_auto_impl(
"new",
new_t,
Immutable,
Visibility::BUILTIN_PUBLIC,
None,
)?;
} else {
methods.register_auto_impl(
"__call__",
new_t,
Immutable,
Visibility::BUILTIN_PUBLIC,
Some("__call__".into()),
)?;
}
ctx.methods_list
.push((ClassDefType::Simple(gen.typ().clone()), methods));
Ok(())

View file

@ -1730,21 +1730,19 @@ impl ASTLowerer {
if let Some(sup_type) = call.args.get_left_or_key("Super") {
Self::check_inheritable(&self.cfg, &mut self.errs, type_obj, sup_type, &hir_def.sig);
}
let (__new__, need_to_gen_new) = if let (Some(dunder_new_vi), Some(new_vi)) = (
class_ctx.get_current_scope_var(&VarName::from_static("__new__")),
class_ctx.get_current_scope_var(&VarName::from_static("new")),
) {
(dunder_new_vi.t.clone(), new_vi.kind == VarKind::Auto)
} else {
let Some(__new__) = class_ctx.get_current_scope_var(&VarName::from_static("__new__")).or(class_ctx.get_current_scope_var(&VarName::from_static("__call__"))) else {
return unreachable_error!(LowerErrors, LowerError, self);
};
let need_to_gen_new = class_ctx
.get_current_scope_var(&VarName::from_static("new"))
.map_or(false, |vi| vi.kind == VarKind::Auto);
let require_or_sup = Self::get_require_or_sup_or_base(hir_def.body.block.remove(0));
Ok(hir::ClassDef::new(
type_obj.clone(),
hir_def.sig,
require_or_sup,
need_to_gen_new,
__new__,
__new__.t.clone(),
hir_methods,
))
}