feat: Implement while loops

This commit is contained in:
Alvin
2025-07-22 16:22:49 +02:00
parent f3e4be5949
commit 65e53daa66
4 changed files with 40 additions and 1 deletions

5
examples/loops.fem Normal file
View File

@@ -0,0 +1,5 @@
counter is 0
Otokonoko counter < 5 Femboycore
UwU Boy counter
counter is counter + 1
Periodt

View File

@@ -75,3 +75,7 @@ class Interpreter:
self.visit(node.if_block) self.visit(node.if_block)
elif node.else_block: elif node.else_block:
self.visit(node.else_block) self.visit(node.else_block)
def visit_WhileStatement(self, node):
while self.visit(node.condition):
self.visit(node.body)

View File

@@ -90,6 +90,9 @@ class Lexer:
if re.match(r'\bAndrogyny\b', self.text[self.pos:]): if re.match(r'\bAndrogyny\b', self.text[self.pos:]):
self.pos += len('Androgyny') self.pos += len('Androgyny')
return Token('ANDROGYNY', 'Androgyny') return Token('ANDROGYNY', 'Androgyny')
if re.match(r'\bOtokonoko\b', self.text[self.pos:]):
self.pos += len('Otokonoko')
return Token('OTOKONOKO', 'Otokonoko')
if re.match(r'\bis\b', self.text[self.pos:]): if re.match(r'\bis\b', self.text[self.pos:]):
self.pos += 2 self.pos += 2
return Token('ASSIGN', 'is') return Token('ASSIGN', 'is')

View File

@@ -48,6 +48,11 @@ class IfStatement(AST):
self.if_block = if_block self.if_block = if_block
self.else_block = else_block self.else_block = else_block
class WhileStatement(AST):
def __init__(self, condition, body):
self.condition = condition
self.body = body
class Parser: class Parser:
def __init__(self, tokens): def __init__(self, tokens):
self.tokens = tokens self.tokens = tokens
@@ -83,6 +88,9 @@ class Parser:
if token.type == 'FEMBOY_FEMININE': if token.type == 'FEMBOY_FEMININE':
return self.parse_if_statement() return self.parse_if_statement()
if token.type == 'OTOKONOKO':
return self.parse_while_statement()
raise Exception(f"Invalid statement starting with token {token.type}") raise Exception(f"Invalid statement starting with token {token.type}")
def parse_print_statement(self): def parse_print_statement(self):
@@ -135,6 +143,25 @@ class Parser:
return IfStatement(condition, if_block, else_block) return IfStatement(condition, if_block, else_block)
def parse_while_statement(self):
self.get_next_token() # Consume OTOKONOKO
condition = self.expression()
if self.peek_next_token().type != 'FEMBOYCORE':
raise Exception("Expected 'Femboycore' to start while loop body")
self.get_next_token() # Consume FEMBOYCORE
body_statements = []
while self.peek_next_token().type != 'PERIODT':
if self.peek_next_token().type == 'EOF':
raise Exception("Unterminated while loop: Expected 'Periodt'")
body_statements.append(self.parse_statement())
self.get_next_token() # Consume PERIODT
body = Block(body_statements)
return WhileStatement(condition, body)
def factor(self): def factor(self):
token = self.get_next_token() token = self.get_next_token()
if token.type == 'INTEGER': if token.type == 'INTEGER':