t27.aiEnglish

Стадии t27c

Вы узнаете

Путь спеки внутри t27c: токены, синтаксическое дерево, типы, HIR, код.

t27c читает спеку по стадиям. Лексер режет текст на токены. Парсер строит синтаксическое дерево. Проверка типов проверяет каждую ширину и каждый вызов. Дерево опускается в HIR, более простую форму, и каждый бэкенд пишет код из неё. Этот виджет прогоняет стадии на спеке в вашем браузере и показывает, что выдала каждая, так что у ошибки есть стадия, на которую можно указать.

Попробуйте

Выберите пример и пройдите по стадиям; найдите стадию, на которой остановилась бы ошибка типов.

Открыть интерактивный урок →

Inside t27c: watch a compiler read your code, stage by stage
Inside t27c: watch a compiler read your code, stage by stage ↗

Edit a small t27 spec and see what the real t27c compiler, running as WebAssembly in your tab, makes of it: tokens, tree, type check, HIR and code in seven languages.

specs/tutorial/06_structs_enums_switch.t27

// SPDX-License-Identifier: Apache-2.0
; 06 — Structs, enums, and switch
; Lesson 6. Grouping fields, naming a fixed set of states, and choosing
; between them.
; .
; The important rule in this file: `switch` is an EXPRESSION here. The
; statement form parses without complaint and then discards the body of the
; function containing it, emitting a panic stub instead. Nothing warns you.
; Always write `return switch (x) { ... };`.
; phi^2 + 1/phi^2 = 3 | TRINITY

module tutorial-06-structs;

pub const TRIT_NEG : i8 = -1;
pub const TRIT_ZERO : i8 = 0;
pub const TRIT_POS : i8 = 1;

// ============================================================================
// Structs
//
// `packed` fixes the layout: fields sit adjacent in declaration order with no
// padding inserted. For anything that becomes a register or crosses a bus,
// that is the point -- an unpacked layout is the compiler's choice, and a
// spec should not be making the reader guess.
// ============================================================================

pub const Sample = packed struct {
    value : i8,
    valid : bool,
};

// Only one struct in this module, and that is deliberate. A second `packed
// struct` in the same module currently breaks the Verilog-from-HIR backend:
//
//     HIR validation failed: duplicate signal name:
//
// Note the name is empty. Bisected to exactly this -- one struct emits, two
// collide, regardless of whether their field names differ; enums are
// unaffected, and a struct beside an enum is fine. Six real specs in the
// corpus are stuck on it (chips/*/specs/fpga/gf16_to_fp16.t27 and
// gf32_to_fp32.t27, each declaring two structs). Filed as t27#3283.
//
// The other four backends are unaffected, so this bites only if you target
// Verilog through HIR. Until it is fixed, one struct per module.

// ── Building one ────────────────────────────────────────────────────────────
// `Type{ .field = value }` -- the leading dot names the field.
pub fn make_sample(value: i8) Sample {
    return Sample{ .value = value, .valid = true };
}

pub fn empty_sample() Sample {
    return Sample{ .value = TRIT_ZERO, .valid = false };
}

// ── Reading one ─────────────────────────────────────────────────────────────
pub fn sample_value(s: Sample) i8 {
    return s.value;
}

pub fn sample_is_valid(s: Sample) bool {
    return s.valid;
}

// ============================================================================
// Enums
//
// A fixed set of named states, with the backing integer type written out.
// ============================================================================

pub const Trit = enum(i8) {
    Negative,
    Zero,
    Positive,
};

pub const Rounding = enum(u8) {
    TowardZero,
    TowardNearest,
    TowardPositive,
    TowardNegative,
};

// ============================================================================
// switch — expression form only
//
// Each arm is `pattern => value,` and `else` catches the rest. The whole thing
// produces a value, so it is returned or bound, never left standing alone.
// ============================================================================

pub fn trit_to_number(t: i8) i8 {
    return switch (t) {
        0 => TRIT_ZERO,
        1 => TRIT_POS,
        else => TRIT_NEG,
    };
}

pub fn rounding_bias(mode: u8) u8 {
    return switch (mode) {
        0 => 0,
        1 => 128,
        2 => 255,
        else => 0,
    };
}

// A switch bound to a local reads well when the result feeds further work.
pub fn describe_width(bits: u8) u8 {
    const category = switch (bits) {
        8 => 1,
        16 => 2,
        32 => 3,
        else => 0,
    };
    return category;
}

// ============================================================================
// Tests
// ============================================================================

test "a struct literal round-trips through its fields" {
    const s = make_sample(TRIT_POS);
    try std.testing.expectEqual(@as(i8, TRIT_POS), sample_value(s));
    try std.testing.expect(sample_is_valid(s));
    try std.testing.expect(!sample_is_valid(empty_sample()));
}

test "switch covers its arms and falls through to else" {
    try std.testing.expectEqual(@as(i8, TRIT_ZERO), trit_to_number(0));
    try std.testing.expectEqual(@as(i8, TRIT_POS), trit_to_number(1));
    try std.testing.expectEqual(@as(i8, TRIT_NEG), trit_to_number(7));
}

test "describe_width maps known widths and defaults the rest" {
    try std.testing.expectEqual(@as(u8, 1), describe_width(8));
    try std.testing.expectEqual(@as(u8, 3), describe_width(32));
    try std.testing.expectEqual(@as(u8, 0), describe_width(7));
}

Открыть спеку урока в плеере ↗

Все уроки