Skip to content

Commit

Permalink
structure loops
Browse files Browse the repository at this point in the history
  • Loading branch information
mathcat4 committed Mar 30, 2022
1 parent ac24529 commit e21b4ce
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 30 deletions.
65 changes: 36 additions & 29 deletions structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,42 +19,49 @@ def __repr__(self):
return f"ForLoop(number={self.number}, body={self.body})"


def helper(string):
# Todo: handle errors
n = 1

for i in range(len(string)):
if string[i] == "(":
n += 1
if string[i] == ")":
n -= 1
if n == 0:
return i


def structure_forLoop(string):
result = []
i = 0

while i < len(string):
h = string[i]

if h == "W":
body = helper(string[3 + i:])
result += [(string[i + 1], helper(string[3 + i:body + 3 + i]))]
i += body + 3
def get_bracket_index(token_list):
balance = 1
index = 0
for index in range(len(token_list)):
if token_list[index].value == "{":
balance += 1
if token_list[index].value == "}":
balance -= 1
if balance == 0:
return index

return index


def structure_forLoop(token_list: list[Token]):
output_lst = []
index = 0
while index < len(token_list):
token = token_list[index]

if token.value == "↹":
bracket_index = get_bracket_index(token_list[3 + index :])
output_lst += [
ForLoop(
token_list[index + 1],
structure_forLoop(
token_list[3 + index : bracket_index + 3 + index]
),
)
]

index += bracket_index + 3
else:
result.append([h])
output_lst.append(token)

i += 1
index += 1

return result
return output_lst


def structure(tokens):
return structure_forLoop(tokens)


if __name__ == "__main__":
print(structure(tokenize("+2 3↹4{¶1} 5")))
print(structure(tokenize("+2 3↹{¶1} 5")))
print(structure(tokenize("2↹4{1↹7{9}}5")))
3 changes: 2 additions & 1 deletion tokenizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ def __init__(self, name: TokenType, value):
self.value = value

def __repr__(self):
return f"Token(name={self.name}, value={repr(self.value)})" # {self.value} for debugging
# return f"Token(name={self.name}, value={repr(self.value)})" # {self.value} for debugging
return f"Token({repr(self.value)})" # {self.value} for debugging


def tokenize(text: str) -> list[Token]:
Expand Down

0 comments on commit e21b4ce

Please sign in to comment.