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

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));
}
Все уроки
Модуль 1 · Чип
Что такое FPGA, какой чип у нас и как его выводы встречаются с платой.
Модуль 2 · Числа в железе
Биты, триты и форматы чисел, и сколько стоит арифметика в логике.
Модуль 3 · Ваша программа на t27
Напишите спеку, проверьте её и увидьте, почему «компилируется» не значит «верно».
Модуль 4 · Внутри t27c
Как компилятор читает спеку и что он пишет, включая нативный t27b.
Модуль 5 · От спеки к железу
Verilog, который пишет t27c, ячейки, в которые он превращается, и что делает одна LUT.
Модуль 6 · Читаем синтез
Что yosys сообщает о вашем дизайне и какие предупреждения важны.
Модуль 7 · Размещение, трассировка, тайминг
Где ячейки оказываются на кристалле и успевает ли тактовая частота.
Модуль 8 · Битстрим
Как оттрассированный дизайн становится битами, которые загружает чип, без Vivado.
Модуль 9 · На плате
Спросите чип, кто он, загрузите биты и проверьте их.