also looking at this
fix(types): give catch clauses the enclosing scope as their parent
#933
2 files
+31
-7
| @@ -2254,16 +2254,20 @@ pub const TypeChecker = struct { | ||
| 2254 | 2254 | for (try_stmt.catch_clauses) |catch_clause| { |
| 2255 | 2255 | // Create new scope for error variable if present |
| 2256 | 2256 | if (catch_clause.error_name) |error_name| { |
| 2257 | const saved_env = try self.allocator.create(TypeEnvironment); | |
| 2258 | saved_env.* = self.env; | |
| 2259 | ||
| 2257 | 2260 | var catch_env = TypeEnvironment.init(self.allocator); |
| 2258 | catch_env.parent = &self.env; | |
| 2259 | defer catch_env.deinit(); | |
| 2261 | catch_env.parent = saved_env; | |
| 2262 | self.env = catch_env; | |
| 2263 | defer { | |
| 2264 | self.env.deinit(); | |
| 2265 | self.env = saved_env.*; | |
| 2266 | self.allocator.destroy(saved_env); | |
| 2267 | } | |
| 2260 | 2268 | |
| 2261 | 2269 | // Define error variable (type is string for now) |
| 2262 | try catch_env.define(error_name, Type.String); | |
| 2263 | ||
| 2264 | const saved_env = self.env; | |
| 2265 | self.env = catch_env; | |
| 2266 | defer self.env = saved_env; | |
| 2270 | try self.env.define(error_name, Type.String); | |
| 2267 | 2271 | |
| 2268 | 2272 | for (catch_clause.body.statements) |catch_body_stmt| { |
| 2269 | 2273 | self.checkStatement(catch_body_stmt) catch |err| { |
| @@ -886,3 +886,23 @@ test "checker rejects missing static methods" { | ||
| 886 | 886 | \\} |
| 887 | 887 | )); |
| 888 | 888 | } |
| 889 | ||
| 890 | test "checker resolves enclosing variables inside a catch clause" { | |
| 891 | try std.testing.expect(try checkSource( | |
| 892 | \\fn run() { | |
| 893 | \\ let x = 1 | |
| 894 | \\ try { | |
| 895 | \\ } catch (e) { | |
| 896 | \\ let y = x | |
| 897 | \\ } | |
| 898 | \\} | |
| 899 | )); | |
| 900 | try std.testing.expect(try checkSourceErrorContains( | |
| 901 | \\fn run() { | |
| 902 | \\ try { | |
| 903 | \\ } catch (e) { | |
| 904 | \\ let y = missing | |
| 905 | \\ } | |
| 906 | \\} | |
| 907 | , "Undefined variable")); | |
| 908 | } | |