Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GDScript: Add Self to reference a class from inside #74618

Closed
wants to merge 1 commit into from
Closed
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
6 changes: 3 additions & 3 deletions modules/gdscript/gdscript.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2481,7 +2481,7 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b
subclass = nullptr;
break;
} else {
Vector<StringName> extend_classes = subclass->extends;
Vector<GDScriptParser::IdentifierNode *> extend_classes = subclass->extends;

Ref<FileAccess> subfile = FileAccess::open(subclass->extends_path, FileAccess::READ);
if (subfile.is_null()) {
Expand Down Expand Up @@ -2511,7 +2511,7 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b
}

const GDScriptParser::ClassNode *inner_class = subclass->members[i].m_class;
if (inner_class->identifier->name == extend_classes[0]) {
if (inner_class->identifier->name == extend_classes[0]->name) {
extend_classes.remove_at(0);
found = true;
subclass = inner_class;
Expand All @@ -2525,7 +2525,7 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b
}
}
} else if (subclass->extends.size() == 1) {
*r_base_type = subclass->extends[0];
*r_base_type = subclass->extends[0]->name;
subclass = nullptr;
} else {
break;
Expand Down
80 changes: 51 additions & 29 deletions modules/gdscript/gdscript_analyzer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,11 @@ Error GDScriptAnalyzer::check_native_member_name_conflict(const StringName &p_me
return ERR_PARSE_ERROR;
}

if (p_member_name == SNAME("Self")) {
push_error(R"(Cannot have a member named "Self": shadows a reference to a current class.)", p_member_node);
return ERR_PARSE_ERROR;
}

return OK;
}

Expand Down Expand Up @@ -415,44 +420,51 @@ Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_c
push_error("Could not resolve an empty super class path.", p_class);
return ERR_PARSE_ERROR;
}
const StringName &name = p_class->extends[extends_index++];
GDScriptParser::IdentifierNode *id = p_class->extends[extends_index++];
const StringName &name = id->name;
base.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;

if (ScriptServer::is_global_class(name)) {
if (name == SNAME("Self")) {
if (!p_class->outer) {
push_error(R"(Cannot extend "Self" in a non-nested class.)", p_class);
return ERR_PARSE_ERROR;
}
base = p_class->outer->get_datatype();
} else if (ScriptServer::is_global_class(name)) {
String base_path = ScriptServer::get_global_class_path(name);

if (base_path == parser->script_path) {
base = parser->head->get_datatype();
} else {
Ref<GDScriptParserRef> base_parser = get_parser_for(base_path);
if (base_parser.is_null()) {
push_error(vformat(R"(Could not resolve super class "%s".)", name), p_class);
push_error(vformat(R"(Could not resolve super class "%s".)", name), id);
return ERR_PARSE_ERROR;
}

Error err = base_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
if (err != OK) {
push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), id);
return err;
}
base = base_parser->get_parser()->head->get_datatype();
}
} else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {
const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);
if (info.path.get_extension().to_lower() != GDScriptLanguage::get_singleton()->get_extension()) {
push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), p_class);
push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), id);
return ERR_PARSE_ERROR;
}

Ref<GDScriptParserRef> info_parser = get_parser_for(info.path);
if (info_parser.is_null()) {
push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), p_class);
push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), id);
return ERR_PARSE_ERROR;
}

Error err = info_parser->raise_status(GDScriptParserRef::INHERITANCE_SOLVED);
if (err != OK) {
push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), id);
return err;
}
base = info_parser->get_parser()->head->get_datatype();
Expand All @@ -467,7 +479,7 @@ Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_c
for (GDScriptParser::ClassNode *look_class : script_classes) {
if (look_class->identifier && look_class->identifier->name == name) {
if (!look_class->get_datatype().is_set()) {
Error err = resolve_class_inheritance(look_class, p_class);
Error err = resolve_class_inheritance(look_class, id);
if (err) {
return err;
}
Expand All @@ -477,35 +489,33 @@ Error GDScriptAnalyzer::resolve_class_inheritance(GDScriptParser::ClassNode *p_c
break;
}
if (look_class->has_member(name)) {
resolve_class_member(look_class, name, p_class);
resolve_class_member(look_class, name, id);
base = look_class->get_member(name).get_datatype();
found = true;
break;
}
}

if (!found) {
push_error(vformat(R"(Could not find base class "%s".)", name), p_class);
push_error(vformat(R"(Could not find base class "%s".)", name), id);
return ERR_PARSE_ERROR;
}
}
}

