Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,6 @@ dmypy.json
.pyre/

.direnv/

#PyCharm
.idea
5 changes: 3 additions & 2 deletions godot_parser/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"editable",
]


GDFileType = TypeVar("GDFileType", bound="GDFile")


Expand Down Expand Up @@ -304,7 +303,9 @@ def get_node(self, path: str = ".") -> Optional[GDNodeSection]:
@classmethod
def parse(cls: Type[GDFileType], contents: str) -> GDFileType:
"""Parse the contents of a Godot file"""
return cls.from_parser(scene_file.parse_string(contents, parseAll=True))
return cls.from_parser(
scene_file.parse_with_tabs().parse_string(contents, parse_all=True)
)

@classmethod
def load(cls: Type[GDFileType], filepath: str) -> GDFileType:
Expand Down
119 changes: 118 additions & 1 deletion godot_parser/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
"NodePath",
"ExtResource",
"SubResource",
"StringName",
"TypedArray",
"TypedDictionary",
]

GD_OBJECT_REGISTRY = {}
Expand Down Expand Up @@ -55,7 +58,7 @@ def from_parser(cls: Type[GDObjectType], parse_result) -> GDObjectType:
return factory(*parse_result[1:])

def __str__(self) -> str:
return "%s( %s )" % (
return "%s(%s)" % (
self.name,
", ".join([stringify_object(v) for v in self.args]),
)
Expand All @@ -71,6 +74,9 @@ def __eq__(self, other) -> bool:
def __ne__(self, other) -> bool:
return not self.__eq__(other)

def __hash__(self):
return hash(frozenset((self.name, *self.args)))


class Vector2(GDObject):
def __init__(self, x: float, y: float) -> None:
Expand Down Expand Up @@ -245,3 +251,114 @@ def id(self) -> int:
def id(self, id: int) -> None:
"""Setter for id"""
self.args[0] = id


class TypedArray:
def __init__(self, type, list_) -> None:
self.name = "Array"
self.type = type
self.list_ = list_

@classmethod
def WithCustomName(cls: Type["TypedArray"], name, type, list_) -> "TypedArray":
custom_array = TypedArray(type, list_)
custom_array.name = name
return custom_array

@classmethod
def from_parser(cls: Type["TypedArray"], parse_result) -> "TypedArray":
return TypedArray.WithCustomName(*parse_result)

def __str__(self) -> str:
return "%s[%s](%s)" % (self.name, self.type, stringify_object(self.list_))

def __repr__(self) -> str:
return self.__str__()

def __eq__(self, other) -> bool:
if not isinstance(other, TypedArray):
return False
return (
self.name == other.name
and self.type == other.type
and self.list_ == other.list_
)

def __ne__(self, other) -> bool:
return not self.__eq__(other)

def __hash__(self):
return hash(frozenset((self.name, self.type, self.list_)))


class TypedDictionary:
def __init__(self, key_type, value_type, dict_) -> None:
self.name = "Dictionary"
self.key_type = key_type
self.value_type = value_type
self.dict_ = dict_

@classmethod
def WithCustomName(
cls: Type["TypedDictionary"], name, key_type, value_type, dict_
) -> "TypedDictionary":
custom_dict = TypedDictionary(key_type, value_type, dict_)
custom_dict.name = name
return custom_dict

@classmethod
def from_parser(cls: Type["TypedDictionary"], parse_result) -> "TypedDictionary":
return TypedDictionary.WithCustomName(*parse_result)

def __str__(self) -> str:
return "%s[%s, %s](%s)" % (
self.name,
self.key_type,
self.value_type,
stringify_object(self.dict_),
)

def __repr__(self) -> str:
return self.__str__()

def __eq__(self, other) -> bool:
if not isinstance(other, TypedDictionary):
return False
return (
self.name == other.name
and self.key_type == other.key_type
and self.value_type == other.value_type
and self.dict_ == other.dict_
)

def __ne__(self, other) -> bool:
return not self.__eq__(other)

def __hash__(self):
return hash(frozenset((self.name, self.key_type, self.value_type, self.dict_)))


class StringName:
def __init__(self, str) -> None:
self.str = str

@classmethod
def from_parser(cls: Type["StringName"], parse_result) -> "StringName":
return StringName(parse_result[0])

def __str__(self) -> str:
return "&" + stringify_object(self.str)

def __repr__(self) -> str:
return self.__str__()

def __eq__(self, other) -> bool:
if not isinstance(other, StringName):
return False
return self.str == other.str

def __ne__(self, other) -> bool:
return not self.__eq__(other)

def __hash__(self):
return hash(self.str)
3 changes: 1 addition & 2 deletions godot_parser/sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
"GDResourceSection",
]


