Skip to content

Commit ee643e0

Browse files
committed
fix #72: Incorrectly parsing strings
1 parent cef7320 commit ee643e0

File tree

2 files changed

+30
-10
lines changed

2 files changed

+30
-10
lines changed

luaparser/builder.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
TNode = TypeVar("TNode", bound=Node)
1616

1717

18+
LUA_DOUBLE_SQUARE_RE = re.compile(r'^\[(?P<eq>=*)\[(?P<body>[\s\S]*?)\]\1\]$')
19+
1820
def _listify(obj):
1921
if not isinstance(obj, list):
2022
return [obj]
@@ -643,22 +645,19 @@ def visitString(self, ctx: LuaParser.StringContext):
643645
lua_str = ctx.getText()
644646

645647
delimiter: StringDelimiter = StringDelimiter.SINGLE_QUOTE
646-
p = re.compile(r"^\[=+\[(.*)]=+]") # nested quote pattern
647-
# try remove double quote:
648+
649+
# try to remove double quote:
648650
if lua_str.startswith('"') and lua_str.endswith('"'):
649651
lua_str = lua_str[1:-1]
650652
delimiter = StringDelimiter.DOUBLE_QUOTE
651-
# try remove single quote:
653+
# try to remove single quote:
652654
elif lua_str.startswith("'") and lua_str.endswith("'"):
653655
lua_str = lua_str[1:-1]
654656
delimiter = StringDelimiter.SINGLE_QUOTE
655-
# try remove double square bracket:
656-
elif lua_str.startswith("[[") and lua_str.endswith("]]"):
657-
lua_str = lua_str[2:-2]
657+
# double square brackets notation:
658+
elif m := LUA_DOUBLE_SQUARE_RE.match(lua_str):
659+
lua_str = m.group("body")
658660
delimiter = StringDelimiter.DOUBLE_SQUARE
659-
# nested quote
660-
elif p.match(lua_str):
661-
lua_str = p.search(lua_str).group(1)
662661

663662
if delimiter == StringDelimiter.DOUBLE_QUOTE or delimiter == StringDelimiter.SINGLE_QUOTE:
664663
unescaped_str = unescape_lua_string(lua_str)

luaparser/tests/test_types_values.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,28 @@ def test_string_dbl_square(self):
136136
def test_string_dbl_square_equal(self):
137137
tree = ast.parse(r"b = [=[one [[two]] one]=]")
138138
exp = Chunk(
139-
Block([Assign(targets=[Name("b")], values=[String(b"one [[two]] one", "one [[two]] one")])])
139+
Block([Assign(targets=[Name("b")], values=[String(b"one [[two]] one", "one [[two]] one", delimiter=StringDelimiter.DOUBLE_SQUARE)])])
140+
)
141+
self.assertEqual(exp, tree)
142+
143+
def test_string_dbl_square_equal_newlines(self):
144+
tree = ast.parse(
145+
textwrap.dedent(
146+
r"""
147+
a = [=[
148+
four
149+
]=]
150+
b = [===[
151+
five
152+
]===]
153+
"""
154+
)
155+
)
156+
exp = Chunk(
157+
Block([
158+
Assign(targets=[Name("a")], values=[String(b"\nfour\n", "\nfour\n", delimiter=StringDelimiter.DOUBLE_SQUARE)]),
159+
Assign(targets=[Name("b")], values=[String(b"\nfive\n", "\nfive\n", delimiter=StringDelimiter.DOUBLE_SQUARE)]),
160+
])
140161
)
141162
self.assertEqual(exp, tree)
142163

0 commit comments

Comments
 (0)