for (int index = extends_index; index < p_class->extends.size(); index++) {
GDScriptParser::IdentifierNode *id = p_class->extends[index];

if (base.kind != GDScriptParser::DataType::CLASS) {
push_error(R"(Super type "%s" is not a GDScript. Cannot get nested types.)", p_class);
push_error(R"(Super type "%s" is not a GDScript. Cannot get nested types.)", id);
return ERR_PARSE_ERROR;
}

// TODO: Extends could use identifier nodes. That way errors can be pointed out properly and it can be used here.
GDScriptParser::IdentifierNode *id = parser->alloc_node<GDScriptParser::IdentifierNode>();
id->name = p_class->extends[index];

reduce_identifier_from_base(id, &base);

GDScriptParser::DataType id_type = id->get_datatype();
if (!id_type.is_set()) {
push_error(vformat(R"(Could not find type "%s" under base "%s".)", id->name, base.to_string()), p_class);
push_error(vformat(R"(Could not find type "%s" under base "%s".)", id->name, base.to_string()), id);
}

base = id_type;
Expand Down Expand Up @@ -616,6 +626,8 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type
result.kind = GDScriptParser::DataType::NATIVE;
result.builtin_type = Variant::OBJECT;
result.native_type = SNAME("Object");
} else if (first == SNAME("Self")) {
result = parser->current_class->get_datatype();
} else if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {
// Built-in types.
if (p_type->type_chain.size() > 1) {
Expand Down Expand Up @@ -3631,6 +3643,11 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident
}
}

if (name == SNAME("Self")) {
reduce_identifier_from_base_set_class(p_identifier, parser->current_class->get_datatype());
return;
}

if (class_exists(name)) {
p_identifier->set_datatype(make_native_meta_type(name));
return;
Expand Down Expand Up @@ -4778,7 +4795,7 @@ void GDScriptAnalyzer::validate_call_arg(const List<GDScriptParser::DataType> &p
}

#ifdef DEBUG_ENABLED
bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
void GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
const StringName &name = p_local->name;
GDScriptParser::DataType base = parser->current_class->get_datatype();
GDScriptParser::ClassNode *base_class = base.class_type;
Expand All @@ -4790,50 +4807,55 @@ bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, con
for (MethodInfo &info : gdscript_funcs) {
if (info.name == name) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
return true;
return;
}
}

if (Variant::has_utility_function(name)) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in function");
return true;
return;
} else if (ClassDB::class_exists(name)) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "global class");
return true;
return;
} else if (GDScriptParser::get_builtin_type(name) != Variant::VARIANT_MAX) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "built-in type");
return;
} else if (name == SNAME("Self")) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_context, name, "current class reference");
return;
}
}

while (base_class != nullptr) {
if (base_class->has_member(name)) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE, p_context, p_local->name, base_class->get_member(name).get_type_name(), itos(base_class->get_member(name).get_line()));
return true;
return;
}
base_class = base_class->base_type.class_type;
}

StringName parent = base.native_type;
while (parent != StringName()) {
ERR_FAIL_COND_V_MSG(!class_exists(parent), false, "Non-existent native base class.");
ERR_FAIL_COND_MSG(!class_exists(parent), "Non-existent native base class.");

if (ClassDB::has_method(parent, name, true)) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
return true;
return;
} else if (ClassDB::has_signal(parent, name, true)) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
return true;
return;
} else if (ClassDB::has_property(parent, name, true)) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
return true;
return;
} else if (ClassDB::has_integer_constant(parent, name, true)) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
return true;
return;
} else if (ClassDB::has_enum(parent, name, true)) {
parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
return true;
return;
}
parent = ClassDB::get_parent_class(parent);
}

return false;
}
#endif

Expand Down
2 changes: 1 addition & 1 deletion modules/gdscript/gdscript_analyzer.h
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ class GDScriptAnalyzer {
Ref<GDScriptParserRef> get_parser_for(const String &p_path);
void reduce_identifier_from_base_set_class(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType p_identifier_datatype);
#ifdef DEBUG_ENABLED
bool is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context);
void is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context);
#endif