GD_SECTION_REGISTRY = {}


Expand Down Expand Up @@ -137,7 +136,7 @@ def __str__(self) -> str:
if self.properties:
ret += "\n" + "\n".join(
[
"%s = %s" % (k, stringify_object(v))
"%s = %s" % ('"' + k + '"' if " " in k else k, stringify_object(v))
for k, v in self.properties.items()
]
)
Expand Down
9 changes: 7 additions & 2 deletions godot_parser/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,20 @@ def stringify_object(value):
elif isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, dict):
if len(value) == 0:
return "{}"
return (
"{\n"
+ ",\n".join(
['"%s": %s' % (k, stringify_object(v)) for k, v in value.items()]
[
"%s: %s" % (stringify_object(k), stringify_object(v))
for k, v in value.items()
]
)
+ "\n}"
)
elif isinstance(value, list):
return "[ " + ", ".join([stringify_object(v) for v in value]) + " ]"
return "[" + ", ".join([stringify_object(v) for v in value]) + "]"
else:
return str(value)

Expand Down
48 changes: 41 additions & 7 deletions godot_parser/values.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
common,
)

from .objects import GDObject
from .objects import GDObject, StringName, TypedArray, TypedDictionary

boolean = (
(Keyword("true") | Keyword("false"))
Expand All @@ -24,20 +24,27 @@

null = Keyword("null").set_parse_action(lambda _: [None])

_string = QuotedString('"', escChar="\\", multiline=True).set_name("string")

primitive = (
null | QuotedString('"', escChar="\\", multiline=True) | boolean | common.number
_string_name = (
(Suppress("&") + _string)
.set_name("string_name")
.set_parse_action(StringName.from_parser)
)

primitive = null | _string | _string_name | boolean | common.number
value = Forward()

# Vector2( 1, 2 )
obj_type = (
obj_ = (
Word(alphas, alphanums).set_results_name("object_name")
+ Suppress("(")
+ DelimitedList(value)
+ Opt(DelimitedList(value))
+ Suppress(")")
).set_parse_action(GDObject.from_parser)

obj_type = obj_ | Word(alphas, alphanums)

# [ 1, 2 ] or [ 1, 2, ]
list_ = (
Group(
Expand All @@ -46,7 +53,17 @@
.set_name("list")
.set_parse_action(lambda p: p.as_list())
)
key_val = Group(QuotedString('"', escChar="\\") + Suppress(":") + value)

# Array[StringName]([&"a", &"b", &"c"])
typed_list = (
Word(alphas, alphanums).set_results_name("object_name")
+ (Suppress("[") + obj_type.set_results_name("type") + Suppress("]"))
+ Suppress("(")
+ list_
+ Suppress(")")
).set_parse_action(TypedArray.from_parser)

key_val = Group(value + Suppress(":") + value)

# {
# "_edit_use_anchors_": false
Expand All @@ -57,6 +74,23 @@
.set_parse_action(lambda d: {k: v for k, v in d})
)

# Dictionary[StringName,ExtResource("1_qwert")]({
# &"_edit_use_anchors_": ExtResource("2_testt")
# })
typed_dict = (
Word(alphas, alphanums).set_results_name("object_name")
+ (
Suppress("[")
+ obj_type.set_results_name("key_type")
+ Suppress(",")
+ obj_type.set_results_name("value_type")
+ Suppress("]")
)
+ Suppress("(")
+ dict_
+ Suppress(")")
).set_parse_action(TypedDictionary.from_parser)

# Exports

value <<= primitive | list_ | dict_ | obj_type
value <<= list_ | typed_list | dict_ | typed_dict | obj_ | primitive
4 changes: 2 additions & 2 deletions tests/test_gdfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ def test_all_data_types(self):
"""[gd_resource load_steps=1 format=2]

[resource]
list = [ 1, 2.0, "string" ]
list = [1, 2.0, "string"]
map = {
"key": [ "nested", Vector2( 1, 1 ) ]
"key": ["nested", Vector2(1, 1)]
}
empty = null
escaped = "foo(\\"bar\\")"
Expand Down
Loading