1// WGSL's syntax, as far as the package's shaders use it: tokens, and a2// tree of nodes kept in arrays and named by index, which the checker3// walks. Parsing stops at the first error, reported with its line and4// column.56import std::string;7import std::vector;8import std::option;9import std::text;1011pub type TokenKind = enum {12 Name,13 Integer,14 Float,15 Symbol,16 End,17};1819pub type Token = struct {20 pub kind: TokenKind,21 pub start: u32,22 pub end: u32,23 pub line: u32,24 pub column: u32,25};2627// A run of entries in one of the tree's arrays.28pub type Run = struct {29 pub first: u32 = 0,30 pub count: u32 = 0,31};3233pub type Expr = struct {34 pub token: u32,35 pub form: ExprForm,36};3738pub type ExprForm = enum {39 Integer, // a literal; `token` its text40 Float,41 Bool,42 Name,43 Unary: u32, // the operand; `token` the operator44 Binary: Operands, // `token` the operator45 Call: Call, // `token` the function or type's name46 Member: u32, // the value; `token` the member47 Index: Operands, // the value and the index; `token` the `[`48};4950pub type Operands = struct {51 pub left: u32,52 pub right: u32,53};5455pub type Call = struct {56 pub ty: Option<u32>, // a TypeNode, when written as one57 pub arguments: Run, // in `lists`58};5960// A type as written: a name with its template arguments, each a type or,61// for an array's length, an expression.62pub type TypeNode = struct {63 pub token: u32,64 pub arguments: Run = Run {}, // in `lists`, each a TypeNode65 pub length: Option<u32> = ::None, // an array's length expression66};6768pub type Stmt = struct {69 pub token: u32,70 pub form: StmtForm,71};7273pub type StmtForm = enum {74 Let: LetStatement, // `token` the name75 Var: VarStatement, // `token` the name76 Assign: Operands, // the target and the value; `token` the operator (`=`, `+=`, ...)77 Increment: u32, // the target; `token` `++` or `--`78 Call: u32,79 If: IfStatement,80 Loop: LoopStatement,81 Break,82 Continue,83 Return: Option<u32>,84 Discard,85 Block: Run, // the statements, in `lists`86};8788pub type LetStatement = struct {89 pub ty: Option<u32>,90 pub value: u32,91};9293pub type VarStatement = struct {94 pub ty: Option<u32>,95 pub value: Option<u32>,96};9798pub type IfStatement = struct {99 pub condition: u32,100 pub body: u32,101 pub otherwise: Option<u32>, // the else statement102};103104pub type LoopStatement = struct {105 pub condition: Option<u32>,106 pub body: u32,107 pub continuing: Option<u32>,108};109110// `@name` or `@name(value)`.111pub type Attribute = struct {112 pub token: u32, // the name113 pub value: Option<u32>,114};115116pub type Field = struct {117 pub attributes: Run,118 pub token: u32,119 pub ty: u32,120};121122pub type StructDecl = struct {123 pub token: u32,124 pub fields: Run,125};126127pub type GlobalVar = struct {128 pub attributes: Run,129 pub space: Option<u32>, // the address space's token (`uniform`, `storage`)130 pub access: Option<u32>, // `read` or `read_write`131 pub token: u32,132 pub ty: u32,133};134135pub type ConstDecl = struct {136 pub token: u32,137 pub ty: Option<u32>,138 pub value: u32,139};140141pub type FnDecl = struct {142 pub attributes: Run,143 pub token: u32,144 pub parameters: Run, // in `fields`145 pub result: Option<u32>, // a TypeNode146 pub result_attributes: Run,147 pub body: u32, // a Block statement148};149150pub type Syntax = struct {151 pub text: String,152 pub tokens: Vector<Token> = Vector<Token>::empty(),153 pub exprs: Vector<Expr> = Vector<Expr>::empty(),154 pub types: Vector<TypeNode> = Vector<TypeNode>::empty(),155 pub stmts: Vector<Stmt> = Vector<Stmt>::empty(),156 pub lists: Vector<u32> = Vector<u32>::empty(),157 pub attributes: Vector<Attribute> = Vector<Attribute>::empty(),158 pub fields: Vector<Field> = Vector<Field>::empty(),159 pub structs: Vector<StructDecl> = Vector<StructDecl>::empty(),160 pub globals: Vector<GlobalVar> = Vector<GlobalVar>::empty(),161 pub constants: Vector<ConstDecl> = Vector<ConstDecl>::empty(),162 pub functions: Vector<FnDecl> = Vector<FnDecl>::empty(),163 pub error: String = String::empty(), // empty when parsed164 at: u32 = 0, // the next token165};166167// The token's text.168pub fn text_of(self s: &Syntax, token: u32) -> &[u8] {169 const t = &s.tokens.get(token to u64);170 return &s.text.view()[t.start to u64..t.end to u64];171}172173// `line:column: message` at the token.174pub fn located(self s: &Syntax, token: u32, message: &[u8]) -> String {175 const t = &s.tokens.get(token to u64);176 return f"{t.line}:{t.column}: {message}";177}178179pub fn parse(source: &[u8]) -> Syntax {180 var s = Syntax { .text = String::from(&source) };181 s.tokenize();182 if (s.error.length() == 0) {183 s.module();184 }185 return move s;186}187188/* --- Tokens --- */189190const SYMBOLS: [&[u8] : 41] = [191 &"<<=", &">>=", &"->", &"&&", &"||", &"==", &"!=", &"<=", &">=", &"<<", &">>", &"+=",192 &"-=", &"*=", &"/=", &"%=", &"&=", &"|=", &"^=", &"++", &"--", &"(", &")", &"{",193 &"}", &"[", &"]", &"<", &">", &",", &";", &":", &".", &"=", &"@", &"+", &"-", &"*",194 &"/", &"!", &"&"195];196const MORE_SYMBOLS: [&[u8] : 4] = [&"%", &"|", &"^", &"~"];197198fn tokenize(self s: &var Syntax) {199 const text = &s.text.view();200 var at: u64 = 0;201 var line: u32 = 1;202 var line_start: u64 = 0;203 while (at < text.length()) {204 const c = text[at];205 if (c == '\n') {206 at += 1;207 line += 1;208 line_start = at;209 continue;210 }211 if (c == ' ' || c == '\t' || c == '\r') {212 at += 1;213 continue;214 }215 if (text[at..].starts_with(&"//")) {216 while (at < text.length() && text[at] != '\n') {217 at += 1;218 }219 continue;220 }221 if (text[at..].starts_with(&"/*")) {222 at += 2;223 while (at < text.length() && !text[at..].starts_with(&"*/")) {224 if (text[at] == '\n') {225 line += 1;226 line_start = at + 1;227 }228 at += 1;229 }230 at += 2;231 continue;232 }233 const start = at;234 var kind = TokenKind::Symbol;235 if (is_name_start(c)) {236 kind = TokenKind::Name;237 while (at < text.length() && (is_name_start(text[at]) || is_digit(text[at]))) {238 at += 1;239 }240 } else if (is_digit(c) || (c == '.' && at + 1 < text.length() && is_digit(text[at + 1]))) {241 kind = TokenKind::Integer;242 if (text[at..].starts_with(&"0x")) {243 at += 2;244 while (at < text.length() && is_hex(text[at])) {245 at += 1;246 }247 } else {248 while (at < text.length() && is_digit(text[at])) {249 at += 1;250 }251 if (at < text.length() && text[at] == '.') {252 kind = TokenKind::Float;253 at += 1;254 while (at < text.length() && is_digit(text[at])) {255 at += 1;256 }257 }258 if (at < text.length() && (text[at] == 'e' || text[at] == 'E')) {259 kind = TokenKind::Float;260 at += 1;261 if (at < text.length() && (text[at] == '+' || text[at] == '-')) {262 at += 1;263 }264 while (at < text.length() && is_digit(text[at])) {265 at += 1;266 }267 }268 }269 // a suffix: `u`, `i`, `f` or `h`270 if (at < text.length() && (text[at] == 'u' || text[at] == 'i' || text[at] == 'f')) {271 if (text[at] == 'f') {272 kind = TokenKind::Float;273 }274 at += 1;275 }276 } else {277 var length: u64 = 0;278 for (SYMBOLS) |&symbol| {279 if (length == 0 && text[at..].starts_with(&symbol)) {280 length = symbol.length();281 }282 }283 for (MORE_SYMBOLS) |&symbol| {284 if (length == 0 && text[at..].starts_with(&symbol)) {285 length = symbol.length();286 }287 }288 if (length == 0) {289 s.error = f"{line}:{at - line_start + 1}: unexpected character";290 return;291 }292 at += length;293 }294 s.tokens.push(Token {295 .kind = kind,296 .start = start to u32,297 .end = at to u32,298 .line = line,299 .column = (start - line_start + 1) to u32300 });301 }302 s.tokens.push(Token {303 .kind = TokenKind::End,304 .start = text.length() to u32,305 .end = text.length() to u32,306 .line = line,307 .column = (text.length() - line_start + 1) to u32308 });309}310311fn is_name_start(c: u8) -> bool {312 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';313}314315fn is_digit(c: u8) -> bool {316 return c >= '0' && c <= '9';317}318319fn is_hex(c: u8) -> bool {320 return is_digit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');321}322323/* --- Parsing --- */324325fn peek(self s: &Syntax) -> &[u8] {326 return &s.text_of(s.at);327}328329fn peek_kind(self s: &Syntax) -> TokenKind {330 return s.tokens.get(s.at to u64).kind;331}332333fn failed(self s: &Syntax) -> bool {334 return s.error.length() != 0;335}336337fn fail(self s: &var Syntax, message: &[u8]) {338 if (s.error.length() == 0) {339 const found = String::from(&s.peek());340 s.error = s.located(s.at, &f"{message}, found '{found}'".view());341 }342}343344// Takes the token when it is the text.345fn take(self s: &var Syntax, text: &[u8]) -> bool {346 if (!s.failed() && s.peek_kind() != TokenKind::End && s.peek() == text) {347 s.at += 1;348 return true;349 }350 return false;351}352353fn expect(self s: &var Syntax, text: &[u8]) {354 if (!s.take(&text)) {355 s.fail(&f"expected '{text}'".view());356 }357}358359fn name(self s: &var Syntax) -> u32 {360 if (s.failed() || s.peek_kind() != TokenKind::Name) {361 s.fail(&"expected a name");362 return 0;363 }364 s.at += 1;365 return s.at - 1;366}367368fn module(self s: &var Syntax) {369 while (!s.failed() && s.peek_kind() != TokenKind::End) {370 const attributes = s.attribute_list();371 if (s.take(&"struct")) {372 s.struct_decl();373 } else if (s.take(&"var")) {374 s.global_var(attributes);375 } else if (s.take(&"const")) {376 const token = s.name();377 const ty = s.optional_type();378 s.expect(&"=");379 const value = s.expression();380 s.expect(&";");381 s.constants.push(ConstDecl { .token = token, .ty = ty, .value = value });382 } else if (s.take(&"fn")) {383 s.function(attributes);384 } else if (!s.take(&";")) {385 s.fail(&"expected 'struct', 'var', 'const' or 'fn'");386 }387 }388}389390// The attributes before a declaration.391fn attribute_list(self s: &var Syntax) -> Run {392 const first = s.attributes.length() to u32;393 while (s.take(&"@")) {394 const token = s.name();395 var value: Option<u32> = ::None;396 if (s.take(&"(")) {397 value = ::Some(s.expression());398 s.expect(&")");399 }400 s.attributes.push(Attribute { .token = token, .value = value });401 }402 return Run { .first = first, .count = s.attributes.length() to u32 - first };403}404405// `: type` when there.406fn optional_type(self s: &var Syntax) -> Option<u32> {407 return if (s.take(&":")) ::Some(s.type_node()) else ::None;408}409410// Fields up to the closing text: `name: type`, each after its attributes.411fn field_list(self s: &var Syntax, close: &[u8]) -> Run {412 const first = s.fields.length() to u32;413 while (!s.failed() && !s.take(&close)) {414 const attributes = s.attribute_list();415 const token = s.name();416 s.expect(&":");417 const ty = s.type_node();418 s.fields.push(Field { .attributes = attributes, .token = token, .ty = ty });419 if (!s.take(&",")) {420 s.expect(&close);421 break;422 }423 }424 return Run { .first = first, .count = s.fields.length() to u32 - first };425}426427fn struct_decl(self s: &var Syntax) {428 const token = s.name();429 s.expect(&"{");430 const fields = s.field_list(&"}");431 s.take(&";");432 s.structs.push(StructDecl { .token = token, .fields = fields });433}434435fn global_var(self s: &var Syntax, attributes: Run) {436 var space: Option<u32> = ::None;437 var access: Option<u32> = ::None;438 if (s.take(&"<")) {439 space = ::Some(s.name());440 if (s.take(&",")) {441 access = ::Some(s.name());442 }443 s.expect(&">");444 }445 const token = s.name();446 s.expect(&":");447 const ty = s.type_node();448 s.expect(&";");449 s.globals.push(GlobalVar {450 .attributes = attributes,451 .space = space,452 .access = access,453 .token = token,454 .ty = ty455 });456}457458fn function(self s: &var Syntax, attributes: Run) {459 const token = s.name();460 s.expect(&"(");461 const parameters = s.field_list(&")");462 var result: Option<u32> = ::None;463 var result_attributes = Run { .first = s.attributes.length() to u32 };464 if (s.take(&"->")) {465 result_attributes = s.attribute_list();466 result = ::Some(s.type_node());467 }468 const body = s.block();469 s.functions.push(FnDecl {470 .attributes = attributes,471 .token = token,472 .parameters = parameters,473 .result = result,474 .result_attributes = result_attributes,475 .body = body476 });477}478479fn type_node(self s: &var Syntax) -> u32 {480 const token = s.name();481 var arguments: Vector<u32> = Vector<u32>::empty();482 var length: Option<u32> = ::None;483 if (s.take(&"<")) {484 while (!s.failed()) {485 if (s.text_of(token) == "array" && arguments.length() == 1) {486 length = ::Some(s.additive());487 } else {488 arguments.push(s.type_node());489 }490 if (!s.take(&",")) {491 break;492 }493 }494 s.close_template();495 }496 const listed = s.list(&arguments.view());497 s.types.push(TypeNode { .token = token, .arguments = listed, .length = length });498 return s.types.length() to u32 - 1;499}500501// The indices put into `lists`.502fn list(self s: &var Syntax, items: &[u32]) -> Run {503 const first = s.lists.length() to u32;504 s.lists.append(&items);505 return Run { .first = first, .count = items.length() to u32 };506}507508// A template's closing `>`, splitting a `>>` or `>=` the tokenizer joined.509fn close_template(self s: &var Syntax) {510 if (s.take(&">")) {511 return;512 }513 if (!s.failed() && (s.peek() == ">>" || s.peek() == ">=")) {514 var t = &var s.tokens.get_var(s.at to u64);515 t.start += 1;516 t.column += 1;517 return;518 }519 s.fail(&"expected '>'");520}521522/* --- Statements --- */523524fn add_stmt(self s: &var Syntax, token: u32, form: StmtForm) -> u32 {525 s.stmts.push(Stmt { .token = token, .form = form });526 return s.stmts.length() to u32 - 1;527}528529fn block(self s: &var Syntax) -> u32 {530 const token = s.at;531 s.expect(&"{");532 var statements = Vector<u32>::empty();533 while (!s.failed() && !s.take(&"}")) {534 if (s.peek_kind() == TokenKind::End) {535 s.fail(&"expected '}'");536 break;537 }538 statements.push(s.statement());539 }540 const listed = s.list(&statements.view());541 return s.add_stmt(token, ::Block(listed));542}543544fn statement(self s: &var Syntax) -> u32 {545 const token = s.at;546 if (s.peek() == "{") {547 return s.block();548 }549 if (s.take(&"let") || s.take(&"const")) {550 const name = s.name();551 const ty = s.optional_type();552 s.expect(&"=");553 const value = s.expression();554 s.expect(&";");555 return s.add_stmt(name, ::Let(LetStatement { .ty = ty, .value = value }));556 }557 if (s.take(&"var")) {558 const name = s.name();559 const ty = s.optional_type();560 var value: Option<u32> = ::None;561 if (s.take(&"=")) {562 value = ::Some(s.expression());563 }564 s.expect(&";");565 return s.add_stmt(name, ::Var(VarStatement { .ty = ty, .value = value }));566 }567 if (s.take(&"if")) {568 return s.if_statement(token);569 }570 if (s.take(&"for")) {571 // for (init; condition; update) block, as a block holding the572 // init and a loop573 s.expect(&"(");574 var init: Option<u32> = ::None;575 if (!s.take(&";")) {576 init = ::Some(s.statement());577 }578 var condition: Option<u32> = ::None;579 if (!s.take(&";")) {580 condition = ::Some(s.expression());581 s.expect(&";");582 }583 var continuing: Option<u32> = ::None;584 if (!s.take(&")")) {585 continuing = ::Some(s.simple_statement());586 s.expect(&")");587 }588 const body = s.block();589 const looped = s.add_stmt(token, ::Loop(LoopStatement {590 .condition = condition,591 .body = body,592 .continuing = continuing593 }));594 var statements = Vector<u32>::empty();595 if (init is ::Some |i|) {596 statements.push(i);597 }598 statements.push(looped);599 const listed = s.list(&statements.view());600 return s.add_stmt(token, ::Block(listed));601 }602 if (s.take(&"while")) {603 const condition = s.expression();604 const body = s.block();605 return s.add_stmt(token, ::Loop(LoopStatement {606 .condition = ::Some(condition),607 .body = body,608 .continuing = ::None609 }));610 }611 if (s.take(&"loop")) {612 const body = s.block();613 return s.add_stmt(token, ::Loop(LoopStatement {614 .condition = ::None,615 .body = body,616 .continuing = ::None617 }));618 }619 if (s.take(&"break")) {620 s.expect(&";");621 return s.add_stmt(token, ::Break);622 }623 if (s.take(&"continue")) {624 s.expect(&";");625 return s.add_stmt(token, ::Continue);626 }627 if (s.take(&"discard")) {628 s.expect(&";");629 return s.add_stmt(token, ::Discard);630 }631 if (s.take(&"return")) {632 var value: Option<u32> = ::None;633 if (!s.take(&";")) {634 value = ::Some(s.expression());635 s.expect(&";");636 }637 return s.add_stmt(token, ::Return(value));638 }639 const simple = s.simple_statement();640 s.expect(&";");641 return simple;642}643644fn if_statement(self s: &var Syntax, token: u32) -> u32 {645 const condition = s.expression();646 const body = s.block();647 var otherwise: Option<u32> = ::None;648 if (s.take(&"else")) {649 const else_token = s.at;650 otherwise = ::Some(if (s.take(&"if")) s.if_statement(else_token) else s.block());651 }652 return s.add_stmt(token, ::If(IfStatement {653 .condition = condition,654 .body = body,655 .otherwise = otherwise656 }));657}658659const ASSIGNMENTS: [&[u8] : 11] = [660 &"=",661 &"+=",662 &"-=",663 &"*=",664 &"/=",665 &"%=",666 &"&=",667 &"|=",668 &"^=",669 &"<<=",670 &">>="671];672673// An assignment, increment or call, without its `;`.674fn simple_statement(self s: &var Syntax) -> u32 {675 const token = s.at;676 const target = s.unary();677 for (ASSIGNMENTS) |&operator| {678 if (!s.failed() && s.peek() == operator) {679 const operator_token = s.at;680 s.at += 1;681 const value = s.expression();682 return s.add_stmt(683 operator_token,684 ::Assign(Operands { .left = target, .right = value })685 );686 }687 }688 if (!s.failed() && (s.peek() == "++" || s.peek() == "--")) {689 const operator_token = s.at;690 s.at += 1;691 return s.add_stmt(operator_token, ::Increment(target));692 }693 if (!s.failed() && s.exprs.get(target to u64).form is ::Call) {694 return s.add_stmt(token, ::Call(target));695 }696 s.fail(&"expected a statement");697 return 0;698}699700/* --- Expressions --- */701702fn add_expr(self s: &var Syntax, token: u32, form: ExprForm) -> u32 {703 s.exprs.push(Expr { .token = token, .form = form });704 return s.exprs.length() to u32 - 1;705}706707pub fn expression(self s: &var Syntax) -> u32 => s.binary(0);708709// The binary operators, loosest first, a level each.710const LEVELS: [&[&[u8]] : 10] = [711 &[&"||"],712 &[&"&&"],713 &[&"|"],714 &[&"^"],715 &[&"&"],716 &[&"==", &"!="],717 &[&"<", &">", &"<=", &">="],718 &[&"<<", &">>"],719 &[&"+", &"-"],720 &[&"*", &"/", &"%"]721];722723fn binary(self s: &var Syntax, level: u64) -> u32 {724 if (level == LEVELS.length()) {725 return s.unary();726 }727 var left = s.binary(level + 1);728 while (729 !s.failed()730 && s.peek_kind() == TokenKind::Symbol731 && in_level(&LEVELS[level], &s.peek())732 ) {733 const token = s.at;734 s.at += 1;735 const right = s.binary(level + 1);736 left = s.add_expr(token, ::Binary(Operands { .left = left, .right = right }));737 }738 return left;739}740741fn additive(self s: &var Syntax) -> u32 => s.binary(8);742743fn in_level(level: &[&[u8]], operator: &[u8]) -> bool {744 for (level) |&o| {745 if (o == operator) {746 return true;747 }748 }749 return false;750}751752fn unary(self s: &var Syntax) -> u32 {753 if (!s.failed() && s.peek_kind() == TokenKind::Symbol) {754 const operator = &s.peek();755 if (operator == "-" || operator == "!" || operator == "~") {756 const token = s.at;757 s.at += 1;758 const operand = s.unary();759 return s.add_expr(token, ::Unary(operand));760 }761 }762 return s.postfix();763}764765fn postfix(self s: &var Syntax) -> u32 {766 var value = s.primary();767 while (!s.failed()) {768 if (s.take(&".")) {769 const member = s.name();770 value = s.add_expr(member, ::Member(value));771 } else if (s.peek() == "[") {772 const token = s.at;773 s.at += 1;774 const index = s.expression();775 s.expect(&"]");776 value = s.add_expr(token, ::Index(Operands { .left = value, .right = index }));777 } else {778 break;779 }780 }781 return value;782}783784fn primary(self s: &var Syntax) -> u32 {785 if (s.failed()) {786 return 0;787 }788 const token = s.at;789 const kind = s.peek_kind();790 if (kind == TokenKind::Integer) {791 s.at += 1;792 return s.add_expr(token, ::Integer);793 }794 if (kind == TokenKind::Float) {795 s.at += 1;796 return s.add_expr(token, ::Float);797 }798 if (s.take(&"(")) {799 const inner = s.expression();800 s.expect(&")");801 return inner;802 }803 if (kind != TokenKind::Name) {804 s.fail(&"expected an expression");805 return 0;806 }807 if (s.peek() == "true" || s.peek() == "false") {808 s.at += 1;809 return s.add_expr(token, ::Bool);810 }811 // a call, or a constructor whose type has template arguments812 var ty: Option<u32> = ::None;813 if (s.text_of(token + 1) == "<" && s.is_template_start()) {814 ty = ::Some(s.type_node());815 } else {816 s.at += 1;817 }818 if (!s.take(&"(")) {819 if (ty is ::Some) {820 s.fail(&"expected '('");821 }822 return s.add_expr(token, ::Name);823 }824 var arguments = Vector<u32>::empty();825 while (!s.failed() && !s.take(&")")) {826 arguments.push(s.expression());827 if (!s.take(&",")) {828 s.expect(&")");829 break;830 }831 }832 const listed = s.list(&arguments.view());833 return s.add_expr(token, ::Call(Call { .ty = ty, .arguments = listed }));834}835836// Whether the name before `<` starts a template, as for `vec4<f32>(` or837// `bitcast<u32>(`, rather than a comparison: a matching `>` follows,838// then `(`.839fn is_template_start(self s: &Syntax) -> bool {840 var depth: u32 = 0;841 for ([s.at + 1..s.tokens.length() to u32]) |k| {842 const t = &s.text_of(k);843 match (t) {844 "<" {845 depth += 1;846 }847 ">", ">>" {848 const closing = t.length() to u32;849 if (closing >= depth) {850 return s.text_of(k + 1) == "(";851 }852 depth -= closing;853 }854 ";", "{", "}", "=", "&&", "||" {855 return false;856 }857 }858 }859 return false;860}