public:
Expand Down
4 changes: 4 additions & 0 deletions modules/gdscript/gdscript_compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,10 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code
}
}

if (identifier == SNAME("Self")) {
return codegen.add_constant(codegen.script);
}

// Try globals.
if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {
// If it's an autoload singleton, we postpone to load it at runtime.
Expand Down
4 changes: 2 additions & 2 deletions modules/gdscript/gdscript_editor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3368,10 +3368,10 @@ ::Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symb

if (context.current_class && context.current_class->extends.size() > 0) {
bool success = false;
ClassDB::get_integer_constant(context.current_class->extends[0], p_symbol, &success);
ClassDB::get_integer_constant(context.current_class->extends[0]->name, p_symbol, &success);
if (success) {
r_result.type = ScriptLanguage::LOOKUP_RESULT_CLASS_CONSTANT;
r_result.class_name = context.current_class->extends[0];
r_result.class_name = context.current_class->extends[0]->name;
r_result.class_member = p_symbol;
return OK;
}
Expand Down
6 changes: 3 additions & 3 deletions modules/gdscript/gdscript_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -712,14 +712,14 @@ void GDScriptParser::parse_extends() {
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after "extends".)")) {
return;
}
current_class->extends.push_back(previous.literal);
current_class->extends.push_back(parse_identifier());

while (match(GDScriptTokenizer::Token::PERIOD)) {
make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after ".".)")) {
return;
}
current_class->extends.push_back(previous.literal);
current_class->extends.push_back(parse_identifier());
}
}

Expand Down Expand Up @@ -4479,7 +4479,7 @@ void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
} else {
first = false;
}
push_text(p_class->extends[i]);
push_text(p_class->extends[i]->name);
}
}

Expand Down
2 changes: 1 addition & 1 deletion modules/gdscript/gdscript_parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ class GDScriptParser {
bool extends_used = false;
bool onready_used = false;
String extends_path;
Vector<StringName> extends; // List for indexing: extends A.B.C
Vector<IdentifierNode *> extends; // List for indexing: extends A.B.C
DataType base_type;
String fqcn; // Fully-qualified class name. Identifies uniquely any class in the project.
#ifdef TOOLS_ENABLED
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode
class_api["path"] = path;
Array extends_class;
for (int i = 0; i < p_class->extends.size(); i++) {
extends_class.append(String(p_class->extends[i]));
extends_class.append(String(p_class->extends[i]->name));
}
class_api["extends_class"] = extends_class;
class_api["extends_file"] = String(p_class->extends_path);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
extends Self

func test():
print('not ok')
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
GDTEST_ANALYZER_ERROR
Cannot extend "Self" in a non-nested class.
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class_name SelfClassReference


const Constant := Self

class Extended extends Self:
pass

static func static_func(instance: Self) -> Self:
return instance

func instance_func() -> Self:
return self


func test():
@warning_ignore("assert_always_true")
assert(Self == Constant)

@warning_ignore("assert_always_true")
assert(Self == SelfClassReference)

var extended := Extended.new()
assert(extended is Self)
assert(extended is Constant)
assert(extended is SelfClassReference)

var constructed := Self.new()
assert(constructed is Self)
assert(constructed is Constant)
assert(constructed is SelfClassReference)

var static_funced := Self.static_func(self)
assert(static_funced is Self)
assert(static_funced is Constant)
assert(static_funced is SelfClassReference)

var instance_funced := instance_func()
assert(instance_funced is Self)
assert(instance_funced is Constant)
assert(instance_funced is SelfClassReference)

var variable: Self = self
assert(variable is Self)
assert(variable is Constant)
assert(variable is SelfClassReference)

print('ok')
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
GDTEST_OK
ok
13 changes: 13 additions & 0 deletions modules/gdscript/tests/scripts/analyzer/warnings/shadowning.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
var member: int = 0

@warning_ignore("unused_variable")
func test():
var Array := 'Array'
var Self := 'Self'
var Node := 'Node'
var is_same := 'is_same'
var sqrt := 'sqrt'
var member := 'member'
var reference := 'reference'

print('warn')
Loading