air: data model, text parser and canonical serializer (P0-4, P0-5, P0-6)
- src/air/module.zig: types, values, instructions, blocks, functions - src/air/parse.zig: lexer and parser for text AIR format 0 with name resolution; reports E0001-E0006, E5001 (undefined/double definition), E5002 (unknown block label) - src/air/print.zig: canonical serializer (spec 07 §8.5) with a deterministic round-trip fuzz test - diag registry: E0xxx, E1003, T0xxx
This commit is contained in:
1 parent
41b764ccfd
commit
ef6a2c5475
5 files changed
+1636
-9
No files matched your search
@@ -0,0 +1,273 @@
|
||||
//! AIR data model, format version 0 (spec 07 §8, spec 07a).
|
||||
//!
|
||||
//! A `Module` is produced by `parse.zig` with all names resolved to indices.
|
||||
//! Every slice is owned by the arena the module was parsed into.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
pub const format_version: u32 = 0;
|
||||
pub const lang_version: [2]u32 = .{ 0, 1 };
|
||||
|
||||
pub const Span = struct {
|
||||
/// 1-based.
|
||||
line: u32,
|
||||
/// 1-based, in bytes.
|
||||
col: u32,
|
||||
};
|
||||
|
||||
pub const IntType = enum {
|
||||
u8,
|
||||
u16,
|
||||
u32,
|
||||
u64,
|
||||
u128,
|
||||
usize,
|
||||
i8,
|
||||
i16,
|
||||
i32,
|
||||
i64,
|
||||
i128,
|
||||
isize,
|
||||
|
||||
/// Width under the `air64` target description (spec 09 §9).
|
||||
pub fn bits(t: IntType) u8 {
|
||||
return switch (t) {
|
||||
.u8, .i8 => 8,
|
||||
.u16, .i16 => 16,
|
||||
.u32, .i32 => 32,
|
||||
.u64, .i64, .usize, .isize => 64,
|
||||
.u128, .i128 => 128,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn signed(t: IntType) bool {
|
||||
return switch (t) {
|
||||
.i8, .i16, .i32, .i64, .i128, .isize => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn pointerSized(t: IntType) bool {
|
||||
return t == .usize or t == .isize;
|
||||
}
|
||||
|
||||
/// Host integer type used by the interpreter under `air64`.
|
||||
pub fn Zig(comptime t: IntType) type {
|
||||
return @Int(if (t.signed()) .signed else .unsigned, t.bits());
|
||||
}
|
||||
};
|
||||
|
||||
pub const Type = union(enum) {
|
||||
int: IntType,
|
||||
bool,
|
||||
void,
|
||||
never,
|
||||
/// Index into `Module.types`.
|
||||
named: u32,
|
||||
|
||||
pub fn eql(a: Type, b: Type) bool {
|
||||
return switch (a) {
|
||||
.int => |x| b == .int and b.int == x,
|
||||
.named => |x| b == .named and b.named == x,
|
||||
else => std.meta.activeTag(a) == std.meta.activeTag(b),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Field = struct {
|
||||
name: []const u8,
|
||||
ty: Type,
|
||||
};
|
||||
|
||||
pub const Variant = struct {
|
||||
name: []const u8,
|
||||
payload: []const Type,
|
||||
};
|
||||
|
||||
pub const TypeDecl = struct {
|
||||
name: []const u8,
|
||||
span: Span,
|
||||
kind: union(enum) {
|
||||
@"struct": []const Field,
|
||||
@"enum": []const Variant,
|
||||
},
|
||||
|
||||
pub fn fieldIndex(d: TypeDecl, name: []const u8) ?u32 {
|
||||
for (d.kind.@"struct", 0..) |f, i| if (std.mem.eql(u8, f.name, name)) return @intCast(i);
|
||||
return null;
|
||||
}
|
||||
|
||||
pub fn variantIndex(d: TypeDecl, name: []const u8) ?u32 {
|
||||
for (d.kind.@"enum", 0..) |v, i| if (std.mem.eql(u8, v.name, name)) return @intCast(i);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/// Index into `Function.values`.
|
||||
pub const ValueId = u32;
|
||||
|
||||
pub const ValueInfo = struct {
|
||||
name: []const u8,
|
||||
/// Location of the definition, or of the first use if never defined.
|
||||
span: Span,
|
||||
def: Def,
|
||||
|
||||
pub const Def = union(enum) {
|
||||
none,
|
||||
param: u32,
|
||||
block_param: struct { block: u32, index: u32 },
|
||||
inst: struct { block: u32, index: u32 },
|
||||
};
|
||||
};
|
||||
|
||||
pub const Param = struct {
|
||||
value: ValueId,
|
||||
ty: Type,
|
||||
};
|
||||
|
||||
pub const Target = struct {
|
||||
block: u32,
|
||||
args: []const ValueId,
|
||||
};
|
||||
|
||||
pub const ArithOp = enum { add, sub, mul, div, rem };
|
||||
pub const ArithMode = enum { checked, wrap };
|
||||
pub const BitOp = enum { @"and", @"or", xor, shl, shr };
|
||||
pub const CmpOp = enum { eq, ne, lt, le, gt, ge };
|
||||
pub const CastMode = enum { checked, wrap, widen };
|
||||
|
||||
pub const Op = union(enum) {
|
||||
@"const": struct { ty: Type, bits: u128 },
|
||||
copy: ValueId,
|
||||
arith: struct { op: ArithOp, mode: ArithMode, ty: IntType, a: ValueId, b: ValueId },
|
||||
bit: struct { op: BitOp, ty: Type, a: ValueId, b: ValueId },
|
||||
cmp: struct { op: CmpOp, ty: Type, a: ValueId, b: ValueId },
|
||||
cast: struct { mode: CastMode, to: IntType, a: ValueId },
|
||||
assert: ValueId,
|
||||
struct_make: struct { decl: u32, args: []const ValueId },
|
||||
struct_get: struct { decl: u32, field: u32, a: ValueId },
|
||||
enum_make: struct { decl: u32, variant: u32, args: []const ValueId },
|
||||
call: struct { callee: u32, args: []const ValueId },
|
||||
// Terminators.
|
||||
br: Target,
|
||||
cbr: struct { cond: ValueId, then: Target, @"else": Target },
|
||||
@"switch": struct { ty: IntType, value: ValueId, cases: []const Case, default: Target },
|
||||
enum_switch: struct { decl: u32, value: ValueId, arms: []const Arm, default: ?Target },
|
||||
ret: ?ValueId,
|
||||
trap,
|
||||
|
||||
pub const Case = struct { bits: u128, target: Target, span: Span };
|
||||
pub const Arm = struct { variant: u32, block: u32, span: Span };
|
||||
|
||||
pub fn isTerminator(op: Op) bool {
|
||||
return switch (op) {
|
||||
.br, .cbr, .@"switch", .enum_switch, .ret, .trap => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Inst = struct {
|
||||
result: ?ValueId,
|
||||
op: Op,
|
||||
span: Span,
|
||||
};
|
||||
|
||||
pub const Block = struct {
|
||||
name: []const u8,
|
||||
span: Span,
|
||||
params: []const Param,
|
||||
insts: []const Inst,
|
||||
};
|
||||
|
||||
pub const Function = struct {
|
||||
name: []const u8,
|
||||
span: Span,
|
||||
params: []const Param,
|
||||
ret: Type,
|
||||
effects: []const []const u8,
|
||||
blocks: []const Block,
|
||||
values: []const ValueInfo,
|
||||
};
|
||||
|
||||
pub const Module = struct {
|
||||
name: []const u8,
|
||||
format_version: u32,
|
||||
lang: [2]u32,
|
||||
features: []const []const u8,
|
||||
types: []const TypeDecl,
|
||||
functions: []const Function,
|
||||
|
||||
pub fn functionIndex(m: Module, name: []const u8) ?u32 {
|
||||
for (m.functions, 0..) |f, i| if (std.mem.eql(u8, f.name, name)) return @intCast(i);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/// Operands read by an instruction, in source order. Block-argument operands
|
||||
/// of terminators are included.
|
||||
pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) void) void {
|
||||
switch (op) {
|
||||
.@"const", .trap => {},
|
||||
.copy, .assert => |v| f(ctx, v),
|
||||
.arith => |x| {
|
||||
f(ctx, x.a);
|
||||
f(ctx, x.b);
|
||||
},
|
||||
.bit => |x| {
|
||||
f(ctx, x.a);
|
||||
f(ctx, x.b);
|
||||
},
|
||||
.cmp => |x| {
|
||||
f(ctx, x.a);
|
||||
f(ctx, x.b);
|
||||
},
|
||||
.cast => |x| f(ctx, x.a),
|
||||
.struct_make => |x| for (x.args) |v| f(ctx, v),
|
||||
.struct_get => |x| f(ctx, x.a),
|
||||
.enum_make => |x| for (x.args) |v| f(ctx, v),
|
||||
.call => |x| for (x.args) |v| f(ctx, v),
|
||||
.br => |t| for (t.args) |v| f(ctx, v),
|
||||
.cbr => |x| {
|
||||
f(ctx, x.cond);
|
||||
for (x.then.args) |v| f(ctx, v);
|
||||
for (x.@"else".args) |v| f(ctx, v);
|
||||
},
|
||||
.@"switch" => |x| {
|
||||
f(ctx, x.value);
|
||||
for (x.cases) |c| for (c.target.args) |v| f(ctx, v);
|
||||
for (x.default.args) |v| f(ctx, v);
|
||||
},
|
||||
.enum_switch => |x| {
|
||||
f(ctx, x.value);
|
||||
if (x.default) |d| for (d.args) |v| f(ctx, v);
|
||||
},
|
||||
.ret => |v| if (v) |x| f(ctx, x),
|
||||
}
|
||||
}
|
||||
|
||||
/// Successor block indices of a terminator, in source order (may repeat).
|
||||
pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !void {
|
||||
switch (op) {
|
||||
.br => |t| try buf.append(gpa, t.block),
|
||||
.cbr => |x| {
|
||||
try buf.append(gpa, x.then.block);
|
||||
try buf.append(gpa, x.@"else".block);
|
||||
},
|
||||
.@"switch" => |x| {
|
||||
for (x.cases) |c| try buf.append(gpa, c.target.block);
|
||||
try buf.append(gpa, x.default.block);
|
||||
},
|
||||
.enum_switch => |x| {
|
||||
for (x.arms) |a| try buf.append(gpa, a.block);
|
||||
if (x.default) |d| try buf.append(gpa, d.block);
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
test "IntType host types" {
|
||||
try std.testing.expect(IntType.Zig(.i8) == i8);
|
||||
try std.testing.expect(IntType.Zig(.usize) == u64);
|
||||
try std.testing.expectEqual(@as(u8, 128), IntType.u128.bits());
|
||||
}
|
||||
@@ -0,0 +1,975 @@
|
||||
//! Text AIR lexer and parser, format version 0 (reference/air-text.ebnf).
|
||||
//!
|
||||
//! Parsing also resolves names. Resolution failures are reported with the
|
||||
//! semantic code of the rule they break (spec 07 §8.2):
|
||||
//! undefined or doubly defined value -> E5001, unknown block label -> E5002,
|
||||
//! unknown type/function/field/variant/opcode -> E0004, duplicates -> E0003.
|
||||
//! Syntax errors (E0001) stop parsing; all other errors are collected.
|
||||
|
||||
const std = @import("std");
|
||||
const diag = @import("../diag.zig");
|
||||
const air = @import("module.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const Span = air.Span;
|
||||
|
||||
pub const Result = struct {
|
||||
/// Present when parsing reached the end of input. It is only meaningful
|
||||
/// for verification if `diagnostics` is empty.
|
||||
module: ?air.Module,
|
||||
diagnostics: []const diag.Diagnostic,
|
||||
};
|
||||
|
||||
pub fn parse(arena: Allocator, file: []const u8, source: []const u8) Allocator.Error!Result {
|
||||
var p: Parser = .{
|
||||
.arena = arena,
|
||||
.file = file,
|
||||
.tokens = try tokenize(arena, source),
|
||||
};
|
||||
const module = p.parseModule() catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
error.SyntaxError => null,
|
||||
};
|
||||
return .{ .module = module, .diagnostics = p.diags.items };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- lexer
|
||||
|
||||
const Tag = enum {
|
||||
nl,
|
||||
comma,
|
||||
colon,
|
||||
dot,
|
||||
equals,
|
||||
arrow,
|
||||
l_paren,
|
||||
r_paren,
|
||||
l_bracket,
|
||||
r_bracket,
|
||||
l_brace,
|
||||
r_brace,
|
||||
/// Identifier, possibly dotted: opcodes, keywords, types, paths.
|
||||
word,
|
||||
/// `%name`; text excludes the sigil.
|
||||
local,
|
||||
/// `@name`; text excludes the sigil.
|
||||
global,
|
||||
/// Raw numeric text, including an optional leading `-` and any `.`.
|
||||
number,
|
||||
invalid,
|
||||
eof,
|
||||
};
|
||||
|
||||
const Token = struct {
|
||||
tag: Tag,
|
||||
text: []const u8,
|
||||
span: Span,
|
||||
};
|
||||
|
||||
fn isNameChar(c: u8) bool {
|
||||
return std.ascii.isAlphanumeric(c) or c == '_';
|
||||
}
|
||||
|
||||
fn tokenize(arena: Allocator, src: []const u8) Allocator.Error![]const Token {
|
||||
var tokens: std.ArrayList(Token) = .empty;
|
||||
var i: usize = 0;
|
||||
var line: u32 = 1;
|
||||
var line_start: usize = 0;
|
||||
var depth: u32 = 0; // bracket nesting; newlines inside brackets are ignored
|
||||
while (true) {
|
||||
while (i < src.len and (src[i] == ' ' or src[i] == '\t' or src[i] == '\r')) i += 1;
|
||||
const span: Span = .{ .line = line, .col = @intCast(i - line_start + 1) };
|
||||
if (i >= src.len) {
|
||||
try tokens.append(arena, .{ .tag = .nl, .text = "", .span = span });
|
||||
try tokens.append(arena, .{ .tag = .eof, .text = "", .span = span });
|
||||
return tokens.items;
|
||||
}
|
||||
const start = i;
|
||||
const c = src[i];
|
||||
var tag: Tag = .invalid;
|
||||
switch (c) {
|
||||
';' => {
|
||||
while (i < src.len and src[i] != '\n') i += 1;
|
||||
continue;
|
||||
},
|
||||
'\n' => {
|
||||
i += 1;
|
||||
line += 1;
|
||||
line_start = i;
|
||||
if (depth > 0) continue;
|
||||
tag = .nl;
|
||||
},
|
||||
',' => {
|
||||
i += 1;
|
||||
tag = .comma;
|
||||
},
|
||||
':' => {
|
||||
i += 1;
|
||||
tag = .colon;
|
||||
},
|
||||
'.' => {
|
||||
i += 1;
|
||||
tag = .dot;
|
||||
},
|
||||
'=' => {
|
||||
i += 1;
|
||||
tag = .equals;
|
||||
},
|
||||
'(', '[', '{' => {
|
||||
i += 1;
|
||||
depth += 1;
|
||||
tag = switch (c) {
|
||||
'(' => .l_paren,
|
||||
'[' => .l_bracket,
|
||||
else => .l_brace,
|
||||
};
|
||||
},
|
||||
')', ']', '}' => {
|
||||
i += 1;
|
||||
depth -|= 1;
|
||||
tag = switch (c) {
|
||||
')' => .r_paren,
|
||||
']' => .r_bracket,
|
||||
else => .r_brace,
|
||||
};
|
||||
},
|
||||
'%', '@' => {
|
||||
i += 1;
|
||||
while (i < src.len and isNameChar(src[i])) i += 1;
|
||||
if (i == start + 1) {
|
||||
tag = .invalid;
|
||||
} else {
|
||||
try tokens.append(arena, .{ .tag = if (c == '%') .local else .global, .text = src[start + 1 .. i], .span = span });
|
||||
continue;
|
||||
}
|
||||
},
|
||||
'-' => {
|
||||
i += 1;
|
||||
if (i < src.len and src[i] == '>') {
|
||||
i += 1;
|
||||
tag = .arrow;
|
||||
} else if (i < src.len and std.ascii.isDigit(src[i])) {
|
||||
while (i < src.len and (isNameChar(src[i]) or src[i] == '.')) i += 1;
|
||||
tag = .number;
|
||||
}
|
||||
},
|
||||
else => {
|
||||
if (std.ascii.isDigit(c)) {
|
||||
while (i < src.len and (isNameChar(src[i]) or src[i] == '.')) i += 1;
|
||||
tag = .number;
|
||||
} else if (std.ascii.isAlphabetic(c) or c == '_') {
|
||||
while (i < src.len and (isNameChar(src[i]) or src[i] == '.')) i += 1;
|
||||
tag = .word;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
},
|
||||
}
|
||||
try tokens.append(arena, .{ .tag = tag, .text = src[start..i], .span = span });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- parser
|
||||
|
||||
const Error = error{ SyntaxError, OutOfMemory };
|
||||
|
||||
const Parser = struct {
|
||||
arena: Allocator,
|
||||
file: []const u8,
|
||||
tokens: []const Token,
|
||||
pos: usize = 0,
|
||||
diags: std.ArrayList(diag.Diagnostic) = .empty,
|
||||
|
||||
// Module-level names, collected by a pre-scan so that forward references work.
|
||||
type_names: std.ArrayList([]const u8) = .empty,
|
||||
fn_names: std.ArrayList([]const u8) = .empty,
|
||||
types: []air.TypeDecl = &.{},
|
||||
|
||||
// Function-level state.
|
||||
fn_name: []const u8 = "",
|
||||
block_names: std.ArrayList([]const u8) = .empty,
|
||||
values: std.ArrayList(air.ValueInfo) = .empty,
|
||||
value_map: std.StringHashMapUnmanaged(air.ValueId) = .empty,
|
||||
|
||||
fn peek(p: *Parser) Token {
|
||||
return p.tokens[p.pos];
|
||||
}
|
||||
|
||||
fn peekAt(p: *Parser, offset: usize) Token {
|
||||
return p.tokens[@min(p.pos + offset, p.tokens.len - 1)];
|
||||
}
|
||||
|
||||
fn next(p: *Parser) Token {
|
||||
const t = p.tokens[p.pos];
|
||||
if (t.tag != .eof) p.pos += 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
fn atWord(p: *Parser, text: []const u8) bool {
|
||||
const t = p.peek();
|
||||
return t.tag == .word and std.mem.eql(u8, t.text, text);
|
||||
}
|
||||
|
||||
fn report(p: *Parser, id: []const u8, span: Span, message: []const u8, fields: []const diag.Field) Allocator.Error!void {
|
||||
try p.diags.append(p.arena, .{
|
||||
.code = diag.lookup(id).?,
|
||||
.span = .{ .file = p.file, .line = span.line, .col = span.col },
|
||||
.message = message,
|
||||
.fields = try p.arena.dupe(diag.Field, fields),
|
||||
});
|
||||
}
|
||||
|
||||
fn fail(p: *Parser, t: Token, expected: []const u8) Error {
|
||||
try p.report("E0001", t.span, try std.fmt.allocPrint(p.arena, "expected {s}", .{expected}), &.{
|
||||
.{ .name = "expected", .value = .{ .str = expected } },
|
||||
.{ .name = "found", .value = .{ .str = describe(t) } },
|
||||
});
|
||||
return error.SyntaxError;
|
||||
}
|
||||
|
||||
fn expect(p: *Parser, tag: Tag, what: []const u8) Error!Token {
|
||||
const t = p.peek();
|
||||
if (t.tag != tag) return p.fail(t, what);
|
||||
return p.next();
|
||||
}
|
||||
|
||||
fn expectWord(p: *Parser, text: []const u8) Error!Token {
|
||||
if (!p.atWord(text)) return p.fail(p.peek(), text);
|
||||
return p.next();
|
||||
}
|
||||
|
||||
fn skipNewlines(p: *Parser) void {
|
||||
while (p.peek().tag == .nl) _ = p.next();
|
||||
}
|
||||
|
||||
fn atLineStartKeyword(p: *Parser) bool {
|
||||
return p.atWord("fn") or p.atWord("type") or p.peek().tag == .eof;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ module
|
||||
|
||||
fn parseModule(p: *Parser) Error!air.Module {
|
||||
p.skipNewlines();
|
||||
_ = try p.expectWord("module");
|
||||
const name = try p.parsePath();
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
|
||||
_ = try p.expectWord("air");
|
||||
const ver_tok = try p.expect(.number, "AIR format version");
|
||||
const ver = std.fmt.parseInt(u32, ver_tok.text, 10) catch return p.fail(ver_tok, "AIR format version");
|
||||
if (ver != air.format_version) try p.report("E0005", ver_tok.span, "unsupported AIR format version", &.{
|
||||
.{ .name = "found", .value = .{ .str = ver_tok.text } },
|
||||
.{ .name = "supported", .value = .{ .str = "0" } },
|
||||
});
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
|
||||
_ = try p.expectWord("lang");
|
||||
const lang_tok = try p.expect(.number, "language version");
|
||||
const lang = parseVersion(lang_tok.text) orelse return p.fail(lang_tok, "language version like 0.1");
|
||||
if (!std.mem.eql(u32, &lang, &air.lang_version)) try p.report("E0005", lang_tok.span, "unsupported language version", &.{
|
||||
.{ .name = "found", .value = .{ .str = lang_tok.text } },
|
||||
.{ .name = "supported", .value = .{ .str = "0.1" } },
|
||||
});
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
|
||||
_ = try p.expectWord("features");
|
||||
const features = try p.parsePathList();
|
||||
for (features) |f| try p.report("E0006", lang_tok.span, "unsupported feature", &.{
|
||||
.{ .name = "feature", .value = .{ .str = f } },
|
||||
});
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
|
||||
try p.prescanDeclarations();
|
||||
|
||||
var types: std.ArrayList(air.TypeDecl) = .empty;
|
||||
var functions: std.ArrayList(air.Function) = .empty;
|
||||
// Types are parsed first in a separate sweep so that functions can see
|
||||
// every declaration regardless of order.
|
||||
const body_start = p.pos;
|
||||
p.types = try p.arena.alloc(air.TypeDecl, p.type_names.items.len);
|
||||
var ti: usize = 0;
|
||||
while (true) {
|
||||
p.skipNewlines();
|
||||
if (p.peek().tag == .eof) break;
|
||||
if (p.atWord("type")) {
|
||||
p.types[ti] = try p.parseTypeDecl();
|
||||
ti += 1;
|
||||
} else if (p.atWord("fn")) {
|
||||
p.skipFunction();
|
||||
} else return p.fail(p.peek(), "`type` or `fn`");
|
||||
}
|
||||
try types.appendSlice(p.arena, p.types);
|
||||
|
||||
p.pos = body_start;
|
||||
while (true) {
|
||||
p.skipNewlines();
|
||||
if (p.peek().tag == .eof) break;
|
||||
if (p.atWord("type")) {
|
||||
while (p.peek().tag != .nl) _ = p.next();
|
||||
} else {
|
||||
try functions.append(p.arena, try p.parseFunction());
|
||||
}
|
||||
}
|
||||
|
||||
return .{
|
||||
.name = name,
|
||||
.format_version = ver,
|
||||
.lang = lang,
|
||||
.features = features,
|
||||
.types = types.items,
|
||||
.functions = functions.items,
|
||||
};
|
||||
}
|
||||
|
||||
fn prescanDeclarations(p: *Parser) Error!void {
|
||||
var i = p.pos;
|
||||
var line_start = true;
|
||||
while (i < p.tokens.len) : (i += 1) {
|
||||
const t = p.tokens[i];
|
||||
if (t.tag == .nl) {
|
||||
line_start = true;
|
||||
continue;
|
||||
}
|
||||
defer line_start = false;
|
||||
if (!line_start or t.tag != .word) continue;
|
||||
const is_type = std.mem.eql(u8, t.text, "type");
|
||||
const is_fn = std.mem.eql(u8, t.text, "fn");
|
||||
if (!is_type and !is_fn) continue;
|
||||
const n = p.tokens[i + 1];
|
||||
if (n.tag != .global) continue; // reported by the main parse
|
||||
const list = if (is_type) &p.type_names else &p.fn_names;
|
||||
if (indexOf(p.type_names.items, n.text) != null or indexOf(p.fn_names.items, n.text) != null) {
|
||||
try p.report("E0003", n.span, "duplicate name", &.{.{ .name = "name", .value = .{ .str = n.text } }});
|
||||
// Keep a slot so declaration indices stay aligned with source order.
|
||||
}
|
||||
try list.append(p.arena, n.text);
|
||||
}
|
||||
}
|
||||
|
||||
fn skipFunction(p: *Parser) void {
|
||||
_ = p.next();
|
||||
while (true) {
|
||||
while (p.peek().tag != .nl and p.peek().tag != .eof) _ = p.next();
|
||||
p.skipNewlines();
|
||||
if (p.atLineStartKeyword()) return;
|
||||
}
|
||||
}
|
||||
|
||||
fn parsePath(p: *Parser) Error![]const u8 {
|
||||
const t = try p.expect(.word, "name");
|
||||
return t.text;
|
||||
}
|
||||
|
||||
fn parsePathList(p: *Parser) Error![]const []const u8 {
|
||||
_ = try p.expect(.l_bracket, "`[`");
|
||||
var list: std.ArrayList([]const u8) = .empty;
|
||||
if (p.peek().tag != .r_bracket) {
|
||||
while (true) {
|
||||
try list.append(p.arena, try p.parsePath());
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
}
|
||||
_ = try p.expect(.r_bracket, "`]`");
|
||||
return list.items;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ types
|
||||
|
||||
fn parseTypeDecl(p: *Parser) Error!air.TypeDecl {
|
||||
_ = try p.expectWord("type");
|
||||
const name = try p.expect(.global, "type name");
|
||||
_ = try p.expect(.equals, "`=`");
|
||||
var decl: air.TypeDecl = .{ .name = name.text, .span = name.span, .kind = undefined };
|
||||
if (p.atWord("struct")) {
|
||||
_ = p.next();
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
var fields: std.ArrayList(air.Field) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const fname = try p.expect(.word, "field name");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const ty = try p.parseType();
|
||||
for (fields.items) |f| if (std.mem.eql(u8, f.name, fname.text))
|
||||
try p.report("E0003", fname.span, "duplicate field", &.{.{ .name = "name", .value = .{ .str = fname.text } }});
|
||||
try fields.append(p.arena, .{ .name = fname.text, .ty = ty });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
decl.kind = .{ .@"struct" = fields.items };
|
||||
} else if (p.atWord("enum")) {
|
||||
_ = p.next();
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
var variants: std.ArrayList(air.Variant) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const vname = try p.expect(.word, "variant name");
|
||||
var payload: std.ArrayList(air.Type) = .empty;
|
||||
if (p.peek().tag == .l_paren) {
|
||||
_ = p.next();
|
||||
while (p.peek().tag != .r_paren) {
|
||||
try payload.append(p.arena, try p.parseType());
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
}
|
||||
for (variants.items) |v| if (std.mem.eql(u8, v.name, vname.text))
|
||||
try p.report("E0003", vname.span, "duplicate variant", &.{.{ .name = "name", .value = .{ .str = vname.text } }});
|
||||
try variants.append(p.arena, .{ .name = vname.text, .payload = payload.items });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
if (variants.items.len == 0) return p.fail(p.peek(), "at least one variant");
|
||||
decl.kind = .{ .@"enum" = variants.items };
|
||||
} else return p.fail(p.peek(), "`struct` or `enum`");
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
return decl;
|
||||
}
|
||||
|
||||
fn parseType(p: *Parser) Error!air.Type {
|
||||
const t = p.next();
|
||||
switch (t.tag) {
|
||||
.global => {
|
||||
if (indexOf(p.type_names.items, t.text)) |i| return .{ .named = @intCast(i) };
|
||||
try p.report("E0004", t.span, "unknown type", &.{.{ .name = "name", .value = .{ .str = t.text } }});
|
||||
return .void;
|
||||
},
|
||||
.word => {
|
||||
if (std.meta.stringToEnum(air.IntType, t.text)) |it| return .{ .int = it };
|
||||
if (std.mem.eql(u8, t.text, "bool")) return .bool;
|
||||
if (std.mem.eql(u8, t.text, "void")) return .void;
|
||||
if (std.mem.eql(u8, t.text, "never")) return .never;
|
||||
if (std.mem.eql(u8, t.text, "f32") or std.mem.eql(u8, t.text, "f64")) {
|
||||
try p.report("E0006", t.span, "floating-point types are reserved (spec 07 §8.4)", &.{.{ .name = "type", .value = .{ .str = t.text } }});
|
||||
return .void;
|
||||
}
|
||||
try p.report("E0004", t.span, "unknown type", &.{.{ .name = "name", .value = .{ .str = t.text } }});
|
||||
return .void;
|
||||
},
|
||||
else => return p.fail(t, "type"),
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ functions
|
||||
|
||||
fn parseFunction(p: *Parser) Error!air.Function {
|
||||
_ = try p.expectWord("fn");
|
||||
const name = try p.expect(.global, "function name");
|
||||
p.fn_name = name.text;
|
||||
p.values = .empty;
|
||||
p.value_map = .empty;
|
||||
p.block_names = .empty;
|
||||
|
||||
_ = try p.expect(.l_paren, "`(`");
|
||||
var params: std.ArrayList(air.Param) = .empty;
|
||||
while (p.peek().tag != .r_paren) {
|
||||
const v = try p.expect(.local, "parameter");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const ty = try p.parseType();
|
||||
const id = try p.defineValue(v, .{ .param = @intCast(params.items.len) });
|
||||
try params.append(p.arena, .{ .value = id, .ty = ty });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
_ = try p.expect(.arrow, "`->`");
|
||||
const ret = try p.parseType();
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
p.skipNewlines();
|
||||
_ = try p.expectWord("effects");
|
||||
const effects = try p.parsePathList();
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
|
||||
try p.prescanBlocks();
|
||||
|
||||
var blocks: std.ArrayList(air.Block) = .empty;
|
||||
while (true) {
|
||||
p.skipNewlines();
|
||||
if (p.atLineStartKeyword()) break;
|
||||
try blocks.append(p.arena, try p.parseBlock(@intCast(blocks.items.len)));
|
||||
}
|
||||
|
||||
for (p.values.items) |v| if (v.def == .none) {
|
||||
try p.report("E5001", v.span, "value used but never defined", &.{
|
||||
.{ .name = "function", .value = .{ .str = p.fn_name } },
|
||||
.{ .name = "value", .value = .{ .str = try std.fmt.allocPrint(p.arena, "%{s}", .{v.name}) } },
|
||||
});
|
||||
};
|
||||
|
||||
return .{
|
||||
.name = name.text,
|
||||
.span = name.span,
|
||||
.params = params.items,
|
||||
.ret = ret,
|
||||
.effects = effects,
|
||||
.blocks = blocks.items,
|
||||
.values = p.values.items,
|
||||
};
|
||||
}
|
||||
|
||||
/// Records block labels of the current function so branches can refer forward.
|
||||
fn prescanBlocks(p: *Parser) Error!void {
|
||||
var i = p.pos;
|
||||
var line_start = true;
|
||||
while (i < p.tokens.len) : (i += 1) {
|
||||
const t = p.tokens[i];
|
||||
if (t.tag == .nl) {
|
||||
line_start = true;
|
||||
continue;
|
||||
}
|
||||
if (t.tag == .eof) return;
|
||||
defer line_start = false;
|
||||
if (!line_start or t.tag != .word) continue;
|
||||
if (std.mem.eql(u8, t.text, "fn") or std.mem.eql(u8, t.text, "type")) return;
|
||||
const n = p.tokens[i + 1].tag;
|
||||
if (n != .colon and n != .l_paren) continue;
|
||||
if (indexOf(p.block_names.items, t.text) != null)
|
||||
try p.report("E0003", t.span, "duplicate block label", &.{
|
||||
.{ .name = "function", .value = .{ .str = p.fn_name } },
|
||||
.{ .name = "block", .value = .{ .str = t.text } },
|
||||
});
|
||||
try p.block_names.append(p.arena, t.text);
|
||||
}
|
||||
}
|
||||
|
||||
fn defineValue(p: *Parser, t: Token, def: air.ValueInfo.Def) Error!air.ValueId {
|
||||
const gop = try p.value_map.getOrPut(p.arena, t.text);
|
||||
if (!gop.found_existing) {
|
||||
gop.value_ptr.* = @intCast(p.values.items.len);
|
||||
try p.values.append(p.arena, .{ .name = t.text, .span = t.span, .def = def });
|
||||
return gop.value_ptr.*;
|
||||
}
|
||||
const info = &p.values.items[gop.value_ptr.*];
|
||||
if (info.def != .none) {
|
||||
try p.report("E5001", t.span, "value defined more than once", &.{
|
||||
.{ .name = "function", .value = .{ .str = p.fn_name } },
|
||||
.{ .name = "value", .value = .{ .str = try std.fmt.allocPrint(p.arena, "%{s}", .{t.text}) } },
|
||||
});
|
||||
// A fresh id keeps later passes from seeing two definitions of one id.
|
||||
try p.values.append(p.arena, .{ .name = t.text, .span = t.span, .def = def });
|
||||
return @intCast(p.values.items.len - 1);
|
||||
}
|
||||
info.def = def;
|
||||
info.span = t.span;
|
||||
return gop.value_ptr.*;
|
||||
}
|
||||
|
||||
fn useValue(p: *Parser) Error!air.ValueId {
|
||||
const t = try p.expect(.local, "value");
|
||||
const gop = try p.value_map.getOrPut(p.arena, t.text);
|
||||
if (!gop.found_existing) {
|
||||
gop.value_ptr.* = @intCast(p.values.items.len);
|
||||
try p.values.append(p.arena, .{ .name = t.text, .span = t.span, .def = .none });
|
||||
}
|
||||
return gop.value_ptr.*;
|
||||
}
|
||||
|
||||
fn parseBlock(p: *Parser, index: u32) Error!air.Block {
|
||||
const label = try p.expect(.word, "block label");
|
||||
var params: std.ArrayList(air.Param) = .empty;
|
||||
if (p.peek().tag == .l_paren) {
|
||||
_ = p.next();
|
||||
while (p.peek().tag != .r_paren) {
|
||||
const v = try p.expect(.local, "block parameter");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const ty = try p.parseType();
|
||||
const id = try p.defineValue(v, .{ .block_param = .{ .block = index, .index = @intCast(params.items.len) } });
|
||||
try params.append(p.arena, .{ .value = id, .ty = ty });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
}
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
|
||||
var insts: std.ArrayList(air.Inst) = .empty;
|
||||
while (true) {
|
||||
p.skipNewlines();
|
||||
if (p.atLineStartKeyword()) break;
|
||||
const t = p.peek();
|
||||
if (t.tag == .word and (p.peekAt(1).tag == .colon or p.peekAt(1).tag == .l_paren)) break; // next label
|
||||
if (try p.parseInst(index, @intCast(insts.items.len))) |inst| try insts.append(p.arena, inst);
|
||||
}
|
||||
return .{ .name = label.text, .span = label.span, .params = params.items, .insts = insts.items };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ instructions
|
||||
|
||||
/// Returns null if the line was skipped after an unknown-opcode error.
|
||||
fn parseInst(p: *Parser, block: u32, index: u32) Error!?air.Inst {
|
||||
var result_tok: ?Token = null;
|
||||
if (p.peek().tag == .local and p.peekAt(1).tag == .equals) {
|
||||
result_tok = p.next();
|
||||
_ = p.next();
|
||||
}
|
||||
const op_tok = try p.expect(.word, "opcode");
|
||||
var parts_buf: [4][]const u8 = undefined;
|
||||
const parts = splitOpcode(op_tok.text, &parts_buf) orelse return p.unknownOpcode(op_tok);
|
||||
const head = parts[0];
|
||||
|
||||
const op: air.Op = op: {
|
||||
if (eql(head, "const") and parts.len == 2) {
|
||||
if (eql(parts[1], "bool")) {
|
||||
const lit = try p.expect(.word, "`true` or `false`");
|
||||
if (!eql(lit.text, "true") and !eql(lit.text, "false")) return p.fail(lit, "`true` or `false`");
|
||||
break :op .{ .@"const" = .{ .ty = .bool, .bits = @intFromBool(eql(lit.text, "true")) } };
|
||||
}
|
||||
const it = std.meta.stringToEnum(air.IntType, parts[1]) orelse return p.unknownOpcode(op_tok);
|
||||
break :op .{ .@"const" = .{ .ty = .{ .int = it }, .bits = try p.parseIntLiteral(it) } };
|
||||
}
|
||||
if (eql(head, "copy") and parts.len == 1) break :op .{ .copy = try p.useValue() };
|
||||
if (eql(head, "assert") and parts.len == 1) break :op .{ .assert = try p.useValue() };
|
||||
if (std.meta.stringToEnum(air.ArithOp, head)) |aop| {
|
||||
if (parts.len != 3) return p.unknownOpcode(op_tok);
|
||||
const mode = std.meta.stringToEnum(air.ArithMode, parts[1]) orelse return p.unknownOpcode(op_tok);
|
||||
if ((aop == .div or aop == .rem) and mode != .checked) return p.unknownOpcode(op_tok);
|
||||
const it = std.meta.stringToEnum(air.IntType, parts[2]) orelse return p.unknownOpcode(op_tok);
|
||||
const a, const b = try p.twoOperands();
|
||||
break :op .{ .arith = .{ .op = aop, .mode = mode, .ty = it, .a = a, .b = b } };
|
||||
}
|
||||
if (std.meta.stringToEnum(air.BitOp, head)) |bop| {
|
||||
if (parts.len != 2) return p.unknownOpcode(op_tok);
|
||||
const ty = parseScalarType(parts[1]) orelse return p.unknownOpcode(op_tok);
|
||||
if ((bop == .shl or bop == .shr) and ty != .int) return p.unknownOpcode(op_tok);
|
||||
const a, const b = try p.twoOperands();
|
||||
break :op .{ .bit = .{ .op = bop, .ty = ty, .a = a, .b = b } };
|
||||
}
|
||||
if (std.meta.stringToEnum(air.CmpOp, head)) |cop| {
|
||||
if (parts.len != 2) return p.unknownOpcode(op_tok);
|
||||
const ty = parseScalarType(parts[1]) orelse return p.unknownOpcode(op_tok);
|
||||
if (cop != .eq and cop != .ne and ty != .int) return p.unknownOpcode(op_tok);
|
||||
const a, const b = try p.twoOperands();
|
||||
break :op .{ .cmp = .{ .op = cop, .ty = ty, .a = a, .b = b } };
|
||||
}
|
||||
if (eql(head, "cast") and parts.len == 3) {
|
||||
const mode = std.meta.stringToEnum(air.CastMode, parts[1]) orelse return p.unknownOpcode(op_tok);
|
||||
const it = std.meta.stringToEnum(air.IntType, parts[2]) orelse return p.unknownOpcode(op_tok);
|
||||
break :op .{ .cast = .{ .mode = mode, .to = it, .a = try p.useValue() } };
|
||||
}
|
||||
if (eql(op_tok.text, "struct.make")) {
|
||||
const decl = try p.typeRef(.@"struct");
|
||||
break :op .{ .struct_make = .{ .decl = decl, .args = try p.valueList() } };
|
||||
}
|
||||
if (eql(op_tok.text, "struct.get")) {
|
||||
const decl = try p.typeRef(.@"struct");
|
||||
_ = try p.expect(.dot, "`.`");
|
||||
const field_tok = try p.expect(.word, "field name");
|
||||
const field = p.types[decl].fieldIndex(field_tok.text) orelse blk: {
|
||||
try p.report("E0004", field_tok.span, "unknown field", &.{.{ .name = "name", .value = .{ .str = field_tok.text } }});
|
||||
break :blk 0;
|
||||
};
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
break :op .{ .struct_get = .{ .decl = decl, .field = field, .a = try p.useValue() } };
|
||||
}
|
||||
if (eql(op_tok.text, "enum.make")) {
|
||||
const decl = try p.typeRef(.@"enum");
|
||||
_ = try p.expect(.dot, "`.`");
|
||||
const variant = try p.variantRef(decl);
|
||||
break :op .{ .enum_make = .{ .decl = decl, .variant = variant, .args = try p.valueList() } };
|
||||
}
|
||||
if (eql(op_tok.text, "call")) {
|
||||
const callee_tok = try p.expect(.global, "function name");
|
||||
const callee = indexOf(p.fn_names.items, callee_tok.text) orelse blk: {
|
||||
try p.report("E0004", callee_tok.span, "unknown function", &.{.{ .name = "name", .value = .{ .str = callee_tok.text } }});
|
||||
break :blk 0;
|
||||
};
|
||||
break :op .{ .call = .{ .callee = @intCast(callee), .args = try p.valueList() } };
|
||||
}
|
||||
if (eql(op_tok.text, "br")) break :op .{ .br = try p.target() };
|
||||
if (eql(op_tok.text, "cbr")) {
|
||||
const cond = try p.useValue();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
const then = try p.target();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
break :op .{ .cbr = .{ .cond = cond, .then = then, .@"else" = try p.target() } };
|
||||
}
|
||||
if (eql(head, "switch") and parts.len == 2) {
|
||||
const it = std.meta.stringToEnum(air.IntType, parts[1]) orelse return p.unknownOpcode(op_tok);
|
||||
const value = try p.useValue();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
var cases: std.ArrayList(air.Op.Case) = .empty;
|
||||
while (!p.atWord("default")) {
|
||||
const span = p.peek().span;
|
||||
const bits = try p.parseIntLiteral(it);
|
||||
_ = try p.expect(.arrow, "`->`");
|
||||
try cases.append(p.arena, .{ .bits = bits, .target = try p.target(), .span = span });
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
}
|
||||
_ = p.next();
|
||||
_ = try p.expect(.arrow, "`->`");
|
||||
break :op .{ .@"switch" = .{ .ty = it, .value = value, .cases = cases.items, .default = try p.target() } };
|
||||
}
|
||||
if (eql(op_tok.text, "enum.switch")) {
|
||||
const decl = try p.typeRef(.@"enum");
|
||||
const value = try p.useValue();
|
||||
var arms: std.ArrayList(air.Op.Arm) = .empty;
|
||||
var default: ?air.Target = null;
|
||||
while (p.peek().tag == .comma) {
|
||||
_ = p.next();
|
||||
if (p.atWord("default")) {
|
||||
_ = p.next();
|
||||
_ = try p.expect(.arrow, "`->`");
|
||||
default = try p.target();
|
||||
break;
|
||||
}
|
||||
const span = p.peek().span;
|
||||
const variant = try p.variantRef(decl);
|
||||
_ = try p.expect(.arrow, "`->`");
|
||||
const blk = try p.blockRef();
|
||||
try arms.append(p.arena, .{ .variant = variant, .block = blk, .span = span });
|
||||
}
|
||||
break :op .{ .enum_switch = .{ .decl = decl, .value = value, .arms = arms.items, .default = default } };
|
||||
}
|
||||
if (eql(op_tok.text, "ret")) {
|
||||
break :op .{ .ret = if (p.peek().tag == .local) try p.useValue() else null };
|
||||
}
|
||||
if (eql(op_tok.text, "trap")) break :op .trap;
|
||||
return p.unknownOpcode(op_tok);
|
||||
};
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
|
||||
const produces_value = switch (op) {
|
||||
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
|
||||
else => false,
|
||||
};
|
||||
const may_bind = produces_value or op == .call;
|
||||
if (result_tok) |rt| {
|
||||
if (!may_bind) return p.fail(rt, "instruction without result binding");
|
||||
} else if (produces_value) {
|
||||
return p.fail(op_tok, "result binding `%name =`");
|
||||
}
|
||||
const result = if (result_tok) |rt| try p.defineValue(rt, .{ .inst = .{ .block = block, .index = index } }) else null;
|
||||
return .{ .result = result, .op = op, .span = if (result_tok) |rt| rt.span else op_tok.span };
|
||||
}
|
||||
|
||||
fn unknownOpcode(p: *Parser, t: Token) Error!?air.Inst {
|
||||
try p.report("E0004", t.span, "unknown opcode", &.{.{ .name = "name", .value = .{ .str = t.text } }});
|
||||
while (p.peek().tag != .nl) _ = p.next();
|
||||
return null;
|
||||
}
|
||||
|
||||
fn twoOperands(p: *Parser) Error!struct { air.ValueId, air.ValueId } {
|
||||
const a = try p.useValue();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
return .{ a, try p.useValue() };
|
||||
}
|
||||
|
||||
fn valueList(p: *Parser) Error![]const air.ValueId {
|
||||
_ = try p.expect(.l_paren, "`(`");
|
||||
var list: std.ArrayList(air.ValueId) = .empty;
|
||||
while (p.peek().tag != .r_paren) {
|
||||
try list.append(p.arena, try p.useValue());
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
return list.items;
|
||||
}
|
||||
|
||||
fn blockRef(p: *Parser) Error!u32 {
|
||||
const t = try p.expect(.global, "block label");
|
||||
if (indexOf(p.block_names.items, t.text)) |i| return @intCast(i);
|
||||
try p.report("E5002", t.span, "branch to unknown block", &.{
|
||||
.{ .name = "function", .value = .{ .str = p.fn_name } },
|
||||
.{ .name = "block", .value = .{ .str = t.text } },
|
||||
});
|
||||
return 0;
|
||||
}
|
||||
|
||||
fn target(p: *Parser) Error!air.Target {
|
||||
const blk = try p.blockRef();
|
||||
return .{ .block = blk, .args = try p.valueList() };
|
||||
}
|
||||
|
||||
fn typeRef(p: *Parser, comptime kind: std.meta.Tag(@FieldType(air.TypeDecl, "kind"))) Error!u32 {
|
||||
const t = try p.expect(.global, "type name");
|
||||
if (indexOf(p.type_names.items, t.text)) |i| {
|
||||
if (p.types[i].kind == kind) return @intCast(i);
|
||||
}
|
||||
try p.report("E0004", t.span, "unknown " ++ @tagName(kind) ++ " type", &.{.{ .name = "name", .value = .{ .str = t.text } }});
|
||||
// Fall back to any declaration of the right kind so parsing can continue.
|
||||
for (p.types, 0..) |d, i| if (d.kind == kind) return @intCast(i);
|
||||
return error.SyntaxError;
|
||||
}
|
||||
|
||||
fn variantRef(p: *Parser, decl: u32) Error!u32 {
|
||||
const t = try p.expect(.word, "variant name");
|
||||
if (p.types[decl].variantIndex(t.text)) |i| return i;
|
||||
try p.report("E0004", t.span, "unknown variant", &.{.{ .name = "name", .value = .{ .str = t.text } }});
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// Parses an integer literal and checks that it is representable in `ty`.
|
||||
/// Returns the two's-complement bit pattern zero-extended to 128 bits.
|
||||
fn parseIntLiteral(p: *Parser, ty: air.IntType) Error!u128 {
|
||||
const t = try p.expect(.number, "integer literal");
|
||||
return literalBits(t.text, ty) orelse {
|
||||
try p.report("E0002", t.span, "integer literal not representable in its type", &.{
|
||||
.{ .name = "literal", .value = .{ .str = t.text } },
|
||||
.{ .name = "type", .value = .{ .str = @tagName(ty) } },
|
||||
});
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/// Two's-complement bit pattern of `text` in `ty`, zero-extended to 128 bits,
|
||||
/// or null if the literal is malformed or not representable.
|
||||
pub fn literalBits(text: []const u8, ty: air.IntType) ?u128 {
|
||||
const neg = text[0] == '-';
|
||||
const digits = if (neg) text[1..] else text;
|
||||
const mag = std.fmt.parseInt(u128, digits, 0) catch return null;
|
||||
const n = ty.bits();
|
||||
if (ty.signed()) {
|
||||
const limit: u128 = @as(u128, 1) << @intCast(n - 1);
|
||||
if (neg and mag > limit) return null;
|
||||
if (!neg and mag >= limit) return null;
|
||||
} else {
|
||||
if (neg and mag != 0) return null;
|
||||
if (n < 128 and mag >= (@as(u128, 1) << @intCast(n))) return null;
|
||||
}
|
||||
const raw: u128 = if (neg) 0 -% mag else mag;
|
||||
return if (n == 128) raw else raw & ((@as(u128, 1) << @intCast(n)) - 1);
|
||||
}
|
||||
|
||||
fn parseScalarType(text: []const u8) ?air.Type {
|
||||
if (eql(text, "bool")) return .bool;
|
||||
if (std.meta.stringToEnum(air.IntType, text)) |it| return .{ .int = it };
|
||||
return null;
|
||||
}
|
||||
|
||||
fn splitOpcode(text: []const u8, buf: *[4][]const u8) ?[]const []const u8 {
|
||||
var n: usize = 0;
|
||||
var it = std.mem.splitScalar(u8, text, '.');
|
||||
while (it.next()) |part| {
|
||||
if (n == buf.len or part.len == 0) return null;
|
||||
buf[n] = part;
|
||||
n += 1;
|
||||
}
|
||||
return buf[0..n];
|
||||
}
|
||||
|
||||
fn parseVersion(text: []const u8) ?[2]u32 {
|
||||
const dot = std.mem.indexOfScalar(u8, text, '.') orelse return null;
|
||||
return .{
|
||||
std.fmt.parseInt(u32, text[0..dot], 10) catch return null,
|
||||
std.fmt.parseInt(u32, text[dot + 1 ..], 10) catch return null,
|
||||
};
|
||||
}
|
||||
|
||||
fn describe(t: Token) []const u8 {
|
||||
return switch (t.tag) {
|
||||
.nl => "end of line",
|
||||
.eof => "end of file",
|
||||
else => t.text,
|
||||
};
|
||||
}
|
||||
|
||||
fn eql(a: []const u8, b: []const u8) bool {
|
||||
return std.mem.eql(u8, a, b);
|
||||
}
|
||||
|
||||
fn indexOf(list: []const []const u8, name: []const u8) ?usize {
|
||||
for (list, 0..) |n, i| if (eql(n, name)) return i;
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- tests
|
||||
|
||||
const header = "module t\nair 0\nlang 0.1\nfeatures []\n";
|
||||
|
||||
fn parseOk(arena: Allocator, src: []const u8) !air.Module {
|
||||
const r = try parse(arena, "t.air", src);
|
||||
if (r.diagnostics.len != 0) {
|
||||
for (r.diagnostics) |d| std.debug.print("{s} {s} at {d}:{d}\n", .{ d.code.id, d.message, d.span.?.line, d.span.?.col });
|
||||
return error.UnexpectedDiagnostics;
|
||||
}
|
||||
return r.module.?;
|
||||
}
|
||||
|
||||
fn expectCodes(src: []const u8, codes: []const []const u8) !void {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const r = try parse(arena_state.allocator(), "t.air", src);
|
||||
try std.testing.expectEqual(codes.len, r.diagnostics.len);
|
||||
for (codes, r.diagnostics) |c, d| try std.testing.expectEqualStrings(c, d.code.id);
|
||||
}
|
||||
|
||||
test "parse function with loop, block params and forward references" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const m = try parseOk(arena_state.allocator(), header ++
|
||||
\\
|
||||
\\fn @count(%n: u64) -> u64
|
||||
\\effects []
|
||||
\\entry:
|
||||
\\ %zero = const.u64 0
|
||||
\\ br @loop(%zero) ; comment
|
||||
\\loop(%i: u64):
|
||||
\\ %done = ge.u64 %i, %n
|
||||
\\ cbr %done, @exit(%i), @body(%i)
|
||||
\\body(%j: u64):
|
||||
\\ %one = const.u64 1
|
||||
\\ %next = add.checked.u64 %j, %one
|
||||
\\ br @loop(%next)
|
||||
\\exit(%r: u64):
|
||||
\\ ret %r
|
||||
\\
|
||||
);
|
||||
try std.testing.expectEqual(@as(usize, 1), m.functions.len);
|
||||
const f = m.functions[0];
|
||||
try std.testing.expectEqual(@as(usize, 4), f.blocks.len);
|
||||
try std.testing.expectEqual(@as(u32, 1), f.blocks[0].insts[1].op.br.block);
|
||||
try std.testing.expectEqual(@as(u32, 3), f.blocks[1].insts[1].op.cbr.then.block);
|
||||
}
|
||||
|
||||
test "parse types, aggregates and calls" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const m = try parseOk(arena_state.allocator(), header ++
|
||||
\\type @P = struct { x: i32, y: i32 }
|
||||
\\type @O = enum { None, Some(@P) }
|
||||
\\fn @main() -> i32
|
||||
\\effects []
|
||||
\\entry:
|
||||
\\ %a = const.i32 -7
|
||||
\\ %p = struct.make @P(%a, %a)
|
||||
\\ %o = enum.make @O.Some(%p)
|
||||
\\ enum.switch @O %o, None -> @none, Some -> @some
|
||||
\\none:
|
||||
\\ trap
|
||||
\\some(%q: @P):
|
||||
\\ %y = struct.get @P.y, %q
|
||||
\\ %r = call @id(%y)
|
||||
\\ ret %r
|
||||
\\fn @id(%v: i32) -> i32
|
||||
\\effects []
|
||||
\\entry:
|
||||
\\ ret %v
|
||||
\\
|
||||
);
|
||||
try std.testing.expectEqual(@as(usize, 2), m.types.len);
|
||||
try std.testing.expectEqual(@as(u128, 0xffff_fff9), m.functions[0].blocks[0].insts[0].op.@"const".bits);
|
||||
try std.testing.expectEqual(@as(u32, 1), m.functions[0].blocks[2].insts[1].op.call.callee);
|
||||
}
|
||||
|
||||
test "resolution diagnostics" {
|
||||
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n ret %x\n", &.{"E5001"});
|
||||
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n br @nowhere()\n", &.{"E5002"});
|
||||
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n %a = const.u8 1\n %a = const.u8 2\n ret %a\n", &.{"E5001"});
|
||||
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n %a = const.u8 256\n ret %a\n", &.{"E0002"});
|
||||
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n %a = frob.u8 1\n ret %a\n", &.{ "E0004", "E5001" });
|
||||
try expectCodes(header ++ "fn @f() -> f32\neffects []\nentry:\n trap\n", &.{"E0006"});
|
||||
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n trap\nfn @f() -> u8\neffects []\nentry:\n trap\n", &.{"E0003"});
|
||||
try expectCodes("module t\nair 1\nlang 0.1\nfeatures []\n", &.{"E0005"});
|
||||
try expectCodes(header ++ "fn @f( -> u8\n", &.{"E0001"});
|
||||
}
|
||||
|
||||
test "integer literal ranges" {
|
||||
try expectCodes(header ++ "fn @f() -> i8\neffects []\nentry:\n %a = const.i8 -128\n ret %a\n", &.{});
|
||||
try expectCodes(header ++ "fn @f() -> i8\neffects []\nentry:\n %a = const.i8 128\n ret %a\n", &.{"E0002"});
|
||||
try expectCodes(header ++ "fn @f() -> u128\neffects []\nentry:\n %a = const.u128 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff\n ret %a\n", &.{});
|
||||
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n %a = const.u8 -1\n ret %a\n", &.{"E0002"});
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
//! Canonical text AIR serializer (spec 07 §8.5).
|
||||
|
||||
const std = @import("std");
|
||||
const air = @import("module.zig");
|
||||
|
||||
const Writer = std.Io.Writer;
|
||||
|
||||
pub fn print(m: air.Module, w: *Writer) Writer.Error!void {
|
||||
try w.print("module {s}\nair {d}\nlang {d}.{d}\nfeatures [", .{ m.name, m.format_version, m.lang[0], m.lang[1] });
|
||||
try list(w, m.features);
|
||||
try w.writeAll("]\n");
|
||||
|
||||
if (m.types.len != 0) try w.writeByte('\n');
|
||||
for (m.types) |d| {
|
||||
try w.print("type @{s} = ", .{d.name});
|
||||
switch (d.kind) {
|
||||
.@"struct" => |fields| {
|
||||
try w.writeAll("struct {");
|
||||
for (fields, 0..) |f, i| {
|
||||
try w.writeAll(if (i == 0) " " else ", ");
|
||||
try w.print("{s}: ", .{f.name});
|
||||
try printType(m, f.ty, w);
|
||||
}
|
||||
try w.writeAll(if (fields.len == 0) "}\n" else " }\n");
|
||||
},
|
||||
.@"enum" => |variants| {
|
||||
try w.writeAll("enum { ");
|
||||
for (variants, 0..) |v, i| {
|
||||
if (i != 0) try w.writeAll(", ");
|
||||
try w.writeAll(v.name);
|
||||
if (v.payload.len != 0) {
|
||||
try w.writeByte('(');
|
||||
for (v.payload, 0..) |t, j| {
|
||||
if (j != 0) try w.writeAll(", ");
|
||||
try printType(m, t, w);
|
||||
}
|
||||
try w.writeByte(')');
|
||||
}
|
||||
}
|
||||
try w.writeAll(" }\n");
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
for (m.functions) |f| {
|
||||
try w.print("\nfn @{s}(", .{f.name});
|
||||
try params(m, f, f.params, w);
|
||||
try w.writeAll(") -> ");
|
||||
try printType(m, f.ret, w);
|
||||
try w.writeAll("\neffects [");
|
||||
try list(w, f.effects);
|
||||
try w.writeAll("]\n");
|
||||
for (f.blocks) |b| {
|
||||
try w.writeAll(b.name);
|
||||
if (b.params.len != 0) {
|
||||
try w.writeByte('(');
|
||||
try params(m, f, b.params, w);
|
||||
try w.writeByte(')');
|
||||
}
|
||||
try w.writeAll(":\n");
|
||||
for (b.insts) |inst| {
|
||||
try w.writeAll(" ");
|
||||
if (inst.result) |r| try w.print("%{s} = ", .{f.values[r].name});
|
||||
try printOp(m, f, inst.op, w);
|
||||
try w.writeByte('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list(w: *Writer, items: []const []const u8) Writer.Error!void {
|
||||
for (items, 0..) |s, i| {
|
||||
if (i != 0) try w.writeAll(", ");
|
||||
try w.writeAll(s);
|
||||
}
|
||||
}
|
||||
|
||||
fn params(m: air.Module, f: air.Function, ps: []const air.Param, w: *Writer) Writer.Error!void {
|
||||
for (ps, 0..) |p, i| {
|
||||
if (i != 0) try w.writeAll(", ");
|
||||
try w.print("%{s}: ", .{f.values[p.value].name});
|
||||
try printType(m, p.ty, w);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
|
||||
switch (t) {
|
||||
.int => |it| try w.writeAll(@tagName(it)),
|
||||
.named => |i| try w.print("@{s}", .{m.types[i].name}),
|
||||
else => try w.writeAll(@tagName(t)),
|
||||
}
|
||||
}
|
||||
|
||||
fn scalarName(t: air.Type) []const u8 {
|
||||
return switch (t) {
|
||||
.int => |it| @tagName(it),
|
||||
else => @tagName(t),
|
||||
};
|
||||
}
|
||||
|
||||
fn value(f: air.Function, v: air.ValueId, w: *Writer) Writer.Error!void {
|
||||
try w.print("%{s}", .{f.values[v].name});
|
||||
}
|
||||
|
||||
fn values(f: air.Function, vs: []const air.ValueId, w: *Writer) Writer.Error!void {
|
||||
try w.writeByte('(');
|
||||
for (vs, 0..) |v, i| {
|
||||
if (i != 0) try w.writeAll(", ");
|
||||
try value(f, v, w);
|
||||
}
|
||||
try w.writeByte(')');
|
||||
}
|
||||
|
||||
fn target(f: air.Function, t: air.Target, w: *Writer) Writer.Error!void {
|
||||
try w.print("@{s}", .{f.blocks[t.block].name});
|
||||
try values(f, t.args, w);
|
||||
}
|
||||
|
||||
/// Writes the literal for a bit pattern of integer type `it`.
|
||||
pub fn literal(it: air.IntType, bits: u128, w: *Writer) Writer.Error!void {
|
||||
switch (it) {
|
||||
inline else => |t| {
|
||||
const T = air.IntType.Zig(t);
|
||||
const U = @Int(.unsigned, @bitSizeOf(T));
|
||||
const v: T = @bitCast(@as(U, @truncate(bits)));
|
||||
try w.print("{d}", .{v});
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!void {
|
||||
switch (op) {
|
||||
.@"const" => |c| switch (c.ty) {
|
||||
.bool => try w.print("const.bool {s}", .{if (c.bits != 0) "true" else "false"}),
|
||||
.int => |it| {
|
||||
try w.print("const.{s} ", .{@tagName(it)});
|
||||
try literal(it, c.bits, w);
|
||||
},
|
||||
else => unreachable,
|
||||
},
|
||||
.copy => |v| {
|
||||
try w.writeAll("copy ");
|
||||
try value(f, v, w);
|
||||
},
|
||||
.assert => |v| {
|
||||
try w.writeAll("assert ");
|
||||
try value(f, v, w);
|
||||
},
|
||||
.arith => |x| {
|
||||
try w.print("{s}.{s}.{s} ", .{ @tagName(x.op), @tagName(x.mode), @tagName(x.ty) });
|
||||
try value(f, x.a, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.b, w);
|
||||
},
|
||||
.bit => |x| {
|
||||
try w.print("{s}.{s} ", .{ @tagName(x.op), scalarName(x.ty) });
|
||||
try value(f, x.a, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.b, w);
|
||||
},
|
||||
.cmp => |x| {
|
||||
try w.print("{s}.{s} ", .{ @tagName(x.op), scalarName(x.ty) });
|
||||
try value(f, x.a, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.b, w);
|
||||
},
|
||||
.cast => |x| {
|
||||
try w.print("cast.{s}.{s} ", .{ @tagName(x.mode), @tagName(x.to) });
|
||||
try value(f, x.a, w);
|
||||
},
|
||||
.struct_make => |x| {
|
||||
try w.print("struct.make @{s}", .{m.types[x.decl].name});
|
||||
try values(f, x.args, w);
|
||||
},
|
||||
.struct_get => |x| {
|
||||
const d = m.types[x.decl];
|
||||
try w.print("struct.get @{s}.{s}, ", .{ d.name, d.kind.@"struct"[x.field].name });
|
||||
try value(f, x.a, w);
|
||||
},
|
||||
.enum_make => |x| {
|
||||
const d = m.types[x.decl];
|
||||
try w.print("enum.make @{s}.{s}", .{ d.name, d.kind.@"enum"[x.variant].name });
|
||||
try values(f, x.args, w);
|
||||
},
|
||||
.call => |x| {
|
||||
try w.print("call @{s}", .{m.functions[x.callee].name});
|
||||
try values(f, x.args, w);
|
||||
},
|
||||
.br => |t| {
|
||||
try w.writeAll("br ");
|
||||
try target(f, t, w);
|
||||
},
|
||||
.cbr => |x| {
|
||||
try w.writeAll("cbr ");
|
||||
try value(f, x.cond, w);
|
||||
try w.writeAll(", ");
|
||||
try target(f, x.then, w);
|
||||
try w.writeAll(", ");
|
||||
try target(f, x.@"else", w);
|
||||
},
|
||||
.@"switch" => |x| {
|
||||
try w.print("switch.{s} ", .{@tagName(x.ty)});
|
||||
try value(f, x.value, w);
|
||||
for (x.cases) |c| {
|
||||
try w.writeAll(", ");
|
||||
try literal(x.ty, c.bits, w);
|
||||
try w.writeAll(" -> ");
|
||||
try target(f, c.target, w);
|
||||
}
|
||||
try w.writeAll(", default -> ");
|
||||
try target(f, x.default, w);
|
||||
},
|
||||
.enum_switch => |x| {
|
||||
const d = m.types[x.decl];
|
||||
try w.print("enum.switch @{s} ", .{d.name});
|
||||
try value(f, x.value, w);
|
||||
for (x.arms) |a| try w.print(", {s} -> @{s}", .{ d.kind.@"enum"[a.variant].name, f.blocks[a.block].name });
|
||||
if (x.default) |dt| {
|
||||
try w.writeAll(", default -> ");
|
||||
try target(f, dt, w);
|
||||
}
|
||||
},
|
||||
.ret => |v| {
|
||||
try w.writeAll("ret");
|
||||
if (v) |x| {
|
||||
try w.writeByte(' ');
|
||||
try value(f, x, w);
|
||||
}
|
||||
},
|
||||
.trap => try w.writeAll("trap"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- tests
|
||||
|
||||
const parse = @import("parse.zig").parse;
|
||||
|
||||
fn roundTrip(src: []const u8) !void {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
|
||||
const r1 = try parse(arena, "a.air", src);
|
||||
try std.testing.expectEqual(@as(usize, 0), r1.diagnostics.len);
|
||||
var out1: Writer.Allocating = .init(arena);
|
||||
try print(r1.module.?, &out1.writer);
|
||||
|
||||
const r2 = try parse(arena, "b.air", out1.written());
|
||||
try std.testing.expectEqual(@as(usize, 0), r2.diagnostics.len);
|
||||
var out2: Writer.Allocating = .init(arena);
|
||||
try print(r2.module.?, &out2.writer);
|
||||
|
||||
try std.testing.expectEqualStrings(out1.written(), out2.written());
|
||||
}
|
||||
|
||||
test "canonical form of a messy module" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const src =
|
||||
\\; leading comment
|
||||
\\module t.x
|
||||
\\air 0
|
||||
\\lang 0.1
|
||||
\\features [ ]
|
||||
\\type @P = struct {
|
||||
\\ x: i8,
|
||||
\\ y: bool,
|
||||
\\}
|
||||
\\type @O = enum { A, B(@P, u8) }
|
||||
\\fn @main() -> i8
|
||||
\\effects []
|
||||
\\entry:
|
||||
\\ %a = const.i8 -0x80
|
||||
\\ %t = const.bool true
|
||||
\\ %p = struct.make @P(%a,%t)
|
||||
\\ %s = const.u8 0b11
|
||||
\\ %o = enum.make @O.B(%p, %s)
|
||||
\\ enum.switch @O %o, A -> @x, default -> @y(%a)
|
||||
\\x:
|
||||
\\ trap
|
||||
\\y(%v: i8):
|
||||
\\ %w = cast.widen.i16 %v
|
||||
\\ switch.i16 %w, -1 -> @x(), 5 -> @x(), default -> @z()
|
||||
\\z:
|
||||
\\ ret %v
|
||||
\\
|
||||
;
|
||||
const r = try parse(arena, "t.air", src);
|
||||
try std.testing.expectEqual(@as(usize, 0), r.diagnostics.len);
|
||||
var out: Writer.Allocating = .init(arena);
|
||||
try print(r.module.?, &out.writer);
|
||||
try std.testing.expectEqualStrings(
|
||||
\\module t.x
|
||||
\\air 0
|
||||
\\lang 0.1
|
||||
\\features []
|
||||
\\
|
||||
\\type @P = struct { x: i8, y: bool }
|
||||
\\type @O = enum { A, B(@P, u8) }
|
||||
\\
|
||||
\\fn @main() -> i8
|
||||
\\effects []
|
||||
\\entry:
|
||||
\\ %a = const.i8 -128
|
||||
\\ %t = const.bool true
|
||||
\\ %p = struct.make @P(%a, %t)
|
||||
\\ %s = const.u8 3
|
||||
\\ %o = enum.make @O.B(%p, %s)
|
||||
\\ enum.switch @O %o, A -> @x, default -> @y(%a)
|
||||
\\x:
|
||||
\\ trap
|
||||
\\y(%v: i8):
|
||||
\\ %w = cast.widen.i16 %v
|
||||
\\ switch.i16 %w, -1 -> @x(), 5 -> @x(), default -> @z()
|
||||
\\z:
|
||||
\\ ret %v
|
||||
\\
|
||||
, out.written());
|
||||
try roundTrip(src);
|
||||
}
|
||||
|
||||
test "round-trip fuzz over generated arithmetic modules" {
|
||||
// Deterministic pseudo-random modules; the seed is fixed so failures reproduce.
|
||||
var prng: std.Random.DefaultPrng = .init(0xA11);
|
||||
const rnd = prng.random();
|
||||
const ops = [_][]const u8{ "add.checked", "sub.wrap", "mul.wrap", "div.checked", "rem.checked" };
|
||||
const types = [_][]const u8{ "u8", "i16", "u32", "i64", "u128", "usize", "isize" };
|
||||
var buf: [8192]u8 = undefined;
|
||||
for (0..200) |_| {
|
||||
var w: Writer = .fixed(&buf);
|
||||
const ty = types[rnd.uintLessThan(usize, types.len)];
|
||||
try w.print("module f\nair 0\nlang 0.1\nfeatures []\nfn @f(%p0: {s}) -> {s}\neffects []\nentry:\n", .{ ty, ty });
|
||||
const n = rnd.uintLessThan(usize, 20) + 1;
|
||||
for (1..n + 1) |i| {
|
||||
const op = ops[rnd.uintLessThan(usize, ops.len)];
|
||||
try w.print(" %p{d} = {s}.{s} %p{d}, %p{d}\n", .{ i, op, ty, rnd.uintLessThan(usize, i), rnd.uintLessThan(usize, i) });
|
||||
}
|
||||
try w.print(" ret %p{d}\n", .{n});
|
||||
try roundTrip(w.buffered());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user