diff options
Diffstat (limited to 'modules/gdscript')
66 files changed, 1334 insertions, 719 deletions
diff --git a/modules/gdscript/SCsub b/modules/gdscript/SCsub index 2f507db548..1dc4768186 100644 --- a/modules/gdscript/SCsub +++ b/modules/gdscript/SCsub @@ -7,7 +7,7 @@ env_gdscript = env_modules.Clone() env_gdscript.add_source_files(env.modules_sources, "*.cpp") -if env["tools"]: +if env.editor_build: env_gdscript.add_source_files(env.modules_sources, "./editor/*.cpp") SConscript("editor/script_templates/SCsub") diff --git a/modules/gdscript/config.py b/modules/gdscript/config.py index 61ce6185a5..a7d5c406e9 100644 --- a/modules/gdscript/config.py +++ b/modules/gdscript/config.py @@ -1,4 +1,5 @@ def can_build(env, platform): + env.module_add_dependencies("gdscript", ["jsonrpc", "websocket"], True) return True diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml index e995cce651..c8eda53a2d 100644 --- a/modules/gdscript/doc_classes/@GDScript.xml +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -8,48 +8,47 @@ For the list of the global functions and constants see [@GlobalScope]. </description> <tutorials> + <link title="GDScript exports">$DOCS_URL/tutorials/scripting/gdscript/gdscript_exports.html</link> </tutorials> <methods> <method name="Color8"> <return type="Color" /> - <argument index="0" name="r8" type="int" /> - <argument index="1" name="g8" type="int" /> - <argument index="2" name="b8" type="int" /> - <argument index="3" name="a8" type="int" default="255" /> + <param index="0" name="r8" type="int" /> + <param index="1" name="g8" type="int" /> + <param index="2" name="b8" type="int" /> + <param index="3" name="a8" type="int" default="255" /> <description> - Returns a color constructed from integer red, green, blue, and alpha channels. Each channel should have 8 bits of information ranging from 0 to 255. - [code]r8[/code] red channel - [code]g8[/code] green channel - [code]b8[/code] blue channel - [code]a8[/code] alpha channel + Returns a [Color] constructed from red ([param r8]), green ([param g8]), blue ([param b8]), and optionally alpha ([param a8]) integer channels, each divided by [code]255.0[/code] for their final value. [codeblock] - red = Color8(255, 0, 0) + var red = Color8(255, 0, 0) # Same as Color(1, 0, 0) + var dark_blue = Color8(0, 0, 51) # Same as Color(0, 0, 0.2). + var my_color = Color8(306, 255, 0, 102) # Same as Color(1.2, 1, 0, 0.4). [/codeblock] </description> </method> <method name="assert"> <return type="void" /> - <argument index="0" name="condition" type="bool" /> - <argument index="1" name="message" type="String" default="""" /> + <param index="0" name="condition" type="bool" /> + <param index="1" name="message" type="String" default="""" /> <description> - Asserts that the [code]condition[/code] is [code]true[/code]. If the [code]condition[/code] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users. - [b]Note:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode. - The optional [code]message[/code] argument, if given, is shown in addition to the generic "Assertion failed" message. You can use this to provide additional details about why the assertion failed. + Asserts that the [param condition] is [code]true[/code]. If the [param condition] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users. + An optional [param message] can be shown in addition to the generic "Assertion failed" message. You can use this to provide additional details about why the assertion failed. + [b]Warning:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode. [codeblock] # Imagine we always want speed to be between 0 and 20. var speed = -10 assert(speed < 20) # True, the program will continue assert(speed >= 0) # False, the program will stop assert(speed >= 0 and speed < 20) # You can also combine the two conditional statements in one check - assert(speed < 20, "speed = %f, but the speed limit is 20" % speed) # Show a message with clarifying details + assert(speed < 20, "the speed limit is 20") # Show a message [/codeblock] </description> </method> <method name="char"> <return type="String" /> - <argument index="0" name="char" type="int" /> + <param index="0" name="char" type="int" /> <description> - Returns a character as a String of the given Unicode code point (which is compatible with ASCII code). + Returns a single character (as a [String]) of the given Unicode code point (which is compatible with ASCII code). [codeblock] a = char(65) # a is "A" a = char(65 + 32) # a is "a" @@ -59,31 +58,31 @@ </method> <method name="convert"> <return type="Variant" /> - <argument index="0" name="what" type="Variant" /> - <argument index="1" name="type" type="int" /> + <param index="0" name="what" type="Variant" /> + <param index="1" name="type" type="int" /> <description> - Converts from a type to another in the best way possible. The [code]type[/code] parameter uses the [enum Variant.Type] values. + Converts [param what] to [param type] in the best way possible. The [param type] uses the [enum Variant.Type] values. [codeblock] - a = Vector2(1, 0) - # Prints 1 - print(a.length()) - a = convert(a, TYPE_STRING) - # Prints 6 as "(1, 0)" is 6 characters - print(a.length()) + var a = [4, 2.5, 1.2] + print(a is Array) # Prints true + + var b = convert(a, TYPE_PACKED_BYTE_ARRAY) + print(b) # Prints [4, 2, 1] + print(b is Array) # Prints false [/codeblock] </description> </method> - <method name="dict2inst"> + <method name="dict_to_inst"> <return type="Object" /> - <argument index="0" name="dictionary" type="Dictionary" /> + <param index="0" name="dictionary" type="Dictionary" /> <description> - Converts a dictionary (previously created with [method inst2dict]) back to an instance. Useful for deserializing. + Converts a [param dictionary] (created with [method inst_to_dict]) back to an Object instance. Can be useful for deserializing. </description> </method> <method name="get_stack"> <return type="Array" /> <description> - Returns an array of dictionaries representing the current call stack. + Returns an array of dictionaries representing the current call stack. See also [method print_stack]. [codeblock] func _ready(): foo() @@ -94,22 +93,23 @@ func bar(): print(get_stack()) [/codeblock] - would print + Starting from [code]_ready()[/code], [code]bar()[/code] would print: [codeblock] [{function:bar, line:12, source:res://script.gd}, {function:foo, line:9, source:res://script.gd}, {function:_ready, line:6, source:res://script.gd}] [/codeblock] - [b]Note:[/b] Not supported for calling from threads. Instead, this will return an empty array. + [b]Note:[/b] This function only works if the running instance is connected to a debugging server (i.e. an editor instance). [method get_stack] will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server. + [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will return an empty array. </description> </method> - <method name="inst2dict"> + <method name="inst_to_dict"> <return type="Dictionary" /> - <argument index="0" name="instance" type="Object" /> + <param index="0" name="instance" type="Object" /> <description> - Returns the passed instance converted to a dictionary (useful for serializing). + Returns the passed [param instance] converted to a Dictionary. Can be useful for serializing. [codeblock] var foo = "bar" func _ready(): - var d = inst2dict(self) + var d = inst_to_dict(self) print(d.keys()) print(d.values()) [/codeblock] @@ -122,38 +122,41 @@ </method> <method name="len"> <return type="int" /> - <argument index="0" name="var" type="Variant" /> + <param index="0" name="var" type="Variant" /> <description> - Returns length of Variant [code]var[/code]. Length is the character count of String, element count of Array, size of Dictionary, etc. - [b]Note:[/b] Generates a fatal error if Variant can not provide a length. + Returns the length of the given Variant [param var]. The length can be the character count of a [String], the element count of any array type or the size of a [Dictionary]. For every other Variant type, a run-time error is generated and execution is stopped. [codeblock] a = [1, 2, 3, 4] len(a) # Returns 4 + + b = "Hello!" + len(b) # Returns 6 [/codeblock] </description> </method> <method name="load"> <return type="Resource" /> - <argument index="0" name="path" type="String" /> + <param index="0" name="path" type="String" /> <description> - Loads a resource from the filesystem located at [code]path[/code]. The resource is loaded on the method call (unless it's referenced already elsewhere, e.g. in another script or in the scene), which might cause slight delay, especially when loading scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use [method preload]. + Returns a [Resource] from the filesystem located at the absolute [param path]. Unless it's already referenced elsewhere (such as in another script or in the scene), the resource is loaded from disk on function call, which might cause a slight delay, especially when loading large scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use [method preload]. [b]Note:[/b] Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing "Copy Path" or by dragging the file from the FileSystem dock into the script. [codeblock] - # Load a scene called main located in the root of the project directory and cache it in a variable. + # Load a scene called "main" located in the root of the project directory and cache it in a variable. var main = load("res://main.tscn") # main will contain a PackedScene resource. [/codeblock] - [b]Important:[/b] The path must be absolute, a local path will just return [code]null[/code]. - This method is a simplified version of [method ResourceLoader.load], which can be used for more advanced scenarios. + [b]Important:[/b] The path must be absolute. A relative path will always return [code]null[/code]. + This function is a simplified version of [method ResourceLoader.load], which can be used for more advanced scenarios. + [b]Note:[/b] Files have to be imported into the engine first to load them using this function. If you want to load [Image]s at run-time, you may use [method Image.load]. If you want to import audio files, you can use the snippet described in [member AudioStreamMP3.data]. </description> </method> <method name="preload"> <return type="Resource" /> - <argument index="0" name="path" type="String" /> + <param index="0" name="path" type="String" /> <description> - Returns a [Resource] from the filesystem located at [code]path[/code]. The resource is loaded during script parsing, i.e. is loaded with the script and [method preload] effectively acts as a reference to that resource. Note that the method requires a constant path. If you want to load a resource from a dynamic/variable path, use [method load]. + Returns a [Resource] from the filesystem located at [param path]. During run-time, the resource is loaded when the script is being parsed. This function effectively acts as a reference to that resource. Note that this function requires [param path] to be a constant [String]. If you want to load a resource from a dynamic/variable path, use [method load]. [b]Note:[/b] Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing "Copy Path" or by dragging the file from the FileSystem dock into the script. [codeblock] - # Instance a scene. + # Create instance of a scene. var diamond = preload("res://diamond.tscn").instantiate() [/codeblock] </description> @@ -162,23 +165,24 @@ <return type="void" /> <description> Like [method @GlobalScope.print], but includes the current stack frame when running with the debugger turned on. - Output in the console would look something like this: + The output in the console may look like the following: [codeblock] Test print - At: res://test.gd:15:_process() + At: res://test.gd:15:_process() [/codeblock] - [b]Note:[/b] Not supported for calling from threads. Instead of the stack frame, this will print the thread ID. + [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will instead print the thread ID. </description> </method> <method name="print_stack"> <return type="void" /> <description> - Prints a stack trace at the current code location. Only works when running with debugger turned on. - Output in the console would look something like this: + Prints a stack trace at the current code location. See also [method get_stack]. + The output in the console may look like the following: [codeblock] Frame 0 - res://test.gd:16 in function '_process' [/codeblock] - [b]Note:[/b] Not supported for calling from threads. Instead of the stack trace, this will print the thread ID. + [b]Note:[/b] This function only works if the running instance is connected to a debugging server (i.e. an editor instance). [method print_stack] will not work in projects exported in release mode, or in projects exported in debug mode if not connected to a debugging server. + [b]Note:[/b] Calling this function from a [Thread] is not supported. Doing so will instead print the thread ID. </description> </method> <method name="range" qualifiers="vararg"> @@ -225,7 +229,7 @@ <method name="str" qualifiers="vararg"> <return type="String" /> <description> - Converts one or more arguments to string in the best way possible. + Converts one or more arguments to a [String] in the best way possible. [codeblock] var a = [10, 20, 30] var b = str(a); @@ -236,8 +240,13 @@ </method> <method name="type_exists"> <return type="bool" /> - <argument index="0" name="type" type="StringName" /> + <param index="0" name="type" type="StringName" /> <description> + Returns [code]true[/code] if the given [Object]-derived class exists in [ClassDB]. Note that [Variant] data types are not registered in [ClassDB]. + [codeblock] + type_exists("Sprite2D") # Returns true + type_exists("NonExistentClass") # Returns false + [/codeblock] </description> </method> </methods> @@ -250,168 +259,345 @@ </constant> <constant name="INF" value="inf"> Positive floating-point infinity. This is the result of floating-point division when the divisor is [code]0.0[/code]. For negative infinity, use [code]-INF[/code]. Dividing by [code]-0.0[/code] will result in negative infinity if the numerator is positive, so dividing by [code]0.0[/code] is not the same as dividing by [code]-0.0[/code] (despite [code]0.0 == -0.0[/code] returning [code]true[/code]). - [b]Note:[/b] Numeric infinity is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer number by [code]0[/code] will not result in [constant INF] and will result in a run-time error instead. + [b]Warning:[/b] Numeric infinity is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer number by [code]0[/code] will not result in [constant INF] and will result in a run-time error instead. </constant> <constant name="NAN" value="nan"> "Not a Number", an invalid floating-point value. [constant NAN] has special properties, including that it is not equal to itself ([code]NAN == NAN[/code] returns [code]false[/code]). It is output by some invalid operations, such as dividing floating-point [code]0.0[/code] by [code]0.0[/code]. - [b]Note:[/b] "Not a Number" is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer [code]0[/code] by [code]0[/code] will not result in [constant NAN] and will result in a run-time error instead. + [b]Warning:[/b] "Not a Number" is only a concept with floating-point numbers, and has no equivalent for integers. Dividing an integer [code]0[/code] by [code]0[/code] will not result in [constant NAN] and will result in a run-time error instead. </constant> </constants> <annotations> <annotation name="@export"> <return type="void" /> <description> + Mark the following property as exported (editable in the Inspector dock and saved to disk). To control the type of the exported property use the type hint notation. + [codeblock] + @export var int_number = 5 + @export var float_number: float = 5 + [/codeblock] </description> </annotation> <annotation name="@export_category"> <return type="void" /> - <argument index="0" name="name" type="String" /> + <param index="0" name="name" type="String" /> <description> + Define a new category for the following exported properties. This helps to organize properties in the Inspector dock. + See also [constant PROPERTY_USAGE_CATEGORY]. + [codeblock] + @export_category("My Properties") + @export var number = 3 + @export var string = "" + [/codeblock] + [b]Note:[/b] Categories in the property list are supposed to indicate different base types, so the use of this annotation is not encouraged. See [annotation @export_group] and [annotation @export_subgroup] instead. </description> </annotation> <annotation name="@export_color_no_alpha"> <return type="void" /> <description> + Export a [Color] property without transparency (its alpha fixed as [code]1.0[/code]). + See also [constant PROPERTY_HINT_COLOR_NO_ALPHA]. + [codeblock] + @export_color_no_alpha var modulate_color: Color + [/codeblock] </description> </annotation> <annotation name="@export_dir"> <return type="void" /> <description> + Export a [String] property as a path to a directory. The path will be limited to the project folder and its subfolders. See [annotation @export_global_dir] to allow picking from the entire filesystem. + See also [constant PROPERTY_HINT_DIR]. + [codeblock] + @export_dir var sprite_folder: String + [/codeblock] </description> </annotation> <annotation name="@export_enum" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="names" type="String" /> + <param index="0" name="names" type="String" /> <description> + Export a [String] or integer property as an enumerated list of options. If the property is an integer field, then the index of the value is stored, in the same order the values are provided. You can add specific identifiers for allowed values using a colon. + See also [constant PROPERTY_HINT_ENUM]. + [codeblock] + @export_enum("Rebecca", "Mary", "Leah") var character_name: String + @export_enum("Warrior", "Magician", "Thief") var character_class: int + @export_enum("Slow:30", "Average:60", "Very Fast:200") var character_speed: int + [/codeblock] </description> </annotation> <annotation name="@export_exp_easing" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="hints" type="String" default="""" /> + <param index="0" name="hints" type="String" default="""" /> <description> + Export a floating-point property with an easing editor widget. Additional hints can be provided to adjust the behavior of the widget. [code]"attenuation"[/code] flips the curve, which makes it more intuitive for editing attenuation properties. [code]"positive_only"[/code] limits values to only be greater than or equal to zero. + See also [constant PROPERTY_HINT_EXP_EASING]. + [codeblock] + @export_exp_easing var transition_speed + @export_exp_easing("attenuation") var fading_attenuation + @export_exp_easing("positive_only") var effect_power + [/codeblock] </description> </annotation> <annotation name="@export_file" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="filter" type="String" default="""" /> + <param index="0" name="filter" type="String" default="""" /> <description> + Export a [String] property as a path to a file. The path will be limited to the project folder and its subfolders. See [annotation @export_global_file] to allow picking from the entire filesystem. + If [param filter] is provided, only matching files will be available for picking. + See also [constant PROPERTY_HINT_FILE]. + [codeblock] + @export_file var sound_effect_file: String + @export_file("*.txt") var notes_file: String + [/codeblock] </description> </annotation> <annotation name="@export_flags" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="names" type="String" /> + <param index="0" name="names" type="String" /> <description> + Export an integer property as a bit flag field. This allows to store several "checked" or [code]true[/code] values with one property, and comfortably select them from the Inspector dock. + See also [constant PROPERTY_HINT_FLAGS]. + [codeblock] + @export_flags("Fire", "Water", "Earth", "Wind") var spell_elements = 0 + [/codeblock] </description> </annotation> <annotation name="@export_flags_2d_navigation"> <return type="void" /> <description> + Export an integer property as a bit flag field for 2D navigation layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/2d_navigation/layer_1]. + See also [constant PROPERTY_HINT_LAYERS_2D_NAVIGATION]. + [codeblock] + @export_flags_2d_navigation var navigation_layers: int + [/codeblock] </description> </annotation> <annotation name="@export_flags_2d_physics"> <return type="void" /> <description> + Export an integer property as a bit flag field for 2D physics layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/2d_physics/layer_1]. + See also [constant PROPERTY_HINT_LAYERS_2D_PHYSICS]. + [codeblock] + @export_flags_2d_physics var physics_layers: int + [/codeblock] </description> </annotation> <annotation name="@export_flags_2d_render"> <return type="void" /> <description> + Export an integer property as a bit flag field for 2D render layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/2d_render/layer_1]. + See also [constant PROPERTY_HINT_LAYERS_2D_RENDER]. + [codeblock] + @export_flags_2d_render var render_layers: int + [/codeblock] </description> </annotation> <annotation name="@export_flags_3d_navigation"> <return type="void" /> <description> + Export an integer property as a bit flag field for 3D navigation layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/3d_navigation/layer_1]. + See also [constant PROPERTY_HINT_LAYERS_3D_NAVIGATION]. + [codeblock] + @export_flags_3d_navigation var navigation_layers: int + [/codeblock] </description> </annotation> <annotation name="@export_flags_3d_physics"> <return type="void" /> <description> + Export an integer property as a bit flag field for 3D physics layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/3d_physics/layer_1]. + See also [constant PROPERTY_HINT_LAYERS_3D_PHYSICS]. + [codeblock] + @export_flags_3d_physics var physics_layers: int + [/codeblock] </description> </annotation> <annotation name="@export_flags_3d_render"> <return type="void" /> <description> + Export an integer property as a bit flag field for 3D render layers. The widget in the Inspector dock will use the layer names defined in [member ProjectSettings.layer_names/3d_render/layer_1]. + See also [constant PROPERTY_HINT_LAYERS_3D_RENDER]. + [codeblock] + @export_flags_3d_render var render_layers: int + [/codeblock] </description> </annotation> <annotation name="@export_global_dir"> <return type="void" /> <description> + Export a [String] property as a path to a directory. The path can be picked from the entire filesystem. See [annotation @export_dir] to limit it to the project folder and its subfolders. + See also [constant PROPERTY_HINT_GLOBAL_DIR]. + [codeblock] + @export_global_dir var sprite_folder: String + [/codeblock] </description> </annotation> <annotation name="@export_global_file" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="filter" type="String" default="""" /> + <param index="0" name="filter" type="String" default="""" /> <description> + Export a [String] property as a path to a file. The path can be picked from the entire filesystem. See [annotation @export_file] to limit it to the project folder and its subfolders. + If [param filter] is provided, only matching files will be available for picking. + See also [constant PROPERTY_HINT_GLOBAL_FILE]. + [codeblock] + @export_global_file var sound_effect_file: String + @export_global_file("*.txt") var notes_file: String + [/codeblock] </description> </annotation> <annotation name="@export_group"> <return type="void" /> - <argument index="0" name="name" type="String" /> - <argument index="1" name="prefix" type="String" default="""" /> + <param index="0" name="name" type="String" /> + <param index="1" name="prefix" type="String" default="""" /> <description> + Define a new group for the following exported properties. This helps to organize properties in the Inspector dock. Groups can be added with an optional [param prefix], which would make group to only consider properties that have this prefix. The grouping will break on the first property that doesn't have a prefix. The prefix is also removed from the property's name in the Inspector dock. + If no [param prefix] is provided, the every following property is added to the group. The group ends when then next group or category is defined. You can also force end a group by using this annotation with empty strings for parameters, [code]@export_group("", "")[/code]. + Groups cannot be nested, use [annotation @export_subgroup] to add subgroups within groups. + See also [constant PROPERTY_USAGE_GROUP]. + [codeblock] + @export_group("My Properties") + @export var number = 3 + @export var string = "" + + @export_group("Prefixed Properties", "prefix_") + @export var prefix_number = 3 + @export var prefix_string = "" + + @export_group("", "") + @export var ungrouped_number = 3 + [/codeblock] </description> </annotation> <annotation name="@export_multiline"> <return type="void" /> <description> + Export a [String] property with a large [TextEdit] widget instead of a [LineEdit]. This adds support for multiline content and makes it easier to edit large amount of text stored in the property. + See also [constant PROPERTY_HINT_MULTILINE_TEXT]. + [codeblock] + @export_multiline var character_biography + [/codeblock] </description> </annotation> <annotation name="@export_node_path" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="type" type="String" default="""" /> + <param index="0" name="type" type="String" default="""" /> <description> + Export a [NodePath] property with a filter for allowed node types. + See also [constant PROPERTY_HINT_NODE_PATH_VALID_TYPES]. + [codeblock] + @export_node_path(Button, TouchScreenButton) var some_button + [/codeblock] </description> </annotation> <annotation name="@export_placeholder"> <return type="void" /> + <param index="0" name="placeholder" type="String" /> <description> + Export a [String] property with a placeholder text displayed in the editor widget when no value is present. + See also [constant PROPERTY_HINT_PLACEHOLDER_TEXT]. + [codeblock] + @export_placeholder("Name in lowercase") var character_id: String + [/codeblock] </description> </annotation> <annotation name="@export_range" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="min" type="float" /> - <argument index="1" name="max" type="float" /> - <argument index="2" name="step" type="float" default="1.0" /> - <argument index="3" name="extra_hints" type="String" default="""" /> - <description> + <param index="0" name="min" type="float" /> + <param index="1" name="max" type="float" /> + <param index="2" name="step" type="float" default="1.0" /> + <param index="3" name="extra_hints" type="String" default="""" /> + <description> + Export a numeric property as a range value. The range must be defined by [param min] and [param max], as well as an optional [param step] and a variety of extra hints. The [param step] defaults to [code]1[/code] for integer properties. For floating-point numbers this value depends on your [code]EditorSettings.interface/inspector/default_float_step[/code] setting. + If hints [code]"or_greater"[/code] and [code]"or_less"[/code] are provided, the editor widget will not cap the value at range boundaries. The [code]"exp"[/code] hint will make the edited values on range to change exponentially. The [code]"hide_slider"[/code] hint will hide the slider element of the editor widget. + Hints also allow to indicate the units for the edited value. Using [code]"radians"[/code] you can specify that the actual value is in radians, but should be displayed in degrees in the Inspector dock. [code]"degrees"[/code] allows to add a degree sign as a unit suffix. Finally, a custom suffix can be provided using [code]"suffix:unit"[/code], where "unit" can be any string. + See also [constant PROPERTY_HINT_RANGE]. + [codeblock] + @export_range(0, 20) var number + @export_range(-10, 20) var number + @export_range(-10, 20, 0.2) var number: float + + @export_range(0, 100, 1, "or_greater") var power_percent + @export_range(0, 100, 1, "or_greater", "or_less") var health_delta + + @export_range(-3.14, 3.14, 0.001, "radians") var angle_radians + @export_range(0, 360, 1, "degrees") var angle_degrees + @export_range(-8, 8, 2, "suffix:px") var target_offset + [/codeblock] </description> </annotation> <annotation name="@export_subgroup"> <return type="void" /> - <argument index="0" name="name" type="String" /> - <argument index="1" name="prefix" type="String" default="""" /> + <param index="0" name="name" type="String" /> + <param index="1" name="prefix" type="String" default="""" /> <description> + Define a new subgroup for the following exported properties. This helps to organize properties in the Inspector dock. Subgroups work exactly like groups, except they need a parent group to exist. See [annotation @export_group]. + See also [constant PROPERTY_USAGE_SUBGROUP]. + [codeblock] + @export_group("My Properties") + @export var number = 3 + @export var string = "" + + @export_subgroup("My Prefixed Properties", "prefix_") + @export var prefix_number = 3 + @export var prefix_string = "" + [/codeblock] + [b]Note:[/b] Subgroups cannot be nested, they only provide one extra level of depth. Just like the next group ends the previous group, so do the subsequent subgroups. </description> </annotation> <annotation name="@icon"> <return type="void" /> - <argument index="0" name="icon_path" type="String" /> + <param index="0" name="icon_path" type="String" /> <description> + Add a custom icon to the current script. After loading an icon at [param icon_path], the icon is displayed in the Scene dock for every node that the script is attached to. For named classes, the icon is also displayed in various editor dialogs. + [codeblock] + @icon("res://path/to/class/icon.svg") + [/codeblock] + [b]Note:[/b] Only the script can have a custom icon. Inner classes are not supported. </description> </annotation> <annotation name="@onready"> <return type="void" /> <description> + Mark the following property as assigned on [Node]'s ready state change. Values for these properties are not assigned immediately upon the node's creation, and instead are computed and stored right before [method Node._ready]. + [codeblock] + @onready var character_name: Label = $Label + [/codeblock] </description> </annotation> <annotation name="@rpc" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="mode" type="String" default="""" /> - <argument index="1" name="sync" type="String" default="""" /> - <argument index="2" name="transfer_mode" type="String" default="""" /> - <argument index="3" name="transfer_channel" type="int" default="0" /> + <param index="0" name="mode" type="String" default="""" /> + <param index="1" name="sync" type="String" default="""" /> + <param index="2" name="transfer_mode" type="String" default="""" /> + <param index="3" name="transfer_channel" type="int" default="0" /> <description> + Mark the following method for remote procedure calls. See [url=$DOCS_URL/tutorials/networking/high_level_multiplayer.html]High-level multiplayer[/url]. + [codeblock] + @rpc() + [/codeblock] </description> </annotation> <annotation name="@tool"> <return type="void" /> <description> + Mark the current script as a tool script, allowing it to be loaded and executed by the editor. See [url=$DOCS_URL/tutorials/plugins/running_code_in_the_editor.html]Running code in the editor[/url]. + [codeblock] + @tool + extends Node + [/codeblock] </description> </annotation> <annotation name="@warning_ignore" qualifiers="vararg"> <return type="void" /> - <argument index="0" name="warning" type="String" /> + <param index="0" name="warning" type="String" /> <description> + Mark the following statement to ignore the specified [param warning]. See [url=$DOCS_URL/tutorials/scripting/gdscript/warning_system.html]GDScript warning system[/url]. + [codeblock] + func test(): + print("hello") + return + @warning_ignore("unreachable_code") + print("unreachable") + [/codeblock] </description> </annotation> </annotations> diff --git a/modules/gdscript/doc_classes/GDScript.xml b/modules/gdscript/doc_classes/GDScript.xml index 578e7a34f3..8246c96c15 100644 --- a/modules/gdscript/doc_classes/GDScript.xml +++ b/modules/gdscript/doc_classes/GDScript.xml @@ -4,7 +4,7 @@ A script implemented in the GDScript programming language. </brief_description> <description> - A script implemented in the GDScript programming language. The script extends the functionality of all objects that instance it. + A script implemented in the GDScript programming language. The script extends the functionality of all objects that instantiate it. [method new] creates a new instance of the script. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes. </description> <tutorials> diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp index b86e9b386d..996d323a7f 100644 --- a/modules/gdscript/editor/gdscript_highlighter.cpp +++ b/modules/gdscript/editor/gdscript_highlighter.cpp @@ -39,26 +39,32 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l Type next_type = NONE; Type current_type = NONE; - Type previous_type = NONE; - - String previous_text = ""; - int previous_column = 0; + Type prev_type = NONE; + String prev_text = ""; + int prev_column = 0; bool prev_is_char = false; - bool prev_is_number = false; + bool prev_is_digit = false; + bool prev_is_binary_op = false; + bool in_keyword = false; bool in_word = false; - bool in_function_name = false; - bool in_lambda = false; - bool in_variable_declaration = false; - bool in_signal_declaration = false; - bool in_function_args = false; - bool in_member_variable = false; + bool in_number = false; bool in_node_path = false; + bool in_node_ref = false; bool in_annotation = false; + bool in_string_name = false; bool is_hex_notation = false; bool is_bin_notation = false; + bool in_member_variable = false; + bool in_lambda = false; + + bool in_function_name = false; + bool in_function_args = false; + bool in_variable_declaration = false; + bool in_signal_declaration = false; bool expect_type = false; + Color keyword_color; Color color; @@ -82,16 +88,17 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l const int line_length = str.length(); Color prev_color; - if (in_region != -1 && str.length() == 0) { + if (in_region != -1 && line_length == 0) { color_region_cache[p_line] = in_region; } - for (int j = 0; j < str.length(); j++) { + for (int j = 0; j < line_length; j++) { Dictionary highlighter_info; color = font_color; bool is_char = !is_symbol(str[j]); bool is_a_symbol = is_symbol(str[j]); - bool is_number = is_digit(str[j]); + bool is_a_digit = is_digit(str[j]); + bool is_binary_op = false; /* color regions */ if (is_a_symbol || in_region != -1) { @@ -165,6 +172,12 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l if (in_node_path && (color_regions[in_region].start_key == "\"" || color_regions[in_region].start_key == "\'")) { region_color = node_path_color; } + if (in_node_ref && (color_regions[in_region].start_key == "\"" || color_regions[in_region].start_key == "\'")) { + region_color = node_ref_color; + } + if (in_string_name && (color_regions[in_region].start_key == "\"" || color_regions[in_region].start_key == "\'")) { + region_color = string_name_color; + } prev_color = region_color; highlighter_info["color"] = region_color; @@ -213,9 +226,9 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l } } - previous_type = REGION; - previous_text = ""; - previous_column = j; + prev_type = REGION; + prev_text = ""; + prev_column = j; j = from + (end_key_length - 1); if (region_end_index == -1) { color_region_cache[p_line] = in_region; @@ -223,68 +236,112 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l in_region = -1; prev_is_char = false; - prev_is_number = false; + prev_is_digit = false; + prev_is_binary_op = false; continue; } } } + // VERY hacky... but couldn't come up with anything better. + if (j > 0 && (str[j] == '&' || str[j] == '^' || str[j] == '%' || str[j] == '+' || str[j] == '-' || str[j] == '~' || str[j] == '.')) { + int to = j - 1; + // Find what the last text was (prev_text won't work if there's no whitespace, so we need to do it manually). + while (to > 0 && is_whitespace(str[to])) { + to--; + } + int from = to; + while (from > 0 && !is_symbol(str[from])) { + from--; + } + String word = str.substr(from + 1, to - from); + // Keywords need to be exceptions, except for keywords that represent a value. + if (word == "true" || word == "false" || word == "null" || word == "PI" || word == "TAU" || word == "INF" || word == "NAN" || word == "self" || word == "super" || !reserved_keywords.has(word)) { + if (!is_symbol(str[to]) || str[to] == '"' || str[to] == '\'' || str[to] == ')' || str[to] == ']' || str[to] == '}') { + is_binary_op = true; + } + } + } + + if (!is_char) { + in_keyword = false; + } + // allow ABCDEF in hex notation - if (is_hex_notation && (is_hex_digit(str[j]) || is_number)) { - is_number = true; + if (is_hex_notation && (is_hex_digit(str[j]) || is_a_digit)) { + is_a_digit = true; } else { is_hex_notation = false; } - // disallow anything not a 0 or 1 - if (is_bin_notation && (is_binary_digit(str[j]))) { - is_number = true; - } else if (is_bin_notation) { - is_bin_notation = false; - is_number = false; - } else { + // disallow anything not a 0 or 1 in binary notation + if (is_bin_notation && !is_binary_digit(str[j])) { + is_a_digit = false; is_bin_notation = false; } - // check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation - if ((str[j] == '.' || str[j] == 'x' || str[j] == 'b' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) { - is_number = true; - is_a_symbol = false; - is_char = false; + if (!in_number && !in_word && is_a_digit) { + in_number = true; + } - if (str[j] == 'x' && str[j - 1] == '0') { - is_hex_notation = true; - } else if (str[j] == 'b' && str[j - 1] == '0') { + // Special cases for numbers + if (in_number && !is_a_digit) { + if (str[j] == 'b' && str[j - 1] == '0') { is_bin_notation = true; + } else if (str[j] == 'x' && str[j - 1] == '0') { + is_hex_notation = true; + } else if (!((str[j] == '-' || str[j] == '+') && str[j - 1] == 'e' && !prev_is_digit) && + !(str[j] == '_' && (prev_is_digit || str[j - 1] == 'b' || str[j - 1] == 'x' || str[j - 1] == '.')) && + !(str[j] == 'e' && (prev_is_digit || str[j - 1] == '_')) && + !(str[j] == '.' && (prev_is_digit || (!prev_is_binary_op && (j > 0 && (str[j - 1] == '-' || str[j - 1] == '+' || str[j - 1] == '~'))))) && + !((str[j] == '-' || str[j] == '+' || str[j] == '~') && !prev_is_binary_op && str[j - 1] != 'e')) { + /* This condition continues Number highlighting in special cases. + 1st row: '+' or '-' after scientific notation; + 2nd row: '_' as a numeric separator; + 3rd row: Scientific notation 'e' and floating points; + 4th row: Floating points inside the number, or leading if after a unary mathematical operator; + 5th row: Multiple unary mathematical operators */ + in_number = false; } + } else if (!is_binary_op && (str[j] == '-' || str[j] == '+' || str[j] == '~' || (str[j] == '.' && str[j + 1] != '.' && (j == 0 || (j > 0 && str[j - 1] != '.'))))) { + in_number = true; } - if (!in_word && (is_ascii_char(str[j]) || is_underscore(str[j])) && !is_number) { + if (!in_word && (is_ascii_char(str[j]) || is_underscore(str[j])) && !in_number) { in_word = true; } - if ((in_keyword || in_word) && !is_hex_notation) { - is_number = false; - } - if (is_a_symbol && str[j] != '.' && in_word) { in_word = false; } - if (!is_char) { - in_keyword = false; - } - if (!in_keyword && is_char && !prev_is_char) { int to = j; - while (to < str.length() && !is_symbol(str[to])) { + while (to < line_length && !is_symbol(str[to])) { to++; } String word = str.substr(j, to - j); Color col = Color(); - if (keywords.has(word)) { - col = keywords[word]; + if (global_functions.has(word)) { + // "assert" and "preload" are reserved, so highlight even if not followed by a bracket. + if (word == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::ASSERT) || word == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::PRELOAD)) { + col = global_function_color; + } else { + // For other global functions, check if followed by bracket. + int k = to; + while (k < line_length && is_whitespace(str[k])) { + k++; + } + + if (str[k] == '(') { + col = global_function_color; + } + } + } else if (class_names.has(word)) { + col = class_names[word]; + } else if (reserved_keywords.has(word)) { + col = reserved_keywords[word]; } else if (member_keywords.has(word)) { col = member_keywords[word]; } @@ -292,12 +349,13 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l if (col != Color()) { for (int k = j - 1; k >= 0; k--) { if (str[k] == '.') { - col = Color(); // keyword & member indexing not allowed + col = Color(); // keyword, member & global func indexing not allowed break; } else if (str[k] > 32) { break; } } + if (col != Color()) { in_keyword = true; keyword_color = col; @@ -306,29 +364,29 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l } if (!in_function_name && in_word && !in_keyword) { - if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::SIGNAL)) { + if (prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::SIGNAL)) { in_signal_declaration = true; } else { int k = j; - while (k < str.length() && !is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') { + while (k < line_length && !is_symbol(str[k]) && !is_whitespace(str[k])) { k++; } // check for space between name and bracket - while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) { + while (k < line_length && is_whitespace(str[k])) { k++; } if (str[k] == '(') { in_function_name = true; - } else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::VAR)) { + } else if (prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::VAR)) { in_variable_declaration = true; } // Check for lambda. - if (in_function_name && previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) { + if (in_function_name && prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) { k = j - 1; - while (k > 0 && (str[k] == '\t' || str[k] == ' ')) { + while (k > 0 && is_whitespace(str[k])) { k--; } @@ -339,9 +397,9 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l } } - if (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) { + if (!in_function_name && !in_member_variable && !in_keyword && !in_number && in_word) { int k = j; - while (k > 0 && !is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') { + while (k > 0 && !is_symbol(str[k]) && !is_whitespace(str[k])) { k--; } @@ -359,18 +417,18 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l in_function_args = false; } - if (expect_type && (prev_is_char || str[j] == '=')) { + if (expect_type && (prev_is_char || str[j] == '=') && str[j] != '[') { expect_type = false; } - if (j > 0 && str[j] == '>' && str[j - 1] == '-') { + if (j > 0 && str[j - 1] == '-' && str[j] == '>') { expect_type = true; } if (in_variable_declaration || in_function_args) { int k = j; // Skip space - while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) { + while (k < line_length && is_whitespace(str[k])) { k++; } @@ -387,24 +445,48 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l in_member_variable = false; } - if (!in_node_path && in_region == -1 && (str[j] == '$' || str[j] == '%')) { + // Keep symbol color for binary '&&'. In the case of '&&&' use StringName color for the last ampersand + if (!in_string_name && in_region == -1 && str[j] == '&' && !is_binary_op) { + if (j >= 2 && str[j - 1] == '&' && str[j - 2] != '&' && prev_is_binary_op) { + is_binary_op = true; + } else if (j == 0 || (j > 0 && str[j - 1] != '&') || prev_is_binary_op) { + in_string_name = true; + } + } else if (in_region != -1 || is_a_symbol) { + in_string_name = false; + } + + // '^^' has no special meaning, so unlike StringName, when binary, use NodePath color for the last caret + if (!in_node_path && in_region == -1 && str[j] == '^' && !is_binary_op && (j == 0 || (j > 0 && str[j - 1] != '^') || prev_is_binary_op)) { in_node_path = true; - } else if (in_region != -1 || (is_a_symbol && str[j] != '/' && str[j] != '%')) { + } else if (in_region != -1 || is_a_symbol) { in_node_path = false; } + if (!in_node_ref && in_region == -1 && (str[j] == '$' || (str[j] == '%' && !is_binary_op))) { + in_node_ref = true; + } else if (in_region != -1 || (is_a_symbol && str[j] != '/' && str[j] != '%')) { + in_node_ref = false; + } + if (!in_annotation && in_region == -1 && str[j] == '@') { in_annotation = true; } else if (in_region != -1 || is_a_symbol) { in_annotation = false; } - if (in_node_path) { - next_type = NODE_PATH; - color = node_path_color; + if (in_node_ref) { + next_type = NODE_REF; + color = node_ref_color; } else if (in_annotation) { next_type = ANNOTATION; color = annotation_color; + } else if (in_string_name) { + next_type = STRING_NAME; + color = string_name_color; + } else if (in_node_path) { + next_type = NODE_PATH; + color = node_path_color; } else if (in_keyword) { next_type = KEYWORD; color = keyword_color; @@ -418,17 +500,17 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l } else if (in_function_name) { next_type = FUNCTION; - if (!in_lambda && previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) { + if (!in_lambda && prev_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) { color = function_definition_color; } else { color = function_color; } + } else if (in_number) { + next_type = NUMBER; + color = number_color; } else if (is_a_symbol) { next_type = SYMBOL; color = symbol_color; - } else if (is_number) { - next_type = NUMBER; - color = number_color; } else if (expect_type) { next_type = TYPE; color = type_color; @@ -440,27 +522,28 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting_impl(int p_l if (current_type == NONE) { current_type = next_type; } else { - previous_type = current_type; + prev_type = current_type; current_type = next_type; // no need to store regions... - if (previous_type == REGION) { - previous_text = ""; - previous_column = j; + if (prev_type == REGION) { + prev_text = ""; + prev_column = j; } else { - String text = str.substr(previous_column, j - previous_column).strip_edges(); - previous_column = j; + String text = str.substr(prev_column, j - prev_column).strip_edges(); + prev_column = j; // ignore if just whitespace if (!text.is_empty()) { - previous_text = text; + prev_text = text; } } } } prev_is_char = is_char; - prev_is_number = is_number; + prev_is_digit = is_a_digit; + prev_is_binary_op = is_binary_op; if (color != prev_color) { prev_color = color; @@ -475,15 +558,17 @@ String GDScriptSyntaxHighlighter::_get_name() const { return "GDScript"; } -Array GDScriptSyntaxHighlighter::_get_supported_languages() const { - Array languages; +PackedStringArray GDScriptSyntaxHighlighter::_get_supported_languages() const { + PackedStringArray languages; languages.push_back("GDScript"); return languages; } void GDScriptSyntaxHighlighter::_update_cache() { - keywords.clear(); + class_names.clear(); + reserved_keywords.clear(); member_keywords.clear(); + global_functions.clear(); color_regions.clear(); color_region_cache.clear(); @@ -498,7 +583,7 @@ void GDScriptSyntaxHighlighter::_update_cache() { List<StringName> types; ClassDB::get_class_list(&types); for (const StringName &E : types) { - keywords[E] = types_color; + class_names[E] = types_color; } /* User types. */ @@ -506,14 +591,14 @@ void GDScriptSyntaxHighlighter::_update_cache() { List<StringName> global_classes; ScriptServer::get_global_class_list(&global_classes); for (const StringName &E : global_classes) { - keywords[E] = usertype_color; + class_names[E] = usertype_color; } /* Autoloads. */ for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : ProjectSettings::get_singleton()->get_autoload_list()) { const ProjectSettings::AutoloadInfo &info = E.value; if (info.is_singleton) { - keywords[info.name] = usertype_color; + class_names[info.name] = usertype_color; } } @@ -524,7 +609,7 @@ void GDScriptSyntaxHighlighter::_update_cache() { List<String> core_types; gdscript->get_core_type_words(&core_types); for (const String &E : core_types) { - keywords[StringName(E)] = basetype_color; + class_names[StringName(E)] = basetype_color; } /* Reserved words. */ @@ -534,12 +619,23 @@ void GDScriptSyntaxHighlighter::_update_cache() { gdscript->get_reserved_words(&keyword_list); for (const String &E : keyword_list) { if (gdscript->is_control_flow_keyword(E)) { - keywords[StringName(E)] = control_flow_keyword_color; + reserved_keywords[StringName(E)] = control_flow_keyword_color; } else { - keywords[StringName(E)] = keyword_color; + reserved_keywords[StringName(E)] = keyword_color; } } + /* Global functions. */ + List<StringName> global_function_list; + GDScriptUtilityFunctions::get_function_list(&global_function_list); + Variant::get_utility_function_list(&global_function_list); + // "assert" and "preload" are not utility functions, but are global nonetheless, so insert them. + global_functions.insert(SNAME("assert")); + global_functions.insert(SNAME("preload")); + for (const StringName &E : global_function_list) { + global_functions.insert(E); + } + /* Comments */ const Color comment_color = EDITOR_GET("text_editor/theme/highlighting/comment_color"); List<String> comments; @@ -560,23 +656,23 @@ void GDScriptSyntaxHighlighter::_update_cache() { add_color_region(beg, end, string_color, end.is_empty()); } - const Ref<Script> script = _get_edited_resource(); - if (script.is_valid()) { + const Ref<Script> scr = _get_edited_resource(); + if (scr.is_valid()) { /* Member types. */ const Color member_variable_color = EDITOR_GET("text_editor/theme/highlighting/member_variable_color"); - StringName instance_base = script->get_instance_base_type(); + StringName instance_base = scr->get_instance_base_type(); if (instance_base != StringName()) { List<PropertyInfo> plist; ClassDB::get_property_list(instance_base, &plist); for (const PropertyInfo &E : plist) { - String name = E.name; + String prop_name = E.name; if (E.usage & PROPERTY_USAGE_CATEGORY || E.usage & PROPERTY_USAGE_GROUP || E.usage & PROPERTY_USAGE_SUBGROUP) { continue; } - if (name.contains("/")) { + if (prop_name.contains("/")) { continue; } - member_keywords[name] = member_variable_color; + member_keywords[prop_name] = member_variable_color; } List<String> clist; @@ -592,35 +688,59 @@ void GDScriptSyntaxHighlighter::_update_cache() { if (godot_2_theme || EditorSettings::get_singleton()->is_dark_theme()) { function_definition_color = Color(0.4, 0.9, 1.0); - node_path_color = Color(0.39, 0.76, 0.35); + global_function_color = Color(0.64, 0.64, 0.96); + node_path_color = Color(0.72, 0.77, 0.49); + node_ref_color = Color(0.39, 0.76, 0.35); annotation_color = Color(1.0, 0.7, 0.45); + string_name_color = Color(1.0, 0.76, 0.65); } else { - function_definition_color = Color(0.0, 0.65, 0.73); - node_path_color = Color(0.32, 0.55, 0.29); - annotation_color = Color(0.8, 0.5, 0.25); + function_definition_color = Color(0, 0.6, 0.6); + global_function_color = Color(0.36, 0.18, 0.72); + node_path_color = Color(0.18, 0.55, 0); + node_ref_color = Color(0.0, 0.5, 0); + annotation_color = Color(0.8, 0.37, 0); + string_name_color = Color(0.8, 0.56, 0.45); } EDITOR_DEF("text_editor/theme/highlighting/gdscript/function_definition_color", function_definition_color); + EDITOR_DEF("text_editor/theme/highlighting/gdscript/global_function_color", global_function_color); EDITOR_DEF("text_editor/theme/highlighting/gdscript/node_path_color", node_path_color); + EDITOR_DEF("text_editor/theme/highlighting/gdscript/node_reference_color", node_ref_color); EDITOR_DEF("text_editor/theme/highlighting/gdscript/annotation_color", annotation_color); + EDITOR_DEF("text_editor/theme/highlighting/gdscript/string_name_color", string_name_color); if (text_edit_color_theme == "Default" || godot_2_theme) { EditorSettings::get_singleton()->set_initial_value( "text_editor/theme/highlighting/gdscript/function_definition_color", function_definition_color, true); EditorSettings::get_singleton()->set_initial_value( + "text_editor/theme/highlighting/gdscript/global_function_color", + global_function_color, + true); + EditorSettings::get_singleton()->set_initial_value( "text_editor/theme/highlighting/gdscript/node_path_color", node_path_color, true); EditorSettings::get_singleton()->set_initial_value( + "text_editor/theme/highlighting/gdscript/node_reference_color", + node_ref_color, + true); + EditorSettings::get_singleton()->set_initial_value( "text_editor/theme/highlighting/gdscript/annotation_color", annotation_color, true); + EditorSettings::get_singleton()->set_initial_value( + "text_editor/theme/highlighting/gdscript/string_name_color", + string_name_color, + true); } function_definition_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/function_definition_color"); + global_function_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/global_function_color"); node_path_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/node_path_color"); + node_ref_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/node_reference_color"); annotation_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/annotation_color"); + string_name_color = EDITOR_GET("text_editor/theme/highlighting/gdscript/string_name_color"); type_color = EDITOR_GET("text_editor/theme/highlighting/base_type_color"); } diff --git a/modules/gdscript/editor/gdscript_highlighter.h b/modules/gdscript/editor/gdscript_highlighter.h index 92764e3891..7c22eb30b1 100644 --- a/modules/gdscript/editor/gdscript_highlighter.h +++ b/modules/gdscript/editor/gdscript_highlighter.h @@ -47,14 +47,18 @@ private: Vector<ColorRegion> color_regions; HashMap<int, int> color_region_cache; - HashMap<StringName, Color> keywords; + HashMap<StringName, Color> class_names; + HashMap<StringName, Color> reserved_keywords; HashMap<StringName, Color> member_keywords; + HashSet<StringName> global_functions; enum Type { NONE, REGION, NODE_PATH, + NODE_REF, ANNOTATION, + STRING_NAME, SYMBOL, NUMBER, FUNCTION, @@ -65,16 +69,19 @@ private: TYPE, }; - // colours + // Colors. Color font_color; Color symbol_color; Color function_color; + Color global_function_color; Color function_definition_color; Color built_in_type_color; Color number_color; Color member_color; Color node_path_color; + Color node_ref_color; Color annotation_color; + Color string_name_color; Color type_color; void add_color_region(const String &p_start_key, const String &p_end_key, const Color &p_color, bool p_line_only = false); @@ -84,7 +91,7 @@ public: virtual Dictionary _get_line_syntax_highlighting_impl(int p_line) override; virtual String _get_name() const override; - virtual Array _get_supported_languages() const override; + virtual PackedStringArray _get_supported_languages() const override; virtual Ref<EditorSyntaxHighlighter> _create() const override; }; diff --git a/modules/gdscript/editor/gdscript_translation_parser_plugin.cpp b/modules/gdscript/editor/gdscript_translation_parser_plugin.cpp index 9b540b16f2..518d4bcb62 100644 --- a/modules/gdscript/editor/gdscript_translation_parser_plugin.cpp +++ b/modules/gdscript/editor/gdscript_translation_parser_plugin.cpp @@ -41,7 +41,7 @@ Error GDScriptEditorTranslationParserPlugin::parse_file(const String &p_path, Ve // Extract all translatable strings using the parsed tree from GDSriptParser. // The strategy is to find all ExpressionNode and AssignmentNode from the tree and extract strings if relevant, i.e // Search strings in ExpressionNode -> CallNode -> tr(), set_text(), set_placeholder() etc. - // Search strings in AssignmentNode -> text = "__", hint_tooltip = "__" etc. + // Search strings in AssignmentNode -> text = "__", tooltip_text = "__" etc. Error err; Ref<Resource> loaded_res = ResourceLoader::load(p_path, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err); @@ -221,7 +221,7 @@ void GDScriptEditorTranslationParserPlugin::_assess_assignment(GDScriptParser::A } if (assignment_patterns.has(assignee_name) && p_assignment->assigned_value->type == GDScriptParser::Node::LITERAL) { - // If the assignment is towards one of the extract patterns (text, hint_tooltip etc.), and the value is a string literal, we collect the string. + // If the assignment is towards one of the extract patterns (text, tooltip_text etc.), and the value is a string literal, we collect the string. ids->push_back(static_cast<GDScriptParser::LiteralNode *>(p_assignment->assigned_value)->value); } else if (assignee_name == fd_filters && p_assignment->assigned_value->type == GDScriptParser::Node::CALL) { // FileDialog.filters accepts assignment in the form of PackedStringArray. For example, @@ -330,10 +330,10 @@ void GDScriptEditorTranslationParserPlugin::_extract_fd_literals(GDScriptParser: GDScriptEditorTranslationParserPlugin::GDScriptEditorTranslationParserPlugin() { assignment_patterns.insert("text"); assignment_patterns.insert("placeholder_text"); - assignment_patterns.insert("hint_tooltip"); + assignment_patterns.insert("tooltip_text"); first_arg_patterns.insert("set_text"); - first_arg_patterns.insert("set_tooltip"); + first_arg_patterns.insert("set_tooltip_text"); first_arg_patterns.insert("set_placeholder"); first_arg_patterns.insert("add_tab"); first_arg_patterns.insert("add_check_item"); diff --git a/modules/gdscript/editor/script_templates/CharacterBody2D/basic_movement.gd b/modules/gdscript/editor/script_templates/CharacterBody2D/basic_movement.gd index a379d915a9..b8fc8c75dc 100644 --- a/modules/gdscript/editor/script_templates/CharacterBody2D/basic_movement.gd +++ b/modules/gdscript/editor/script_templates/CharacterBody2D/basic_movement.gd @@ -6,7 +6,7 @@ extends _BASE_ const SPEED = 300.0 const JUMP_VELOCITY = -400.0 -# Get the gravity from the project settings to be synced with RigidDynamicBody nodes. +# Get the gravity from the project settings to be synced with RigidBody nodes. var gravity: int = ProjectSettings.get_setting("physics/2d/default_gravity") diff --git a/modules/gdscript/editor/script_templates/CharacterBody3D/basic_movement.gd b/modules/gdscript/editor/script_templates/CharacterBody3D/basic_movement.gd index 360b199e56..53bc606c9a 100644 --- a/modules/gdscript/editor/script_templates/CharacterBody3D/basic_movement.gd +++ b/modules/gdscript/editor/script_templates/CharacterBody3D/basic_movement.gd @@ -6,7 +6,7 @@ extends _BASE_ const SPEED = 5.0 const JUMP_VELOCITY = 4.5 -# Get the gravity from the project settings to be synced with RigidDynamicBody nodes. +# Get the gravity from the project settings to be synced with RigidBody nodes. var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity") diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index e7aa3214b4..b4da9c1224 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -51,7 +51,7 @@ #endif #ifdef TOOLS_ENABLED -#include "editor/editor_settings.h" +#include "editor/editor_paths.h" #endif /////////////////////////// @@ -111,9 +111,9 @@ GDScriptFunction *GDScript::_super_constructor(GDScript *p_script) { if (p_script->initializer) { return p_script->initializer; } else { - GDScript *base = p_script->_base; - if (base != nullptr) { - return _super_constructor(base); + GDScript *base_src = p_script->_base; + if (base_src != nullptr) { + return _super_constructor(base_src); } else { return nullptr; } @@ -121,9 +121,9 @@ GDScriptFunction *GDScript::_super_constructor(GDScript *p_script) { } void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error) { - GDScript *base = p_script->_base; - if (base != nullptr) { - _super_implicit_constructor(base, p_instance, r_error); + GDScript *base_src = p_script->_base; + if (base_src != nullptr) { + _super_implicit_constructor(base_src, p_instance, r_error); if (r_error.error != Callable::CallError::CALL_OK) { return; } @@ -151,7 +151,7 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco /* STEP 2, INITIALIZE AND CONSTRUCT */ { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); instances.insert(instance->owner); } @@ -160,7 +160,7 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco instance->script = Ref<GDScript>(); instance->owner->set_script_instance(nullptr); { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); instances.erase(p_owner); } ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance."); @@ -177,7 +177,7 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco instance->script = Ref<GDScript>(); instance->owner->set_script_instance(nullptr); { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); instances.erase(p_owner); } ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance."); @@ -278,6 +278,11 @@ void GDScript::_get_script_method_list(List<MethodInfo> *r_list, bool p_include_ GDScriptFunction *func = E.value; MethodInfo mi; mi.name = E.key; + + if (func->is_static()) { + mi.flags |= METHOD_FLAG_STATIC; + } + for (int i = 0; i < func->get_argument_count(); i++) { PropertyInfo arginfo = func->get_argument_type(i); #ifdef TOOLS_ENABLED @@ -285,7 +290,9 @@ void GDScript::_get_script_method_list(List<MethodInfo> *r_list, bool p_include_ #endif mi.arguments.push_back(arginfo); } - +#ifdef TOOLS_ENABLED + mi.default_arguments.append_array(func->get_default_arg_values()); +#endif mi.return_val = func->get_return_type(); r_list->push_back(mi); } @@ -320,16 +327,23 @@ void GDScript::_get_script_property_list(List<PropertyInfo> *r_list, bool p_incl for (int i = 0; i < msort.size(); i++) { props.push_front(sptr->member_info[msort[i].name]); } + +#ifdef TOOLS_ENABLED + r_list->push_back(sptr->get_class_category()); +#endif // TOOLS_ENABLED + + for (const PropertyInfo &E : props) { + r_list->push_back(E); + } + + props.clear(); + if (!p_include_base) { break; } sptr = sptr->_base; } - - for (const PropertyInfo &E : props) { - r_list->push_back(E); - } } void GDScript::get_script_property_list(List<PropertyInfo> *r_list) const { @@ -382,9 +396,9 @@ ScriptInstance *GDScript::instance_create(Object *p_this) { if (top->native.is_valid()) { if (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) { if (EngineDebugger::is_active()) { - GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), 1, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'"); + GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), 1, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'"); } - ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instantiated in object of type '" + p_this->get_class() + "'" + "."); + ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be assigned to an object of type '" + p_this->get_class() + "'" + "."); } } @@ -404,7 +418,7 @@ PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this) } bool GDScript::instance_has(const Object *p_this) const { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); return instances.has((Object *)p_this); } @@ -429,10 +443,6 @@ void GDScript::set_source_code(const String &p_code) { #ifdef TOOLS_ENABLED void GDScript::_update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames) { - if (base_cache.is_valid()) { - base_cache->_update_exports_values(values, propnames); - } - for (const KeyValue<StringName, Variant> &E : member_default_values_cache) { values[E.key] = E.value; } @@ -440,6 +450,10 @@ void GDScript::_update_exports_values(HashMap<StringName, Variant> &values, List for (const PropertyInfo &E : members_cache) { propnames.push_back(E); } + + if (base_cache.is_valid()) { + base_cache->_update_exports_values(values, propnames); + } } void GDScript::_add_doc(const DocData::ClassDoc &p_inner_class) { @@ -536,6 +550,9 @@ void GDScript::_update_doc() { List<PropertyInfo> props; _get_script_property_list(&props, false); for (int i = 0; i < props.size(); i++) { + if (props[i].usage & PROPERTY_USAGE_CATEGORY || props[i].usage & PROPERTY_USAGE_GROUP || props[i].usage & PROPERTY_USAGE_SUBGROUP) { + continue; + } ScriptMemberInfo scr_member_info; scr_member_info.propinfo = props[i]; scr_member_info.propinfo.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; @@ -603,11 +620,11 @@ void GDScript::_update_doc() { } if (!is_enum) { DocData::ConstantDoc constant_doc; - String doc_description; + String const_description; if (doc_constants.has(E.key)) { - doc_description = doc_constants[E.key]; + const_description = doc_constants[E.key]; } - DocData::constant_doc_from_variant(constant_doc, E.key, E.value, doc_description); + DocData::constant_doc_from_variant(constant_doc, E.key, E.value, const_description); doc.constants.push_back(constant_doc); } } @@ -658,35 +675,35 @@ bool GDScript::_update_exports(bool *r_err, bool p_recursive_call, PlaceHolderSc } if (c->extends_used) { - String path = ""; + String ext_path = ""; if (String(c->extends_path) != "" && String(c->extends_path) != get_path()) { - path = c->extends_path; - if (path.is_relative_path()) { - String base = get_path(); - if (base.is_empty() || base.is_relative_path()) { - ERR_PRINT(("Could not resolve relative path for parent class: " + path).utf8().get_data()); + ext_path = c->extends_path; + if (ext_path.is_relative_path()) { + String base_path = get_path(); + if (base_path.is_empty() || base_path.is_relative_path()) { + ERR_PRINT(("Could not resolve relative path for parent class: " + ext_path).utf8().get_data()); } else { - path = base.get_base_dir().plus_file(path); + ext_path = base_path.get_base_dir().path_join(ext_path); } } } else if (c->extends.size() != 0) { - const StringName &base = c->extends[0]; + const StringName &base_class = c->extends[0]; - if (ScriptServer::is_global_class(base)) { - path = ScriptServer::get_global_class_path(base); + if (ScriptServer::is_global_class(base_class)) { + ext_path = ScriptServer::get_global_class_path(base_class); } } - if (!path.is_empty()) { - if (path != get_path()) { - Ref<GDScript> bf = ResourceLoader::load(path); + if (!ext_path.is_empty()) { + if (ext_path != get_path()) { + Ref<GDScript> bf = ResourceLoader::load(ext_path); if (bf.is_valid()) { base_cache = bf; bf->inheriters_cache.insert(get_instance_id()); } } else { - ERR_PRINT(("Path extending itself in " + path).utf8().get_data()); + ERR_PRINT(("Path extending itself in " + ext_path).utf8().get_data()); } } } @@ -695,6 +712,8 @@ bool GDScript::_update_exports(bool *r_err, bool p_recursive_call, PlaceHolderSc member_default_values_cache.clear(); _signals.clear(); + members_cache.push_back(get_class_category()); + for (int i = 0; i < c->members.size(); i++) { const GDScriptParser::ClassNode::Member &member = c->members[i]; @@ -720,6 +739,9 @@ bool GDScript::_update_exports(bool *r_err, bool p_recursive_call, PlaceHolderSc } _signals[member.signal->identifier->name] = parameters_names; } break; + case GDScriptParser::ClassNode::Member::GROUP: { + members_cache.push_back(member.annotation->export_info); + } break; default: break; // Nothing. } @@ -821,7 +843,7 @@ String GDScript::_get_debug_path() const { Error GDScript::reload(bool p_keep_state) { bool has_instances; { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); has_instances = instances.size(); } @@ -840,7 +862,7 @@ Error GDScript::reload(bool p_keep_state) { // Loading a template, don't parse. #ifdef TOOLS_ENABLED - if (EditorSettings::get_singleton() && basedir.begins_with(EditorSettings::get_singleton()->get_project_script_templates_dir())) { + if (EditorPaths::get_singleton() && basedir.begins_with(EditorPaths::get_singleton()->get_project_script_templates_dir())) { return OK; } #endif @@ -867,7 +889,7 @@ Error GDScript::reload(bool p_keep_state) { } // TODO: Show all error messages. _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_errors().front()->get().line, ("Parse Error: " + parser.get_errors().front()->get().message).utf8().get_data(), false, ERR_HANDLER_SCRIPT); - ERR_FAIL_V(ERR_PARSE_ERROR); + return ERR_PARSE_ERROR; } GDScriptAnalyzer analyzer(&parser); @@ -883,7 +905,7 @@ Error GDScript::reload(bool p_keep_state) { _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), e->get().line, ("Parse Error: " + e->get().message).utf8().get_data(), false, ERR_HANDLER_SCRIPT); e = e->next(); } - ERR_FAIL_V(ERR_PARSE_ERROR); + return ERR_PARSE_ERROR; } bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool(); @@ -901,7 +923,7 @@ Error GDScript::reload(bool p_keep_state) { GDScriptLanguage::get_singleton()->debug_break_parse(_get_debug_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error()); } _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), false, ERR_HANDLER_SCRIPT); - ERR_FAIL_V(ERR_COMPILATION_FAILED); + return ERR_COMPILATION_FAILED; } else { return err; } @@ -946,8 +968,8 @@ void GDScript::get_members(HashSet<StringName> *p_members) { } } -const Vector<Multiplayer::RPCConfig> GDScript::get_rpc_methods() const { - return rpc_functions; +const Variant GDScript::get_rpc_config() const { + return rpc_config; } Variant GDScript::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { @@ -1028,6 +1050,11 @@ Error GDScript::load_byte_code(const String &p_path) { return ERR_COMPILATION_FAILED; } +void GDScript::set_path(const String &p_path, bool p_take_over) { + Script::set_path(p_path, p_take_over); + this->path = p_path; +} + Error GDScript::load_source_code(const String &p_path) { Vector<uint8_t> sourcef; Error err; @@ -1055,10 +1082,12 @@ Error GDScript::load_source_code(const String &p_path) { } source = s; + path = p_path; #ifdef TOOLS_ENABLED source_changed_cache = true; -#endif - path = p_path; + set_edited(false); + set_last_modified_time(FileAccess::get_modified_time(path)); +#endif // TOOLS_ENABLED return OK; } @@ -1163,7 +1192,7 @@ GDScript::GDScript() : script_list(this) { #ifdef DEBUG_ENABLED { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); GDScriptLanguage::get_singleton()->script_list.add(&script_list); } @@ -1204,9 +1233,9 @@ void GDScript::_save_orphaned_subclasses() { void GDScript::_init_rpc_methods_properties() { // Copy the base rpc methods so we don't mask their IDs. - rpc_functions.clear(); + rpc_config.clear(); if (base.is_valid()) { - rpc_functions = base->rpc_functions; + rpc_config = base->rpc_config.duplicate(); } GDScript *cscript = this; @@ -1214,12 +1243,9 @@ void GDScript::_init_rpc_methods_properties() { while (cscript) { // RPC Methods for (KeyValue<StringName, GDScriptFunction *> &E : cscript->member_functions) { - Multiplayer::RPCConfig config = E.value->get_rpc_config(); - if (config.rpc_mode != Multiplayer::RPC_MODE_DISABLED) { - config.name = E.value->get_name(); - if (rpc_functions.find(config) == -1) { - rpc_functions.push_back(config); - } + Variant config = E.value->get_rpc_config(); + if (config.get_type() != Variant::NIL) { + rpc_config[E.value->get_name()] = config; } } @@ -1233,14 +1259,11 @@ void GDScript::_init_rpc_methods_properties() { cscript = nullptr; } } - - // Sort so we are 100% that they are always the same. - rpc_functions.sort_custom<Multiplayer::SortRPCConfig>(); } GDScript::~GDScript() { { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) { // Order matters since clearing the stack may already cause @@ -1277,7 +1300,7 @@ GDScript::~GDScript() { #ifdef DEBUG_ENABLED { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); GDScriptLanguage::get_singleton()->script_list.remove(&script_list); } @@ -1400,9 +1423,7 @@ bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const { while (sl) { HashMap<StringName, GDScriptFunction *>::ConstIterator E = sl->member_functions.find(p_name); if (E) { - Multiplayer::RPCConfig config; - config.name = p_name; - if (sptr->rpc_functions.find(config) != -1) { + if (sptr->rpc_config.has(p_name)) { r_ret = Callable(memnew(GDScriptRPCCallable(this->owner, E->key))); } else { r_ret = Callable(this->owner, E->key); @@ -1510,12 +1531,59 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const props.push_front(sptr->member_info[msort[i].name]); } +#ifdef TOOLS_ENABLED + p_properties->push_back(sptr->get_class_category()); +#endif // TOOLS_ENABLED + + for (const PropertyInfo &prop : props) { + p_properties->push_back(prop); + } + + props.clear(); + + sptr = sptr->_base; + } +} + +bool GDScriptInstance::property_can_revert(const StringName &p_name) const { + Variant name = p_name; + const Variant *args[1] = { &name }; + + const GDScript *sptr = script.ptr(); + while (sptr) { + HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._property_can_revert); + if (E) { + Callable::CallError err; + Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err); + if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) { + return true; + } + } sptr = sptr->_base; } - for (const PropertyInfo &E : props) { - p_properties->push_back(E); + return false; +} + +bool GDScriptInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const { + Variant name = p_name; + const Variant *args[1] = { &name }; + + const GDScript *sptr = script.ptr(); + while (sptr) { + HashMap<StringName, GDScriptFunction *>::ConstIterator E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._property_get_revert); + if (E) { + Callable::CallError err; + Variant ret = E->value->call(const_cast<GDScriptInstance *>(this), args, 1, err); + if (err.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) { + r_ret = ret; + return true; + } + } + sptr = sptr->_base; } + + return false; } void GDScriptInstance::get_method_list(List<MethodInfo> *p_list) const { @@ -1621,15 +1689,13 @@ ScriptLanguage *GDScriptInstance::get_language() { return GDScriptLanguage::get_singleton(); } -const Vector<Multiplayer::RPCConfig> GDScriptInstance::get_rpc_methods() const { - return script->get_rpc_methods(); +const Variant GDScriptInstance::get_rpc_config() const { + return script->get_rpc_config(); } void GDScriptInstance::reload_members() { #ifdef DEBUG_ENABLED - members.resize(script->member_indices.size()); //resize - Vector<Variant> new_members; new_members.resize(script->member_indices.size()); @@ -1641,6 +1707,8 @@ void GDScriptInstance::reload_members() { } } + members.resize(new_members.size()); //resize + //apply members = new_members; @@ -1659,7 +1727,7 @@ GDScriptInstance::GDScriptInstance() { } GDScriptInstance::~GDScriptInstance() { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) { // Order matters since clearing the stack may already cause @@ -1762,7 +1830,7 @@ void GDScriptLanguage::finish() { void GDScriptLanguage::profiling_start() { #ifdef DEBUG_ENABLED - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScriptFunction> *elem = function_list.first(); while (elem) { @@ -1784,7 +1852,7 @@ void GDScriptLanguage::profiling_start() { void GDScriptLanguage::profiling_stop() { #ifdef DEBUG_ENABLED - MutexLock lock(this->lock); + MutexLock lock(this->mutex); profiling = false; #endif @@ -1794,7 +1862,7 @@ int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int current = 0; #ifdef DEBUG_ENABLED - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScriptFunction> *elem = function_list.first(); while (elem) { @@ -1817,7 +1885,7 @@ int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_ int current = 0; #ifdef DEBUG_ENABLED - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScriptFunction> *elem = function_list.first(); while (elem) { @@ -1863,7 +1931,7 @@ void GDScriptLanguage::reload_all_scripts() { print_verbose("GDScript: Reloading all scripts"); List<Ref<GDScript>> scripts; { - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScript> *elem = script_list.first(); while (elem) { @@ -1879,10 +1947,10 @@ void GDScriptLanguage::reload_all_scripts() { scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for (Ref<GDScript> &script : scripts) { - print_verbose("GDScript: Reloading: " + script->get_path()); - script->load_source_code(script->get_path()); - script->reload(true); + for (Ref<GDScript> &scr : scripts) { + print_verbose("GDScript: Reloading: " + scr->get_path()); + scr->load_source_code(scr->get_path()); + scr->reload(true); } #endif } @@ -1892,7 +1960,7 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so List<Ref<GDScript>> scripts; { - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScript> *elem = script_list.first(); while (elem) { @@ -1911,21 +1979,21 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for (Ref<GDScript> &script : scripts) { - bool reload = script == p_script || to_reload.has(script->get_base()); + for (Ref<GDScript> &scr : scripts) { + bool reload = scr == p_script || to_reload.has(scr->get_base()); if (!reload) { continue; } - to_reload.insert(script, HashMap<ObjectID, List<Pair<StringName, Variant>>>()); + to_reload.insert(scr, HashMap<ObjectID, List<Pair<StringName, Variant>>>()); if (!p_soft_reload) { //save state and remove script from instances - HashMap<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[script]; + HashMap<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[scr]; - while (script->instances.front()) { - Object *obj = script->instances.front()->get(); + while (scr->instances.front()) { + Object *obj = scr->instances.front()->get(); //save instance info List<Pair<StringName, Variant>> state; if (obj->get_script_instance()) { @@ -1938,8 +2006,8 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so //same thing for placeholders #ifdef TOOLS_ENABLED - while (script->placeholders.size()) { - Object *obj = (*script->placeholders.begin())->get_owner(); + while (scr->placeholders.size()) { + Object *obj = (*scr->placeholders.begin())->get_owner(); //save instance info if (obj->get_script_instance()) { @@ -1949,13 +2017,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so obj->set_script(Variant()); } else { // no instance found. Let's remove it so we don't loop forever - script->placeholders.erase(*script->placeholders.begin()); + scr->placeholders.erase(*scr->placeholders.begin()); } } #endif - for (const KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : script->pending_reload_state) { + for (const KeyValue<ObjectID, List<Pair<StringName, Variant>>> &F : scr->pending_reload_state) { map[F.key] = F.value; //pending to reload, use this one instead } } @@ -1980,9 +2048,9 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so } obj->set_script(scr); - ScriptInstance *script_instance = obj->get_script_instance(); + ScriptInstance *script_inst = obj->get_script_instance(); - if (!script_instance) { + if (!script_inst) { //failed, save reload state for next time if not saved if (!scr->pending_reload_state.has(obj->get_instance_id())) { scr->pending_reload_state[obj->get_instance_id()] = saved_state; @@ -1990,14 +2058,14 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so continue; } - if (script_instance->is_placeholder() && scr->is_placeholder_fallback_enabled()) { - PlaceHolderScriptInstance *placeholder = static_cast<PlaceHolderScriptInstance *>(script_instance); + if (script_inst->is_placeholder() && scr->is_placeholder_fallback_enabled()) { + PlaceHolderScriptInstance *placeholder = static_cast<PlaceHolderScriptInstance *>(script_inst); for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) { placeholder->property_set_fallback(G->get().first, G->get().second); } } else { for (List<Pair<StringName, Variant>>::Element *G = saved_state.front(); G; G = G->next()) { - script_instance->set(G->get().first, G->get().second); + script_inst->set(G->get().first, G->get().second); } } @@ -2015,7 +2083,7 @@ void GDScriptLanguage::frame() { #ifdef DEBUG_ENABLED if (profiling) { - MutexLock lock(this->lock); + MutexLock lock(this->mutex); SelfList<GDScriptFunction> *elem = function_list.first(); while (elem) { @@ -2143,7 +2211,7 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b if (c->icon_path.is_empty() || c->icon_path.is_absolute_path()) { *r_icon_path = c->icon_path; } else if (c->icon_path.is_relative_path()) { - *r_icon_path = p_path.get_base_dir().plus_file(c->icon_path).simplify_path(); + *r_icon_path = p_path.get_base_dir().path_join(c->icon_path).simplify_path(); } } if (r_base_type) { @@ -2171,7 +2239,7 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b } String subpath = subclass->extends_path; if (subpath.is_relative_path()) { - subpath = path.get_base_dir().plus_file(subpath).simplify_path(); + subpath = path.get_base_dir().path_join(subpath).simplify_path(); } if (OK != subparser.parse(subsource, subpath, false)) { @@ -2228,6 +2296,8 @@ GDScriptLanguage::GDScriptLanguage() { strings._set = StaticCString::create("_set"); strings._get = StaticCString::create("_get"); strings._get_property_list = StaticCString::create("_get_property_list"); + strings._property_can_revert = StaticCString::create("_property_can_revert"); + strings._property_get_revert = StaticCString::create("_property_get_revert"); strings._script_source = StaticCString::create("script/source"); _debug_parse_err_line = -1; _debug_parse_err_file = ""; @@ -2274,26 +2344,26 @@ GDScriptLanguage::~GDScriptLanguage() { // Clear dependencies between scripts, to ensure cyclic references are broken (to avoid leaks at exit). SelfList<GDScript> *s = script_list.first(); while (s) { - GDScript *script = s->self(); + GDScript *scr = s->self(); // This ensures the current script is not released before we can check what's the next one // in the list (we can't get the next upfront because we don't know if the reference breaking // will cause it -or any other after it, for that matter- to be released so the next one // is not the same as before). - script->reference(); + scr->reference(); - for (KeyValue<StringName, GDScriptFunction *> &E : script->member_functions) { + for (KeyValue<StringName, GDScriptFunction *> &E : scr->member_functions) { GDScriptFunction *func = E.value; for (int i = 0; i < func->argument_types.size(); i++) { func->argument_types.write[i].script_type_ref = Ref<Script>(); } func->return_type.script_type_ref = Ref<Script>(); } - for (KeyValue<StringName, GDScript::MemberInfo> &E : script->member_indices) { + for (KeyValue<StringName, GDScript::MemberInfo> &E : scr->member_indices) { E.value.data_type.script_type_ref = Ref<Script>(); } s = s->next(); - script->unreference(); + scr->unreference(); } singleton = nullptr; @@ -2325,20 +2395,20 @@ Ref<Resource> ResourceFormatLoaderGDScript::load(const String &p_path, const Str } Error err; - Ref<GDScript> script = GDScriptCache::get_full_script(p_path, err); + Ref<GDScript> scr = GDScriptCache::get_full_script(p_path, err, "", p_cache_mode == CACHE_MODE_IGNORE); // TODO: Reintroduce binary and encrypted scripts. - if (script.is_null()) { + if (scr.is_null()) { // Don't fail loading because of parsing error. - script.instantiate(); + scr.instantiate(); } if (r_error) { *r_error = OK; } - return script; + return scr; } void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const { @@ -2380,7 +2450,7 @@ void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<S } } -Error ResourceFormatSaverGDScript::save(const String &p_path, const Ref<Resource> &p_resource, uint32_t p_flags) { +Error ResourceFormatSaverGDScript::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) { Ref<GDScript> sqscr = p_resource; ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER); diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index e9a206f48b..72ad890fbc 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -87,7 +87,7 @@ class GDScript : public Script { HashMap<StringName, MemberInfo> member_indices; //members are just indices to the instantiated script. HashMap<StringName, Ref<GDScript>> subclasses; HashMap<StringName, Vector<StringName>> _signals; - Vector<Multiplayer::RPCConfig> rpc_functions; + Dictionary rpc_config; #ifdef TOOLS_ENABLED @@ -222,6 +222,7 @@ public: virtual Error reload(bool p_keep_state = false) override; + virtual void set_path(const String &p_path, bool p_take_over = false) override; void set_script_path(const String &p_path) { path = p_path; } //because subclasses need a path too... Error load_source_code(const String &p_path); Error load_byte_code(const String &p_path); @@ -250,7 +251,7 @@ public: virtual void get_constants(HashMap<StringName, Variant> *p_constants) override; virtual void get_members(HashSet<StringName> *p_members) override; - virtual const Vector<Multiplayer::RPCConfig> get_rpc_methods() const override; + virtual const Variant get_rpc_config() const override; #ifdef TOOLS_ENABLED virtual bool is_placeholder_fallback_enabled() const override { return placeholder_fallback_enabled; } @@ -287,6 +288,9 @@ public: virtual void get_property_list(List<PropertyInfo> *p_properties) const; virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = nullptr) const; + virtual bool property_can_revert(const StringName &p_name) const; + virtual bool property_get_revert(const StringName &p_name, Variant &r_ret) const; + virtual void get_method_list(List<MethodInfo> *p_list) const; virtual bool has_method(const StringName &p_method) const; virtual Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error); @@ -304,7 +308,7 @@ public: void reload_members(); - virtual const Vector<Multiplayer::RPCConfig> get_rpc_methods() const; + virtual const Variant get_rpc_config() const; GDScriptInstance(); ~GDScriptInstance(); @@ -339,7 +343,7 @@ class GDScriptLanguage : public ScriptLanguage { friend class GDScriptInstance; - Mutex lock; + Mutex mutex; friend class GDScript; @@ -423,6 +427,8 @@ public: StringName _set; StringName _get; StringName _get_property_list; + StringName _property_can_revert; + StringName _property_get_revert; StringName _script_source; } strings; @@ -524,7 +530,7 @@ public: class ResourceFormatSaverGDScript : public ResourceFormatSaver { public: - virtual Error save(const String &p_path, const Ref<Resource> &p_resource, uint32_t p_flags = 0); + virtual Error save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags = 0); virtual void get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const; virtual bool recognize(const Ref<Resource> &p_resource) const; }; diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index 50e319fdd6..46904f0f9d 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -260,21 +260,21 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, if (!p_class->extends_path.is_empty()) { if (p_class->extends_path.is_relative_path()) { - p_class->extends_path = class_type.script_path.get_base_dir().plus_file(p_class->extends_path).simplify_path(); + p_class->extends_path = class_type.script_path.get_base_dir().path_join(p_class->extends_path).simplify_path(); } - Ref<GDScriptParserRef> parser = get_parser_for(p_class->extends_path); - if (parser.is_null()) { + Ref<GDScriptParserRef> ext_parser = get_parser_for(p_class->extends_path); + if (ext_parser.is_null()) { push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class); return ERR_PARSE_ERROR; } - Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Error err = ext_parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err != OK) { push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class); return err; } - base = parser->get_parser()->head->get_datatype(); + base = ext_parser->get_parser()->head->get_datatype(); } else { if (p_class->extends.is_empty()) { push_error("Could not resolve an empty super class path.", p_class); @@ -289,18 +289,18 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, if (base_path == parser->script_path) { base = parser->head->get_datatype(); } else { - Ref<GDScriptParserRef> parser = get_parser_for(base_path); - if (parser.is_null()) { + 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); return ERR_PARSE_ERROR; } - Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Error err = base_parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err != OK) { push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class); return err; } - base = parser->get_parser()->head->get_datatype(); + 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); @@ -309,13 +309,13 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, return ERR_PARSE_ERROR; } - Ref<GDScriptParserRef> parser = get_parser_for(info.path); - if (parser.is_null()) { + 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); return ERR_PARSE_ERROR; } - Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Error err = info_parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err != OK) { push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class); return err; @@ -484,12 +484,23 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type if (parser->script_path == ScriptServer::get_global_class_path(first)) { result = parser->head->get_datatype(); } else { - Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(first)); - if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) { - push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type); - return GDScriptParser::DataType(); + String path = ScriptServer::get_global_class_path(first); + String ext = path.get_extension(); + if (ext == GDScriptLanguage::get_singleton()->get_extension()) { + Ref<GDScriptParserRef> ref = get_parser_for(path); + if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) { + push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type); + return GDScriptParser::DataType(); + } + result = ref->get_parser()->head->get_datatype(); + } else { + result.kind = GDScriptParser::DataType::SCRIPT; + result.native_type = ScriptServer::get_global_class_native_base(first); + result.script_type = ResourceLoader::load(path, "Script"); + result.script_path = path; + result.is_constant = true; + result.is_meta_type = false; } - result = ref->get_parser()->head->get_datatype(); } } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) { const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first); @@ -540,12 +551,13 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type result = ref->get_parser()->head->get_datatype(); result.is_meta_type = false; } else { - Ref<GDScript> script = member.constant->initializer->reduced_value; + Ref<Script> script = member.constant->initializer->reduced_value; result.kind = GDScriptParser::DataType::SCRIPT; result.builtin_type = Variant::OBJECT; result.script_type = script; result.script_path = script->get_path(); result.native_type = script->get_instance_base_type(); + result.is_meta_type = false; } break; } @@ -1029,7 +1041,7 @@ void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) { } } -void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) { +void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node, bool p_is_root) { ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node."); switch (p_node->type) { @@ -1102,7 +1114,7 @@ void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) { case GDScriptParser::Node::SUBSCRIPT: case GDScriptParser::Node::TERNARY_OPERATOR: case GDScriptParser::Node::UNARY_OPERATOR: - reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), true); + reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node), p_is_root); break; case GDScriptParser::Node::BREAK: case GDScriptParser::Node::BREAKPOINT: @@ -1399,7 +1411,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { variable_type.builtin_type = Variant::INT; // Can this ever be a float or something else? p_for->variable->set_datatype(variable_type); } else if (p_for->list) { - resolve_node(p_for->list); + resolve_node(p_for->list, false); if (p_for->list->datatype.has_container_element_type()) { variable_type = p_for->list->datatype.get_container_element_type(); variable_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED; @@ -1427,7 +1439,7 @@ void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) { } void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) { - resolve_node(p_while->condition); + resolve_node(p_while->condition, false); resolve_suite(p_while->loop); p_while->set_datatype(p_while->loop->get_datatype()); @@ -1812,7 +1824,7 @@ void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expre reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression)); break; case GDScriptParser::Node::CALL: - reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), p_is_root); + reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression), false, p_is_root); break; case GDScriptParser::Node::CAST: reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression)); @@ -2536,6 +2548,16 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a mark_lambda_use_self(); } +#ifdef DEBUG_ENABLED + if (p_is_root && return_type.kind != GDScriptParser::DataType::UNRESOLVED && return_type.builtin_type != Variant::NIL) { + parser->push_warning(p_call, GDScriptWarning::RETURN_VALUE_DISCARDED, p_call->function_name); + } + + if (is_static && !base_type.is_meta_type && !(callee_type != GDScriptParser::Node::SUBSCRIPT && parser->current_function != nullptr && parser->current_function->is_static)) { + parser->push_warning(p_call, GDScriptWarning::STATIC_CALLED_ON_INSTANCE, p_call->function_name, base_type.to_string()); + } +#endif // DEBUG_ENABLED + call_type = return_type; } else { bool found = false; @@ -2676,31 +2698,45 @@ void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) { GDScriptParser::DataType type; - Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name)); - if (ref.is_null()) { - push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source); - type.type_source = GDScriptParser::DataType::UNDETECTED; - type.kind = GDScriptParser::DataType::VARIANT; + String path = ScriptServer::get_global_class_path(p_class_name); + String ext = path.get_extension(); + if (ext == GDScriptLanguage::get_singleton()->get_extension()) { + Ref<GDScriptParserRef> ref = get_parser_for(path); + if (ref.is_null()) { + push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source); + type.type_source = GDScriptParser::DataType::UNDETECTED; + type.kind = GDScriptParser::DataType::VARIANT; + return type; + } + + Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + if (err) { + push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source); + type.type_source = GDScriptParser::DataType::UNDETECTED; + type.kind = GDScriptParser::DataType::VARIANT; + return type; + } + + type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; + type.kind = GDScriptParser::DataType::CLASS; + type.builtin_type = Variant::OBJECT; + type.native_type = ScriptServer::get_global_class_native_base(p_class_name); + type.class_type = ref->get_parser()->head; + type.script_path = ref->get_parser()->script_path; + type.is_constant = true; + type.is_meta_type = true; return type; - } - - Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); - if (err) { - push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source); - type.type_source = GDScriptParser::DataType::UNDETECTED; - type.kind = GDScriptParser::DataType::VARIANT; + } else { + type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; + type.kind = GDScriptParser::DataType::SCRIPT; + type.builtin_type = Variant::OBJECT; + type.native_type = ScriptServer::get_global_class_native_base(p_class_name); + type.script_type = ResourceLoader::load(path, "Script"); + type.script_path = path; + type.is_constant = true; + type.is_meta_type = true; return type; } - - type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; - type.kind = GDScriptParser::DataType::CLASS; - type.builtin_type = Variant::OBJECT; - type.native_type = ScriptServer::get_global_class_native_base(p_class_name); - type.class_type = ref->get_parser()->head; - type.script_path = ref->get_parser()->script_path; - type.is_constant = true; - type.is_meta_type = true; - return type; } void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) { @@ -2726,6 +2762,7 @@ void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNod result.builtin_type = Variant::INT; result.native_type = base.native_type; result.enum_type = base.enum_type; + result.enum_values = base.enum_values; p_identifier->set_datatype(result); return; } else { @@ -3066,11 +3103,11 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident result.kind = GDScriptParser::DataType::NATIVE; result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; if (autoload.path.to_lower().ends_with(GDScriptLanguage::get_singleton()->get_extension())) { - Ref<GDScriptParserRef> parser = get_parser_for(autoload.path); - if (parser.is_valid()) { - Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + Ref<GDScriptParserRef> singl_parser = get_parser_for(autoload.path); + if (singl_parser.is_valid()) { + Error err = singl_parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED); if (err == OK) { - result = type_from_metatype(parser->get_parser()->head->get_datatype()); + result = type_from_metatype(singl_parser->get_parser()->head->get_datatype()); } } } @@ -3185,11 +3222,17 @@ void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) { p_preload->resolved_path = p_preload->path->reduced_value; // TODO: Save this as script dependency. if (p_preload->resolved_path.is_relative_path()) { - p_preload->resolved_path = parser->script_path.get_base_dir().plus_file(p_preload->resolved_path); + p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path); } p_preload->resolved_path = p_preload->resolved_path.simplify_path(); - if (!FileAccess::exists(p_preload->resolved_path)) { - push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path); + if (!ResourceLoader::exists(p_preload->resolved_path)) { + Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES); + + if (file_check->file_exists(p_preload->resolved_path)) { + push_error(vformat(R"(Preload file "%s" has no resource loaders (unrecognized file extension).)", p_preload->resolved_path), p_preload->path); + } else { + push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path); + } } else { // TODO: Don't load if validating: use completion cache. p_preload->resource = ResourceLoader::load(p_preload->resolved_path); @@ -3238,12 +3281,12 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid); if (!valid) { push_error(vformat(R"(Cannot get member "%s" from "%s".)", p_subscript->attribute->name, p_subscript->base->reduced_value), p_subscript->index); + result_type.kind = GDScriptParser::DataType::VARIANT; } else { p_subscript->is_constant = true; p_subscript->reduced_value = value; result_type = type_from_variant(value, p_subscript); } - result_type.kind = GDScriptParser::DataType::VARIANT; } else { GDScriptParser::DataType base_type = p_subscript->base->get_datatype(); @@ -3329,8 +3372,11 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri case Variant::VECTOR2I: case Variant::VECTOR3: case Variant::VECTOR3I: + case Variant::VECTOR4: + case Variant::VECTOR4I: case Variant::TRANSFORM2D: case Variant::TRANSFORM3D: + case Variant::PROJECTION: error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT && index_type.builtin_type != Variant::STRING; break; @@ -3393,6 +3439,7 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri case Variant::PACKED_INT64_ARRAY: case Variant::VECTOR2I: case Variant::VECTOR3I: + case Variant::VECTOR4I: result_type.builtin_type = Variant::INT; break; // Return float. @@ -3400,6 +3447,7 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri case Variant::PACKED_FLOAT64_ARRAY: case Variant::VECTOR2: case Variant::VECTOR3: + case Variant::VECTOR4: case Variant::QUATERNION: result_type.builtin_type = Variant::FLOAT; break; @@ -3430,6 +3478,7 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri break; // Depends on the index. case Variant::TRANSFORM3D: + case Variant::PROJECTION: case Variant::PLANE: case Variant::COLOR: case Variant::DICTIONARY: @@ -3801,7 +3850,7 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bo Ref<Script> base_script = p_base_type.script_type; - while (base_script.is_valid() && base_script->is_valid()) { + while (base_script.is_valid() && base_script->has_method(function_name)) { MethodInfo info = base_script->get_method_info(function_name); if (!(info == MethodInfo())) { diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h index 3966b81b6e..217a856ce0 100644 --- a/modules/gdscript/gdscript_analyzer.h +++ b/modules/gdscript/gdscript_analyzer.h @@ -63,7 +63,7 @@ class GDScriptAnalyzer { void resolve_class_body(GDScriptParser::ClassNode *p_class); void resolve_function_signature(GDScriptParser::FunctionNode *p_function); void resolve_function_body(GDScriptParser::FunctionNode *p_function); - void resolve_node(GDScriptParser::Node *p_node); + void resolve_node(GDScriptParser::Node *p_node, bool p_is_root = true); void resolve_suite(GDScriptParser::SuiteNode *p_suite); void resolve_if(GDScriptParser::IfNode *p_if); void resolve_for(GDScriptParser::ForNode *p_for); diff --git a/modules/gdscript/gdscript_byte_codegen.cpp b/modules/gdscript/gdscript_byte_codegen.cpp index 6a1effd680..fa158591fd 100644 --- a/modules/gdscript/gdscript_byte_codegen.cpp +++ b/modules/gdscript/gdscript_byte_codegen.cpp @@ -84,11 +84,14 @@ uint32_t GDScriptByteCodeGenerator::add_temporary(const GDScriptDataType &p_type case Variant::VECTOR3: case Variant::VECTOR3I: case Variant::TRANSFORM2D: + case Variant::VECTOR4: + case Variant::VECTOR4I: case Variant::PLANE: case Variant::QUATERNION: case Variant::AABB: case Variant::BASIS: case Variant::TRANSFORM3D: + case Variant::PROJECTION: case Variant::COLOR: case Variant::STRING_NAME: case Variant::NODE_PATH: @@ -155,7 +158,7 @@ void GDScriptByteCodeGenerator::end_parameters() { function->default_arguments.reverse(); } -void GDScriptByteCodeGenerator::write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, Multiplayer::RPCConfig p_rpc_config, const GDScriptDataType &p_return_type) { +void GDScriptByteCodeGenerator::write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, Variant p_rpc_config, const GDScriptDataType &p_return_type) { function = memnew(GDScriptFunction); debug_stack = EngineDebugger::is_active(); @@ -453,6 +456,12 @@ void GDScriptByteCodeGenerator::write_type_adjust(const Address &p_target, Varia case Variant::TRANSFORM2D: append(GDScriptFunction::OPCODE_TYPE_ADJUST_TRANSFORM2D, 1); break; + case Variant::VECTOR4: + append(GDScriptFunction::OPCODE_TYPE_ADJUST_VECTOR3, 1); + break; + case Variant::VECTOR4I: + append(GDScriptFunction::OPCODE_TYPE_ADJUST_VECTOR3I, 1); + break; case Variant::PLANE: append(GDScriptFunction::OPCODE_TYPE_ADJUST_PLANE, 1); break; @@ -468,6 +477,9 @@ void GDScriptByteCodeGenerator::write_type_adjust(const Address &p_target, Varia case Variant::TRANSFORM3D: append(GDScriptFunction::OPCODE_TYPE_ADJUST_TRANSFORM3D, 1); break; + case Variant::PROJECTION: + append(GDScriptFunction::OPCODE_TYPE_ADJUST_PROJECTION, 1); + break; case Variant::COLOR: append(GDScriptFunction::OPCODE_TYPE_ADJUST_COLOR, 1); break; @@ -1596,7 +1608,7 @@ void GDScriptByteCodeGenerator::write_return(const Address &p_return_value) { // Typed array. const GDScriptDataType &element_type = function->return_type.get_container_element_type(); - Variant script = function->return_type.script_type; + Variant script = element_type.script_type; int script_idx = get_constant_pos(script) | (GDScriptFunction::ADDR_TYPE_CONSTANT << GDScriptFunction::ADDR_BITS); append(GDScriptFunction::OPCODE_RETURN_TYPED_ARRAY, 2); diff --git a/modules/gdscript/gdscript_byte_codegen.h b/modules/gdscript/gdscript_byte_codegen.h index f4b402fc96..7dd51845df 100644 --- a/modules/gdscript/gdscript_byte_codegen.h +++ b/modules/gdscript/gdscript_byte_codegen.h @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GDSCRIPT_BYTE_CODEGEN -#define GDSCRIPT_BYTE_CODEGEN +#ifndef GDSCRIPT_BYTE_CODEGEN_H +#define GDSCRIPT_BYTE_CODEGEN_H #include "gdscript_codegen.h" @@ -419,7 +419,7 @@ public: virtual void start_block() override; virtual void end_block() override; - virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, Multiplayer::RPCConfig p_rpc_config, const GDScriptDataType &p_return_type) override; + virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, Variant p_rpc_config, const GDScriptDataType &p_return_type) override; virtual GDScriptFunction *write_end() override; #ifdef DEBUG_ENABLED @@ -502,4 +502,4 @@ public: virtual ~GDScriptByteCodeGenerator(); }; -#endif // GDSCRIPT_BYTE_CODEGEN +#endif // GDSCRIPT_BYTE_CODEGEN_H diff --git a/modules/gdscript/gdscript_cache.cpp b/modules/gdscript/gdscript_cache.cpp index 48d5fbc569..271296c2f9 100644 --- a/modules/gdscript/gdscript_cache.cpp +++ b/modules/gdscript/gdscript_cache.cpp @@ -146,9 +146,7 @@ String GDScriptCache::get_source_code(const String &p_path) { Vector<uint8_t> source_file; Error err; Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); - if (err) { - ERR_FAIL_COND_V(err, ""); - } + ERR_FAIL_COND_V(err, ""); uint64_t len = f->get_length(); source_file.resize(len + 1); @@ -185,20 +183,26 @@ Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, const Stri return script; } -Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner) { +Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner, bool p_update_from_disk) { MutexLock lock(singleton->lock); if (!p_owner.is_empty()) { singleton->dependencies[p_owner].insert(p_path); } + Ref<GDScript> script; r_error = OK; if (singleton->full_gdscript_cache.has(p_path)) { - return singleton->full_gdscript_cache[p_path]; + script = Ref<GDScript>(singleton->full_gdscript_cache[p_path]); + if (!p_update_from_disk) { + return script; + } } - Ref<GDScript> script = get_shallow_script(p_path); - ERR_FAIL_COND_V(script.is_null(), Ref<GDScript>()); + if (script.is_null()) { + script = get_shallow_script(p_path); + ERR_FAIL_COND_V(script.is_null(), Ref<GDScript>()); + } r_error = script->load_source_code(p_path); diff --git a/modules/gdscript/gdscript_cache.h b/modules/gdscript/gdscript_cache.h index b971bdd984..3d111ea229 100644 --- a/modules/gdscript/gdscript_cache.h +++ b/modules/gdscript/gdscript_cache.h @@ -88,7 +88,7 @@ public: static Ref<GDScriptParserRef> get_parser(const String &p_path, GDScriptParserRef::Status status, Error &r_error, const String &p_owner = String()); static String get_source_code(const String &p_path); static Ref<GDScript> get_shallow_script(const String &p_path, const String &p_owner = String()); - static Ref<GDScript> get_full_script(const String &p_path, Error &r_error, const String &p_owner = String()); + static Ref<GDScript> get_full_script(const String &p_path, Error &r_error, const String &p_owner = String(), bool p_update_from_disk = false); static Error finish_compiling(const String &p_owner); GDScriptCache(); diff --git a/modules/gdscript/gdscript_codegen.h b/modules/gdscript/gdscript_codegen.h index 81fa265aca..5972481c3a 100644 --- a/modules/gdscript/gdscript_codegen.h +++ b/modules/gdscript/gdscript_codegen.h @@ -28,10 +28,9 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GDSCRIPT_CODEGEN -#define GDSCRIPT_CODEGEN +#ifndef GDSCRIPT_CODEGEN_H +#define GDSCRIPT_CODEGEN_H -#include "core/multiplayer/multiplayer.h" #include "core/string/string_name.h" #include "core/variant/variant.h" #include "gdscript_function.h" @@ -80,7 +79,7 @@ public: virtual void start_block() = 0; virtual void end_block() = 0; - virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, Multiplayer::RPCConfig p_rpc_config, const GDScriptDataType &p_return_type) = 0; + virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, Variant p_rpc_config, const GDScriptDataType &p_return_type) = 0; virtual GDScriptFunction *write_end() = 0; #ifdef DEBUG_ENABLED @@ -163,4 +162,4 @@ public: virtual ~GDScriptCodeGenerator() {} }; -#endif // GDSCRIPT_CODEGEN +#endif // GDSCRIPT_CODEGEN_H diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index af8e4b3746..7acd1cdb96 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -43,7 +43,7 @@ bool GDScriptCompiler::_is_class_member_property(CodeGen &codegen, const StringN return false; } - if (codegen.locals.has(p_name)) { + if (codegen.parameters.has(p_name) || codegen.locals.has(p_name)) { return false; //shadowed } @@ -522,11 +522,11 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code // Create temporary for result first since it will be deleted last. GDScriptCodeGenerator::Address result = codegen.add_temporary(cast_type); - GDScriptCodeGenerator::Address source = _parse_expression(codegen, r_error, cn->operand); + GDScriptCodeGenerator::Address src = _parse_expression(codegen, r_error, cn->operand); - gen->write_cast(result, source, cast_type); + gen->write_cast(result, src, cast_type); - if (source.mode == GDScriptCodeGenerator::Address::TEMPORARY) { + if (src.mode == GDScriptCodeGenerator::Address::TEMPORARY) { gen->pop_temporary(); } @@ -1650,7 +1650,7 @@ void GDScriptCompiler::_add_locals_in_block(CodeGen &codegen, const GDScriptPars } Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals) { - Error error = OK; + Error err = OK; GDScriptCodeGenerator *gen = codegen.generator; codegen.start_block(); @@ -1676,9 +1676,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui // Evaluate the match expression. GDScriptCodeGenerator::Address value = codegen.add_local("@match_value", _gdtype_from_datatype(match->test->get_datatype())); - GDScriptCodeGenerator::Address value_expr = _parse_expression(codegen, error, match->test); - if (error) { - return error; + GDScriptCodeGenerator::Address value_expr = _parse_expression(codegen, err, match->test); + if (err) { + return err; } // Assign to local. @@ -1723,9 +1723,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui // For each pattern in branch. GDScriptCodeGenerator::Address pattern_result = codegen.add_temporary(); for (int k = 0; k < branch->patterns.size(); k++) { - pattern_result = _parse_match_pattern(codegen, error, branch->patterns[k], value, type, pattern_result, k == 0, false); - if (error != OK) { - return error; + pattern_result = _parse_match_pattern(codegen, err, branch->patterns[k], value, type, pattern_result, k == 0, false); + if (err != OK) { + return err; } } @@ -1736,9 +1736,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->pop_temporary(); // Parse the branch block. - error = _parse_block(codegen, branch->block, false); // Don't add locals again. - if (error) { - return error; + err = _parse_block(codegen, branch->block, false); // Don't add locals again. + if (err) { + return err; } codegen.end_block(); // Get out of extra block. @@ -1753,9 +1753,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui } break; case GDScriptParser::Node::IF: { const GDScriptParser::IfNode *if_n = static_cast<const GDScriptParser::IfNode *>(s); - GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, if_n->condition); - if (error) { - return error; + GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, if_n->condition); + if (err) { + return err; } gen->write_if(condition); @@ -1764,17 +1764,17 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui codegen.generator->pop_temporary(); } - error = _parse_block(codegen, if_n->true_block); - if (error) { - return error; + err = _parse_block(codegen, if_n->true_block); + if (err) { + return err; } if (if_n->false_block) { gen->write_else(); - error = _parse_block(codegen, if_n->false_block); - if (error) { - return error; + err = _parse_block(codegen, if_n->false_block); + if (err) { + return err; } } @@ -1788,9 +1788,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->start_for(iterator.type, _gdtype_from_datatype(for_n->list->get_datatype())); - GDScriptCodeGenerator::Address list = _parse_expression(codegen, error, for_n->list); - if (error) { - return error; + GDScriptCodeGenerator::Address list = _parse_expression(codegen, err, for_n->list); + if (err) { + return err; } gen->write_for_assignment(iterator, list); @@ -1801,9 +1801,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->write_for(); - error = _parse_block(codegen, for_n->loop); - if (error) { - return error; + err = _parse_block(codegen, for_n->loop); + if (err) { + return err; } gen->write_endfor(); @@ -1815,9 +1815,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui gen->start_while_condition(); - GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, while_n->condition); - if (error) { - return error; + GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, while_n->condition); + if (err) { + return err; } gen->write_while(condition); @@ -1826,9 +1826,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui codegen.generator->pop_temporary(); } - error = _parse_block(codegen, while_n->loop); - if (error) { - return error; + err = _parse_block(codegen, while_n->loop); + if (err) { + return err; } gen->write_endwhile(); @@ -1850,9 +1850,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui GDScriptCodeGenerator::Address return_value; if (return_n->return_value != nullptr) { - return_value = _parse_expression(codegen, error, return_n->return_value); - if (error) { - return error; + return_value = _parse_expression(codegen, err, return_n->return_value); + if (err) { + return err; } } @@ -1865,17 +1865,17 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui #ifdef DEBUG_ENABLED const GDScriptParser::AssertNode *as = static_cast<const GDScriptParser::AssertNode *>(s); - GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, as->condition); - if (error) { - return error; + GDScriptCodeGenerator::Address condition = _parse_expression(codegen, err, as->condition); + if (err) { + return err; } GDScriptCodeGenerator::Address message; if (as->message) { - message = _parse_expression(codegen, error, as->message); - if (error) { - return error; + message = _parse_expression(codegen, err, as->message); + if (err) { + return err; } } gen->write_assert(condition, message); @@ -1908,9 +1908,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui codegen.generator->write_construct_array(local, Vector<GDScriptCodeGenerator::Address>()); } } - GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, error, lv->initializer); - if (error) { - return error; + GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, err, lv->initializer); + if (err) { + return err; } if (lv->use_conversion_assign) { gen->write_assign_with_conversion(local, src_address); @@ -1946,9 +1946,9 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui default: { // Expression. if (s->is_expression()) { - GDScriptCodeGenerator::Address expr = _parse_expression(codegen, error, static_cast<const GDScriptParser::ExpressionNode *>(s), true); - if (error) { - return error; + GDScriptCodeGenerator::Address expr = _parse_expression(codegen, err, static_cast<const GDScriptParser::ExpressionNode *>(s), true); + if (err) { + return err; } if (expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) { codegen.generator->pop_temporary(); @@ -1975,7 +1975,7 @@ GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_ StringName func_name; bool is_static = false; - Multiplayer::RPCConfig rpc_config; + Variant rpc_config; GDScriptDataType return_type; return_type.has_type = true; return_type.kind = GDScriptDataType::BUILTIN; @@ -2041,7 +2041,7 @@ GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_ codegen.generator->write_newline(field->initializer->start_line); // For typed arrays we need to make sure this is already initialized correctly so typed assignment work. - if (field_type.is_hard_type() && field_type.builtin_type == Variant::ARRAY && field_type.has_container_element_type()) { + if (field_type.is_hard_type() && field_type.builtin_type == Variant::ARRAY) { if (field_type.has_container_element_type()) { codegen.generator->write_construct_typed_array(dst_address, _gdtype_from_datatype(field_type.get_container_element_type(), codegen.script), Vector<GDScriptCodeGenerator::Address>()); } else { @@ -2180,7 +2180,7 @@ GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_ } Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter) { - Error error = OK; + Error err = OK; GDScriptParser::FunctionNode *function; @@ -2190,9 +2190,9 @@ Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptP function = p_variable->getter; } - _parse_function(error, p_script, p_class, function); + _parse_function(err, p_script, p_class, function); - return error; + return err; } Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) { diff --git a/modules/gdscript/gdscript_compiler.h b/modules/gdscript/gdscript_compiler.h index 4841884e2d..e4264ea55b 100644 --- a/modules/gdscript/gdscript_compiler.h +++ b/modules/gdscript/gdscript_compiler.h @@ -81,10 +81,10 @@ class GDScriptCompiler { type.kind = GDScriptDataType::NATIVE; type.native_type = obj->get_class_name(); - Ref<Script> script = obj->get_script(); - if (script.is_valid()) { - type.script_type = script.ptr(); - Ref<GDScript> gdscript = script; + Ref<Script> scr = obj->get_script(); + if (scr.is_valid()) { + type.script_type = scr.ptr(); + Ref<GDScript> gdscript = scr; if (gdscript.is_valid()) { type.kind = GDScriptDataType::GDSCRIPT; } else { diff --git a/modules/gdscript/gdscript_disassembler.cpp b/modules/gdscript/gdscript_disassembler.cpp index 726f0efe2b..b5a209c805 100644 --- a/modules/gdscript/gdscript_disassembler.cpp +++ b/modules/gdscript/gdscript_disassembler.cpp @@ -104,10 +104,10 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { text += ": "; // This makes the compiler complain if some opcode is unchecked in the switch. - Opcode code = Opcode(_code_ptr[ip] & INSTR_MASK); + Opcode opcode = Opcode(_code_ptr[ip] & INSTR_MASK); int instr_var_args = (_code_ptr[ip] & INSTR_ARGS_MASK) >> INSTR_BITS; - switch (code) { + switch (opcode) { case OPCODE_OPERATOR: { int operation = _code_ptr[ip + 4]; @@ -639,10 +639,13 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { DISASSEMBLE_PTRCALL(VECTOR3); DISASSEMBLE_PTRCALL(VECTOR3I); DISASSEMBLE_PTRCALL(TRANSFORM2D); + DISASSEMBLE_PTRCALL(VECTOR4); + DISASSEMBLE_PTRCALL(VECTOR4I); DISASSEMBLE_PTRCALL(PLANE); DISASSEMBLE_PTRCALL(AABB); DISASSEMBLE_PTRCALL(BASIS); DISASSEMBLE_PTRCALL(TRANSFORM3D); + DISASSEMBLE_PTRCALL(PROJECTION); DISASSEMBLE_PTRCALL(COLOR); DISASSEMBLE_PTRCALL(STRING_NAME); DISASSEMBLE_PTRCALL(NODE_PATH); @@ -1013,11 +1016,14 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { DISASSEMBLE_TYPE_ADJUST(VECTOR3); DISASSEMBLE_TYPE_ADJUST(VECTOR3I); DISASSEMBLE_TYPE_ADJUST(TRANSFORM2D); + DISASSEMBLE_TYPE_ADJUST(VECTOR4); + DISASSEMBLE_TYPE_ADJUST(VECTOR4I); DISASSEMBLE_TYPE_ADJUST(PLANE); DISASSEMBLE_TYPE_ADJUST(QUATERNION); DISASSEMBLE_TYPE_ADJUST(AABB); DISASSEMBLE_TYPE_ADJUST(BASIS); DISASSEMBLE_TYPE_ADJUST(TRANSFORM3D); + DISASSEMBLE_TYPE_ADJUST(PROJECTION); DISASSEMBLE_TYPE_ADJUST(COLOR); DISASSEMBLE_TYPE_ADJUST(STRING_NAME); DISASSEMBLE_TYPE_ADJUST(NODE_PATH); diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index 0a1e1a22fb..3c68993b36 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -61,8 +61,8 @@ bool GDScriptLanguage::is_using_templates() { } Ref<Script> GDScriptLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const { - Ref<GDScript> script; - script.instantiate(); + Ref<GDScript> scr; + scr.instantiate(); String processed_template = p_template; bool type_hints = false; #ifdef TOOLS_ENABLED @@ -82,8 +82,8 @@ Ref<Script> GDScriptLanguage::make_template(const String &p_template, const Stri processed_template = processed_template.replace("_BASE_", p_base_class_name) .replace("_CLASS_", p_class_name) .replace("_TS_", _get_indentation()); - script->set_source_code(processed_template); - return script; + scr->set_source_code(processed_template); + return scr; } Vector<ScriptLanguage::ScriptTemplate> GDScriptLanguage::get_built_in_templates(StringName p_object) { @@ -318,10 +318,10 @@ void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> * return; } - Ref<GDScript> script = instance->get_script(); - ERR_FAIL_COND(script.is_null()); + Ref<GDScript> scr = instance->get_script(); + ERR_FAIL_COND(scr.is_null()); - const HashMap<StringName, GDScript::MemberInfo> &mi = script->debug_get_member_indices(); + const HashMap<StringName, GDScript::MemberInfo> &mi = scr->debug_get_member_indices(); for (const KeyValue<StringName, GDScript::MemberInfo> &E : mi) { p_members->push_back(E.key); @@ -344,7 +344,7 @@ ScriptInstance *GDScriptLanguage::debug_get_stack_level_instance(int p_level) { void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { const HashMap<StringName, int> &name_idx = GDScriptLanguage::get_singleton()->get_global_map(); - const Variant *globals = GDScriptLanguage::get_singleton()->get_global_array(); + const Variant *gl_array = GDScriptLanguage::get_singleton()->get_global_array(); List<Pair<String, Variant>> cinfo; get_public_constants(&cinfo); @@ -365,7 +365,7 @@ void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant> continue; } - const Variant &var = globals[E.value]; + const Variant &var = gl_array[E.value]; if (Object *obj = var) { if (Object::cast_to<GDScriptNativeClass>(obj)) { continue; @@ -660,7 +660,13 @@ static String _make_arguments_hint(const MethodInfo &p_info, int p_arg_idx, bool } static String _make_arguments_hint(const GDScriptParser::FunctionNode *p_function, int p_arg_idx) { - String arghint = p_function->get_datatype().to_string() + " " + p_function->identifier->name.operator String() + "("; + String arghint; + + if (p_function->get_datatype().builtin_type == Variant::NIL) { + arghint = "void " + p_function->identifier->name.operator String() + "("; + } else { + arghint = p_function->get_datatype().to_string() + " " + p_function->identifier->name.operator String() + "("; + } for (int i = 0; i < p_function->parameters.size(); i++) { if (i > 0) { @@ -671,7 +677,11 @@ static String _make_arguments_hint(const GDScriptParser::FunctionNode *p_functio arghint += String::chr(0xFFFF); } const GDScriptParser::ParameterNode *par = p_function->parameters[i]; - arghint += par->identifier->name.operator String() + ": " + par->get_datatype().to_string(); + if (!par->get_datatype().is_hard_type()) { + arghint += par->identifier->name.operator String() + ": Variant"; + } else { + arghint += par->identifier->name.operator String() + ": " + par->get_datatype().to_string(); + } if (par->default_value) { String def_val = "<unknown>"; @@ -753,10 +763,10 @@ static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_a ScriptLanguage::CodeCompletionOption slider1("or_greater", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT); slider1.insert_text = slider1.display.quote(p_quote_style); r_result.insert(slider1.display, slider1); - ScriptLanguage::CodeCompletionOption slider2("or_lesser", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT); + ScriptLanguage::CodeCompletionOption slider2("or_less", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT); slider2.insert_text = slider2.display.quote(p_quote_style); r_result.insert(slider2.display, slider2); - ScriptLanguage::CodeCompletionOption slider3("no_slider", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT); + ScriptLanguage::CodeCompletionOption slider3("hide_slider", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT); slider3.insert_text = slider3.display.quote(p_quote_style); r_result.insert(slider3.display, slider3); } @@ -1195,8 +1205,8 @@ static void _find_identifiers(const GDScriptParser::CompletionContext &p_context _find_built_in_variants(r_result); static const char *_keywords[] = { - "false", "PI", "TAU", "INF", "NAN", "self", "true", "breakpoint", "tool", "super", - "break", "continue", "pass", "return", + "true", "false", "PI", "TAU", "INF", "NAN", "null", "self", "super", + "break", "breakpoint", "continue", "pass", "return", nullptr }; @@ -1208,7 +1218,7 @@ static void _find_identifiers(const GDScriptParser::CompletionContext &p_context } static const char *_keywords_with_space[] = { - "and", "in", "not", "or", "as", "class", "extends", "is", "func", "signal", "await", + "and", "not", "or", "in", "as", "class", "class_name", "extends", "is", "func", "signal", "await", "const", "enum", "static", "var", "if", "elif", "else", "for", "match", "while", nullptr }; @@ -1473,11 +1483,16 @@ static bool _guess_expression_type(GDScriptParser::CompletionContext &p_context, if (callee_type == GDScriptParser::Node::IDENTIFIER || call->is_super) { // Simple call, so base is 'self'. if (p_context.current_class) { - base.type.kind = GDScriptParser::DataType::CLASS; - base.type.type_source = GDScriptParser::DataType::INFERRED; - base.type.is_constant = true; - base.type.class_type = p_context.current_class; - base.value = p_context.base; + if (call->is_super) { + base.type = p_context.current_class->base_type; + base.value = p_context.base; + } else { + base.type.kind = GDScriptParser::DataType::CLASS; + base.type.type_source = GDScriptParser::DataType::INFERRED; + base.type.is_constant = true; + base.type.class_type = p_context.current_class; + base.value = p_context.base; + } } else { break; } @@ -2004,8 +2019,8 @@ static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context, return false; } - // Check autoloads. - if (ProjectSettings::get_singleton()->has_autoload(p_identifier)) { + // Check global variables (including autoloads). + if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(p_identifier)) { r_type = _type_from_variant(GDScriptLanguage::get_singleton()->get_named_globals_map()[p_identifier]); return true; } @@ -2016,8 +2031,13 @@ static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context, r_type.type.kind = GDScriptParser::DataType::NATIVE; r_type.type.native_type = p_identifier; r_type.type.is_constant = true; - r_type.type.is_meta_type = !Engine::get_singleton()->has_singleton(p_identifier); - r_type.value = Variant(); + if (Engine::get_singleton()->has_singleton(p_identifier)) { + r_type.type.is_meta_type = false; + r_type.value = Engine::get_singleton()->get_singleton_object(p_identifier); + } else { + r_type.type.is_meta_type = true; + r_type.value = Variant(); + } } return false; @@ -2512,39 +2532,7 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c GDScriptCompletionIdentifier connect_base; - if (Variant::has_utility_function(call->function_name)) { - MethodInfo info = Variant::get_utility_function_info(call->function_name); - r_arghint = _make_arguments_hint(info, p_argidx); - return; - } else if (GDScriptUtilityFunctions::function_exists(call->function_name)) { - MethodInfo info = GDScriptUtilityFunctions::get_function_info(call->function_name); - r_arghint = _make_arguments_hint(info, p_argidx); - return; - } else if (GDScriptParser::get_builtin_type(call->function_name) < Variant::VARIANT_MAX) { - // Complete constructor. - List<MethodInfo> constructors; - Variant::get_constructor_list(GDScriptParser::get_builtin_type(call->function_name), &constructors); - - int i = 0; - for (const MethodInfo &E : constructors) { - if (p_argidx >= E.arguments.size()) { - continue; - } - if (i > 0) { - r_arghint += "\n"; - } - r_arghint += _make_arguments_hint(E, p_argidx); - i++; - } - return; - } else if (call->is_super || callee_type == GDScriptParser::Node::IDENTIFIER) { - base = p_context.base; - - if (p_context.current_class) { - base_type = p_context.current_class->get_datatype(); - _static = !p_context.current_function || p_context.current_function->is_static; - } - } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) { + if (callee_type == GDScriptParser::Node::SUBSCRIPT) { const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(call->callee); if (subscript->base != nullptr && subscript->base->type == GDScriptParser::Node::IDENTIFIER) { @@ -2584,6 +2572,38 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c _static = base_type.is_meta_type; } + } else if (Variant::has_utility_function(call->function_name)) { + MethodInfo info = Variant::get_utility_function_info(call->function_name); + r_arghint = _make_arguments_hint(info, p_argidx); + return; + } else if (GDScriptUtilityFunctions::function_exists(call->function_name)) { + MethodInfo info = GDScriptUtilityFunctions::get_function_info(call->function_name); + r_arghint = _make_arguments_hint(info, p_argidx); + return; + } else if (GDScriptParser::get_builtin_type(call->function_name) < Variant::VARIANT_MAX) { + // Complete constructor. + List<MethodInfo> constructors; + Variant::get_constructor_list(GDScriptParser::get_builtin_type(call->function_name), &constructors); + + int i = 0; + for (const MethodInfo &E : constructors) { + if (p_argidx >= E.arguments.size()) { + continue; + } + if (i > 0) { + r_arghint += "\n"; + } + r_arghint += _make_arguments_hint(E, p_argidx); + i++; + } + return; + } else if (call->is_super || callee_type == GDScriptParser::Node::IDENTIFIER) { + base = p_context.base; + + if (p_context.current_class) { + base_type = p_context.current_class->get_datatype(); + _static = !p_context.current_function || p_context.current_function->is_static; + } } else { return; } @@ -3282,17 +3302,17 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co if (ProjectSettings::get_singleton()->has_autoload(p_symbol)) { const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(p_symbol); if (autoload.is_singleton) { - String script = autoload.path; - if (!script.ends_with(".gd")) { + String scr_path = autoload.path; + if (!scr_path.ends_with(".gd")) { // Not a script, try find the script anyway, // may have some success. - script = script.get_basename() + ".gd"; + scr_path = scr_path.get_basename() + ".gd"; } - if (FileAccess::exists(script)) { + if (FileAccess::exists(scr_path)) { r_result.type = ScriptLanguage::LOOKUP_RESULT_SCRIPT_LOCATION; r_result.location = 0; - r_result.script = ResourceLoader::load(script); + r_result.script = ResourceLoader::load(scr_path); return OK; } } diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp index cd3b7d69c5..98b3e40f1b 100644 --- a/modules/gdscript/gdscript_function.cpp +++ b/modules/gdscript/gdscript_function.cpp @@ -142,7 +142,7 @@ GDScriptFunction::GDScriptFunction() { name = "<anonymous>"; #ifdef DEBUG_ENABLED { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); GDScriptLanguage::get_singleton()->function_list.add(&function_list); } #endif @@ -155,7 +155,7 @@ GDScriptFunction::~GDScriptFunction() { #ifdef DEBUG_ENABLED - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); GDScriptLanguage::get_singleton()->function_list.remove(&function_list); #endif @@ -201,7 +201,7 @@ bool GDScriptFunctionState::is_valid(bool p_extended_check) const { } if (p_extended_check) { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); // Script gone? if (!scripts_list.in_list()) { @@ -219,7 +219,7 @@ bool GDScriptFunctionState::is_valid(bool p_extended_check) const { Variant GDScriptFunctionState::resume(const Variant &p_arg) { ERR_FAIL_COND_V(!function, Variant()); { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); if (!scripts_list.in_list()) { #ifdef DEBUG_ENABLED @@ -304,7 +304,7 @@ GDScriptFunctionState::GDScriptFunctionState() : GDScriptFunctionState::~GDScriptFunctionState() { { - MutexLock lock(GDScriptLanguage::singleton->lock); + MutexLock lock(GDScriptLanguage::singleton->mutex); scripts_list.remove_from_list(); instances_list.remove_from_list(); } diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h index 3f1265679b..e44038d6da 100644 --- a/modules/gdscript/gdscript_function.h +++ b/modules/gdscript/gdscript_function.h @@ -273,11 +273,14 @@ public: OPCODE_CALL_PTRCALL_VECTOR3, OPCODE_CALL_PTRCALL_VECTOR3I, OPCODE_CALL_PTRCALL_TRANSFORM2D, + OPCODE_CALL_PTRCALL_VECTOR4, + OPCODE_CALL_PTRCALL_VECTOR4I, OPCODE_CALL_PTRCALL_PLANE, OPCODE_CALL_PTRCALL_QUATERNION, OPCODE_CALL_PTRCALL_AABB, OPCODE_CALL_PTRCALL_BASIS, OPCODE_CALL_PTRCALL_TRANSFORM3D, + OPCODE_CALL_PTRCALL_PROJECTION, OPCODE_CALL_PTRCALL_COLOR, OPCODE_CALL_PTRCALL_STRING_NAME, OPCODE_CALL_PTRCALL_NODE_PATH, @@ -363,11 +366,14 @@ public: OPCODE_TYPE_ADJUST_VECTOR3, OPCODE_TYPE_ADJUST_VECTOR3I, OPCODE_TYPE_ADJUST_TRANSFORM2D, + OPCODE_TYPE_ADJUST_VECTOR4, + OPCODE_TYPE_ADJUST_VECTOR4I, OPCODE_TYPE_ADJUST_PLANE, OPCODE_TYPE_ADJUST_QUATERNION, OPCODE_TYPE_ADJUST_AABB, OPCODE_TYPE_ADJUST_BASIS, OPCODE_TYPE_ADJUST_TRANSFORM3D, + OPCODE_TYPE_ADJUST_PROJECTION, OPCODE_TYPE_ADJUST_COLOR, OPCODE_TYPE_ADJUST_STRING_NAME, OPCODE_TYPE_ADJUST_NODE_PATH, @@ -471,7 +477,7 @@ private: int _initial_line = 0; bool _static = false; - Multiplayer::RPCConfig rpc_config; + Variant rpc_config; GDScript *_script = nullptr; @@ -593,7 +599,7 @@ public: void disassemble(const Vector<String> &p_code_lines) const; #endif - _FORCE_INLINE_ Multiplayer::RPCConfig get_rpc_config() const { return rpc_config; } + _FORCE_INLINE_ const Variant get_rpc_config() const { return rpc_config; } GDScriptFunction(); ~GDScriptFunction(); }; diff --git a/modules/gdscript/gdscript_lambda_callable.h b/modules/gdscript/gdscript_lambda_callable.h index 248176e32c..1954089983 100644 --- a/modules/gdscript/gdscript_lambda_callable.h +++ b/modules/gdscript/gdscript_lambda_callable.h @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GDSCRIPT_LAMBDA_CALLABLE -#define GDSCRIPT_LAMBDA_CALLABLE +#ifndef GDSCRIPT_LAMBDA_CALLABLE_H +#define GDSCRIPT_LAMBDA_CALLABLE_H #include "core/object/ref_counted.h" #include "core/templates/vector.h" @@ -87,4 +87,4 @@ public: virtual ~GDScriptLambdaSelfCallable() = default; }; -#endif // GDSCRIPT_LAMBDA_CALLABLE +#endif // GDSCRIPT_LAMBDA_CALLABLE_H diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 6c5d416cf1..bdf6fb35b6 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -35,6 +35,7 @@ #include "core/io/resource_loader.h" #include "core/math/math_defs.h" #include "gdscript.h" +#include "scene/main/multiplayer_api.h" #ifdef DEBUG_ENABLED #include "core/os/os.h" @@ -60,11 +61,14 @@ Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) { builtin_types["Transform2D"] = Variant::TRANSFORM2D; builtin_types["Vector3"] = Variant::VECTOR3; builtin_types["Vector3i"] = Variant::VECTOR3I; + builtin_types["Vector4"] = Variant::VECTOR4; + builtin_types["Vector4i"] = Variant::VECTOR4I; builtin_types["AABB"] = Variant::AABB; builtin_types["Plane"] = Variant::PLANE; builtin_types["Quaternion"] = Variant::QUATERNION; builtin_types["Basis"] = Variant::BASIS; builtin_types["Transform3D"] = Variant::TRANSFORM3D; + builtin_types["Projection"] = Variant::PROJECTION; builtin_types["Color"] = Variant::COLOR; builtin_types["RID"] = Variant::RID; builtin_types["Object"] = Variant::OBJECT; @@ -123,7 +127,7 @@ GDScriptParser::GDScriptParser() { register_annotation(MethodInfo("@export_global_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_FILE, Variant::STRING>, varray(""), true); register_annotation(MethodInfo("@export_global_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_DIR, Variant::STRING>); register_annotation(MethodInfo("@export_multiline"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>); - register_annotation(MethodInfo("@export_placeholder"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>); + register_annotation(MethodInfo("@export_placeholder", PropertyInfo(Variant::STRING, "placeholder")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>); register_annotation(MethodInfo("@export_range", PropertyInfo(Variant::FLOAT, "min"), PropertyInfo(Variant::FLOAT, "max"), PropertyInfo(Variant::FLOAT, "step"), PropertyInfo(Variant::STRING, "extra_hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_RANGE, Variant::FLOAT>, varray(1.0, ""), true); register_annotation(MethodInfo("@export_exp_easing", PropertyInfo(Variant::STRING, "hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, varray(""), true); register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>); @@ -142,7 +146,7 @@ GDScriptParser::GDScriptParser() { // Warning annotations. register_annotation(MethodInfo("@warning_ignore", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::CLASS | AnnotationInfo::VARIABLE | AnnotationInfo::SIGNAL | AnnotationInfo::CONSTANT | AnnotationInfo::FUNCTION | AnnotationInfo::STATEMENT, &GDScriptParser::warning_annotations, varray(), true); // Networking. - register_annotation(MethodInfo("@rpc", PropertyInfo(Variant::STRING, "mode"), PropertyInfo(Variant::STRING, "sync"), PropertyInfo(Variant::STRING, "transfer_mode"), PropertyInfo(Variant::INT, "transfer_channel")), AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<Multiplayer::RPC_MODE_AUTHORITY>, varray("", "", "", 0), true); + register_annotation(MethodInfo("@rpc", PropertyInfo(Variant::STRING, "mode"), PropertyInfo(Variant::STRING, "sync"), PropertyInfo(Variant::STRING, "transfer_mode"), PropertyInfo(Variant::INT, "transfer_channel")), AnnotationInfo::FUNCTION, &GDScriptParser::rpc_annotation, varray("", "", "", 0), true); } GDScriptParser::~GDScriptParser() { @@ -682,17 +686,6 @@ void GDScriptParser::parse_class_name() { current_class->identifier = parse_identifier(); } - // TODO: Move this to annotation - if (match(GDScriptTokenizer::Token::COMMA)) { - // Icon path. - if (consume(GDScriptTokenizer::Token::LITERAL, R"(Expected class icon path string after ",".)")) { - if (previous.literal.get_type() != Variant::STRING) { - push_error(vformat(R"(Only strings can be used for the class icon path, found "%s" instead.)", Variant::get_type_name(previous.literal.get_type()))); - } - current_class->icon_path = previous.literal; - } - } - if (match(GDScriptTokenizer::Token::EXTENDS)) { // Allow extends on the same line. parse_extends(); @@ -2939,11 +2932,16 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_pre // Allow for trailing comma. break; } + bool use_identifier_completion = current.cursor_place == GDScriptTokenizer::CURSOR_END || current.cursor_place == GDScriptTokenizer::CURSOR_MIDDLE; ExpressionNode *argument = parse_expression(false); if (argument == nullptr) { push_error(R"(Expected expression as the function argument.)"); } else { call->arguments.push_back(argument); + + if (argument->type == Node::IDENTIFIER && use_identifier_completion) { + completion_context.type = COMPLETION_IDENTIFIER; + } } ct = COMPLETION_CALL_ARGUMENTS; } while (match(GDScriptTokenizer::Token::COMMA)); @@ -3422,7 +3420,16 @@ void GDScriptParser::get_class_doc_comment(int p_line, String &p_brief, String & p_tutorials.append(Pair<String, String>(title, link)); break; case DONE: - return; + break; + } + } + if (current_class->members.size() > 0) { + const ClassNode::Member &m = current_class->members[0]; + int first_member_line = m.get_line(); + if (first_member_line == line) { + p_brief = ""; + p_desc = ""; + p_tutorials.clear(); } } } @@ -3756,6 +3763,33 @@ bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node return false; } break; + case GDScriptParser::DataType::CLASS: + // Can assume type is a global GDScript class. + if (!ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) { + push_error(R"(Exported script type must extend Resource.)"); + return false; + } + variable->export_info.type = Variant::OBJECT; + variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE; + variable->export_info.hint_string = export_type.class_type->identifier->name; + break; + case GDScriptParser::DataType::SCRIPT: { + StringName class_name; + if (export_type.script_type != nullptr && export_type.script_type.is_valid()) { + class_name = export_type.script_type->get_language()->get_global_class_name(export_type.script_type->get_path()); + } + if (class_name == StringName()) { + Ref<Script> script = ResourceLoader::load(export_type.script_path, SNAME("Script")); + if (script.is_valid()) { + class_name = script->get_language()->get_global_class_name(export_type.script_path); + } + } + if (class_name != StringName() && ClassDB::is_parent_class(ScriptServer::get_global_class_native_base(class_name), SNAME("Resource"))) { + variable->export_info.type = Variant::OBJECT; + variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE; + variable->export_info.hint_string = class_name; + } + } break; case GDScriptParser::DataType::ENUM: { variable->export_info.type = Variant::INT; variable->export_info.hint = PROPERTY_HINT_ENUM; @@ -3855,16 +3889,21 @@ bool GDScriptParser::warning_annotations(const AnnotationNode *p_annotation, Nod #endif // DEBUG_ENABLED } -template <Multiplayer::RPCMode t_mode> -bool GDScriptParser::network_annotations(const AnnotationNode *p_annotation, Node *p_node) { - ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE && p_node->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to variables and functions.)", p_annotation->name)); +bool GDScriptParser::rpc_annotation(const AnnotationNode *p_annotation, Node *p_node) { + ERR_FAIL_COND_V_MSG(p_node->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name)); + + FunctionNode *function = static_cast<FunctionNode *>(p_node); + if (function->rpc_config.get_type() != Variant::NIL) { + push_error(R"(RPC annotations can only be used once per function.)", p_annotation); + return false; + } - Multiplayer::RPCConfig rpc_config; - rpc_config.rpc_mode = t_mode; + Dictionary rpc_config; + rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY; if (p_annotation->resolved_arguments.size()) { int last = p_annotation->resolved_arguments.size() - 1; if (p_annotation->resolved_arguments[last].get_type() == Variant::INT) { - rpc_config.channel = p_annotation->resolved_arguments[last].operator int(); + rpc_config["channel"] = p_annotation->resolved_arguments[last].operator int(); last -= 1; } if (last > 3) { @@ -3874,37 +3913,25 @@ bool GDScriptParser::network_annotations(const AnnotationNode *p_annotation, Nod for (int i = last; i >= 0; i--) { String mode = p_annotation->resolved_arguments[i].operator String(); if (mode == "any_peer") { - rpc_config.rpc_mode = Multiplayer::RPC_MODE_ANY_PEER; + rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_ANY_PEER; } else if (mode == "authority") { - rpc_config.rpc_mode = Multiplayer::RPC_MODE_AUTHORITY; + rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY; } else if (mode == "call_local") { - rpc_config.call_local = true; + rpc_config["call_local"] = true; } else if (mode == "call_remote") { - rpc_config.call_local = false; + rpc_config["call_local"] = false; } else if (mode == "reliable") { - rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_RELIABLE; + rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE; } else if (mode == "unreliable") { - rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_UNRELIABLE; + rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE; } else if (mode == "unreliable_ordered") { - rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_UNRELIABLE_ORDERED; + rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED; } else { push_error(R"(Invalid RPC argument. Must be one of: 'call_local'/'call_remote' (local calls), 'any_peer'/'authority' (permission), 'reliable'/'unreliable'/'unreliable_ordered' (transfer mode).)", p_annotation); } } } - switch (p_node->type) { - case Node::FUNCTION: { - FunctionNode *function = static_cast<FunctionNode *>(p_node); - if (function->rpc_config.rpc_mode != Multiplayer::RPC_MODE_DISABLED) { - push_error(R"(RPC annotations can only be used once per function.)", p_annotation); - return false; - } - function->rpc_config = rpc_config; - break; - } - default: - return false; // Unreachable. - } + function->rpc_config = rpc_config; return true; } @@ -3926,28 +3953,22 @@ GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const } String GDScriptParser::SuiteNode::Local::get_name() const { - String name; switch (type) { case SuiteNode::Local::PARAMETER: - name = "parameter"; - break; + return "parameter"; case SuiteNode::Local::CONSTANT: - name = "constant"; - break; + return "constant"; case SuiteNode::Local::VARIABLE: - name = "variable"; - break; + return "variable"; case SuiteNode::Local::FOR_VARIABLE: - name = "for loop iterator"; - break; + return "for loop iterator"; case SuiteNode::Local::PATTERN_BIND: - name = "pattern_bind"; - break; + return "pattern_bind"; case SuiteNode::Local::UNDEFINED: - name = "<undefined>"; - break; + return "<undefined>"; + default: + return String(); } - return name; } String GDScriptParser::DataType::to_string() const { @@ -3979,7 +4000,7 @@ String GDScriptParser::DataType::to_string() const { if (is_meta_type) { return script_type->get_class_name().operator String(); } - String name = script_type->get_name(); + String name = script_type != nullptr ? script_type->get_name() : ""; if (!name.is_empty()) { return name; } diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index 9c97f98fbc..1850a44678 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -32,7 +32,6 @@ #define GDSCRIPT_PARSER_H #include "core/io/resource.h" -#include "core/multiplayer/multiplayer.h" #include "core/object/ref_counted.h" #include "core/object/script_language.h" #include "core/string/string_name.h" @@ -579,19 +578,19 @@ public: return m_enum->get_datatype(); case ENUM_VALUE: { // Always integer. - DataType type; - type.type_source = DataType::ANNOTATED_EXPLICIT; - type.kind = DataType::BUILTIN; - type.builtin_type = Variant::INT; - return type; + DataType out_type; + out_type.type_source = DataType::ANNOTATED_EXPLICIT; + out_type.kind = DataType::BUILTIN; + out_type.builtin_type = Variant::INT; + return out_type; } case SIGNAL: { - DataType type; - type.type_source = DataType::ANNOTATED_EXPLICIT; - type.kind = DataType::BUILTIN; - type.builtin_type = Variant::SIGNAL; + DataType out_type; + out_type.type_source = DataType::ANNOTATED_EXPLICIT; + out_type.kind = DataType::BUILTIN; + out_type.builtin_type = Variant::SIGNAL; // TODO: Add parameter info. - return type; + return out_type; } case GROUP: { return DataType(); @@ -750,7 +749,7 @@ public: SuiteNode *body = nullptr; bool is_static = false; bool is_coroutine = false; - Multiplayer::RPCConfig rpc_config; + Variant rpc_config; MethodInfo info; LambdaNode *source_lambda = nullptr; #ifdef TOOLS_ENABLED @@ -1371,8 +1370,7 @@ private: template <PropertyUsageFlags t_usage> bool export_group_annotations(const AnnotationNode *p_annotation, Node *p_target); bool warning_annotations(const AnnotationNode *p_annotation, Node *p_target); - template <Multiplayer::RPCMode t_mode> - bool network_annotations(const AnnotationNode *p_annotation, Node *p_target); + bool rpc_annotation(const AnnotationNode *p_annotation, Node *p_target); // Statements. Node *parse_statement(); VariableNode *parse_variable(); diff --git a/modules/gdscript/gdscript_rpc_callable.cpp b/modules/gdscript/gdscript_rpc_callable.cpp index 63ebd8acf5..4e12419357 100644 --- a/modules/gdscript/gdscript_rpc_callable.cpp +++ b/modules/gdscript/gdscript_rpc_callable.cpp @@ -76,11 +76,11 @@ GDScriptRPCCallable::GDScriptRPCCallable(Object *p_object, const StringName &p_m ERR_FAIL_COND_MSG(!node, "RPC can only be defined on class that extends Node."); } -void GDScriptRPCCallable::rpc(int p_peer_id, const Variant **p_arguments, int p_argcount, Callable::CallError &r_call_error) const { +Error GDScriptRPCCallable::rpc(int p_peer_id, const Variant **p_arguments, int p_argcount, Callable::CallError &r_call_error) const { if (unlikely(!node)) { r_call_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL; - return; + return ERR_UNCONFIGURED; } r_call_error.error = Callable::CallError::CALL_OK; - node->rpcp(p_peer_id, method, p_arguments, p_argcount); + return node->rpcp(p_peer_id, method, p_arguments, p_argcount); } diff --git a/modules/gdscript/gdscript_rpc_callable.h b/modules/gdscript/gdscript_rpc_callable.h index 2c8734a74b..83b9c7e2df 100644 --- a/modules/gdscript/gdscript_rpc_callable.h +++ b/modules/gdscript/gdscript_rpc_callable.h @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GDSCRIPT_RPC_CALLABLE -#define GDSCRIPT_RPC_CALLABLE +#ifndef GDSCRIPT_RPC_CALLABLE_H +#define GDSCRIPT_RPC_CALLABLE_H #include "core/variant/callable.h" #include "core/variant/variant.h" @@ -52,10 +52,10 @@ public: CompareLessFunc get_compare_less_func() const override; ObjectID get_object() const override; void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override; - void rpc(int p_peer_id, const Variant **p_arguments, int p_argcount, Callable::CallError &r_call_error) const override; + Error rpc(int p_peer_id, const Variant **p_arguments, int p_argcount, Callable::CallError &r_call_error) const override; GDScriptRPCCallable(Object *p_object, const StringName &p_method); virtual ~GDScriptRPCCallable() = default; }; -#endif // GDSCRIPT_RPC_CALLABLE +#endif // GDSCRIPT_RPC_CALLABLE_H diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp index 6c17afe939..9bbfd7aece 100644 --- a/modules/gdscript/gdscript_tokenizer.cpp +++ b/modules/gdscript/gdscript_tokenizer.cpp @@ -516,15 +516,15 @@ GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() { _advance(); } - int length = _current - _start; + int len = _current - _start; - if (length == 1 && _peek(-1) == '_') { + if (len == 1 && _peek(-1) == '_') { // Lone underscore. return make_token(Token::UNDERSCORE); } - String name(_start, length); - if (length < MIN_KEYWORD_LENGTH || length > MAX_KEYWORD_LENGTH) { + String name(_start, len); + if (len < MIN_KEYWORD_LENGTH || len > MAX_KEYWORD_LENGTH) { // Cannot be a keyword, as the length doesn't match any. return make_identifier(name); } @@ -538,7 +538,7 @@ GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() { const int keyword_length = sizeof(keyword) - 1; \ static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \ static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \ - if (keyword_length == length && name == keyword) { \ + if (keyword_length == len && name == keyword) { \ return make_token(token_type); \ } \ } @@ -551,13 +551,13 @@ GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() { } // Check if it's a special literal - if (length == 4) { + if (len == 4) { if (name == "true") { return make_literal(true); } else if (name == "null") { return make_literal(Variant()); } - } else if (length == 5) { + } else if (len == 5) { if (name == "false") { return make_literal(false); } @@ -725,8 +725,8 @@ GDScriptTokenizer::Token GDScriptTokenizer::number() { } // Create a string with the whole number. - int length = _current - _start; - String number = String(_start, length).replace("_", ""); + int len = _current - _start; + String number = String(_start, len).replace("_", ""); // Convert to the appropriate literal type. if (base == 16) { diff --git a/modules/gdscript/gdscript_tokenizer.h b/modules/gdscript/gdscript_tokenizer.h index 7fb715f2c8..68b2c6eb1c 100644 --- a/modules/gdscript/gdscript_tokenizer.h +++ b/modules/gdscript/gdscript_tokenizer.h @@ -273,4 +273,4 @@ public: GDScriptTokenizer(); }; -#endif +#endif // GDSCRIPT_TOKENIZER_H diff --git a/modules/gdscript/gdscript_utility_functions.cpp b/modules/gdscript/gdscript_utility_functions.cpp index a914374985..bcbe8b8d2b 100644 --- a/modules/gdscript/gdscript_utility_functions.cpp +++ b/modules/gdscript/gdscript_utility_functions.cpp @@ -36,6 +36,7 @@ #include "core/object/object.h" #include "core/templates/oa_hash_map.h" #include "core/templates/vector.h" +#include "core/variant/typed_array.h" #include "gdscript.h" #ifdef DEBUG_ENABLED @@ -115,6 +116,7 @@ struct GDScriptUtilityFunctionsDefinitions { if (p_arg_count < 1) { r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.argument = 1; + r_error.expected = 1; *r_ret = Variant(); return; } @@ -260,7 +262,7 @@ struct GDScriptUtilityFunctionsDefinitions { } } - static inline void inst2dict(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { + static inline void inst_to_dict(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { VALIDATE_ARG_COUNT(1); if (p_args[0]->get_type() == Variant::NIL) { @@ -327,7 +329,7 @@ struct GDScriptUtilityFunctionsDefinitions { } } - static inline void dict2inst(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { + static inline void dict_to_inst(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { VALIDATE_ARG_COUNT(1); if (p_args[0]->get_type() != Variant::DICTIONARY) { @@ -467,12 +469,12 @@ struct GDScriptUtilityFunctionsDefinitions { static inline void get_stack(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { VALIDATE_ARG_COUNT(0); if (Thread::get_caller_id() != Thread::get_main_id()) { - *r_ret = Array(); + *r_ret = TypedArray<Dictionary>(); return; } ScriptLanguage *script = GDScriptLanguage::get_singleton(); - Array ret; + TypedArray<Dictionary> ret; for (int i = 0; i < script->debug_get_stack_level_count(); i++) { Dictionary frame; frame["source"] = script->debug_get_stack_level_source(i); @@ -651,8 +653,8 @@ void GDScriptUtilityFunctions::register_functions() { REGISTER_VARARG_FUNC(str, true, Variant::STRING); REGISTER_VARARG_FUNC(range, false, Variant::ARRAY); REGISTER_CLASS_FUNC(load, false, "Resource", ARG("path", Variant::STRING)); - REGISTER_FUNC(inst2dict, false, Variant::DICTIONARY, ARG("instance", Variant::OBJECT)); - REGISTER_FUNC(dict2inst, false, Variant::OBJECT, ARG("dictionary", Variant::DICTIONARY)); + REGISTER_FUNC(inst_to_dict, false, Variant::DICTIONARY, ARG("instance", Variant::OBJECT)); + REGISTER_FUNC(dict_to_inst, false, Variant::OBJECT, ARG("dictionary", Variant::DICTIONARY)); REGISTER_FUNC_DEF(Color8, true, 255, Variant::COLOR, ARG("r8", Variant::INT), ARG("g8", Variant::INT), ARG("b8", Variant::INT), ARG("a8", Variant::INT)); REGISTER_VARARG_FUNC(print_debug, false, Variant::NIL); REGISTER_FUNC_NO_ARGS(print_stack, false, Variant::NIL); diff --git a/modules/gdscript/gdscript_utility_functions.h b/modules/gdscript/gdscript_utility_functions.h index 9ca7cf33d8..0f07db857f 100644 --- a/modules/gdscript/gdscript_utility_functions.h +++ b/modules/gdscript/gdscript_utility_functions.h @@ -34,6 +34,9 @@ #include "core/string/string_name.h" #include "core/variant/variant.h" +template <typename T> +class TypedArray; + class GDScriptUtilityFunctions { public: typedef void (*FunctionPtr)(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error); diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp index e0beed367a..c73ba798aa 100644 --- a/modules/gdscript/gdscript_vm.cpp +++ b/modules/gdscript/gdscript_vm.cpp @@ -199,11 +199,14 @@ void (*type_init_function_table[])(Variant *) = { &VariantInitializer<Vector3>::init, // VECTOR3. &VariantInitializer<Vector3i>::init, // VECTOR3I. &VariantInitializer<Transform2D>::init, // TRANSFORM2D. + &VariantInitializer<Vector4>::init, // VECTOR4. + &VariantInitializer<Vector4i>::init, // VECTOR4I. &VariantInitializer<Plane>::init, // PLANE. &VariantInitializer<Quaternion>::init, // QUATERNION. &VariantInitializer<AABB>::init, // AABB. &VariantInitializer<Basis>::init, // BASIS. &VariantInitializer<Transform3D>::init, // TRANSFORM3D. + &VariantInitializer<Projection>::init, // PROJECTION. &VariantInitializer<Color>::init, // COLOR. &VariantInitializer<StringName>::init, // STRING_NAME. &VariantInitializer<NodePath>::init, // NODE_PATH. @@ -282,11 +285,14 @@ void (*type_init_function_table[])(Variant *) = { &&OPCODE_CALL_PTRCALL_VECTOR3, \ &&OPCODE_CALL_PTRCALL_VECTOR3I, \ &&OPCODE_CALL_PTRCALL_TRANSFORM2D, \ + &&OPCODE_CALL_PTRCALL_VECTOR4, \ + &&OPCODE_CALL_PTRCALL_VECTOR4I, \ &&OPCODE_CALL_PTRCALL_PLANE, \ &&OPCODE_CALL_PTRCALL_QUATERNION, \ &&OPCODE_CALL_PTRCALL_AABB, \ &&OPCODE_CALL_PTRCALL_BASIS, \ &&OPCODE_CALL_PTRCALL_TRANSFORM3D, \ + &&OPCODE_CALL_PTRCALL_PROJECTION, \ &&OPCODE_CALL_PTRCALL_COLOR, \ &&OPCODE_CALL_PTRCALL_STRING_NAME, \ &&OPCODE_CALL_PTRCALL_NODE_PATH, \ @@ -372,11 +378,14 @@ void (*type_init_function_table[])(Variant *) = { &&OPCODE_TYPE_ADJUST_VECTOR3, \ &&OPCODE_TYPE_ADJUST_VECTOR3I, \ &&OPCODE_TYPE_ADJUST_TRANSFORM2D, \ + &&OPCODE_TYPE_ADJUST_VECTOR4, \ + &&OPCODE_TYPE_ADJUST_VECTOR4I, \ &&OPCODE_TYPE_ADJUST_PLANE, \ &&OPCODE_TYPE_ADJUST_QUATERNION, \ &&OPCODE_TYPE_ADJUST_AABB, \ &&OPCODE_TYPE_ADJUST_BASIS, \ &&OPCODE_TYPE_ADJUST_TRANSFORM3D, \ + &&OPCODE_TYPE_ADJUST_PROJECTION, \ &&OPCODE_TYPE_ADJUST_COLOR, \ &&OPCODE_TYPE_ADJUST_STRING_NAME, \ &&OPCODE_TYPE_ADJUST_NODE_PATH, \ @@ -435,6 +444,8 @@ void (*type_init_function_table[])(Variant *) = { #define OP_GET_VECTOR3 get_vector3 #define OP_GET_VECTOR3I get_vector3i #define OP_GET_RECT2 get_rect2 +#define OP_GET_VECTOR4 get_vector4 +#define OP_GET_VECTOR4I get_vector4i #define OP_GET_RECT2I get_rect2i #define OP_GET_QUATERNION get_quaternion #define OP_GET_COLOR get_color @@ -456,6 +467,7 @@ void (*type_init_function_table[])(Variant *) = { #define OP_GET_PACKED_COLOR_ARRAY get_color_array #define OP_GET_TRANSFORM3D get_transform #define OP_GET_TRANSFORM2D get_transform2d +#define OP_GET_PROJECTION get_projection #define OP_GET_PLANE get_plane #define OP_GET_AABB get_aabb #define OP_GET_BASIS get_basis @@ -1827,11 +1839,14 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a OPCODE_CALL_PTR(VECTOR3); OPCODE_CALL_PTR(VECTOR3I); OPCODE_CALL_PTR(TRANSFORM2D); + OPCODE_CALL_PTR(VECTOR4); + OPCODE_CALL_PTR(VECTOR4I); OPCODE_CALL_PTR(PLANE); OPCODE_CALL_PTR(QUATERNION); OPCODE_CALL_PTR(AABB); OPCODE_CALL_PTR(BASIS); OPCODE_CALL_PTR(TRANSFORM3D); + OPCODE_CALL_PTR(PROJECTION); OPCODE_CALL_PTR(COLOR); OPCODE_CALL_PTR(STRING_NAME); OPCODE_CALL_PTR(NODE_PATH); @@ -2148,7 +2163,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a OPCODE(OPCODE_AWAIT) { CHECK_SPACE(2); - // Do the oneshot connect. + // Do the one-shot connect. GET_INSTRUCTION_ARG(argobj, 0); Signal sig; @@ -2201,7 +2216,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a gdfs->state.line = line; gdfs->state.script = _script; { - MutexLock lock(GDScriptLanguage::get_singleton()->lock); + MutexLock lock(GDScriptLanguage::get_singleton()->mutex); _script->pending_func_states.add(&gdfs->scripts_list); if (p_instance) { gdfs->state.instance = p_instance; @@ -2219,7 +2234,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a retvalue = gdfs; - Error err = sig.connect(callable_bind(Callable(gdfs.ptr(), "_signal_callback"), retvalue), Object::CONNECT_ONESHOT); + Error err = sig.connect(Callable(gdfs.ptr(), "_signal_callback").bind(retvalue), Object::CONNECT_ONE_SHOT); if (err != OK) { err_text = "Error connecting to signal: " + sig.get_name() + " during await."; OPCODE_BREAK; @@ -3280,6 +3295,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a int globalname_idx = _code_ptr[ip + 2]; GD_ERR_BREAK(globalname_idx < 0 || globalname_idx >= _global_names_count); const StringName *globalname = &_global_names_ptr[globalname_idx]; + GD_ERR_BREAK(!GDScriptLanguage::get_singleton()->get_named_globals_map().has(*globalname)); GET_INSTRUCTION_ARG(dst, 0); *dst = GDScriptLanguage::get_singleton()->get_named_globals_map()[*globalname]; @@ -3308,11 +3324,14 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a OPCODE_TYPE_ADJUST(VECTOR3, Vector3); OPCODE_TYPE_ADJUST(VECTOR3I, Vector3i); OPCODE_TYPE_ADJUST(TRANSFORM2D, Transform2D); + OPCODE_TYPE_ADJUST(VECTOR4, Vector4); + OPCODE_TYPE_ADJUST(VECTOR4I, Vector4i); OPCODE_TYPE_ADJUST(PLANE, Plane); OPCODE_TYPE_ADJUST(QUATERNION, Quaternion); OPCODE_TYPE_ADJUST(AABB, AABB); OPCODE_TYPE_ADJUST(BASIS, Basis); OPCODE_TYPE_ADJUST(TRANSFORM3D, Transform3D); + OPCODE_TYPE_ADJUST(PROJECTION, Projection); OPCODE_TYPE_ADJUST(COLOR, Color); OPCODE_TYPE_ADJUST(STRING_NAME, StringName); OPCODE_TYPE_ADJUST(NODE_PATH, NodePath); diff --git a/modules/gdscript/gdscript_warning.cpp b/modules/gdscript/gdscript_warning.cpp index 1cae7bdfac..a0c107aa53 100644 --- a/modules/gdscript/gdscript_warning.cpp +++ b/modules/gdscript/gdscript_warning.cpp @@ -155,6 +155,10 @@ String GDScriptWarning::get_message() const { case INT_ASSIGNED_TO_ENUM: { return "Integer used when an enum value is expected. If this is intended cast the integer to the enum type."; } + case STATIC_CALLED_ON_INSTANCE: { + CHECK_SYMBOLS(2); + return vformat(R"(The function '%s()' is a static function but was called from an instance. Instead, it should be directly called from the type: '%s.%s()'.)", symbols[0], symbols[1], symbols[0]); + } case WARNING_MAX: break; // Can't happen, but silences warning } @@ -215,6 +219,7 @@ String GDScriptWarning::get_name_from_code(Code p_code) { "EMPTY_FILE", "SHADOWED_GLOBAL_IDENTIFIER", "INT_ASSIGNED_TO_ENUM", + "STATIC_CALLED_ON_INSTANCE", }; static_assert((sizeof(names) / sizeof(*names)) == WARNING_MAX, "Amount of warning types don't match the amount of warning names."); diff --git a/modules/gdscript/gdscript_warning.h b/modules/gdscript/gdscript_warning.h index f47f31aedf..7e4e975510 100644 --- a/modules/gdscript/gdscript_warning.h +++ b/modules/gdscript/gdscript_warning.h @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GDSCRIPT_WARNINGS -#define GDSCRIPT_WARNINGS +#ifndef GDSCRIPT_WARNING_H +#define GDSCRIPT_WARNING_H #ifdef DEBUG_ENABLED @@ -78,6 +78,7 @@ public: EMPTY_FILE, // A script file is empty. SHADOWED_GLOBAL_IDENTIFIER, // A global class or function has the same name as variable. INT_ASSIGNED_TO_ENUM, // An integer value was assigned to an enum-typed variable without casting. + STATIC_CALLED_ON_INSTANCE, // A static method was called on an instance of a class instead of on the class itself. WARNING_MAX, }; @@ -97,4 +98,4 @@ public: #endif // DEBUG_ENABLED -#endif // GDSCRIPT_WARNINGS +#endif // GDSCRIPT_WARNING_H diff --git a/modules/gdscript/language_server/gdscript_extend_parser.cpp b/modules/gdscript/language_server/gdscript_extend_parser.cpp index 03e93821c7..de3becbaf8 100644 --- a/modules/gdscript/language_server/gdscript_extend_parser.cpp +++ b/modules/gdscript/language_server/gdscript_extend_parser.cpp @@ -38,8 +38,8 @@ void ExtendGDScriptParser::update_diagnostics() { diagnostics.clear(); - const List<ParserError> &errors = get_errors(); - for (const ParserError &error : errors) { + const List<ParserError> &parser_errors = get_errors(); + for (const ParserError &error : parser_errors) { lsp::Diagnostic diagnostic; diagnostic.severity = lsp::DiagnosticSeverity::Error; diagnostic.message = error.message; @@ -47,9 +47,9 @@ void ExtendGDScriptParser::update_diagnostics() { diagnostic.code = -1; lsp::Range range; lsp::Position pos; - const PackedStringArray lines = get_lines(); - int line = CLAMP(LINE_NUMBER_TO_INDEX(error.line), 0, lines.size() - 1); - const String &line_text = lines[line]; + const PackedStringArray line_array = get_lines(); + int line = CLAMP(LINE_NUMBER_TO_INDEX(error.line), 0, line_array.size() - 1); + const String &line_text = line_array[line]; pos.line = line; pos.character = line_text.length() - line_text.strip_edges(true, false).length(); range.start = pos; @@ -59,8 +59,8 @@ void ExtendGDScriptParser::update_diagnostics() { diagnostics.push_back(diagnostic); } - const List<GDScriptWarning> &warnings = get_warnings(); - for (const GDScriptWarning &warning : warnings) { + const List<GDScriptWarning> &parser_warnings = get_warnings(); + for (const GDScriptWarning &warning : parser_warnings) { lsp::Diagnostic diagnostic; diagnostic.severity = lsp::DiagnosticSeverity::Warning; diagnostic.message = "(" + warning.get_name() + "): " + warning.get_message(); @@ -83,8 +83,7 @@ void ExtendGDScriptParser::update_diagnostics() { void ExtendGDScriptParser::update_symbols() { members.clear(); - const GDScriptParser::Node *head = get_tree(); - if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) { + if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) { parse_class_symbol(gdclass, class_symbol); for (int i = 0; i < class_symbol.children.size(); i++) { @@ -107,26 +106,26 @@ void ExtendGDScriptParser::update_symbols() { void ExtendGDScriptParser::update_document_links(const String &p_code) { document_links.clear(); - GDScriptTokenizer tokenizer; + GDScriptTokenizer scr_tokenizer; Ref<FileAccess> fs = FileAccess::create(FileAccess::ACCESS_RESOURCES); - tokenizer.set_source_code(p_code); + scr_tokenizer.set_source_code(p_code); while (true) { - GDScriptTokenizer::Token token = tokenizer.scan(); + GDScriptTokenizer::Token token = scr_tokenizer.scan(); if (token.type == GDScriptTokenizer::Token::TK_EOF) { break; } else if (token.type == GDScriptTokenizer::Token::LITERAL) { const Variant &const_val = token.literal; if (const_val.get_type() == Variant::STRING) { - String path = const_val; - bool exists = fs->file_exists(path); + String scr_path = const_val; + bool exists = fs->file_exists(scr_path); if (!exists) { - path = get_path().get_base_dir() + "/" + path; - exists = fs->file_exists(path); + scr_path = get_path().get_base_dir() + "/" + scr_path; + exists = fs->file_exists(scr_path); } if (exists) { String value = const_val; lsp::DocumentLink link; - link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path); + link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(scr_path); link.range.start.line = LINE_NUMBER_TO_INDEX(token.start_line); link.range.end.line = LINE_NUMBER_TO_INDEX(token.end_line); link.range.start.character = LINE_NUMBER_TO_INDEX(token.start_column); @@ -437,11 +436,11 @@ String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) { if (!p_docs_down) { // inline comment String inline_comment = lines[p_line]; - int comment_start = inline_comment.find("#"); + int comment_start = inline_comment.find("##"); if (comment_start != -1) { inline_comment = inline_comment.substr(comment_start, inline_comment.length()).strip_edges(); if (inline_comment.length() > 1) { - doc_lines.push_back(inline_comment.substr(1, inline_comment.length())); + doc_lines.push_back(inline_comment.substr(2, inline_comment.length())); } } } @@ -454,8 +453,8 @@ String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) { } String line_comment = lines[i].strip_edges(true, false); - if (line_comment.begins_with("#")) { - line_comment = line_comment.substr(1, line_comment.length()); + if (line_comment.begins_with("##")) { + line_comment = line_comment.substr(2, line_comment.length()); if (p_docs_down) { doc_lines.push_back(line_comment); } else { @@ -690,9 +689,7 @@ Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::Functio ERR_FAIL_NULL_V(p_func, func); func["name"] = p_func->identifier->name; func["return_type"] = p_func->get_datatype().to_string(); - func["rpc_mode"] = p_func->rpc_config.rpc_mode; - func["rpc_transfer_mode"] = p_func->rpc_config.transfer_mode; - func["rpc_transfer_channel"] = p_func->rpc_config.channel; + func["rpc_config"] = p_func->rpc_config; Array parameters; for (int i = 0; i < p_func->parameters.size(); i++) { Dictionary arg; @@ -733,7 +730,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode Array nested_classes; Array constants; - Array members; + Array class_members; Array signals; Array methods; Array static_functions; @@ -794,7 +791,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode api["signature"] = symbol->detail; api["description"] = symbol->documentation; } - members.push_back(api); + class_members.push_back(api); } break; case ClassNode::Member::SIGNAL: { Dictionary api; @@ -826,7 +823,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode class_api["sub_classes"] = nested_classes; class_api["constants"] = constants; - class_api["members"] = members; + class_api["members"] = class_members; class_api["signals"] = signals; class_api["methods"] = methods; class_api["static_functions"] = static_functions; @@ -836,8 +833,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode Dictionary ExtendGDScriptParser::generate_api() const { Dictionary api; - const GDScriptParser::Node *head = get_tree(); - if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) { + if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) { api = dump_class_api(gdclass); } return api; diff --git a/modules/gdscript/language_server/gdscript_extend_parser.h b/modules/gdscript/language_server/gdscript_extend_parser.h index 99b0bf45d0..08bba4a2d4 100644 --- a/modules/gdscript/language_server/gdscript_extend_parser.h +++ b/modules/gdscript/language_server/gdscript_extend_parser.h @@ -33,7 +33,7 @@ #include "../gdscript_parser.h" #include "core/variant/variant.h" -#include "lsp.hpp" +#include "godot_lsp.h" #ifndef LINE_NUMBER_TO_INDEX #define LINE_NUMBER_TO_INDEX(p_line) ((p_line)-1) @@ -99,4 +99,4 @@ public: Error parse(const String &p_code, const String &p_path); }; -#endif +#endif // GDSCRIPT_EXTEND_PARSER_H diff --git a/modules/gdscript/language_server/gdscript_language_protocol.cpp b/modules/gdscript/language_server/gdscript_language_protocol.cpp index 7460f8edff..39f4c976a4 100644 --- a/modules/gdscript/language_server/gdscript_language_protocol.cpp +++ b/modules/gdscript/language_server/gdscript_language_protocol.cpp @@ -34,6 +34,7 @@ #include "editor/doc_tools.h" #include "editor/editor_log.h" #include "editor/editor_node.h" +#include "editor/editor_settings.h" GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = nullptr; @@ -183,7 +184,9 @@ Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) { if (root_uri.length() && is_same_workspace) { workspace->root_uri = root_uri; } else { - workspace->root_uri = "file://" + workspace->root; + String r_root = workspace->root; + r_root = r_root.lstrip("/"); + workspace->root_uri = "file:///" + r_root; Dictionary params; params["path"] = workspace->root; diff --git a/modules/gdscript/language_server/gdscript_language_protocol.h b/modules/gdscript/language_server/gdscript_language_protocol.h index 0fed8597f9..3c9cfe512f 100644 --- a/modules/gdscript/language_server/gdscript_language_protocol.h +++ b/modules/gdscript/language_server/gdscript_language_protocol.h @@ -36,7 +36,7 @@ #include "core/io/tcp_server.h" #include "gdscript_text_document.h" #include "gdscript_workspace.h" -#include "lsp.hpp" +#include "godot_lsp.h" #include "modules/modules_enabled.gen.h" // For jsonrpc. #ifdef MODULE_JSONRPC_ENABLED diff --git a/modules/gdscript/language_server/gdscript_language_server.cpp b/modules/gdscript/language_server/gdscript_language_server.cpp index 14337e87da..38bea314a0 100644 --- a/modules/gdscript/language_server/gdscript_language_server.cpp +++ b/modules/gdscript/language_server/gdscript_language_server.cpp @@ -34,6 +34,7 @@ #include "core/os/os.h" #include "editor/editor_log.h" #include "editor/editor_node.h" +#include "editor/editor_settings.h" GDScriptLanguageServer::GDScriptLanguageServer() { _EDITOR_DEF("network/language_server/remote_host", host); @@ -60,12 +61,12 @@ void GDScriptLanguageServer::_notification(int p_what) { } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { - String host = String(_EDITOR_GET("network/language_server/remote_host")); - int port = (int)_EDITOR_GET("network/language_server/remote_port"); - bool use_thread = (bool)_EDITOR_GET("network/language_server/use_thread"); - if (host != this->host || port != this->port || use_thread != this->use_thread) { - this->stop(); - this->start(); + String remote_host = String(_EDITOR_GET("network/language_server/remote_host")); + int remote_port = (int)_EDITOR_GET("network/language_server/remote_port"); + bool remote_use_thread = (bool)_EDITOR_GET("network/language_server/use_thread"); + if (remote_host != host || remote_port != port || remote_use_thread != use_thread) { + stop(); + start(); } } break; } diff --git a/modules/gdscript/language_server/gdscript_text_document.cpp b/modules/gdscript/language_server/gdscript_text_document.cpp index 5ad9680ea0..3905e28bcb 100644 --- a/modules/gdscript/language_server/gdscript_text_document.cpp +++ b/modules/gdscript/language_server/gdscript_text_document.cpp @@ -42,6 +42,7 @@ void GDScriptTextDocument::_bind_methods() { ClassDB::bind_method(D_METHOD("didOpen"), &GDScriptTextDocument::didOpen); ClassDB::bind_method(D_METHOD("didClose"), &GDScriptTextDocument::didClose); ClassDB::bind_method(D_METHOD("didChange"), &GDScriptTextDocument::didChange); + ClassDB::bind_method(D_METHOD("willSaveWaitUntil"), &GDScriptTextDocument::willSaveWaitUntil); ClassDB::bind_method(D_METHOD("didSave"), &GDScriptTextDocument::didSave); ClassDB::bind_method(D_METHOD("nativeSymbol"), &GDScriptTextDocument::nativeSymbol); ClassDB::bind_method(D_METHOD("documentSymbol"), &GDScriptTextDocument::documentSymbol); @@ -81,6 +82,16 @@ void GDScriptTextDocument::didChange(const Variant &p_param) { sync_script_content(doc.uri, doc.text); } +void GDScriptTextDocument::willSaveWaitUntil(const Variant &p_param) { + lsp::TextDocumentItem doc = load_document_item(p_param); + + String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(doc.uri); + Ref<Script> scr = ResourceLoader::load(path); + if (scr.is_valid()) { + ScriptEditor::get_singleton()->clear_docs_from_script(scr); + } +} + void GDScriptTextDocument::didSave(const Variant &p_param) { lsp::TextDocumentItem doc = load_document_item(p_param); Dictionary dict = p_param; @@ -88,11 +99,16 @@ void GDScriptTextDocument::didSave(const Variant &p_param) { sync_script_content(doc.uri, text); - /*String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(doc.uri); - - Ref<GDScript> script = ResourceLoader::load(path); - script->load_source_code(path); - script->reload(true);*/ + String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(doc.uri); + Ref<GDScript> scr = ResourceLoader::load(path); + if (scr.is_valid() && (scr->load_source_code(path) == OK)) { + if (scr->is_tool()) { + scr->get_language()->reload_tool_script(scr, true); + } else { + scr->reload(true); + } + ScriptEditor::get_singleton()->update_docs_from_script(scr); + } } lsp::TextDocumentItem GDScriptTextDocument::load_document_item(const Variant &p_param) { @@ -213,8 +229,8 @@ Array GDScriptTextDocument::completion(const Dictionary &p_params) { arr = native_member_completions.duplicate(); for (KeyValue<String, ExtendGDScriptParser *> &E : GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts) { - ExtendGDScriptParser *script = E.value; - const Array &items = script->get_member_completions(); + ExtendGDScriptParser *scr = E.value; + const Array &items = scr->get_member_completions(); const int start_size = arr.size(); arr.resize(start_size + items.size()); @@ -417,13 +433,6 @@ void GDScriptTextDocument::sync_script_content(const String &p_path, const Strin GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_script(path, p_content); EditorFileSystem::get_singleton()->update_file(path); - Error error; - Ref<GDScript> script = ResourceLoader::load(path, "", ResourceFormatLoader::CACHE_MODE_REUSE, &error); - if (error == OK) { - if (script->load_source_code(path) == OK) { - script->reload(true); - } - } } void GDScriptTextDocument::show_native_symbol_in_editor(const String &p_symbol_id) { diff --git a/modules/gdscript/language_server/gdscript_text_document.h b/modules/gdscript/language_server/gdscript_text_document.h index 9732765f34..456c7d71fe 100644 --- a/modules/gdscript/language_server/gdscript_text_document.h +++ b/modules/gdscript/language_server/gdscript_text_document.h @@ -33,7 +33,7 @@ #include "core/io/file_access.h" #include "core/object/ref_counted.h" -#include "lsp.hpp" +#include "godot_lsp.h" class GDScriptTextDocument : public RefCounted { GDCLASS(GDScriptTextDocument, RefCounted) @@ -45,6 +45,7 @@ protected: void didOpen(const Variant &p_param); void didClose(const Variant &p_param); void didChange(const Variant &p_param); + void willSaveWaitUntil(const Variant &p_param); void didSave(const Variant &p_param); void sync_script_content(const String &p_path, const String &p_content); @@ -77,4 +78,4 @@ public: GDScriptTextDocument(); }; -#endif +#endif // GDSCRIPT_TEXT_DOCUMENT_H diff --git a/modules/gdscript/language_server/gdscript_workspace.cpp b/modules/gdscript/language_server/gdscript_workspace.cpp index 8d484a43b3..390460bed9 100644 --- a/modules/gdscript/language_server/gdscript_workspace.cpp +++ b/modules/gdscript/language_server/gdscript_workspace.cpp @@ -38,6 +38,7 @@ #include "editor/editor_file_system.h" #include "editor/editor_help.h" #include "editor/editor_node.h" +#include "editor/editor_settings.h" #include "gdscript_language_protocol.h" #include "scene/resources/packed_scene.h" @@ -54,14 +55,14 @@ void GDScriptWorkspace::_bind_methods() { } void GDScriptWorkspace::apply_new_signal(Object *obj, String function, PackedStringArray args) { - Ref<Script> script = obj->get_script(); + Ref<Script> scr = obj->get_script(); - if (script->get_language()->get_name() != "GDScript") { + if (scr->get_language()->get_name() != "GDScript") { return; } String function_signature = "func " + function; - String source = script->get_source_code(); + String source = scr->get_source_code(); if (source.contains(function_signature)) { return; @@ -97,7 +98,7 @@ void GDScriptWorkspace::apply_new_signal(Object *obj, String function, PackedStr text_edit.newText = function_body; - String uri = get_file_uri(script->get_path()); + String uri = get_file_uri(scr->get_path()); lsp::ApplyWorkspaceEditParams params; params.edit.add_edit(uri, text_edit); @@ -117,12 +118,12 @@ void GDScriptWorkspace::did_delete_files(const Dictionary &p_params) { void GDScriptWorkspace::remove_cache_parser(const String &p_path) { HashMap<String, ExtendGDScriptParser *>::Iterator parser = parse_results.find(p_path); - HashMap<String, ExtendGDScriptParser *>::Iterator script = scripts.find(p_path); - if (parser && script) { - if (script->value && script->value == parser->value) { - memdelete(script->value); + HashMap<String, ExtendGDScriptParser *>::Iterator scr = scripts.find(p_path); + if (parser && scr) { + if (scr->value && scr->value == parser->value) { + memdelete(scr->value); } else { - memdelete(script->value); + memdelete(scr->value); memdelete(parser->value); } parse_results.erase(p_path); @@ -130,8 +131,8 @@ void GDScriptWorkspace::remove_cache_parser(const String &p_path) { } else if (parser) { memdelete(parser->value); parse_results.erase(p_path); - } else if (script) { - memdelete(script->value); + } else if (scr) { + memdelete(scr->value); scripts.erase(p_path); } } @@ -227,9 +228,9 @@ void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> String file_name = dir->get_next(); while (file_name.length()) { if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") { - list_script_files(p_root_dir.plus_file(file_name), r_files); + list_script_files(p_root_dir.path_join(file_name), r_files); } else if (file_name.ends_with(".gd")) { - String script_file = p_root_dir.plus_file(file_name); + String script_file = p_root_dir.path_join(file_name); r_files.push_back(script_file); } file_name = dir->get_next(); @@ -498,9 +499,9 @@ Error GDScriptWorkspace::parse_local_script(const String &p_path) { } String GDScriptWorkspace::get_file_path(const String &p_uri) const { - String path = p_uri; - path = path.replace(root_uri + "/", "res://"); - path = path.uri_decode(); + String path = p_uri.uri_decode(); + String base_uri = root_uri.uri_decode(); + path = path.replacen(base_uri + "/", "res://"); return path; } @@ -586,8 +587,8 @@ void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<S while (!stack.is_empty()) { current = Object::cast_to<Node>(stack.pop_back()); - Ref<GDScript> script = current->get_script(); - if (script.is_valid() && script->get_path() == path) { + Ref<GDScript> scr = current->get_script(); + if (scr.is_valid() && scr->get_path() == path) { break; } for (int i = 0; i < current->get_child_count(); ++i) { @@ -595,8 +596,8 @@ void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<S } } - Ref<GDScript> script = current->get_script(); - if (!script.is_valid() || script->get_path() != path) { + Ref<GDScript> scr = current->get_script(); + if (!scr.is_valid() || scr->get_path() != path) { current = owner_scene_node; } } @@ -690,13 +691,13 @@ void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionP } for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) { - const ExtendGDScriptParser *script = E.value; - const ClassMembers &members = script->get_members(); + const ExtendGDScriptParser *scr = E.value; + const ClassMembers &members = scr->get_members(); if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) { r_list.push_back(*symbol); } - for (const KeyValue<String, ClassMembers> &F : script->get_inner_classes()) { + for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) { const ClassMembers *inner_class = &F.value; if (const lsp::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) { r_list.push_back(*symbol); diff --git a/modules/gdscript/language_server/gdscript_workspace.h b/modules/gdscript/language_server/gdscript_workspace.h index 7bff5db81f..88f3aaf957 100644 --- a/modules/gdscript/language_server/gdscript_workspace.h +++ b/modules/gdscript/language_server/gdscript_workspace.h @@ -35,7 +35,7 @@ #include "core/variant/variant.h" #include "editor/editor_file_system.h" #include "gdscript_extend_parser.h" -#include "lsp.hpp" +#include "godot_lsp.h" class GDScriptWorkspace : public RefCounted { GDCLASS(GDScriptWorkspace, RefCounted); @@ -100,4 +100,4 @@ public: ~GDScriptWorkspace(); }; -#endif +#endif // GDSCRIPT_WORKSPACE_H diff --git a/modules/gdscript/language_server/lsp.hpp b/modules/gdscript/language_server/godot_lsp.h index 1c9349097f..024da1cab7 100644 --- a/modules/gdscript/language_server/lsp.hpp +++ b/modules/gdscript/language_server/godot_lsp.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* lsp.hpp */ +/* godot_lsp.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -546,7 +546,7 @@ struct TextDocumentSyncOptions { * If present will save wait until requests are sent to the server. If omitted the request should not be * sent. */ - bool willSaveWaitUntil = false; + bool willSaveWaitUntil = true; /** * If present save notifications are sent to the server. If omitted the notification should not be @@ -1975,4 +1975,4 @@ static String marked_documentation(const String &p_bbcode) { } } // namespace lsp -#endif +#endif // GODOT_LSP_H diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp index b230c6ba36..19a8b59c6f 100644 --- a/modules/gdscript/register_types.cpp +++ b/modules/gdscript/register_types.cpp @@ -52,10 +52,10 @@ GDScriptCache *gdscript_cache = nullptr; #ifdef TOOLS_ENABLED -#include "editor/editor_export.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor/editor_translation_parser.h" +#include "editor/export/editor_export.h" #include "editor/gdscript_highlighter.h" #include "editor/gdscript_translation_parser_plugin.h" @@ -88,6 +88,8 @@ public: // TODO: Re-add compiled GDScript on export. return; } + + virtual String _get_name() const override { return "GDScript"; } }; static void _editor_init() { diff --git a/modules/gdscript/tests/gdscript_test_runner.cpp b/modules/gdscript/tests/gdscript_test_runner.cpp index ff4832bde0..15131afde7 100644 --- a/modules/gdscript/tests/gdscript_test_runner.cpp +++ b/modules/gdscript/tests/gdscript_test_runner.cpp @@ -36,6 +36,7 @@ #include "../gdscript_parser.h" #include "core/config/project_settings.h" +#include "core/core_globals.h" #include "core/core_string_names.h" #include "core/io/dir_access.h" #include "core/io/file_access_pack.h" @@ -142,8 +143,8 @@ GDScriptTestRunner::GDScriptTestRunner(const String &p_source_dir, bool p_init_l #endif // Enable printing to show results - _print_line_enabled = true; - _print_error_enabled = true; + CoreGlobals::print_line_enabled = true; + CoreGlobals::print_error_enabled = true; } GDScriptTestRunner::~GDScriptTestRunner() { @@ -246,7 +247,7 @@ bool GDScriptTestRunner::make_tests_for_dir(const String &p_dir) { next = dir->get_next(); continue; } - if (!make_tests_for_dir(current_dir.plus_file(next))) { + if (!make_tests_for_dir(current_dir.path_join(next))) { return false; } } else { @@ -254,7 +255,7 @@ bool GDScriptTestRunner::make_tests_for_dir(const String &p_dir) { #ifndef DEBUG_ENABLED // On release builds, skip tests marked as debug only. Error open_err = OK; - Ref<FileAccess> script_file(FileAccess::open(current_dir.plus_file(next), FileAccess::READ, &open_err)); + Ref<FileAccess> script_file(FileAccess::open(current_dir.path_join(next), FileAccess::READ, &open_err)); if (open_err != OK) { ERR_PRINT(vformat(R"(Couldn't open test file "%s".)", next)); next = dir->get_next(); @@ -271,7 +272,7 @@ bool GDScriptTestRunner::make_tests_for_dir(const String &p_dir) { if (!is_generating && !dir->file_exists(out_file)) { ERR_FAIL_V_MSG(false, "Could not find output file for " + next); } - GDScriptTest test(current_dir.plus_file(next), current_dir.plus_file(out_file), source_dir); + GDScriptTest test(current_dir.path_join(next), current_dir.path_join(out_file), source_dir); tests.push_back(test); } } @@ -478,9 +479,9 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { result.output = get_text_for_status(result.status) + "\n"; const List<GDScriptParser::ParserError> &errors = parser.get_errors(); - for (const GDScriptParser::ParserError &E : errors) { - result.output += E.message + "\n"; // TODO: line, column? - break; // Only the first error since the following might be cascading. + if (!errors.is_empty()) { + // Only the first error since the following might be cascading. + result.output += errors[0].message + "\n"; // TODO: line, column? } if (!p_is_generating) { result.passed = check_output(result.output); @@ -497,9 +498,9 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { result.output = get_text_for_status(result.status) + "\n"; const List<GDScriptParser::ParserError> &errors = parser.get_errors(); - for (const GDScriptParser::ParserError &E : errors) { - result.output += E.message + "\n"; // TODO: line, column? - break; // Only the first error since the following might be cascading. + if (!errors.is_empty()) { + // Only the first error since the following might be cascading. + result.output += errors[0].message + "\n"; // TODO: line, column? } if (!p_is_generating) { result.passed = check_output(result.output); diff --git a/modules/gdscript/tests/gdscript_test_runner.h b/modules/gdscript/tests/gdscript_test_runner.h index ee21afd9c9..033d2fcad1 100644 --- a/modules/gdscript/tests/gdscript_test_runner.h +++ b/modules/gdscript/tests/gdscript_test_runner.h @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GDSCRIPT_TEST_H -#define GDSCRIPT_TEST_H +#ifndef GDSCRIPT_TEST_RUNNER_H +#define GDSCRIPT_TEST_RUNNER_H #include "../gdscript.h" #include "core/error/error_macros.h" @@ -123,4 +123,4 @@ public: } // namespace GDScriptTests -#endif // GDSCRIPT_TEST_H +#endif // GDSCRIPT_TEST_RUNNER_H diff --git a/modules/gdscript/tests/gdscript_test_runner_suite.h b/modules/gdscript/tests/gdscript_test_runner_suite.h index 0722fb800e..90f6d7f7e8 100644 --- a/modules/gdscript/tests/gdscript_test_runner_suite.h +++ b/modules/gdscript/tests/gdscript_test_runner_suite.h @@ -69,6 +69,40 @@ func _init(): CHECK_MESSAGE(int(ref_counted->get_meta("result")) == 42, "The script should assign object metadata successfully."); } +TEST_CASE("[Modules][GDScript] Validate built-in API") { + GDScriptLanguage *lang = GDScriptLanguage::get_singleton(); + + // Validate methods. + List<MethodInfo> builtin_methods; + lang->get_public_functions(&builtin_methods); + + SUBCASE("[Modules][GDScript] Validate built-in methods") { + for (const MethodInfo &mi : builtin_methods) { + for (int j = 0; j < mi.arguments.size(); j++) { + PropertyInfo arg = mi.arguments[j]; + + TEST_COND((arg.name.is_empty() || arg.name.begins_with("_unnamed_arg")), + vformat("Unnamed argument in position %d of built-in method '%s'.", j, mi.name)); + } + } + } + + // Validate annotations. + List<MethodInfo> builtin_annotations; + lang->get_public_annotations(&builtin_annotations); + + SUBCASE("[Modules][GDScript] Validate built-in annotations") { + for (const MethodInfo &ai : builtin_annotations) { + for (int j = 0; j < ai.arguments.size(); j++) { + PropertyInfo arg = ai.arguments[j]; + + TEST_COND((arg.name.is_empty() || arg.name.begins_with("_unnamed_arg")), + vformat("Unnamed argument in position %d of built-in annotation '%s'.", j, ai.name)); + } + } + } +} + } // namespace GDScriptTests #endif // GDSCRIPT_TEST_RUNNER_SUITE_H diff --git a/modules/gdscript/tests/scripts/analyzer/features/gdscript_to_preload.gd b/modules/gdscript/tests/scripts/analyzer/features/gdscript_to_preload.gd index fb0ace6a90..ea744e3027 100644 --- a/modules/gdscript/tests/scripts/analyzer/features/gdscript_to_preload.gd +++ b/modules/gdscript/tests/scripts/analyzer/features/gdscript_to_preload.gd @@ -1,3 +1,5 @@ +const A := 42 + func test(): pass diff --git a/modules/gdscript/tests/scripts/analyzer/features/preload_constant_types_are_inferred.gd b/modules/gdscript/tests/scripts/analyzer/features/preload_constant_types_are_inferred.gd new file mode 100644 index 0000000000..276875dd5a --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/preload_constant_types_are_inferred.gd @@ -0,0 +1,6 @@ +const Constants = preload("gdscript_to_preload.gd") + +func test(): + var a := Constants.A + print(a) + diff --git a/modules/gdscript/tests/scripts/analyzer/features/preload_constant_types_are_inferred.out b/modules/gdscript/tests/scripts/analyzer/features/preload_constant_types_are_inferred.out new file mode 100644 index 0000000000..0982f3718c --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/preload_constant_types_are_inferred.out @@ -0,0 +1,2 @@ +GDTEST_OK +42 diff --git a/modules/gdscript/tests/scripts/analyzer/features/property_inline.out b/modules/gdscript/tests/scripts/analyzer/features/property_inline.out index 5482592e90..63e59398ae 100644 --- a/modules/gdscript/tests/scripts/analyzer/features/property_inline.out +++ b/modules/gdscript/tests/scripts/analyzer/features/property_inline.out @@ -1,5 +1,5 @@ GDTEST_OK -null +<null> 0 1 2 diff --git a/modules/gdscript/tests/scripts/parser/features/class.gd b/modules/gdscript/tests/scripts/parser/features/class.gd index 6652f85ad9..af24b32322 100644 --- a/modules/gdscript/tests/scripts/parser/features/class.gd +++ b/modules/gdscript/tests/scripts/parser/features/class.gd @@ -21,5 +21,5 @@ func test(): assert(test_sub.number == 25) # From Test. assert(test_sub.other_string == "bye") # From TestSub. - TestConstructor.new() - TestConstructor.new(500) + var _test_constructor = TestConstructor.new() + _test_constructor = TestConstructor.new(500) diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary.out b/modules/gdscript/tests/scripts/parser/features/dictionary.out index 5f999f573a..e1eeb46f78 100644 --- a/modules/gdscript/tests/scripts/parser/features/dictionary.out +++ b/modules/gdscript/tests/scripts/parser/features/dictionary.out @@ -7,8 +7,8 @@ null false empty array zero Vector2i -{22:{4:["nesting", "arrays"]}} -{4:["nesting", "arrays"]} +{ 22: { 4: ["nesting", "arrays"] } } +{ 4: ["nesting", "arrays"] } ["nesting", "arrays"] nesting arrays diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out b/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out index 5143d040a9..553d40d953 100644 --- a/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out +++ b/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out @@ -1,2 +1,2 @@ GDTEST_OK -{"a":1, "b":2, "with spaces":3, "2":4} +{ "a": 1, "b": 2, "with spaces": 3, "2": 4 } diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out b/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out index dd28609850..cf79845f53 100644 --- a/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out +++ b/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out @@ -1,2 +1,2 @@ GDTEST_OK -{"hello":{"world":{"is":"beautiful"}}} +{ "hello": { "world": { "is": "beautiful" } } } diff --git a/modules/gdscript/tests/scripts/parser/features/function_many_parameters.out b/modules/gdscript/tests/scripts/parser/features/function_many_parameters.out index 3a979227d4..80df7a3d4c 100644 --- a/modules/gdscript/tests/scripts/parser/features/function_many_parameters.out +++ b/modules/gdscript/tests/scripts/parser/features/function_many_parameters.out @@ -1,2 +1,2 @@ GDTEST_OK -123456789101112131415161718192212223242526272829303132333435363738394041424344454647falsetruenull +123456789101112131415161718192212223242526272829303132333435363738394041424344454647falsetrue<null> diff --git a/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out b/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out index 8b8c33202f..508f0ff217 100644 --- a/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out +++ b/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out @@ -1,5 +1,5 @@ GDTEST_OK -{8:{"key":"value"}} -{"key":"value"} +{ 8: { "key": "value" } } +{ "key": "value" } value value diff --git a/modules/gdscript/tests/scripts/parser/features/str_preserves_case.out b/modules/gdscript/tests/scripts/parser/features/str_preserves_case.out index abba38e87c..867f45f0ac 100644 --- a/modules/gdscript/tests/scripts/parser/features/str_preserves_case.out +++ b/modules/gdscript/tests/scripts/parser/features/str_preserves_case.out @@ -1,4 +1,4 @@ GDTEST_OK -null +<null> true false diff --git a/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out index d73c5eb7cd..13f759dd46 100644 --- a/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out +++ b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out @@ -1 +1,5 @@ GDTEST_OK +>> WARNING +>> Line: 6 +>> RETURN_VALUE_DISCARDED +>> The function 'i_return_int()' returns a value, but this value is never used. diff --git a/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd new file mode 100644 index 0000000000..29d8501b78 --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.gd @@ -0,0 +1,11 @@ +class Player: + var x = 3 + +func test(): + # These should not emit a warning. + var _player = Player.new() + print(String.num_uint64(8589934592)) # 2 ^ 33 + + # This should emit a warning. + var some_string = String() + print(some_string.num_uint64(8589934592)) # 2 ^ 33 diff --git a/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out new file mode 100644 index 0000000000..3933a35178 --- /dev/null +++ b/modules/gdscript/tests/scripts/parser/warnings/static_called_on_instance.out @@ -0,0 +1,7 @@ +GDTEST_OK +>> WARNING +>> Line: 11 +>> STATIC_CALLED_ON_INSTANCE +>> The function 'num_uint64()' is a static function but was called from an instance. Instead, it should be directly called from the type: 'String.num_uint64()'. +8589934592 +8589934592 diff --git a/modules/gdscript/tests/scripts/runtime/features/chain_assignment_works.out b/modules/gdscript/tests/scripts/runtime/features/chain_assignment_works.out index 5e7ccf534a..22929bf636 100644 --- a/modules/gdscript/tests/scripts/runtime/features/chain_assignment_works.out +++ b/modules/gdscript/tests/scripts/runtime/features/chain_assignment_works.out @@ -1,6 +1,6 @@ GDTEST_OK -{1:(2, 0)} -{3:(4, 0)} +{ 1: (2, 0) } +{ 3: (4, 0) } [[(5, 0)]] [[(6, 0)]] [[(7, 0)]] diff --git a/modules/gdscript/tests/scripts/runtime/features/stringify.out b/modules/gdscript/tests/scripts/runtime/features/stringify.out index d4468737a5..1f33de00cc 100644 --- a/modules/gdscript/tests/scripts/runtime/features/stringify.out +++ b/modules/gdscript/tests/scripts/runtime/features/stringify.out @@ -21,7 +21,7 @@ hello/world RID(0) Node::get_name Node::[signal]property_list_changed -{"hello":123} +{ "hello": 123 } ["hello", 123] [255, 0, 1] [-1, 0, 1] |