Skip to content

Commit

Permalink
Fix an issue with scoped assignment.
Browse files Browse the repository at this point in the history
- For loop now work as expected
  • Loading branch information
theSalted committed Jul 3, 2024
1 parent 440839f commit 680c8ed
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Sources/Lox/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ public final class Environment {
return
}

if let enclosing {
try enclosing.assign(name: name, value: value)
return
}

throw InterpreterError.runtime(message: "Undefined variable '\(name.lexeme)'.", onLine: name.line, locationDescription: nil)
}
}
8 changes: 8 additions & 0 deletions Sources/Lox/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ public class Parser {
}

private func forStatement() throws -> Statement {
let printer = AbstractSyntaxTreePrinter()

do { try consume(.leftParenthesis) }
catch { throw reportError("Expect '(' after for 'for'.", token: latestToken) }

Expand All @@ -80,6 +82,10 @@ public class Parser {
initializer = try expressionStatement()
}

/*if let initializer {
print("Initializer: ", printer.toPrint(initializer))
}*/

let condition: Expression = matchLatest(.semicolon) ? Literal(value: true) : try expression()
do { try consume(.semicolon) }
catch { throw reportError("Expect ';' after loop condition.", token: latestToken) }
Expand All @@ -100,6 +106,8 @@ public class Parser {
body = Block(statements: [initializer, body])
}

print(printer.toPrint(body))

return body
}

Expand Down

0 comments on commit 680c8ed

Please sign in to comment.