Compiler/AST interpreter: Difference between revisions

m
Added ;Task
m (Added ;Task)
 
(6 intermediate revisions by 5 users not shown)
Line 1:
{{task}}{{task heading|AST interpreter}}
 
An AST interpreter interprets an [https://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree (AST)]
produced by a [[Compiler/syntax_analyzer|Syntax Analyzer]].
 
;Task
{{task heading}}
 
Take the AST output from the Syntax analyzer [[Compiler/syntax_analyzer|task]], and interpret it as appropriate.
Line 1,624:
Code by Steve Williams. Tested with GnuCOBOL 2.2.
 
<syntaxhighlight lang="cobolcobolfree"> >>SOURCE FORMAT IS FREE
identification division.
*> this code is dedicated to the public domain
Line 6,822:
{{libheader|Wren-fmt}}
{{libheader|Wren-ioutil}}
<syntaxhighlight lang="ecmascriptwren">import "./dynamic" for Enum, Struct, Tuple
import "./fmt" for Conv
import "./ioutil" for FileUtil
 
var nodes = [
Line 7,074:
Total primes found: 26
</pre>
 
{{works with|Zig|0.11.0}}
To simplify memory allocation management <tt>std.heap.ArenaAllocator</tt> is used in the code below. This allows all an arena's allocations to be freed together with a single call to arena.deinit()
 
=={{header|Zig}}==
Line 7,142 ⟶ 7,145:
.prts => _ = try self.out("{s}", .{(try self.interp(t.left)).?.string}),
.prti => _ = try self.out("{d}", .{(try self.interp(t.left)).?.integer}),
.prtc => _ = try self.out("{c}", .{@intCastas(u8, @intCast((try self.interp(t.left)).?.integer))}),
.string => return t.value,
.integer => return t.value,
Line 7,161 ⟶ 7,164:
fn binOp(
self: *Self,
comptime func: fn (a: i32, b: i32) i32,
a: ?*Tree,
b: ?*Tree,
Line 7,172 ⟶ 7,175:
 
fn less(a: i32, b: i32) i32 {
return @boolToIntintFromBool(a < b);
}
fn less_equal(a: i32, b: i32) i32 {
return @boolToIntintFromBool(a <= b);
}
fn greater(a: i32, b: i32) i32 {
return @boolToIntintFromBool(a > b);
}
fn greater_equal(a: i32, b: i32) i32 {
return @boolToIntintFromBool(a >= b);
}
fn equal(a: i32, b: i32) i32 {
return @boolToIntintFromBool(a == b);
}
fn not_equal(a: i32, b: i32) i32 {
return @boolToIntintFromBool(a != b);
}
fn add(a: i32, b: i32) i32 {
Line 7,205 ⟶ 7,208:
}
fn @"or"(a: i32, b: i32) i32 {
return @boolToIntintFromBool((a != 0) or (b != 0));
}
fn @"and"(a: i32, b: i32) i32 {
return @boolToIntintFromBool((a != 0) and (b != 0));
}
};
Line 7,217 ⟶ 7,220:
const allocator = arena.allocator();
 
var arg_it = try std.process.argsargsWithAllocator(allocator);
_ = try arg_it.next(allocator) orelse unreachable; // program name
const file_name = arg_it.next(allocator);
// We accept both files and standard input.
var file_handle = blk: {
if (file_name) |file_name_delimited| {
const fname: []const u8 = try file_name_delimited;
break :blk try std.fs.cwd().openFile(fname, .{});
} else {
Line 7,339 ⟶ 7,342:
fn loadASTHelper(
allocator: std.mem.Allocator,
line_it: *std.mem.SplitIterator(u8, std.mem.DelimiterType.sequence),
string_pool: *std.ArrayList([]const u8),
) LoadASTError!?*Tree {
3,049

edits