From 76ab1d2b6c9eedd861920ae6b6f8ee06aa482159 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 30 Apr 2018 14:20:56 -0400 Subject: [PATCH 01/75] support foo.* for ptr deref See #770 --- doc/langref.html.in | 6 ++++-- src/all_types.hpp | 6 ++++++ src/analyze.cpp | 1 + src/ast_render.cpp | 9 +++++++++ src/ir.cpp | 12 ++++++++++-- src/parser.cpp | 30 ++++++++++++++++++++++++------ test/behavior.zig | 1 + test/cases/pointers.zig | 14 ++++++++++++++ 8 files changed, 69 insertions(+), 10 deletions(-) create mode 100644 test/cases/pointers.zig diff --git a/doc/langref.html.in b/doc/langref.html.in index 16fafdaad9..9fb2ebf9f5 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -5958,10 +5958,12 @@ MultiplyOperator = "||" | "*" | "/" | "%" | "**" | "*%" PrefixOpExpression = PrefixOp TypeExpr | SuffixOpExpression -SuffixOpExpression = ("async" option("<" SuffixOpExpression ">") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | SliceExpression) +SuffixOpExpression = ("async" option("<" SuffixOpExpression ">") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | SliceExpression | PtrDerefExpression) FieldAccessExpression = "." Symbol +PtrDerefExpression = ".*" + FnCallExpression = "(" list(Expression, ",") ")" ArrayAccessExpression = "[" Expression "]" @@ -5974,7 +5976,7 @@ ContainerInitBody = list(StructLiteralField, ",") | list(Expression, ",") StructLiteralField = "." Symbol "=" Expression -PrefixOp = "!" | "-" | "~" | "*" | ("&" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await" +PrefixOp = "!" | "-" | "~" | ("*" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await" PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ContainerDecl | ("continue" option(":" Symbol)) | ErrorSetDecl | PromiseType diff --git a/src/all_types.hpp b/src/all_types.hpp index d1b2ad61d2..2993589f7b 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -379,6 +379,7 @@ enum NodeType { NodeTypeArrayAccessExpr, NodeTypeSliceExpr, NodeTypeFieldAccessExpr, + NodeTypePtrDeref, NodeTypeUse, NodeTypeBoolLiteral, NodeTypeNullLiteral, @@ -603,6 +604,10 @@ struct AstNodeFieldAccessExpr { Buf *field_name; }; +struct AstNodePtrDerefExpr { + AstNode *target; +}; + enum PrefixOp { PrefixOpInvalid, PrefixOpBoolNot, @@ -911,6 +916,7 @@ struct AstNode { AstNodeCompTime comptime_expr; AstNodeAsmExpr asm_expr; AstNodeFieldAccessExpr field_access_expr; + AstNodePtrDerefExpr ptr_deref_expr; AstNodeContainerDecl container_decl; AstNodeStructField struct_field; AstNodeStringLiteral string_literal; diff --git a/src/analyze.cpp b/src/analyze.cpp index 1ecfe32f4c..99712cbfaf 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -3275,6 +3275,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) { case NodeTypeUnreachable: case NodeTypeAsmExpr: case NodeTypeFieldAccessExpr: + case NodeTypePtrDeref: case NodeTypeStructField: case NodeTypeContainerInitExpr: case NodeTypeStructValueField: diff --git a/src/ast_render.cpp b/src/ast_render.cpp index 2c3e1fc873..3e5ef0fcdb 100644 --- a/src/ast_render.cpp +++ b/src/ast_render.cpp @@ -222,6 +222,8 @@ static const char *node_type_str(NodeType node_type) { return "AsmExpr"; case NodeTypeFieldAccessExpr: return "FieldAccessExpr"; + case NodeTypePtrDeref: + return "PtrDerefExpr"; case NodeTypeContainerDecl: return "ContainerDecl"; case NodeTypeStructField: @@ -696,6 +698,13 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) { print_symbol(ar, rhs); break; } + case NodeTypePtrDeref: + { + AstNode *lhs = node->data.ptr_deref_expr.target; + render_node_ungrouped(ar, lhs); + fprintf(ar->f, ".*"); + break; + } case NodeTypeUndefinedLiteral: fprintf(ar->f, "undefined"); break; diff --git a/src/ir.cpp b/src/ir.cpp index 469900bf07..8c7232722e 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -4548,8 +4548,14 @@ static IrInstruction *ir_gen_if_bool_expr(IrBuilder *irb, Scope *scope, AstNode } static IrInstruction *ir_gen_prefix_op_id_lval(IrBuilder *irb, Scope *scope, AstNode *node, IrUnOp op_id, LVal lval) { - assert(node->type == NodeTypePrefixOpExpr); - AstNode *expr_node = node->data.prefix_op_expr.primary_expr; + AstNode *expr_node; + if (node->type == NodeTypePrefixOpExpr) { + expr_node = node->data.prefix_op_expr.primary_expr; + } else if (node->type == NodeTypePtrDeref) { + expr_node = node->data.ptr_deref_expr.target; + } else { + zig_unreachable(); + } IrInstruction *value = ir_gen_node_extra(irb, expr_node, scope, lval); if (value == irb->codegen->invalid_instruction) @@ -6527,6 +6533,8 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop return ir_build_load_ptr(irb, scope, node, ptr_instruction); } + case NodeTypePtrDeref: + return ir_gen_prefix_op_id_lval(irb, scope, node, IrUnOpDereference, lval); case NodeTypeThisLiteral: return ir_lval_wrap(irb, scope, ir_gen_this_literal(irb, scope, node), lval); case NodeTypeBoolLiteral: diff --git a/src/parser.cpp b/src/parser.cpp index 4b70e904b8..c02546a99d 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -1046,11 +1046,12 @@ static AstNode *ast_parse_fn_proto_partial(ParseContext *pc, size_t *token_index } /* -SuffixOpExpression = ("async" option("<" SuffixOpExpression ">") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | SliceExpression) +SuffixOpExpression = ("async" option("<" SuffixOpExpression ">") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | PtrDerefExpression | SliceExpression) FnCallExpression : token(LParen) list(Expression, token(Comma)) token(RParen) ArrayAccessExpression : token(LBracket) Expression token(RBracket) SliceExpression = "[" Expression ".." option(Expression) "]" FieldAccessExpression : token(Dot) token(Symbol) +PtrDerefExpression = ".*" StructLiteralField : token(Dot) token(Symbol) token(Eq) Expression */ static AstNode *ast_parse_suffix_op_expr(ParseContext *pc, size_t *token_index, bool mandatory) { @@ -1131,13 +1132,27 @@ static AstNode *ast_parse_suffix_op_expr(ParseContext *pc, size_t *token_index, } else if (first_token->id == TokenIdDot) { *token_index += 1; - Token *name_token = ast_eat_token(pc, token_index, TokenIdSymbol); + Token *token = &pc->tokens->at(*token_index); - AstNode *node = ast_create_node(pc, NodeTypeFieldAccessExpr, first_token); - node->data.field_access_expr.struct_expr = primary_expr; - node->data.field_access_expr.field_name = token_buf(name_token); + if (token->id == TokenIdSymbol) { + *token_index += 1; + + AstNode *node = ast_create_node(pc, NodeTypeFieldAccessExpr, first_token); + node->data.field_access_expr.struct_expr = primary_expr; + node->data.field_access_expr.field_name = token_buf(token); + + primary_expr = node; + } else if (token->id == TokenIdStar) { + *token_index += 1; + + AstNode *node = ast_create_node(pc, NodeTypePtrDeref, first_token); + node->data.ptr_deref_expr.target = primary_expr; + + primary_expr = node; + } else { + ast_invalid_token_error(pc, token); + } - primary_expr = node; } else { return primary_expr; } @@ -3012,6 +3027,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont case NodeTypeFieldAccessExpr: visit_field(&node->data.field_access_expr.struct_expr, visit, context); break; + case NodeTypePtrDeref: + visit_field(&node->data.ptr_deref_expr.target, visit, context); + break; case NodeTypeUse: visit_field(&node->data.use.expr, visit, context); break; diff --git a/test/behavior.zig b/test/behavior.zig index 2c10c6d71b..cb484b39a5 100644 --- a/test/behavior.zig +++ b/test/behavior.zig @@ -33,6 +33,7 @@ comptime { _ = @import("cases/misc.zig"); _ = @import("cases/namespace_depends_on_compile_var/index.zig"); _ = @import("cases/null.zig"); + _ = @import("cases/pointers.zig"); _ = @import("cases/pub_enum/index.zig"); _ = @import("cases/ref_var_in_if_after_if_2nd_switch_prong.zig"); _ = @import("cases/reflection.zig"); diff --git a/test/cases/pointers.zig b/test/cases/pointers.zig new file mode 100644 index 0000000000..87b3d25a74 --- /dev/null +++ b/test/cases/pointers.zig @@ -0,0 +1,14 @@ +const std = @import("std"); +const assert = std.debug.assert; + +test "dereference pointer" { + comptime testDerefPtr(); + testDerefPtr(); +} + +fn testDerefPtr() void { + var x: i32 = 1234; + var y = &x; + y.* += 1; + assert(x == 1235); +} From a35b366eb64272c6d4646aedc035a837ed0c3cb0 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 30 Apr 2018 20:35:54 -0400 Subject: [PATCH 02/75] [breaking] delete ptr deref prefix op start using zig-fmt-pointer-reform branch build of zig fmt to fix code to use the new syntax all of test/cases/* are processed, but there are more left to be done - all the std lib used by the behavior tests --- src/all_types.hpp | 1 - src/ast_render.cpp | 1 - src/ir.cpp | 2 - src/parser.cpp | 13 +- src/translate_c.cpp | 83 ++- std/debug/index.zig | 233 +++---- std/math/index.zig | 75 +-- std/mem.zig | 197 +++--- std/zig/parser.zig | 9 +- test/cases/align.zig | 86 ++- test/cases/alignof.zig | 6 +- test/cases/array.zig | 41 +- test/cases/bitcast.zig | 8 +- test/cases/bugs/394.zig | 17 +- test/cases/bugs/655.zig | 2 +- test/cases/bugs/656.zig | 11 +- test/cases/bugs/828.zig | 10 +- test/cases/bugs/920.zig | 19 +- test/cases/cast.zig | 72 ++- test/cases/coroutines.zig | 18 +- test/cases/defer.zig | 15 +- test/cases/enum.zig | 606 ++++++++++++++++-- test/cases/enum_with_members.zig | 10 +- test/cases/error.zig | 56 +- test/cases/eval.zig | 143 +++-- test/cases/fn.zig | 44 +- test/cases/for.zig | 44 +- test/cases/generics.zig | 42 +- test/cases/if.zig | 1 - test/cases/import/a_namespace.zig | 4 +- test/cases/ir_block_deps.zig | 4 +- test/cases/math.zig | 92 ++- test/cases/misc.zig | 225 ++++--- .../index.zig | 2 +- test/cases/null.zig | 27 +- ...ef_var_in_if_after_if_2nd_switch_prong.zig | 2 +- test/cases/reflection.zig | 5 +- test/cases/slice.zig | 8 +- test/cases/struct.zig | 83 ++- .../cases/struct_contains_null_ptr_itself.zig | 1 - .../cases/struct_contains_slice_of_itself.zig | 2 +- test/cases/switch.zig | 49 +- test/cases/switch_prong_err_enum.zig | 8 +- test/cases/switch_prong_implicit_cast.zig | 8 +- test/cases/try.zig | 8 +- test/cases/undefined.zig | 4 +- test/cases/union.zig | 87 +-- test/cases/var_args.zig | 25 +- test/cases/while.zig | 65 +- 49 files changed, 1694 insertions(+), 880 deletions(-) diff --git a/src/all_types.hpp b/src/all_types.hpp index 2993589f7b..a25c99edda 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -614,7 +614,6 @@ enum PrefixOp { PrefixOpBinNot, PrefixOpNegation, PrefixOpNegationWrap, - PrefixOpDereference, PrefixOpMaybe, PrefixOpUnwrapMaybe, }; diff --git a/src/ast_render.cpp b/src/ast_render.cpp index 3e5ef0fcdb..0cb8bf4e93 100644 --- a/src/ast_render.cpp +++ b/src/ast_render.cpp @@ -66,7 +66,6 @@ static const char *prefix_op_str(PrefixOp prefix_op) { case PrefixOpNegationWrap: return "-%"; case PrefixOpBoolNot: return "!"; case PrefixOpBinNot: return "~"; - case PrefixOpDereference: return "*"; case PrefixOpMaybe: return "?"; case PrefixOpUnwrapMaybe: return "??"; } diff --git a/src/ir.cpp b/src/ir.cpp index 8c7232722e..ff5afe138c 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -4696,8 +4696,6 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpNegation), lval); case PrefixOpNegationWrap: return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpNegationWrap), lval); - case PrefixOpDereference: - return ir_gen_prefix_op_id_lval(irb, scope, node, IrUnOpDereference, lval); case PrefixOpMaybe: return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpMaybe), lval); case PrefixOpUnwrapMaybe: diff --git a/src/parser.cpp b/src/parser.cpp index c02546a99d..4763d3b987 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -1165,10 +1165,8 @@ static PrefixOp tok_to_prefix_op(Token *token) { case TokenIdDash: return PrefixOpNegation; case TokenIdMinusPercent: return PrefixOpNegationWrap; case TokenIdTilde: return PrefixOpBinNot; - case TokenIdStar: return PrefixOpDereference; case TokenIdMaybe: return PrefixOpMaybe; case TokenIdDoubleQuestion: return PrefixOpUnwrapMaybe; - case TokenIdStarStar: return PrefixOpDereference; default: return PrefixOpInvalid; } } @@ -1214,7 +1212,7 @@ static AstNode *ast_parse_addr_of(ParseContext *pc, size_t *token_index) { /* PrefixOpExpression = PrefixOp ErrorSetExpr | SuffixOpExpression -PrefixOp = "!" | "-" | "~" | "*" | ("&" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await" +PrefixOp = "!" | "-" | "~" | ("*" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await" */ static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index, bool mandatory) { Token *token = &pc->tokens->at(*token_index); @@ -1237,15 +1235,6 @@ static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index, AstNode *node = ast_create_node(pc, NodeTypePrefixOpExpr, token); AstNode *parent_node = node; - if (token->id == TokenIdStarStar) { - // pretend that we got 2 star tokens - - parent_node = ast_create_node(pc, NodeTypePrefixOpExpr, token); - parent_node->data.prefix_op_expr.primary_expr = node; - parent_node->data.prefix_op_expr.prefix_op = PrefixOpDereference; - - node->column += 1; - } AstNode *prefix_op_expr = ast_parse_error_set_expr(pc, token_index, true); node->data.prefix_op_expr.primary_expr = prefix_op_expr; diff --git a/src/translate_c.cpp b/src/translate_c.cpp index 965a8963bd..70a98dcc2e 100644 --- a/src/translate_c.cpp +++ b/src/translate_c.cpp @@ -247,6 +247,12 @@ static AstNode *trans_create_node_field_access_str(Context *c, AstNode *containe return trans_create_node_field_access(c, container, buf_create_from_str(field_name)); } +static AstNode *trans_create_node_ptr_deref(Context *c, AstNode *child_node) { + AstNode *node = trans_create_node(c, NodeTypePtrDeref); + node->data.ptr_deref_expr.target = child_node; + return node; +} + static AstNode *trans_create_node_prefix_op(Context *c, PrefixOp op, AstNode *child_node) { AstNode *node = trans_create_node(c, NodeTypePrefixOpExpr); node->data.prefix_op_expr.prefix_op = op; @@ -1412,8 +1418,7 @@ static AstNode *trans_create_compound_assign_shift(Context *c, ResultUsed result AstNode *operation_type_cast = trans_c_cast(c, rhs_location, stmt->getComputationLHSType(), stmt->getLHS()->getType(), - trans_create_node_prefix_op(c, PrefixOpDereference, - trans_create_node_symbol(c, tmp_var_name))); + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, tmp_var_name))); // result_type(... >> u5(rhs)) AstNode *result_type_cast = trans_c_cast(c, rhs_location, @@ -1426,7 +1431,7 @@ static AstNode *trans_create_compound_assign_shift(Context *c, ResultUsed result // *_ref = ... AstNode *assign_statement = trans_create_node_bin_op(c, - trans_create_node_prefix_op(c, PrefixOpDereference, + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, tmp_var_name)), BinOpTypeAssign, result_type_cast); @@ -1436,7 +1441,7 @@ static AstNode *trans_create_compound_assign_shift(Context *c, ResultUsed result // break :x *_ref child_scope->node->data.block.statements.append( trans_create_node_break(c, label_name, - trans_create_node_prefix_op(c, PrefixOpDereference, + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, tmp_var_name)))); } @@ -1483,11 +1488,11 @@ static AstNode *trans_create_compound_assign(Context *c, ResultUsed result_used, if (rhs == nullptr) return nullptr; AstNode *assign_statement = trans_create_node_bin_op(c, - trans_create_node_prefix_op(c, PrefixOpDereference, + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, tmp_var_name)), BinOpTypeAssign, trans_create_node_bin_op(c, - trans_create_node_prefix_op(c, PrefixOpDereference, + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, tmp_var_name)), bin_op, rhs)); @@ -1496,7 +1501,7 @@ static AstNode *trans_create_compound_assign(Context *c, ResultUsed result_used, // break :x *_ref child_scope->node->data.block.statements.append( trans_create_node_break(c, label_name, - trans_create_node_prefix_op(c, PrefixOpDereference, + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, tmp_var_name)))); return child_scope->node; @@ -1817,13 +1822,13 @@ static AstNode *trans_create_post_crement(Context *c, ResultUsed result_used, Tr // const _tmp = *_ref; Buf* tmp_var_name = buf_create_from_str("_tmp"); AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, - trans_create_node_prefix_op(c, PrefixOpDereference, + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, ref_var_name))); child_scope->node->data.block.statements.append(tmp_var_decl); // *_ref += 1; AstNode *assign_statement = trans_create_node_bin_op(c, - trans_create_node_prefix_op(c, PrefixOpDereference, + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, ref_var_name)), assign_op, trans_create_node_unsigned(c, 1)); @@ -1871,14 +1876,14 @@ static AstNode *trans_create_pre_crement(Context *c, ResultUsed result_used, Tra // *_ref += 1; AstNode *assign_statement = trans_create_node_bin_op(c, - trans_create_node_prefix_op(c, PrefixOpDereference, + trans_create_node_ptr_deref(c, trans_create_node_symbol(c, ref_var_name)), assign_op, trans_create_node_unsigned(c, 1)); child_scope->node->data.block.statements.append(assign_statement); // break :x *_ref - AstNode *deref_expr = trans_create_node_prefix_op(c, PrefixOpDereference, + AstNode *deref_expr = trans_create_node_ptr_deref(c, trans_create_node_symbol(c, ref_var_name)); child_scope->node->data.block.statements.append(trans_create_node_break(c, label_name, deref_expr)); @@ -1923,7 +1928,7 @@ static AstNode *trans_unary_operator(Context *c, ResultUsed result_used, TransSc if (is_fn_ptr) return value_node; AstNode *unwrapped = trans_create_node_prefix_op(c, PrefixOpUnwrapMaybe, value_node); - return trans_create_node_prefix_op(c, PrefixOpDereference, unwrapped); + return trans_create_node_ptr_deref(c, unwrapped); } case UO_Plus: emit_warning(c, stmt->getLocStart(), "TODO handle C translation UO_Plus"); @@ -4469,27 +4474,45 @@ static AstNode *parse_ctok_suffix_op_expr(Context *c, CTokenize *ctok, size_t *t } } -static PrefixOp ctok_to_prefix_op(CTok *token) { - switch (token->id) { - case CTokIdBang: return PrefixOpBoolNot; - case CTokIdMinus: return PrefixOpNegation; - case CTokIdTilde: return PrefixOpBinNot; - case CTokIdAsterisk: return PrefixOpDereference; - default: return PrefixOpInvalid; - } -} static AstNode *parse_ctok_prefix_op_expr(Context *c, CTokenize *ctok, size_t *tok_i) { CTok *op_tok = &ctok->tokens.at(*tok_i); - PrefixOp prefix_op = ctok_to_prefix_op(op_tok); - if (prefix_op == PrefixOpInvalid) { - return parse_ctok_suffix_op_expr(c, ctok, tok_i); - } - *tok_i += 1; - AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i); - if (prefix_op_expr == nullptr) - return nullptr; - return trans_create_node_prefix_op(c, prefix_op, prefix_op_expr); + switch (op_tok->id) { + case CTokIdBang: + { + *tok_i += 1; + AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i); + if (prefix_op_expr == nullptr) + return nullptr; + return trans_create_node_prefix_op(c, PrefixOpBoolNot, prefix_op_expr); + } + case CTokIdMinus: + { + *tok_i += 1; + AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i); + if (prefix_op_expr == nullptr) + return nullptr; + return trans_create_node_prefix_op(c, PrefixOpNegation, prefix_op_expr); + } + case CTokIdTilde: + { + *tok_i += 1; + AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i); + if (prefix_op_expr == nullptr) + return nullptr; + return trans_create_node_prefix_op(c, PrefixOpBinNot, prefix_op_expr); + } + case CTokIdAsterisk: + { + *tok_i += 1; + AstNode *prefix_op_expr = parse_ctok_prefix_op_expr(c, ctok, tok_i); + if (prefix_op_expr == nullptr) + return nullptr; + return trans_create_node_ptr_deref(c, prefix_op_expr); + } + default: + return parse_ctok_suffix_op_expr(c, ctok, tok_i); + } } static void process_macro(Context *c, CTokenize *ctok, Buf *name, const char *char_ptr) { diff --git a/std/debug/index.zig b/std/debug/index.zig index 9057f157de..36ac2e8a3f 100644 --- a/std/debug/index.zig +++ b/std/debug/index.zig @@ -104,9 +104,7 @@ pub fn panic(comptime format: []const u8, args: ...) noreturn { var panicking: u8 = 0; // TODO make this a bool -pub fn panicExtra(trace: ?&const builtin.StackTrace, first_trace_addr: ?usize, - comptime format: []const u8, args: ...) noreturn -{ +pub fn panicExtra(trace: ?&const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn { @setCold(true); if (@atomicRmw(u8, &panicking, builtin.AtomicRmwOp.Xchg, 1, builtin.AtomicOrder.SeqCst) == 1) { @@ -132,9 +130,7 @@ const WHITE = "\x1b[37;1m"; const DIM = "\x1b[2m"; const RESET = "\x1b[0m"; -pub fn writeStackTrace(stack_trace: &const builtin.StackTrace, out_stream: var, allocator: &mem.Allocator, - debug_info: &ElfStackTrace, tty_color: bool) !void -{ +pub fn writeStackTrace(stack_trace: &const builtin.StackTrace, out_stream: var, allocator: &mem.Allocator, debug_info: &ElfStackTrace, tty_color: bool) !void { var frame_index: usize = undefined; var frames_left: usize = undefined; if (stack_trace.index < stack_trace.instruction_addresses.len) { @@ -154,9 +150,7 @@ pub fn writeStackTrace(stack_trace: &const builtin.StackTrace, out_stream: var, } } -pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, - debug_info: &ElfStackTrace, tty_color: bool, start_addr: ?usize) !void -{ +pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_info: &ElfStackTrace, tty_color: bool, start_addr: ?usize) !void { const AddressState = union(enum) { NotLookingForStartAddress, LookingForStartAddress: usize, @@ -166,14 +160,14 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, // else AddressState.NotLookingForStartAddress; var addr_state: AddressState = undefined; if (start_addr) |addr| { - addr_state = AddressState { .LookingForStartAddress = addr }; + addr_state = AddressState{ .LookingForStartAddress = addr }; } else { addr_state = AddressState.NotLookingForStartAddress; } var fp = @ptrToInt(@frameAddress()); - while (fp != 0) : (fp = *@intToPtr(&const usize, fp)) { - const return_address = *@intToPtr(&const usize, fp + @sizeOf(usize)); + while (fp != 0) : (fp = @intToPtr(&const usize, fp).*) { + const return_address = @intToPtr(&const usize, fp + @sizeOf(usize)).*; switch (addr_state) { AddressState.NotLookingForStartAddress => {}, @@ -200,32 +194,32 @@ fn printSourceAtAddress(debug_info: &ElfStackTrace, out_stream: var, address: us // in practice because the compiler dumps everything in a single // object file. Future improvement: use external dSYM data when // available. - const unknown = macho.Symbol { .name = "???", .address = address }; + const unknown = macho.Symbol{ + .name = "???", + .address = address, + }; const symbol = debug_info.symbol_table.search(address) ?? &unknown; - try out_stream.print(WHITE ++ "{}" ++ RESET ++ ": " ++ - DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n", - symbol.name, address); + try out_stream.print(WHITE ++ "{}" ++ RESET ++ ": " ++ DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n", symbol.name, address); }, else => { const compile_unit = findCompileUnit(debug_info, address) catch { - try out_stream.print("???:?:?: " ++ DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n ???\n\n", - address); + try out_stream.print("???:?:?: " ++ DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n ???\n\n", address); return; }; const compile_unit_name = try compile_unit.die.getAttrString(debug_info, DW.AT_name); if (getLineNumberInfo(debug_info, compile_unit, address - 1)) |line_info| { defer line_info.deinit(); - try out_stream.print(WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ - DIM ++ ptr_hex ++ " in ??? ({})" ++ RESET ++ "\n", - line_info.file_name, line_info.line, line_info.column, - address, compile_unit_name); + try out_stream.print(WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ DIM ++ ptr_hex ++ " in ??? ({})" ++ RESET ++ "\n", line_info.file_name, line_info.line, line_info.column, address, compile_unit_name); if (printLineFromFile(debug_info.allocator(), out_stream, line_info)) { if (line_info.column == 0) { try out_stream.write("\n"); } else { - {var col_i: usize = 1; while (col_i < line_info.column) : (col_i += 1) { - try out_stream.writeByte(' '); - }} + { + var col_i: usize = 1; + while (col_i < line_info.column) : (col_i += 1) { + try out_stream.writeByte(' '); + } + } try out_stream.write(GREEN ++ "^" ++ RESET ++ "\n"); } } else |err| switch (err) { @@ -233,7 +227,8 @@ fn printSourceAtAddress(debug_info: &ElfStackTrace, out_stream: var, address: us else => return err, } } else |err| switch (err) { - error.MissingDebugInfo, error.InvalidDebugInfo => { + error.MissingDebugInfo, + error.InvalidDebugInfo => { try out_stream.print(ptr_hex ++ " in ??? ({})\n", address, compile_unit_name); }, else => return err, @@ -247,7 +242,7 @@ pub fn openSelfDebugInfo(allocator: &mem.Allocator) !&ElfStackTrace { builtin.ObjectFormat.elf => { const st = try allocator.create(ElfStackTrace); errdefer allocator.destroy(st); - *st = ElfStackTrace { + st.* = ElfStackTrace{ .self_exe_file = undefined, .elf = undefined, .debug_info = undefined, @@ -279,9 +274,7 @@ pub fn openSelfDebugInfo(allocator: &mem.Allocator) !&ElfStackTrace { const st = try allocator.create(ElfStackTrace); errdefer allocator.destroy(st); - *st = ElfStackTrace { - .symbol_table = try macho.loadSymbols(allocator, &io.FileInStream.init(&exe_file)), - }; + st.* = ElfStackTrace{ .symbol_table = try macho.loadSymbols(allocator, &io.FileInStream.init(&exe_file)) }; return st; }, @@ -325,8 +318,7 @@ fn printLineFromFile(allocator: &mem.Allocator, out_stream: var, line_info: &con } } - if (amt_read < buf.len) - return error.EndOfFile; + if (amt_read < buf.len) return error.EndOfFile; } } @@ -418,10 +410,8 @@ const Constant = struct { signed: bool, fn asUnsignedLe(self: &const Constant) !u64 { - if (self.payload.len > @sizeOf(u64)) - return error.InvalidDebugInfo; - if (self.signed) - return error.InvalidDebugInfo; + if (self.payload.len > @sizeOf(u64)) return error.InvalidDebugInfo; + if (self.signed) return error.InvalidDebugInfo; return mem.readInt(self.payload, u64, builtin.Endian.Little); } }; @@ -438,15 +428,14 @@ const Die = struct { fn getAttr(self: &const Die, id: u64) ?&const FormValue { for (self.attrs.toSliceConst()) |*attr| { - if (attr.id == id) - return &attr.value; + if (attr.id == id) return &attr.value; } return null; } fn getAttrAddr(self: &const Die, id: u64) !u64 { const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; - return switch (*form_value) { + return switch (form_value.*) { FormValue.Address => |value| value, else => error.InvalidDebugInfo, }; @@ -454,7 +443,7 @@ const Die = struct { fn getAttrSecOffset(self: &const Die, id: u64) !u64 { const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; - return switch (*form_value) { + return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), FormValue.SecOffset => |value| value, else => error.InvalidDebugInfo, @@ -463,7 +452,7 @@ const Die = struct { fn getAttrUnsignedLe(self: &const Die, id: u64) !u64 { const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; - return switch (*form_value) { + return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), else => error.InvalidDebugInfo, }; @@ -471,7 +460,7 @@ const Die = struct { fn getAttrString(self: &const Die, st: &ElfStackTrace, id: u64) ![]u8 { const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; - return switch (*form_value) { + return switch (form_value.*) { FormValue.String => |value| value, FormValue.StrPtr => |offset| getString(st, offset), else => error.InvalidDebugInfo, @@ -518,10 +507,8 @@ const LineNumberProgram = struct { prev_basic_block: bool, prev_end_sequence: bool, - pub fn init(is_stmt: bool, include_dirs: []const []const u8, - file_entries: &ArrayList(FileEntry), target_address: usize) LineNumberProgram - { - return LineNumberProgram { + pub fn init(is_stmt: bool, include_dirs: []const []const u8, file_entries: &ArrayList(FileEntry), target_address: usize) LineNumberProgram { + return LineNumberProgram{ .address = 0, .file = 1, .line = 1, @@ -548,14 +535,16 @@ const LineNumberProgram = struct { return error.MissingDebugInfo; } else if (self.prev_file - 1 >= self.file_entries.len) { return error.InvalidDebugInfo; - } else &self.file_entries.items[self.prev_file - 1]; + } else + &self.file_entries.items[self.prev_file - 1]; const dir_name = if (file_entry.dir_index >= self.include_dirs.len) { return error.InvalidDebugInfo; - } else self.include_dirs[file_entry.dir_index]; + } else + self.include_dirs[file_entry.dir_index]; const file_name = try os.path.join(self.file_entries.allocator, dir_name, file_entry.file_name); errdefer self.file_entries.allocator.free(file_name); - return LineInfo { + return LineInfo{ .line = if (self.prev_line >= 0) usize(self.prev_line) else 0, .column = self.prev_column, .file_name = file_name, @@ -578,8 +567,7 @@ fn readStringRaw(allocator: &mem.Allocator, in_stream: var) ![]u8 { var buf = ArrayList(u8).init(allocator); while (true) { const byte = try in_stream.readByte(); - if (byte == 0) - break; + if (byte == 0) break; try buf.append(byte); } return buf.toSlice(); @@ -600,7 +588,7 @@ fn readAllocBytes(allocator: &mem.Allocator, in_stream: var, size: usize) ![]u8 fn parseFormValueBlockLen(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue { const buf = try readAllocBytes(allocator, in_stream, size); - return FormValue { .Block = buf }; + return FormValue{ .Block = buf }; } fn parseFormValueBlock(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue { @@ -609,26 +597,23 @@ fn parseFormValueBlock(allocator: &mem.Allocator, in_stream: var, size: usize) ! } fn parseFormValueConstant(allocator: &mem.Allocator, in_stream: var, signed: bool, size: usize) !FormValue { - return FormValue { .Const = Constant { + return FormValue{ .Const = Constant{ .signed = signed, .payload = try readAllocBytes(allocator, in_stream, size), - }}; + } }; } fn parseFormValueDwarfOffsetSize(in_stream: var, is_64: bool) !u64 { - return if (is_64) try in_stream.readIntLe(u64) - else u64(try in_stream.readIntLe(u32)) ; + return if (is_64) try in_stream.readIntLe(u64) else u64(try in_stream.readIntLe(u32)); } fn parseFormValueTargetAddrSize(in_stream: var) !u64 { - return if (@sizeOf(usize) == 4) u64(try in_stream.readIntLe(u32)) - else if (@sizeOf(usize) == 8) try in_stream.readIntLe(u64) - else unreachable; + return if (@sizeOf(usize) == 4) u64(try in_stream.readIntLe(u32)) else if (@sizeOf(usize) == 8) try in_stream.readIntLe(u64) else unreachable; } fn parseFormValueRefLen(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue { const buf = try readAllocBytes(allocator, in_stream, size); - return FormValue { .Ref = buf }; + return FormValue{ .Ref = buf }; } fn parseFormValueRef(allocator: &mem.Allocator, in_stream: var, comptime T: type) !FormValue { @@ -646,11 +631,9 @@ const ParseFormValueError = error { OutOfMemory, }; -fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64: bool) - ParseFormValueError!FormValue -{ +fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64: bool) ParseFormValueError!FormValue { return switch (form_id) { - DW.FORM_addr => FormValue { .Address = try parseFormValueTargetAddrSize(in_stream) }, + DW.FORM_addr => FormValue{ .Address = try parseFormValueTargetAddrSize(in_stream) }, DW.FORM_block1 => parseFormValueBlock(allocator, in_stream, 1), DW.FORM_block2 => parseFormValueBlock(allocator, in_stream, 2), DW.FORM_block4 => parseFormValueBlock(allocator, in_stream, 4), @@ -662,7 +645,8 @@ fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64 DW.FORM_data2 => parseFormValueConstant(allocator, in_stream, false, 2), DW.FORM_data4 => parseFormValueConstant(allocator, in_stream, false, 4), DW.FORM_data8 => parseFormValueConstant(allocator, in_stream, false, 8), - DW.FORM_udata, DW.FORM_sdata => { + DW.FORM_udata, + DW.FORM_sdata => { const block_len = try readULeb128(in_stream); const signed = form_id == DW.FORM_sdata; return parseFormValueConstant(allocator, in_stream, signed, block_len); @@ -670,11 +654,11 @@ fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64 DW.FORM_exprloc => { const size = try readULeb128(in_stream); const buf = try readAllocBytes(allocator, in_stream, size); - return FormValue { .ExprLoc = buf }; + return FormValue{ .ExprLoc = buf }; }, - DW.FORM_flag => FormValue { .Flag = (try in_stream.readByte()) != 0 }, - DW.FORM_flag_present => FormValue { .Flag = true }, - DW.FORM_sec_offset => FormValue { .SecOffset = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, + DW.FORM_flag => FormValue{ .Flag = (try in_stream.readByte()) != 0 }, + DW.FORM_flag_present => FormValue{ .Flag = true }, + DW.FORM_sec_offset => FormValue{ .SecOffset = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, DW.FORM_ref1 => parseFormValueRef(allocator, in_stream, u8), DW.FORM_ref2 => parseFormValueRef(allocator, in_stream, u16), @@ -685,11 +669,11 @@ fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64 return parseFormValueRefLen(allocator, in_stream, ref_len); }, - DW.FORM_ref_addr => FormValue { .RefAddr = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, - DW.FORM_ref_sig8 => FormValue { .RefSig8 = try in_stream.readIntLe(u64) }, + DW.FORM_ref_addr => FormValue{ .RefAddr = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, + DW.FORM_ref_sig8 => FormValue{ .RefSig8 = try in_stream.readIntLe(u64) }, - DW.FORM_string => FormValue { .String = try readStringRaw(allocator, in_stream) }, - DW.FORM_strp => FormValue { .StrPtr = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, + DW.FORM_string => FormValue{ .String = try readStringRaw(allocator, in_stream) }, + DW.FORM_strp => FormValue{ .StrPtr = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, DW.FORM_indirect => { const child_form_id = try readULeb128(in_stream); return parseFormValue(allocator, in_stream, child_form_id, is_64); @@ -705,9 +689,8 @@ fn parseAbbrevTable(st: &ElfStackTrace) !AbbrevTable { var result = AbbrevTable.init(st.allocator()); while (true) { const abbrev_code = try readULeb128(in_stream); - if (abbrev_code == 0) - return result; - try result.append(AbbrevTableEntry { + if (abbrev_code == 0) return result; + try result.append(AbbrevTableEntry{ .abbrev_code = abbrev_code, .tag_id = try readULeb128(in_stream), .has_children = (try in_stream.readByte()) == DW.CHILDREN_yes, @@ -718,9 +701,8 @@ fn parseAbbrevTable(st: &ElfStackTrace) !AbbrevTable { while (true) { const attr_id = try readULeb128(in_stream); const form_id = try readULeb128(in_stream); - if (attr_id == 0 and form_id == 0) - break; - try attrs.append(AbbrevAttr { + if (attr_id == 0 and form_id == 0) break; + try attrs.append(AbbrevAttr{ .attr_id = attr_id, .form_id = form_id, }); @@ -737,7 +719,7 @@ fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) !&const AbbrevTable { } } try st.self_exe_file.seekTo(st.debug_abbrev.offset + abbrev_offset); - try st.abbrev_table_list.append(AbbrevTableHeader { + try st.abbrev_table_list.append(AbbrevTableHeader{ .offset = abbrev_offset, .table = try parseAbbrevTable(st), }); @@ -746,8 +728,7 @@ fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) !&const AbbrevTable { fn getAbbrevTableEntry(abbrev_table: &const AbbrevTable, abbrev_code: u64) ?&const AbbrevTableEntry { for (abbrev_table.toSliceConst()) |*table_entry| { - if (table_entry.abbrev_code == abbrev_code) - return table_entry; + if (table_entry.abbrev_code == abbrev_code) return table_entry; } return null; } @@ -759,14 +740,14 @@ fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) ! const abbrev_code = try readULeb128(in_stream); const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) ?? return error.InvalidDebugInfo; - var result = Die { + var result = Die{ .tag_id = table_entry.tag_id, .has_children = table_entry.has_children, .attrs = ArrayList(Die.Attr).init(st.allocator()), }; try result.attrs.resize(table_entry.attrs.len); for (table_entry.attrs.toSliceConst()) |attr, i| { - result.attrs.items[i] = Die.Attr { + result.attrs.items[i] = Die.Attr{ .id = attr.attr_id, .value = try parseFormValue(st.allocator(), in_stream, attr.form_id, is_64), }; @@ -790,8 +771,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe var is_64: bool = undefined; const unit_length = try readInitialLength(@typeOf(in_stream.readFn).ReturnType.ErrorSet, in_stream, &is_64); - if (unit_length == 0) - return error.MissingDebugInfo; + if (unit_length == 0) return error.MissingDebugInfo; const next_offset = unit_length + (if (is_64) usize(12) else usize(4)); if (compile_unit.index != this_index) { @@ -803,8 +783,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe // TODO support 3 and 5 if (version != 2 and version != 4) return error.InvalidDebugInfo; - const prologue_length = if (is_64) try in_stream.readInt(st.elf.endian, u64) - else try in_stream.readInt(st.elf.endian, u32); + const prologue_length = if (is_64) try in_stream.readInt(st.elf.endian, u64) else try in_stream.readInt(st.elf.endian, u32); const prog_start_offset = (try in_file.getPos()) + prologue_length; const minimum_instruction_length = try in_stream.readByte(); @@ -819,38 +798,37 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe const line_base = try in_stream.readByteSigned(); const line_range = try in_stream.readByte(); - if (line_range == 0) - return error.InvalidDebugInfo; + if (line_range == 0) return error.InvalidDebugInfo; const opcode_base = try in_stream.readByte(); const standard_opcode_lengths = try st.allocator().alloc(u8, opcode_base - 1); - {var i: usize = 0; while (i < opcode_base - 1) : (i += 1) { - standard_opcode_lengths[i] = try in_stream.readByte(); - }} + { + var i: usize = 0; + while (i < opcode_base - 1) : (i += 1) { + standard_opcode_lengths[i] = try in_stream.readByte(); + } + } var include_directories = ArrayList([]u8).init(st.allocator()); try include_directories.append(compile_unit_cwd); while (true) { const dir = try st.readString(); - if (dir.len == 0) - break; + if (dir.len == 0) break; try include_directories.append(dir); } var file_entries = ArrayList(FileEntry).init(st.allocator()); - var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), - &file_entries, target_address); + var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address); while (true) { const file_name = try st.readString(); - if (file_name.len == 0) - break; + if (file_name.len == 0) break; const dir_index = try readULeb128(in_stream); const mtime = try readULeb128(in_stream); const len_bytes = try readULeb128(in_stream); - try file_entries.append(FileEntry { + try file_entries.append(FileEntry{ .file_name = file_name, .dir_index = dir_index, .mtime = mtime, @@ -866,8 +844,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe var sub_op: u8 = undefined; // TODO move this to the correct scope and fix the compiler crash if (opcode == DW.LNS_extended_op) { const op_size = try readULeb128(in_stream); - if (op_size < 1) - return error.InvalidDebugInfo; + if (op_size < 1) return error.InvalidDebugInfo; sub_op = try in_stream.readByte(); switch (sub_op) { DW.LNE_end_sequence => { @@ -884,7 +861,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe const dir_index = try readULeb128(in_stream); const mtime = try readULeb128(in_stream); const len_bytes = try readULeb128(in_stream); - try file_entries.append(FileEntry { + try file_entries.append(FileEntry{ .file_name = file_name, .dir_index = dir_index, .mtime = mtime, @@ -941,11 +918,9 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe const arg = try in_stream.readInt(st.elf.endian, u16); prog.address += arg; }, - DW.LNS_set_prologue_end => { - }, + DW.LNS_set_prologue_end => {}, else => { - if (opcode - 1 >= standard_opcode_lengths.len) - return error.InvalidDebugInfo; + if (opcode - 1 >= standard_opcode_lengths.len) return error.InvalidDebugInfo; const len_bytes = standard_opcode_lengths[opcode - 1]; try in_file.seekForward(len_bytes); }, @@ -972,16 +947,13 @@ fn scanAllCompileUnits(st: &ElfStackTrace) !void { var is_64: bool = undefined; const unit_length = try readInitialLength(@typeOf(in_stream.readFn).ReturnType.ErrorSet, in_stream, &is_64); - if (unit_length == 0) - return; + if (unit_length == 0) return; const next_offset = unit_length + (if (is_64) usize(12) else usize(4)); const version = try in_stream.readInt(st.elf.endian, u16); if (version < 2 or version > 5) return error.InvalidDebugInfo; - const debug_abbrev_offset = - if (is_64) try in_stream.readInt(st.elf.endian, u64) - else try in_stream.readInt(st.elf.endian, u32); + const debug_abbrev_offset = if (is_64) try in_stream.readInt(st.elf.endian, u64) else try in_stream.readInt(st.elf.endian, u32); const address_size = try in_stream.readByte(); if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo; @@ -992,15 +964,14 @@ fn scanAllCompileUnits(st: &ElfStackTrace) !void { try st.self_exe_file.seekTo(compile_unit_pos); const compile_unit_die = try st.allocator().create(Die); - *compile_unit_die = try parseDie(st, abbrev_table, is_64); + compile_unit_die.* = try parseDie(st, abbrev_table, is_64); - if (compile_unit_die.tag_id != DW.TAG_compile_unit) - return error.InvalidDebugInfo; + if (compile_unit_die.tag_id != DW.TAG_compile_unit) return error.InvalidDebugInfo; const pc_range = x: { if (compile_unit_die.getAttrAddr(DW.AT_low_pc)) |low_pc| { if (compile_unit_die.getAttr(DW.AT_high_pc)) |high_pc_value| { - const pc_end = switch (*high_pc_value) { + const pc_end = switch (high_pc_value.*) { FormValue.Address => |value| value, FormValue.Const => |value| b: { const offset = try value.asUnsignedLe(); @@ -1008,7 +979,7 @@ fn scanAllCompileUnits(st: &ElfStackTrace) !void { }, else => return error.InvalidDebugInfo, }; - break :x PcRange { + break :x PcRange{ .start = low_pc, .end = pc_end, }; @@ -1016,13 +987,12 @@ fn scanAllCompileUnits(st: &ElfStackTrace) !void { break :x null; } } else |err| { - if (err != error.MissingDebugInfo) - return err; + if (err != error.MissingDebugInfo) return err; break :x null; } }; - try st.compile_unit_list.append(CompileUnit { + try st.compile_unit_list.append(CompileUnit{ .version = version, .is_64 = is_64, .pc_range = pc_range, @@ -1040,8 +1010,7 @@ fn findCompileUnit(st: &ElfStackTrace, target_address: u64) !&const CompileUnit const in_stream = &in_file_stream.stream; for (st.compile_unit_list.toSlice()) |*compile_unit| { if (compile_unit.pc_range) |range| { - if (target_address >= range.start and target_address < range.end) - return compile_unit; + if (target_address >= range.start and target_address < range.end) return compile_unit; } if (compile_unit.die.getAttrSecOffset(DW.AT_ranges)) |ranges_offset| { var base_address: usize = 0; @@ -1063,8 +1032,7 @@ fn findCompileUnit(st: &ElfStackTrace, target_address: u64) !&const CompileUnit } } } else |err| { - if (err != error.MissingDebugInfo) - return err; + if (err != error.MissingDebugInfo) return err; continue; } } @@ -1073,8 +1041,8 @@ fn findCompileUnit(st: &ElfStackTrace, target_address: u64) !&const CompileUnit fn readInitialLength(comptime E: type, in_stream: &io.InStream(E), is_64: &bool) !u64 { const first_32_bits = try in_stream.readIntLe(u32); - *is_64 = (first_32_bits == 0xffffffff); - if (*is_64) { + is_64.* = (first_32_bits == 0xffffffff); + if (is_64.*) { return in_stream.readIntLe(u64); } else { if (first_32_bits >= 0xfffffff0) return error.InvalidDebugInfo; @@ -1091,13 +1059,11 @@ fn readULeb128(in_stream: var) !u64 { var operand: u64 = undefined; - if (@shlWithOverflow(u64, byte & 0b01111111, u6(shift), &operand)) - return error.InvalidDebugInfo; + if (@shlWithOverflow(u64, byte & 0b01111111, u6(shift), &operand)) return error.InvalidDebugInfo; result |= operand; - if ((byte & 0b10000000) == 0) - return result; + if ((byte & 0b10000000) == 0) return result; shift += 7; } @@ -1112,15 +1078,13 @@ fn readILeb128(in_stream: var) !i64 { var operand: i64 = undefined; - if (@shlWithOverflow(i64, byte & 0b01111111, u6(shift), &operand)) - return error.InvalidDebugInfo; + if (@shlWithOverflow(i64, byte & 0b01111111, u6(shift), &operand)) return error.InvalidDebugInfo; result |= operand; shift += 7; if ((byte & 0b10000000) == 0) { - if (shift < @sizeOf(i64) * 8 and (byte & 0b01000000) != 0) - result |= -(i64(1) << u6(shift)); + if (shift < @sizeOf(i64) * 8 and (byte & 0b01000000) != 0) result |= -(i64(1) << u6(shift)); return result; } } @@ -1131,7 +1095,6 @@ pub const global_allocator = &global_fixed_allocator.allocator; var global_fixed_allocator = std.heap.FixedBufferAllocator.init(global_allocator_mem[0..]); var global_allocator_mem: [100 * 1024]u8 = undefined; - // TODO make thread safe var debug_info_allocator: ?&mem.Allocator = null; var debug_info_direct_allocator: std.heap.DirectAllocator = undefined; diff --git a/std/math/index.zig b/std/math/index.zig index 83ba055329..05de604c6c 100644 --- a/std/math/index.zig +++ b/std/math/index.zig @@ -47,12 +47,12 @@ pub fn forceEval(value: var) void { f32 => { var x: f32 = undefined; const p = @ptrCast(&volatile f32, &x); - *p = x; + p.* = x; }, f64 => { var x: f64 = undefined; const p = @ptrCast(&volatile f64, &x); - *p = x; + p.* = x; }, else => { @compileError("forceEval not implemented for " ++ @typeName(T)); @@ -179,7 +179,6 @@ test "math" { _ = @import("complex/index.zig"); } - pub fn min(x: var, y: var) @typeOf(x + y) { return if (x < y) x else y; } @@ -280,10 +279,10 @@ pub fn rotr(comptime T: type, x: T, r: var) T { } test "math.rotr" { - assert(rotr(u8, 0b00000001, usize(0)) == 0b00000001); - assert(rotr(u8, 0b00000001, usize(9)) == 0b10000000); - assert(rotr(u8, 0b00000001, usize(8)) == 0b00000001); - assert(rotr(u8, 0b00000001, usize(4)) == 0b00010000); + assert(rotr(u8, 0b00000001, usize(0)) == 0b00000001); + assert(rotr(u8, 0b00000001, usize(9)) == 0b10000000); + assert(rotr(u8, 0b00000001, usize(8)) == 0b00000001); + assert(rotr(u8, 0b00000001, usize(4)) == 0b00010000); assert(rotr(u8, 0b00000001, isize(-1)) == 0b00000010); } @@ -299,14 +298,13 @@ pub fn rotl(comptime T: type, x: T, r: var) T { } test "math.rotl" { - assert(rotl(u8, 0b00000001, usize(0)) == 0b00000001); - assert(rotl(u8, 0b00000001, usize(9)) == 0b00000010); - assert(rotl(u8, 0b00000001, usize(8)) == 0b00000001); - assert(rotl(u8, 0b00000001, usize(4)) == 0b00010000); + assert(rotl(u8, 0b00000001, usize(0)) == 0b00000001); + assert(rotl(u8, 0b00000001, usize(9)) == 0b00000010); + assert(rotl(u8, 0b00000001, usize(8)) == 0b00000001); + assert(rotl(u8, 0b00000001, usize(4)) == 0b00010000); assert(rotl(u8, 0b00000001, isize(-1)) == 0b10000000); } - pub fn Log2Int(comptime T: type) type { return @IntType(false, log2(T.bit_count)); } @@ -323,14 +321,14 @@ fn testOverflow() void { assert((shlExact(i32, 0b11, 4) catch unreachable) == 0b110000); } - pub fn absInt(x: var) !@typeOf(x) { const T = @typeOf(x); comptime assert(@typeId(T) == builtin.TypeId.Int); // must pass an integer to absInt comptime assert(T.is_signed); // must pass a signed integer to absInt - if (x == @minValue(@typeOf(x))) + + if (x == @minValue(@typeOf(x))) { return error.Overflow; - { + } else { @setRuntimeSafety(false); return if (x < 0) -x else x; } @@ -349,10 +347,8 @@ pub const absFloat = @import("fabs.zig").fabs; pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T { @setRuntimeSafety(false); - if (denominator == 0) - return error.DivisionByZero; - if (@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == @minValue(T) and denominator == -1) - return error.Overflow; + if (denominator == 0) return error.DivisionByZero; + if (@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == @minValue(T) and denominator == -1) return error.Overflow; return @divTrunc(numerator, denominator); } @@ -372,10 +368,8 @@ fn testDivTrunc() void { pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T { @setRuntimeSafety(false); - if (denominator == 0) - return error.DivisionByZero; - if (@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == @minValue(T) and denominator == -1) - return error.Overflow; + if (denominator == 0) return error.DivisionByZero; + if (@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == @minValue(T) and denominator == -1) return error.Overflow; return @divFloor(numerator, denominator); } @@ -395,13 +389,10 @@ fn testDivFloor() void { pub fn divExact(comptime T: type, numerator: T, denominator: T) !T { @setRuntimeSafety(false); - if (denominator == 0) - return error.DivisionByZero; - if (@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == @minValue(T) and denominator == -1) - return error.Overflow; + if (denominator == 0) return error.DivisionByZero; + if (@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == @minValue(T) and denominator == -1) return error.Overflow; const result = @divTrunc(numerator, denominator); - if (result * denominator != numerator) - return error.UnexpectedRemainder; + if (result * denominator != numerator) return error.UnexpectedRemainder; return result; } @@ -423,10 +414,8 @@ fn testDivExact() void { pub fn mod(comptime T: type, numerator: T, denominator: T) !T { @setRuntimeSafety(false); - if (denominator == 0) - return error.DivisionByZero; - if (denominator < 0) - return error.NegativeDenominator; + if (denominator == 0) return error.DivisionByZero; + if (denominator < 0) return error.NegativeDenominator; return @mod(numerator, denominator); } @@ -448,10 +437,8 @@ fn testMod() void { pub fn rem(comptime T: type, numerator: T, denominator: T) !T { @setRuntimeSafety(false); - if (denominator == 0) - return error.DivisionByZero; - if (denominator < 0) - return error.NegativeDenominator; + if (denominator == 0) return error.DivisionByZero; + if (denominator < 0) return error.NegativeDenominator; return @rem(numerator, denominator); } @@ -475,8 +462,7 @@ fn testRem() void { /// Result is an unsigned integer. pub fn absCast(x: var) @IntType(false, @typeOf(x).bit_count) { const uint = @IntType(false, @typeOf(x).bit_count); - if (x >= 0) - return uint(x); + if (x >= 0) return uint(x); return uint(-(x + 1)) + 1; } @@ -495,15 +481,12 @@ test "math.absCast" { /// Returns the negation of the integer parameter. /// Result is a signed integer. pub fn negateCast(x: var) !@IntType(true, @typeOf(x).bit_count) { - if (@typeOf(x).is_signed) - return negate(x); + if (@typeOf(x).is_signed) return negate(x); const int = @IntType(true, @typeOf(x).bit_count); - if (x > -@minValue(int)) - return error.Overflow; + if (x > -@minValue(int)) return error.Overflow; - if (x == -@minValue(int)) - return @minValue(int); + if (x == -@minValue(int)) return @minValue(int); return -int(x); } @@ -546,7 +529,7 @@ pub fn floorPowerOfTwo(comptime T: type, value: T) T { var x = value; comptime var i = 1; - inline while(T.bit_count > i) : (i *= 2) { + inline while (T.bit_count > i) : (i *= 2) { x |= (x >> i); } diff --git a/std/mem.zig b/std/mem.zig index d874f8a6c9..3ca87b35d3 100644 --- a/std/mem.zig +++ b/std/mem.zig @@ -6,14 +6,14 @@ const builtin = @import("builtin"); const mem = this; pub const Allocator = struct { - const Error = error {OutOfMemory}; + const Error = error{OutOfMemory}; /// Allocate byte_count bytes and return them in a slice, with the /// slice's pointer aligned at least to alignment bytes. /// The returned newly allocated memory is undefined. /// `alignment` is guaranteed to be >= 1 /// `alignment` is guaranteed to be a power of 2 - allocFn: fn (self: &Allocator, byte_count: usize, alignment: u29) Error![]u8, + allocFn: fn(self: &Allocator, byte_count: usize, alignment: u29) Error![]u8, /// If `new_byte_count > old_mem.len`: /// * `old_mem.len` is the same as what was returned from allocFn or reallocFn. @@ -26,10 +26,10 @@ pub const Allocator = struct { /// The returned newly allocated memory is undefined. /// `alignment` is guaranteed to be >= 1 /// `alignment` is guaranteed to be a power of 2 - reallocFn: fn (self: &Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8, + reallocFn: fn(self: &Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8, /// Guaranteed: `old_mem.len` is the same as what was returned from `allocFn` or `reallocFn` - freeFn: fn (self: &Allocator, old_mem: []u8) void, + freeFn: fn(self: &Allocator, old_mem: []u8) void, fn create(self: &Allocator, comptime T: type) !&T { if (@sizeOf(T) == 0) return &{}; @@ -47,7 +47,7 @@ pub const Allocator = struct { if (@sizeOf(T) == 0) return &{}; const slice = try self.alloc(T, 1); const ptr = &slice[0]; - *ptr = *init; + ptr.* = init.*; return ptr; } @@ -59,9 +59,7 @@ pub const Allocator = struct { return self.alignedAlloc(T, @alignOf(T), n); } - fn alignedAlloc(self: &Allocator, comptime T: type, comptime alignment: u29, - n: usize) ![]align(alignment) T - { + fn alignedAlloc(self: &Allocator, comptime T: type, comptime alignment: u29, n: usize) ![]align(alignment) T { if (n == 0) { return (&align(alignment) T)(undefined)[0..0]; } @@ -70,7 +68,7 @@ pub const Allocator = struct { assert(byte_slice.len == byte_count); // This loop gets optimized out in ReleaseFast mode for (byte_slice) |*byte| { - *byte = undefined; + byte.* = undefined; } return ([]align(alignment) T)(@alignCast(alignment, byte_slice)); } @@ -79,9 +77,7 @@ pub const Allocator = struct { return self.alignedRealloc(T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n); } - fn alignedRealloc(self: &Allocator, comptime T: type, comptime alignment: u29, - old_mem: []align(alignment) T, n: usize) ![]align(alignment) T - { + fn alignedRealloc(self: &Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) ![]align(alignment) T { if (old_mem.len == 0) { return self.alloc(T, n); } @@ -97,7 +93,7 @@ pub const Allocator = struct { if (n > old_mem.len) { // This loop gets optimized out in ReleaseFast mode for (byte_slice[old_byte_slice.len..]) |*byte| { - *byte = undefined; + byte.* = undefined; } } return ([]T)(@alignCast(alignment, byte_slice)); @@ -110,9 +106,7 @@ pub const Allocator = struct { return self.alignedShrink(T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n); } - fn alignedShrink(self: &Allocator, comptime T: type, comptime alignment: u29, - old_mem: []align(alignment) T, n: usize) []align(alignment) T - { + fn alignedShrink(self: &Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) []align(alignment) T { if (n == 0) { self.free(old_mem); return old_mem[0..0]; @@ -131,8 +125,7 @@ pub const Allocator = struct { fn free(self: &Allocator, memory: var) void { const bytes = ([]const u8)(memory); - if (bytes.len == 0) - return; + if (bytes.len == 0) return; const non_const_ptr = @intToPtr(&u8, @ptrToInt(bytes.ptr)); self.freeFn(self, non_const_ptr[0..bytes.len]); } @@ -146,11 +139,13 @@ pub fn copy(comptime T: type, dest: []T, source: []const T) void { // this and automatically omit safety checks for loops @setRuntimeSafety(false); assert(dest.len >= source.len); - for (source) |s, i| dest[i] = s; + for (source) |s, i| + dest[i] = s; } pub fn set(comptime T: type, dest: []T, value: T) void { - for (dest) |*d| *d = value; + for (dest) |*d| + d.* = value; } /// Returns true if lhs < rhs, false otherwise @@ -229,8 +224,7 @@ pub fn lastIndexOfScalar(comptime T: type, slice: []const T, value: T) ?usize { var i: usize = slice.len; while (i != 0) { i -= 1; - if (slice[i] == value) - return i; + if (slice[i] == value) return i; } return null; } @@ -238,8 +232,7 @@ pub fn lastIndexOfScalar(comptime T: type, slice: []const T, value: T) ?usize { pub fn indexOfScalarPos(comptime T: type, slice: []const T, start_index: usize, value: T) ?usize { var i: usize = start_index; while (i < slice.len) : (i += 1) { - if (slice[i] == value) - return i; + if (slice[i] == value) return i; } return null; } @@ -253,8 +246,7 @@ pub fn lastIndexOfAny(comptime T: type, slice: []const T, values: []const T) ?us while (i != 0) { i -= 1; for (values) |value| { - if (slice[i] == value) - return i; + if (slice[i] == value) return i; } } return null; @@ -264,8 +256,7 @@ pub fn indexOfAnyPos(comptime T: type, slice: []const T, start_index: usize, val var i: usize = start_index; while (i < slice.len) : (i += 1) { for (values) |value| { - if (slice[i] == value) - return i; + if (slice[i] == value) return i; } } return null; @@ -279,28 +270,23 @@ pub fn indexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize /// To start looking at a different index, slice the haystack first. /// TODO is there even a better algorithm for this? pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize { - if (needle.len > haystack.len) - return null; + if (needle.len > haystack.len) return null; var i: usize = haystack.len - needle.len; while (true) : (i -= 1) { - if (mem.eql(T, haystack[i..i+needle.len], needle)) - return i; - if (i == 0) - return null; + if (mem.eql(T, haystack[i..i + needle.len], needle)) return i; + if (i == 0) return null; } } // TODO boyer-moore algorithm pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize { - if (needle.len > haystack.len) - return null; + if (needle.len > haystack.len) return null; var i: usize = start_index; const end = haystack.len - needle.len; while (i <= end) : (i += 1) { - if (eql(T, haystack[i .. i + needle.len], needle)) - return i; + if (eql(T, haystack[i..i + needle.len], needle)) return i; } return null; } @@ -355,9 +341,12 @@ pub fn readIntBE(comptime T: type, bytes: []const u8) T { } assert(bytes.len == @sizeOf(T)); var result: T = 0; - {comptime var i = 0; inline while (i < @sizeOf(T)) : (i += 1) { - result = (result << 8) | T(bytes[i]); - }} + { + comptime var i = 0; + inline while (i < @sizeOf(T)) : (i += 1) { + result = (result << 8) | T(bytes[i]); + } + } return result; } @@ -369,9 +358,12 @@ pub fn readIntLE(comptime T: type, bytes: []const u8) T { } assert(bytes.len == @sizeOf(T)); var result: T = 0; - {comptime var i = 0; inline while (i < @sizeOf(T)) : (i += 1) { - result |= T(bytes[i]) << i * 8; - }} + { + comptime var i = 0; + inline while (i < @sizeOf(T)) : (i += 1) { + result |= T(bytes[i]) << i * 8; + } + } return result; } @@ -393,7 +385,7 @@ pub fn writeInt(buf: []u8, value: var, endian: builtin.Endian) void { }, builtin.Endian.Little => { for (buf) |*b| { - *b = @truncate(u8, bits); + b.* = @truncate(u8, bits); bits >>= 8; } }, @@ -401,7 +393,6 @@ pub fn writeInt(buf: []u8, value: var, endian: builtin.Endian) void { assert(bits == 0); } - pub fn hash_slice_u8(k: []const u8) u32 { // FNV 32-bit hash var h: u32 = 2166136261; @@ -420,7 +411,7 @@ pub fn eql_slice_u8(a: []const u8, b: []const u8) bool { /// split(" abc def ghi ", " ") /// Will return slices for "abc", "def", "ghi", null, in that order. pub fn split(buffer: []const u8, split_bytes: []const u8) SplitIterator { - return SplitIterator { + return SplitIterator{ .index = 0, .buffer = buffer, .split_bytes = split_bytes, @@ -436,7 +427,7 @@ test "mem.split" { } pub fn startsWith(comptime T: type, haystack: []const T, needle: []const T) bool { - return if (needle.len > haystack.len) false else eql(T, haystack[0 .. needle.len], needle); + return if (needle.len > haystack.len) false else eql(T, haystack[0..needle.len], needle); } test "mem.startsWith" { @@ -445,10 +436,9 @@ test "mem.startsWith" { } pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool { - return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len ..], needle); + return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len..], needle); } - test "mem.endsWith" { assert(endsWith(u8, "Needle in haystack", "haystack")); assert(!endsWith(u8, "Bob", "Bo")); @@ -542,29 +532,47 @@ test "testReadInt" { } fn testReadIntImpl() void { { - const bytes = []u8{ 0x12, 0x34, 0x56, 0x78 }; - assert(readInt(bytes, u32, builtin.Endian.Big) == 0x12345678); - assert(readIntBE(u32, bytes) == 0x12345678); - assert(readIntBE(i32, bytes) == 0x12345678); + const bytes = []u8{ + 0x12, + 0x34, + 0x56, + 0x78, + }; + assert(readInt(bytes, u32, builtin.Endian.Big) == 0x12345678); + assert(readIntBE(u32, bytes) == 0x12345678); + assert(readIntBE(i32, bytes) == 0x12345678); assert(readInt(bytes, u32, builtin.Endian.Little) == 0x78563412); - assert(readIntLE(u32, bytes) == 0x78563412); - assert(readIntLE(i32, bytes) == 0x78563412); + assert(readIntLE(u32, bytes) == 0x78563412); + assert(readIntLE(i32, bytes) == 0x78563412); } { - const buf = []u8{0x00, 0x00, 0x12, 0x34}; + const buf = []u8{ + 0x00, + 0x00, + 0x12, + 0x34, + }; const answer = readInt(buf, u64, builtin.Endian.Big); assert(answer == 0x00001234); } { - const buf = []u8{0x12, 0x34, 0x00, 0x00}; + const buf = []u8{ + 0x12, + 0x34, + 0x00, + 0x00, + }; const answer = readInt(buf, u64, builtin.Endian.Little); assert(answer == 0x00003412); } { - const bytes = []u8{0xff, 0xfe}; - assert(readIntBE(u16, bytes) == 0xfffe); + const bytes = []u8{ + 0xff, + 0xfe, + }; + assert(readIntBE(u16, bytes) == 0xfffe); assert(readIntBE(i16, bytes) == -0x0002); - assert(readIntLE(u16, bytes) == 0xfeff); + assert(readIntLE(u16, bytes) == 0xfeff); assert(readIntLE(i16, bytes) == -0x0101); } } @@ -577,19 +585,38 @@ fn testWriteIntImpl() void { var bytes: [4]u8 = undefined; writeInt(bytes[0..], u32(0x12345678), builtin.Endian.Big); - assert(eql(u8, bytes, []u8{ 0x12, 0x34, 0x56, 0x78 })); + assert(eql(u8, bytes, []u8{ + 0x12, + 0x34, + 0x56, + 0x78, + })); writeInt(bytes[0..], u32(0x78563412), builtin.Endian.Little); - assert(eql(u8, bytes, []u8{ 0x12, 0x34, 0x56, 0x78 })); + assert(eql(u8, bytes, []u8{ + 0x12, + 0x34, + 0x56, + 0x78, + })); writeInt(bytes[0..], u16(0x1234), builtin.Endian.Big); - assert(eql(u8, bytes, []u8{ 0x00, 0x00, 0x12, 0x34 })); + assert(eql(u8, bytes, []u8{ + 0x00, + 0x00, + 0x12, + 0x34, + })); writeInt(bytes[0..], u16(0x1234), builtin.Endian.Little); - assert(eql(u8, bytes, []u8{ 0x34, 0x12, 0x00, 0x00 })); + assert(eql(u8, bytes, []u8{ + 0x34, + 0x12, + 0x00, + 0x00, + })); } - pub fn min(comptime T: type, slice: []const T) T { var best = slice[0]; for (slice[1..]) |item| { @@ -615,9 +642,9 @@ test "mem.max" { } pub fn swap(comptime T: type, a: &T, b: &T) void { - const tmp = *a; - *a = *b; - *b = tmp; + const tmp = a.*; + a.* = b.*; + b.* = tmp; } /// In-place order reversal of a slice @@ -630,10 +657,22 @@ pub fn reverse(comptime T: type, items: []T) void { } test "std.mem.reverse" { - var arr = []i32{ 5, 3, 1, 2, 4 }; + var arr = []i32{ + 5, + 3, + 1, + 2, + 4, + }; reverse(i32, arr[0..]); - assert(eql(i32, arr, []i32{ 4, 2, 1, 3, 5 })); + assert(eql(i32, arr, []i32{ + 4, + 2, + 1, + 3, + 5, + })); } /// In-place rotation of the values in an array ([0 1 2 3] becomes [1 2 3 0] if we rotate by 1) @@ -645,10 +684,22 @@ pub fn rotate(comptime T: type, items: []T, amount: usize) void { } test "std.mem.rotate" { - var arr = []i32{ 5, 3, 1, 2, 4 }; + var arr = []i32{ + 5, + 3, + 1, + 2, + 4, + }; rotate(i32, arr[0..], 2); - assert(eql(i32, arr, []i32{ 1, 2, 4, 5, 3 })); + assert(eql(i32, arr, []i32{ + 1, + 2, + 4, + 5, + 3, + })); } // TODO: When https://github.com/zig-lang/zig/issues/649 is solved these can be done by diff --git a/std/zig/parser.zig b/std/zig/parser.zig index b5849c3e96..79a38f00ee 100644 --- a/std/zig/parser.zig +++ b/std/zig/parser.zig @@ -3705,7 +3705,9 @@ pub const Parser = struct { }, ast.Node.Id.PrefixOp => { const prefix_op_node = @fieldParentPtr(ast.Node.PrefixOp, "base", base); - try stack.append(RenderState { .Expression = prefix_op_node.rhs }); + if (prefix_op_node.op != ast.Node.PrefixOp.Op.Deref) { + try stack.append(RenderState { .Expression = prefix_op_node.rhs }); + } switch (prefix_op_node.op) { ast.Node.PrefixOp.Op.AddrOf => |addr_of_info| { try stream.write("&"); @@ -3742,7 +3744,10 @@ pub const Parser = struct { }, ast.Node.PrefixOp.Op.BitNot => try stream.write("~"), ast.Node.PrefixOp.Op.BoolNot => try stream.write("!"), - ast.Node.PrefixOp.Op.Deref => try stream.write("*"), + ast.Node.PrefixOp.Op.Deref => { + try stack.append(RenderState { .Text = ".*" }); + try stack.append(RenderState { .Expression = prefix_op_node.rhs }); + }, ast.Node.PrefixOp.Op.Negation => try stream.write("-"), ast.Node.PrefixOp.Op.NegationWrap => try stream.write("-%"), ast.Node.PrefixOp.Op.Try => try stream.write("try "), diff --git a/test/cases/align.zig b/test/cases/align.zig index ad3a66a2e0..a1259e96bf 100644 --- a/test/cases/align.zig +++ b/test/cases/align.zig @@ -10,7 +10,9 @@ test "global variable alignment" { assert(@typeOf(slice) == []align(4) u8); } -fn derp() align(@sizeOf(usize) * 2) i32 { return 1234; } +fn derp() align(@sizeOf(usize) * 2) i32 { + return 1234; +} fn noop1() align(1) void {} fn noop4() align(4) void {} @@ -22,7 +24,6 @@ test "function alignment" { noop4(); } - var baz: packed struct { a: u32, b: u32, @@ -32,7 +33,6 @@ test "packed struct alignment" { assert(@typeOf(&baz.b) == &align(1) u32); } - const blah: packed struct { a: u3, b: u3, @@ -53,29 +53,43 @@ test "implicitly decreasing pointer alignment" { assert(addUnaligned(&a, &b) == 7); } -fn addUnaligned(a: &align(1) const u32, b: &align(1) const u32) u32 { return *a + *b; } +fn addUnaligned(a: &align(1) const u32, b: &align(1) const u32) u32 { + return a.* + b.*; +} test "implicitly decreasing slice alignment" { const a: u32 align(4) = 3; const b: u32 align(8) = 4; assert(addUnalignedSlice((&a)[0..1], (&b)[0..1]) == 7); } -fn addUnalignedSlice(a: []align(1) const u32, b: []align(1) const u32) u32 { return a[0] + b[0]; } +fn addUnalignedSlice(a: []align(1) const u32, b: []align(1) const u32) u32 { + return a[0] + b[0]; +} test "specifying alignment allows pointer cast" { testBytesAlign(0x33); } fn testBytesAlign(b: u8) void { - var bytes align(4) = []u8{b, b, b, b}; + var bytes align(4) = []u8 { + b, + b, + b, + b, + }; const ptr = @ptrCast(&u32, &bytes[0]); - assert(*ptr == 0x33333333); + assert(ptr.* == 0x33333333); } test "specifying alignment allows slice cast" { testBytesAlignSlice(0x33); } fn testBytesAlignSlice(b: u8) void { - var bytes align(4) = []u8{b, b, b, b}; + var bytes align(4) = []u8 { + b, + b, + b, + b, + }; const slice = ([]u32)(bytes[0..]); assert(slice[0] == 0x33333333); } @@ -89,11 +103,14 @@ fn expectsOnly1(x: &align(1) u32) void { expects4(@alignCast(4, x)); } fn expects4(x: &align(4) u32) void { - *x += 1; + x.* += 1; } test "@alignCast slices" { - var array align(4) = []u32{1, 1}; + var array align(4) = []u32 { + 1, + 1, + }; const slice = array[0..]; sliceExpectsOnly1(slice); assert(slice[0] == 2); @@ -105,31 +122,34 @@ fn sliceExpects4(slice: []align(4) u32) void { slice[0] += 1; } - test "implicitly decreasing fn alignment" { testImplicitlyDecreaseFnAlign(alignedSmall, 1234); testImplicitlyDecreaseFnAlign(alignedBig, 5678); } -fn testImplicitlyDecreaseFnAlign(ptr: fn () align(1) i32, answer: i32) void { +fn testImplicitlyDecreaseFnAlign(ptr: fn() align(1) i32, answer: i32) void { assert(ptr() == answer); } -fn alignedSmall() align(8) i32 { return 1234; } -fn alignedBig() align(16) i32 { return 5678; } - +fn alignedSmall() align(8) i32 { + return 1234; +} +fn alignedBig() align(16) i32 { + return 5678; +} test "@alignCast functions" { assert(fnExpectsOnly1(simple4) == 0x19); } -fn fnExpectsOnly1(ptr: fn()align(1) i32) i32 { +fn fnExpectsOnly1(ptr: fn() align(1) i32) i32 { return fnExpects4(@alignCast(4, ptr)); } -fn fnExpects4(ptr: fn()align(4) i32) i32 { +fn fnExpects4(ptr: fn() align(4) i32) i32 { return ptr(); } -fn simple4() align(4) i32 { return 0x19; } - +fn simple4() align(4) i32 { + return 0x19; +} test "generic function with align param" { assert(whyWouldYouEverDoThis(1) == 0x1); @@ -137,8 +157,9 @@ test "generic function with align param" { assert(whyWouldYouEverDoThis(8) == 0x1); } -fn whyWouldYouEverDoThis(comptime align_bytes: u8) align(align_bytes) u8 { return 0x1; } - +fn whyWouldYouEverDoThis(comptime align_bytes: u8) align(align_bytes) u8 { + return 0x1; +} test "@ptrCast preserves alignment of bigger source" { var x: u32 align(16) = 1234; @@ -146,24 +167,38 @@ test "@ptrCast preserves alignment of bigger source" { assert(@typeOf(ptr) == &align(16) u8); } - test "compile-time known array index has best alignment possible" { // take full advantage of over-alignment - var array align(4) = []u8 {1, 2, 3, 4}; + var array align(4) = []u8 { + 1, + 2, + 3, + 4, + }; assert(@typeOf(&array[0]) == &align(4) u8); assert(@typeOf(&array[1]) == &u8); assert(@typeOf(&array[2]) == &align(2) u8); assert(@typeOf(&array[3]) == &u8); // because align is too small but we still figure out to use 2 - var bigger align(2) = []u64{1, 2, 3, 4}; + var bigger align(2) = []u64 { + 1, + 2, + 3, + 4, + }; assert(@typeOf(&bigger[0]) == &align(2) u64); assert(@typeOf(&bigger[1]) == &align(2) u64); assert(@typeOf(&bigger[2]) == &align(2) u64); assert(@typeOf(&bigger[3]) == &align(2) u64); // because pointer is align 2 and u32 align % 2 == 0 we can assume align 2 - var smaller align(2) = []u32{1, 2, 3, 4}; + var smaller align(2) = []u32 { + 1, + 2, + 3, + 4, + }; testIndex(&smaller[0], 0, &align(2) u32); testIndex(&smaller[0], 1, &align(2) u32); testIndex(&smaller[0], 2, &align(2) u32); @@ -182,7 +217,6 @@ fn testIndex2(ptr: &align(4) u8, index: usize, comptime T: type) void { assert(@typeOf(&ptr[index]) == T); } - test "alignstack" { assert(fnWithAlignedStack() == 1234); } diff --git a/test/cases/alignof.zig b/test/cases/alignof.zig index 27b95c7fdc..130a2a5b44 100644 --- a/test/cases/alignof.zig +++ b/test/cases/alignof.zig @@ -1,7 +1,11 @@ const assert = @import("std").debug.assert; const builtin = @import("builtin"); -const Foo = struct { x: u32, y: u32, z: u32, }; +const Foo = struct { + x: u32, + y: u32, + z: u32, +}; test "@alignOf(T) before referencing T" { comptime assert(@alignOf(Foo) != @maxValue(usize)); diff --git a/test/cases/array.zig b/test/cases/array.zig index 577161dd16..0fb61b2a9f 100644 --- a/test/cases/array.zig +++ b/test/cases/array.zig @@ -2,9 +2,9 @@ const assert = @import("std").debug.assert; const mem = @import("std").mem; test "arrays" { - var array : [5]u32 = undefined; + var array: [5]u32 = undefined; - var i : u32 = 0; + var i: u32 = 0; while (i < 5) { array[i] = i + 1; i = array[i]; @@ -34,24 +34,41 @@ test "void arrays" { } test "array literal" { - const hex_mult = []u16{4096, 256, 16, 1}; + const hex_mult = []u16 { + 4096, + 256, + 16, + 1, + }; assert(hex_mult.len == 4); assert(hex_mult[1] == 256); } test "array dot len const expr" { - assert(comptime x: {break :x some_array.len == 4;}); + assert(comptime x: { + break :x some_array.len == 4; + }); } const ArrayDotLenConstExpr = struct { y: [some_array.len]u8, }; -const some_array = []u8 {0, 1, 2, 3}; - +const some_array = []u8 { + 0, + 1, + 2, + 3, +}; test "nested arrays" { - const array_of_strings = [][]const u8 {"hello", "this", "is", "my", "thing"}; + const array_of_strings = [][]const u8 { + "hello", + "this", + "is", + "my", + "thing", + }; for (array_of_strings) |s, i| { if (i == 0) assert(mem.eql(u8, s, "hello")); if (i == 1) assert(mem.eql(u8, s, "this")); @@ -61,7 +78,6 @@ test "nested arrays" { } } - var s_array: [8]Sub = undefined; const Sub = struct { b: u8, @@ -70,7 +86,9 @@ const Str = struct { a: []Sub, }; test "set global var array via slice embedded in struct" { - var s = Str { .a = s_array[0..]}; + var s = Str { + .a = s_array[0..], + }; s.a[0].b = 1; s.a[1].b = 2; @@ -82,7 +100,10 @@ test "set global var array via slice embedded in struct" { } test "array literal with specified size" { - var array = [2]u8{1, 2}; + var array = [2]u8 { + 1, + 2, + }; assert(array[0] == 1); assert(array[1] == 2); } diff --git a/test/cases/bitcast.zig b/test/cases/bitcast.zig index f1f2ccd672..878140954a 100644 --- a/test/cases/bitcast.zig +++ b/test/cases/bitcast.zig @@ -10,5 +10,9 @@ fn testBitCast_i32_u32() void { assert(conv2(@maxValue(u32)) == -1); } -fn conv(x: i32) u32 { return @bitCast(u32, x); } -fn conv2(x: u32) i32 { return @bitCast(i32, x); } +fn conv(x: i32) u32 { + return @bitCast(u32, x); +} +fn conv2(x: u32) i32 { + return @bitCast(i32, x); +} diff --git a/test/cases/bugs/394.zig b/test/cases/bugs/394.zig index 071619d59c..a99bd18b28 100644 --- a/test/cases/bugs/394.zig +++ b/test/cases/bugs/394.zig @@ -1,9 +1,20 @@ -const E = union(enum) { A: [9]u8, B: u64, }; -const S = struct { x: u8, y: E, }; +const E = union(enum) { + A: [9]u8, + B: u64, +}; +const S = struct { + x: u8, + y: E, +}; const assert = @import("std").debug.assert; test "bug 394 fixed" { - const x = S { .x = 3, .y = E {.B = 1 } }; + const x = S { + .x = 3, + .y = E { + .B = 1, + }, + }; assert(x.x == 3); } diff --git a/test/cases/bugs/655.zig b/test/cases/bugs/655.zig index e6a275004c..4431767d5c 100644 --- a/test/cases/bugs/655.zig +++ b/test/cases/bugs/655.zig @@ -8,5 +8,5 @@ test "function with &const parameter with type dereferenced by namespace" { } fn foo(x: &const other_file.Integer) void { - std.debug.assert(*x == 1234); + std.debug.assert(x.* == 1234); } diff --git a/test/cases/bugs/656.zig b/test/cases/bugs/656.zig index ce3eec8046..24a28bf411 100644 --- a/test/cases/bugs/656.zig +++ b/test/cases/bugs/656.zig @@ -14,12 +14,15 @@ test "nullable if after an if in a switch prong of a switch with 2 prongs in an } fn foo(a: bool, b: bool) void { - var prefix_op = PrefixOp { .AddrOf = Value { .align_expr = 1234 } }; - if (a) { - } else { + var prefix_op = PrefixOp { + .AddrOf = Value { + .align_expr = 1234, + }, + }; + if (a) {} else { switch (prefix_op) { PrefixOp.AddrOf => |addr_of_info| { - if (b) { } + if (b) {} if (addr_of_info.align_expr) |align_expr| { assert(align_expr == 1234); } diff --git a/test/cases/bugs/828.zig b/test/cases/bugs/828.zig index c46548cb7a..8f329e4f82 100644 --- a/test/cases/bugs/828.zig +++ b/test/cases/bugs/828.zig @@ -1,10 +1,10 @@ const CountBy = struct { a: usize, - + const One = CountBy { .a = 1, }; - + pub fn counter(self: &const CountBy) Counter { return Counter { .i = 0, @@ -14,7 +14,7 @@ const CountBy = struct { const Counter = struct { i: usize, - + pub fn count(self: &Counter) bool { self.i += 1; return self.i <= 10; @@ -24,8 +24,8 @@ const Counter = struct { fn constCount(comptime cb: &const CountBy, comptime unused: u32) void { comptime { var cnt = cb.counter(); - if(cnt.i != 0) @compileError("Counter instance reused!"); - while(cnt.count()){} + if (cnt.i != 0) @compileError("Counter instance reused!"); + while (cnt.count()) {} } } diff --git a/test/cases/bugs/920.zig b/test/cases/bugs/920.zig index 13c03a304f..c2b6816e94 100644 --- a/test/cases/bugs/920.zig +++ b/test/cases/bugs/920.zig @@ -12,8 +12,7 @@ const ZigTable = struct { zero_case: fn(&Random, f64) f64, }; -fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn(f64) f64, - comptime f_inv: fn(f64) f64, comptime zero_case: fn(&Random, f64) f64) ZigTable { +fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn(f64) f64, comptime f_inv: fn(f64) f64, comptime zero_case: fn(&Random, f64) f64) ZigTable { var tables: ZigTable = undefined; tables.is_symmetric = is_symmetric; @@ -26,12 +25,12 @@ fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, co for (tables.x[2..256]) |*entry, i| { const last = tables.x[2 + i - 1]; - *entry = f_inv(v / last + f(last)); + entry.* = f_inv(v / last + f(last)); } tables.x[256] = 0; for (tables.f[0..]) |*entry, i| { - *entry = f(tables.x[i]); + entry.* = f(tables.x[i]); } return tables; @@ -40,9 +39,15 @@ fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, co const norm_r = 3.6541528853610088; const norm_v = 0.00492867323399; -fn norm_f(x: f64) f64 { return math.exp(-x * x / 2.0); } -fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); } -fn norm_zero_case(random: &Random, u: f64) f64 { return 0.0; } +fn norm_f(x: f64) f64 { + return math.exp(-x * x / 2.0); +} +fn norm_f_inv(y: f64) f64 { + return math.sqrt(-2.0 * math.ln(y)); +} +fn norm_zero_case(random: &Random, u: f64) f64 { + return 0.0; +} const NormalDist = blk: { @setEvalBranchQuota(30000); diff --git a/test/cases/cast.zig b/test/cases/cast.zig index 024ece0055..547cca5797 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -14,10 +14,10 @@ test "integer literal to pointer cast" { } test "pointer reinterpret const float to int" { - const float: f64 = 5.99999999999994648725e-01; + const float: f64 = 5.99999999999994648725e - 01; const float_ptr = &float; const int_ptr = @ptrCast(&const i32, float_ptr); - const int_val = *int_ptr; + const int_val = int_ptr.*; assert(int_val == 858993411); } @@ -29,25 +29,31 @@ test "implicitly cast a pointer to a const pointer of it" { } fn funcWithConstPtrPtr(x: &const &i32) void { - **x += 1; + x.*.* += 1; } test "implicitly cast a container to a const pointer of it" { - const z = Struct(void) { .x = void{} }; + const z = Struct(void) { + .x = void{}, + }; assert(0 == @sizeOf(@typeOf(z))); assert(void{} == Struct(void).pointer(z).x); assert(void{} == Struct(void).pointer(&z).x); assert(void{} == Struct(void).maybePointer(z).x); assert(void{} == Struct(void).maybePointer(&z).x); assert(void{} == Struct(void).maybePointer(null).x); - const s = Struct(u8) { .x = 42 }; + const s = Struct(u8) { + .x = 42, + }; assert(0 != @sizeOf(@typeOf(s))); assert(42 == Struct(u8).pointer(s).x); assert(42 == Struct(u8).pointer(&s).x); assert(42 == Struct(u8).maybePointer(s).x); assert(42 == Struct(u8).maybePointer(&s).x); assert(0 == Struct(u8).maybePointer(null).x); - const u = Union { .x = 42 }; + const u = Union { + .x = 42, + }; assert(42 == Union.pointer(u).x); assert(42 == Union.pointer(&u).x); assert(42 == Union.maybePointer(u).x); @@ -67,12 +73,14 @@ fn Struct(comptime T: type) type { x: T, fn pointer(self: &const Self) Self { - return *self; + return self.*; } fn maybePointer(self: ?&const Self) Self { - const none = Self { .x = if (T == void) void{} else 0 }; - return *(self ?? &none); + const none = Self { + .x = if (T == void) void{} else 0, + }; + return (self ?? &none).*; } }; } @@ -81,12 +89,14 @@ const Union = union { x: u8, fn pointer(self: &const Union) Union { - return *self; + return self.*; } fn maybePointer(self: ?&const Union) Union { - const none = Union { .x = 0 }; - return *(self ?? &none); + const none = Union { + .x = 0, + }; + return (self ?? &none).*; } }; @@ -95,11 +105,11 @@ const Enum = enum { Some, fn pointer(self: &const Enum) Enum { - return *self; + return self.*; } fn maybePointer(self: ?&const Enum) Enum { - return *(self ?? &Enum.None); + return (self ?? &Enum.None).*; } }; @@ -108,19 +118,21 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" { const Self = this; x: u8, fn constConst(p: &const &const Self) u8 { - return (*p).x; + return (p.*).x; } fn maybeConstConst(p: ?&const &const Self) u8 { - return (*??p).x; + return (??p.*).x; } fn constConstConst(p: &const &const &const Self) u8 { - return (**p).x; + return (p.*.*).x; } fn maybeConstConstConst(p: ?&const &const &const Self) u8 { - return (**??p).x; + return (??p.*.*).x; } }; - const s = S { .x = 42 }; + const s = S { + .x = 42, + }; const p = &s; const q = &p; const r = &q; @@ -154,7 +166,6 @@ fn boolToStr(b: bool) []const u8 { return if (b) "true" else "false"; } - test "peer resolve array and const slice" { testPeerResolveArrayConstSlice(true); comptime testPeerResolveArrayConstSlice(true); @@ -168,12 +179,12 @@ fn testPeerResolveArrayConstSlice(b: bool) void { test "integer literal to &const int" { const x: &const i32 = 3; - assert(*x == 3); + assert(x.* == 3); } test "string literal to &const []const u8" { const x: &const []const u8 = "hello"; - assert(mem.eql(u8, *x, "hello")); + assert(mem.eql(u8, x.*, "hello")); } test "implicitly cast from T to error!?T" { @@ -191,7 +202,9 @@ fn castToMaybeTypeError(z: i32) void { const f = z; const g: error!?i32 = f; - const a = A{ .a = z }; + const a = A { + .a = z, + }; const b: error!?A = a; assert((??(b catch unreachable)).a == 1); } @@ -205,7 +218,6 @@ fn implicitIntLitToMaybe() void { const g: error!?i32 = 1; } - test "return null from fn() error!?&T" { const a = returnNullFromMaybeTypeErrorRef(); const b = returnNullLitFromMaybeTypeErrorRef(); @@ -235,7 +247,6 @@ fn peerTypeTAndMaybeT(c: bool, b: bool) ?usize { return usize(3); } - test "peer type resolution: [0]u8 and []const u8" { assert(peerTypeEmptyArrayAndSlice(true, "hi").len == 0); assert(peerTypeEmptyArrayAndSlice(false, "hi").len == 1); @@ -246,7 +257,7 @@ test "peer type resolution: [0]u8 and []const u8" { } fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 { if (a) { - return []const u8 {}; + return []const u8{}; } return slice[0..1]; @@ -261,7 +272,6 @@ fn castToMaybeSlice() ?[]const u8 { return "hi"; } - test "implicitly cast from [0]T to error![]T" { testCastZeroArrayToErrSliceMut(); comptime testCastZeroArrayToErrSliceMut(); @@ -329,7 +339,6 @@ fn foo(args: ...) void { assert(@typeOf(args[0]) == &const [5]u8); } - test "peer type resolution: error and [N]T" { // TODO: implicit error!T to error!U where T can implicitly cast to U //assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK")); @@ -378,7 +387,12 @@ fn cast128Float(x: u128) f128 { } test "const slice widen cast" { - const bytes align(4) = []u8{0x12, 0x12, 0x12, 0x12}; + const bytes align(4) = []u8 { + 0x12, + 0x12, + 0x12, + 0x12, + }; const u32_value = ([]const u32)(bytes[0..])[0]; assert(u32_value == 0x12121212); diff --git a/test/cases/coroutines.zig b/test/cases/coroutines.zig index 46055d7469..d00617eb7c 100644 --- a/test/cases/coroutines.zig +++ b/test/cases/coroutines.zig @@ -36,7 +36,7 @@ async fn testAsyncSeq() void { suspend; seq('d'); } -var points = []u8{0} ** "abcdefg".len; +var points = []u8 {0} ** "abcdefg".len; var index: usize = 0; fn seq(c: u8) void { @@ -94,7 +94,7 @@ async fn await_another() i32 { return 1234; } -var await_points = []u8{0} ** "abcdefghi".len; +var await_points = []u8 {0} ** "abcdefghi".len; var await_seq_index: usize = 0; fn await_seq(c: u8) void { @@ -102,7 +102,6 @@ fn await_seq(c: u8) void { await_seq_index += 1; } - var early_final_result: i32 = 0; test "coroutine await early return" { @@ -126,7 +125,7 @@ async fn early_another() i32 { return 1234; } -var early_points = []u8{0} ** "abcdef".len; +var early_points = []u8 {0} ** "abcdef".len; var early_seq_index: usize = 0; fn early_seq(c: u8) void { @@ -175,8 +174,8 @@ test "async fn pointer in a struct field" { } async<&std.mem.Allocator> fn simpleAsyncFn2(y: &i32) void { - defer *y += 2; - *y += 1; + defer y.* += 2; + y.* += 1; suspend; } @@ -205,7 +204,8 @@ test "error return trace across suspend points - async return" { cancel p2; } -fn nonFailing() promise->error!void { +// TODO https://github.com/zig-lang/zig/issues/760 +fn nonFailing() (promise->error!void) { return async suspendThenFail() catch unreachable; } @@ -238,7 +238,7 @@ async fn testBreakFromSuspend(my_result: &i32) void { s: suspend |p| { break :s; } - *my_result += 1; + my_result.* += 1; suspend; - *my_result += 1; + my_result.* += 1; } diff --git a/test/cases/defer.zig b/test/cases/defer.zig index 5470b4bbd0..d2b00d1f91 100644 --- a/test/cases/defer.zig +++ b/test/cases/defer.zig @@ -5,9 +5,18 @@ var index: usize = undefined; fn runSomeErrorDefers(x: bool) !bool { index = 0; - defer {result[index] = 'a'; index += 1;} - errdefer {result[index] = 'b'; index += 1;} - defer {result[index] = 'c'; index += 1;} + defer { + result[index] = 'a'; + index += 1; + } + errdefer { + result[index] = 'b'; + index += 1; + } + defer { + result[index] = 'c'; + index += 1; + } return if (x) x else error.FalseNotAllowed; } diff --git a/test/cases/enum.zig b/test/cases/enum.zig index 644c989b04..872e753f20 100644 --- a/test/cases/enum.zig +++ b/test/cases/enum.zig @@ -2,8 +2,15 @@ const assert = @import("std").debug.assert; const mem = @import("std").mem; test "enum type" { - const foo1 = Foo{ .One = 13}; - const foo2 = Foo{. Two = Point { .x = 1234, .y = 5678, }}; + const foo1 = Foo { + .One = 13, + }; + const foo2 = Foo { + .Two = Point { + .x = 1234, + .y = 5678, + }, + }; const bar = Bar.B; assert(bar == Bar.B); @@ -41,26 +48,31 @@ const Bar = enum { }; fn returnAnInt(x: i32) Foo { - return Foo { .One = x }; + return Foo { + .One = x, + }; } - test "constant enum with payload" { - var empty = AnEnumWithPayload {.Empty = {}}; - var full = AnEnumWithPayload {.Full = 13}; + var empty = AnEnumWithPayload { + .Empty = {}, + }; + var full = AnEnumWithPayload { + .Full = 13, + }; shouldBeEmpty(empty); shouldBeNotEmpty(full); } fn shouldBeEmpty(x: &const AnEnumWithPayload) void { - switch (*x) { + switch (x.*) { AnEnumWithPayload.Empty => {}, else => unreachable, } } fn shouldBeNotEmpty(x: &const AnEnumWithPayload) void { - switch (*x) { + switch (x.*) { AnEnumWithPayload.Empty => unreachable, else => {}, } @@ -71,8 +83,6 @@ const AnEnumWithPayload = union(enum) { Full: i32, }; - - const Number = enum { Zero, One, @@ -93,7 +103,6 @@ fn shouldEqual(n: Number, expected: u3) void { assert(u3(n) == expected); } - test "int to enum" { testIntToEnumEval(3); } @@ -108,7 +117,6 @@ const IntToEnumNumber = enum { Four, }; - test "@tagName" { assert(mem.eql(u8, testEnumTagNameBare(BareNumber.Three), "Three")); comptime assert(mem.eql(u8, testEnumTagNameBare(BareNumber.Three), "Three")); @@ -124,7 +132,6 @@ const BareNumber = enum { Three, }; - test "enum alignment" { comptime { assert(@alignOf(AlignTestEnum) >= @alignOf([9]u8)); @@ -137,47 +144,529 @@ const AlignTestEnum = union(enum) { B: u64, }; -const ValueCount1 = enum { I0 }; -const ValueCount2 = enum { I0, I1 }; +const ValueCount1 = enum { + I0, +}; +const ValueCount2 = enum { + I0, + I1, +}; const ValueCount256 = enum { - I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12, I13, I14, I15, - I16, I17, I18, I19, I20, I21, I22, I23, I24, I25, I26, I27, I28, I29, I30, I31, - I32, I33, I34, I35, I36, I37, I38, I39, I40, I41, I42, I43, I44, I45, I46, I47, - I48, I49, I50, I51, I52, I53, I54, I55, I56, I57, I58, I59, I60, I61, I62, I63, - I64, I65, I66, I67, I68, I69, I70, I71, I72, I73, I74, I75, I76, I77, I78, I79, - I80, I81, I82, I83, I84, I85, I86, I87, I88, I89, I90, I91, I92, I93, I94, I95, - I96, I97, I98, I99, I100, I101, I102, I103, I104, I105, I106, I107, I108, I109, - I110, I111, I112, I113, I114, I115, I116, I117, I118, I119, I120, I121, I122, I123, - I124, I125, I126, I127, I128, I129, I130, I131, I132, I133, I134, I135, I136, I137, - I138, I139, I140, I141, I142, I143, I144, I145, I146, I147, I148, I149, I150, I151, - I152, I153, I154, I155, I156, I157, I158, I159, I160, I161, I162, I163, I164, I165, - I166, I167, I168, I169, I170, I171, I172, I173, I174, I175, I176, I177, I178, I179, - I180, I181, I182, I183, I184, I185, I186, I187, I188, I189, I190, I191, I192, I193, - I194, I195, I196, I197, I198, I199, I200, I201, I202, I203, I204, I205, I206, I207, - I208, I209, I210, I211, I212, I213, I214, I215, I216, I217, I218, I219, I220, I221, - I222, I223, I224, I225, I226, I227, I228, I229, I230, I231, I232, I233, I234, I235, - I236, I237, I238, I239, I240, I241, I242, I243, I244, I245, I246, I247, I248, I249, - I250, I251, I252, I253, I254, I255 + I0, + I1, + I2, + I3, + I4, + I5, + I6, + I7, + I8, + I9, + I10, + I11, + I12, + I13, + I14, + I15, + I16, + I17, + I18, + I19, + I20, + I21, + I22, + I23, + I24, + I25, + I26, + I27, + I28, + I29, + I30, + I31, + I32, + I33, + I34, + I35, + I36, + I37, + I38, + I39, + I40, + I41, + I42, + I43, + I44, + I45, + I46, + I47, + I48, + I49, + I50, + I51, + I52, + I53, + I54, + I55, + I56, + I57, + I58, + I59, + I60, + I61, + I62, + I63, + I64, + I65, + I66, + I67, + I68, + I69, + I70, + I71, + I72, + I73, + I74, + I75, + I76, + I77, + I78, + I79, + I80, + I81, + I82, + I83, + I84, + I85, + I86, + I87, + I88, + I89, + I90, + I91, + I92, + I93, + I94, + I95, + I96, + I97, + I98, + I99, + I100, + I101, + I102, + I103, + I104, + I105, + I106, + I107, + I108, + I109, + I110, + I111, + I112, + I113, + I114, + I115, + I116, + I117, + I118, + I119, + I120, + I121, + I122, + I123, + I124, + I125, + I126, + I127, + I128, + I129, + I130, + I131, + I132, + I133, + I134, + I135, + I136, + I137, + I138, + I139, + I140, + I141, + I142, + I143, + I144, + I145, + I146, + I147, + I148, + I149, + I150, + I151, + I152, + I153, + I154, + I155, + I156, + I157, + I158, + I159, + I160, + I161, + I162, + I163, + I164, + I165, + I166, + I167, + I168, + I169, + I170, + I171, + I172, + I173, + I174, + I175, + I176, + I177, + I178, + I179, + I180, + I181, + I182, + I183, + I184, + I185, + I186, + I187, + I188, + I189, + I190, + I191, + I192, + I193, + I194, + I195, + I196, + I197, + I198, + I199, + I200, + I201, + I202, + I203, + I204, + I205, + I206, + I207, + I208, + I209, + I210, + I211, + I212, + I213, + I214, + I215, + I216, + I217, + I218, + I219, + I220, + I221, + I222, + I223, + I224, + I225, + I226, + I227, + I228, + I229, + I230, + I231, + I232, + I233, + I234, + I235, + I236, + I237, + I238, + I239, + I240, + I241, + I242, + I243, + I244, + I245, + I246, + I247, + I248, + I249, + I250, + I251, + I252, + I253, + I254, + I255, }; const ValueCount257 = enum { - I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, I12, I13, I14, I15, - I16, I17, I18, I19, I20, I21, I22, I23, I24, I25, I26, I27, I28, I29, I30, I31, - I32, I33, I34, I35, I36, I37, I38, I39, I40, I41, I42, I43, I44, I45, I46, I47, - I48, I49, I50, I51, I52, I53, I54, I55, I56, I57, I58, I59, I60, I61, I62, I63, - I64, I65, I66, I67, I68, I69, I70, I71, I72, I73, I74, I75, I76, I77, I78, I79, - I80, I81, I82, I83, I84, I85, I86, I87, I88, I89, I90, I91, I92, I93, I94, I95, - I96, I97, I98, I99, I100, I101, I102, I103, I104, I105, I106, I107, I108, I109, - I110, I111, I112, I113, I114, I115, I116, I117, I118, I119, I120, I121, I122, I123, - I124, I125, I126, I127, I128, I129, I130, I131, I132, I133, I134, I135, I136, I137, - I138, I139, I140, I141, I142, I143, I144, I145, I146, I147, I148, I149, I150, I151, - I152, I153, I154, I155, I156, I157, I158, I159, I160, I161, I162, I163, I164, I165, - I166, I167, I168, I169, I170, I171, I172, I173, I174, I175, I176, I177, I178, I179, - I180, I181, I182, I183, I184, I185, I186, I187, I188, I189, I190, I191, I192, I193, - I194, I195, I196, I197, I198, I199, I200, I201, I202, I203, I204, I205, I206, I207, - I208, I209, I210, I211, I212, I213, I214, I215, I216, I217, I218, I219, I220, I221, - I222, I223, I224, I225, I226, I227, I228, I229, I230, I231, I232, I233, I234, I235, - I236, I237, I238, I239, I240, I241, I242, I243, I244, I245, I246, I247, I248, I249, - I250, I251, I252, I253, I254, I255, I256 + I0, + I1, + I2, + I3, + I4, + I5, + I6, + I7, + I8, + I9, + I10, + I11, + I12, + I13, + I14, + I15, + I16, + I17, + I18, + I19, + I20, + I21, + I22, + I23, + I24, + I25, + I26, + I27, + I28, + I29, + I30, + I31, + I32, + I33, + I34, + I35, + I36, + I37, + I38, + I39, + I40, + I41, + I42, + I43, + I44, + I45, + I46, + I47, + I48, + I49, + I50, + I51, + I52, + I53, + I54, + I55, + I56, + I57, + I58, + I59, + I60, + I61, + I62, + I63, + I64, + I65, + I66, + I67, + I68, + I69, + I70, + I71, + I72, + I73, + I74, + I75, + I76, + I77, + I78, + I79, + I80, + I81, + I82, + I83, + I84, + I85, + I86, + I87, + I88, + I89, + I90, + I91, + I92, + I93, + I94, + I95, + I96, + I97, + I98, + I99, + I100, + I101, + I102, + I103, + I104, + I105, + I106, + I107, + I108, + I109, + I110, + I111, + I112, + I113, + I114, + I115, + I116, + I117, + I118, + I119, + I120, + I121, + I122, + I123, + I124, + I125, + I126, + I127, + I128, + I129, + I130, + I131, + I132, + I133, + I134, + I135, + I136, + I137, + I138, + I139, + I140, + I141, + I142, + I143, + I144, + I145, + I146, + I147, + I148, + I149, + I150, + I151, + I152, + I153, + I154, + I155, + I156, + I157, + I158, + I159, + I160, + I161, + I162, + I163, + I164, + I165, + I166, + I167, + I168, + I169, + I170, + I171, + I172, + I173, + I174, + I175, + I176, + I177, + I178, + I179, + I180, + I181, + I182, + I183, + I184, + I185, + I186, + I187, + I188, + I189, + I190, + I191, + I192, + I193, + I194, + I195, + I196, + I197, + I198, + I199, + I200, + I201, + I202, + I203, + I204, + I205, + I206, + I207, + I208, + I209, + I210, + I211, + I212, + I213, + I214, + I215, + I216, + I217, + I218, + I219, + I220, + I221, + I222, + I223, + I224, + I225, + I226, + I227, + I228, + I229, + I230, + I231, + I232, + I233, + I234, + I235, + I236, + I237, + I238, + I239, + I240, + I241, + I242, + I243, + I244, + I245, + I246, + I247, + I248, + I249, + I250, + I251, + I252, + I253, + I254, + I255, + I256, }; test "enum sizes" { @@ -189,11 +678,11 @@ test "enum sizes" { } } -const Small2 = enum (u2) { +const Small2 = enum(u2) { One, Two, }; -const Small = enum (u2) { +const Small = enum(u2) { One, Two, Three, @@ -213,8 +702,7 @@ test "set enum tag type" { } } - -const A = enum (u3) { +const A = enum(u3) { One, Two, Three, @@ -225,7 +713,7 @@ const A = enum (u3) { Four2, }; -const B = enum (u3) { +const B = enum(u3) { One3, Two3, Three3, @@ -236,7 +724,7 @@ const B = enum (u3) { Four23, }; -const C = enum (u2) { +const C = enum(u2) { One4, Two4, Three4, @@ -389,6 +877,8 @@ test "enum with tag values don't require parens" { } test "enum with 1 field but explicit tag type should still have the tag type" { - const Enum = enum(u8) { B = 2 }; + const Enum = enum(u8) { + B = 2, + }; comptime @import("std").debug.assert(@sizeOf(Enum) == @sizeOf(u8)); } diff --git a/test/cases/enum_with_members.zig b/test/cases/enum_with_members.zig index 0c2ae1c383..9e3e031f92 100644 --- a/test/cases/enum_with_members.zig +++ b/test/cases/enum_with_members.zig @@ -7,7 +7,7 @@ const ET = union(enum) { UINT: u32, pub fn print(a: &const ET, buf: []u8) error!usize { - return switch (*a) { + return switch (a.*) { ET.SINT => |x| fmt.formatIntBuf(buf, x, 10, false, 0), ET.UINT => |x| fmt.formatIntBuf(buf, x, 10, false, 0), }; @@ -15,8 +15,12 @@ const ET = union(enum) { }; test "enum with members" { - const a = ET { .SINT = -42 }; - const b = ET { .UINT = 42 }; + const a = ET { + .SINT = -42, + }; + const b = ET { + .UINT = 42, + }; var buf: [20]u8 = undefined; assert((a.print(buf[0..]) catch unreachable) == 3); diff --git a/test/cases/error.zig b/test/cases/error.zig index 2a1433df5b..70d96e4d01 100644 --- a/test/cases/error.zig +++ b/test/cases/error.zig @@ -30,14 +30,12 @@ test "@errorName" { assert(mem.eql(u8, @errorName(error.ALongerErrorName), "ALongerErrorName")); } - test "error values" { const a = i32(error.err1); const b = i32(error.err2); assert(a != b); } - test "redefinition of error values allowed" { shouldBeNotEqual(error.AnError, error.SecondError); } @@ -45,7 +43,6 @@ fn shouldBeNotEqual(a: error, b: error) void { if (a == b) unreachable; } - test "error binary operator" { const a = errBinaryOperatorG(true) catch 3; const b = errBinaryOperatorG(false) catch 3; @@ -56,20 +53,20 @@ fn errBinaryOperatorG(x: bool) error!isize { return if (x) error.ItBroke else isize(10); } - test "unwrap simple value from error" { const i = unwrapSimpleValueFromErrorDo() catch unreachable; assert(i == 13); } -fn unwrapSimpleValueFromErrorDo() error!isize { return 13; } - +fn unwrapSimpleValueFromErrorDo() error!isize { + return 13; +} test "error return in assignment" { doErrReturnInAssignment() catch unreachable; } fn doErrReturnInAssignment() error!void { - var x : i32 = undefined; + var x: i32 = undefined; x = try makeANonErr(); } @@ -95,7 +92,10 @@ test "error set type " { comptime testErrorSetType(); } -const MyErrSet = error {OutOfMemory, FileNotFound}; +const MyErrSet = error { + OutOfMemory, + FileNotFound, +}; fn testErrorSetType() void { assert(@memberCount(MyErrSet) == 2); @@ -109,14 +109,19 @@ fn testErrorSetType() void { } } - test "explicit error set cast" { testExplicitErrorSetCast(Set1.A); comptime testExplicitErrorSetCast(Set1.A); } -const Set1 = error{A, B}; -const Set2 = error{A, C}; +const Set1 = error { + A, + B, +}; +const Set2 = error { + A, + C, +}; fn testExplicitErrorSetCast(set1: Set1) void { var x = Set2(set1); @@ -129,7 +134,8 @@ test "comptime test error for empty error set" { comptime testComptimeTestErrorEmptySet(1234); } -const EmptyErrorSet = error {}; +const EmptyErrorSet = error { +}; fn testComptimeTestErrorEmptySet(x: EmptyErrorSet!i32) void { if (x) |v| assert(v == 1234) else |err| @compileError("bad"); @@ -145,7 +151,9 @@ test "comptime err to int of error set with only 1 possible value" { testErrToIntWithOnePossibleValue(error.A, u32(error.A)); comptime testErrToIntWithOnePossibleValue(error.A, u32(error.A)); } -fn testErrToIntWithOnePossibleValue(x: error{A}, comptime value: u32) void { +fn testErrToIntWithOnePossibleValue(x: error { + A, +}, comptime value: u32) void { if (u32(x) != value) { @compileError("bad"); } @@ -176,7 +184,6 @@ fn quux_1() !i32 { return error.C; } - test "error: fn returning empty error set can be passed as fn returning any error" { entry(); comptime entry(); @@ -186,24 +193,24 @@ fn entry() void { foo2(bar2); } -fn foo2(f: fn()error!void) void { +fn foo2(f: fn() error!void) void { const x = f(); } -fn bar2() (error{}!void) { } - +fn bar2() (error { +}!void) {} test "error: Zero sized error set returned with value payload crash" { _ = foo3(0); _ = comptime foo3(0); } -const Error = error{}; +const Error = error { +}; fn foo3(b: usize) Error!usize { return b; } - test "error: Infer error set from literals" { _ = nullLiteral("n") catch |err| handleErrors(err); _ = floatLiteral("n") catch |err| handleErrors(err); @@ -215,29 +222,26 @@ test "error: Infer error set from literals" { fn handleErrors(err: var) noreturn { switch (err) { - error.T => {} + error.T => {}, } unreachable; } fn nullLiteral(str: []const u8) !?i64 { - if (str[0] == 'n') - return null; + if (str[0] == 'n') return null; return error.T; } fn floatLiteral(str: []const u8) !?f64 { - if (str[0] == 'n') - return 1.0; + if (str[0] == 'n') return 1.0; return error.T; } fn intLiteral(str: []const u8) !?i64 { - if (str[0] == 'n') - return 1; + if (str[0] == 'n') return 1; return error.T; } diff --git a/test/cases/eval.zig b/test/cases/eval.zig index 364db5e152..2571686b0b 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -11,8 +11,6 @@ fn fibonacci(x: i32) i32 { return fibonacci(x - 1) + fibonacci(x - 2); } - - fn unwrapAndAddOne(blah: ?i32) i32 { return ??blah + 1; } @@ -40,13 +38,13 @@ test "inline variable gets result of const if" { assert(gimme1or2(false) == 2); } - test "static function evaluation" { assert(statically_added_number == 3); } const statically_added_number = staticAdd(1, 2); -fn staticAdd(a: i32, b: i32) i32 { return a + b; } - +fn staticAdd(a: i32, b: i32) i32 { + return a + b; +} test "const expr eval on single expr blocks" { assert(constExprEvalOnSingleExprBlocksFn(1, true) == 3); @@ -64,9 +62,6 @@ fn constExprEvalOnSingleExprBlocksFn(x: i32, b: bool) i32 { return result; } - - - test "statically initialized list" { assert(static_point_list[0].x == 1); assert(static_point_list[0].y == 2); @@ -77,7 +72,10 @@ const Point = struct { x: i32, y: i32, }; -const static_point_list = []Point { makePoint(1, 2), makePoint(3, 4) }; +const static_point_list = []Point { + makePoint(1, 2), + makePoint(3, 4), +}; fn makePoint(x: i32, y: i32) Point { return Point { .x = x, @@ -85,7 +83,6 @@ fn makePoint(x: i32, y: i32) Point { }; } - test "static eval list init" { assert(static_vec3.data[2] == 1.0); assert(vec3(0.0, 0.0, 3.0).data[2] == 3.0); @@ -96,17 +93,19 @@ pub const Vec3 = struct { }; pub fn vec3(x: f32, y: f32, z: f32) Vec3 { return Vec3 { - .data = []f32 { x, y, z, }, + .data = []f32 { + x, + y, + z, + }, }; } - test "constant expressions" { - var array : [array_size]u8 = undefined; + var array: [array_size]u8 = undefined; assert(@sizeOf(@typeOf(array)) == 20); } -const array_size : u8 = 20; - +const array_size: u8 = 20; test "constant struct with negation" { assert(vertices[0].x == -0.6); @@ -119,12 +118,29 @@ const Vertex = struct { b: f32, }; const vertices = []Vertex { - Vertex { .x = -0.6, .y = -0.4, .r = 1.0, .g = 0.0, .b = 0.0 }, - Vertex { .x = 0.6, .y = -0.4, .r = 0.0, .g = 1.0, .b = 0.0 }, - Vertex { .x = 0.0, .y = 0.6, .r = 0.0, .g = 0.0, .b = 1.0 }, + Vertex { + .x = -0.6, + .y = -0.4, + .r = 1.0, + .g = 0.0, + .b = 0.0, + }, + Vertex { + .x = 0.6, + .y = -0.4, + .r = 0.0, + .g = 1.0, + .b = 0.0, + }, + Vertex { + .x = 0.0, + .y = 0.6, + .r = 0.0, + .g = 0.0, + .b = 1.0, + }, }; - test "statically initialized struct" { st_init_str_foo.x += 1; assert(st_init_str_foo.x == 14); @@ -133,15 +149,21 @@ const StInitStrFoo = struct { x: i32, y: bool, }; -var st_init_str_foo = StInitStrFoo { .x = 13, .y = true, }; - +var st_init_str_foo = StInitStrFoo { + .x = 13, + .y = true, +}; test "statically initalized array literal" { - const y : [4]u8 = st_init_arr_lit_x; + const y: [4]u8 = st_init_arr_lit_x; assert(y[3] == 4); } -const st_init_arr_lit_x = []u8{1,2,3,4}; - +const st_init_arr_lit_x = []u8 { + 1, + 2, + 3, + 4, +}; test "const slice" { comptime { @@ -198,14 +220,29 @@ const CmdFn = struct { func: fn(i32) i32, }; -const cmd_fns = []CmdFn{ - CmdFn {.name = "one", .func = one}, - CmdFn {.name = "two", .func = two}, - CmdFn {.name = "three", .func = three}, +const cmd_fns = []CmdFn { + CmdFn { + .name = "one", + .func = one, + }, + CmdFn { + .name = "two", + .func = two, + }, + CmdFn { + .name = "three", + .func = three, + }, }; -fn one(value: i32) i32 { return value + 1; } -fn two(value: i32) i32 { return value + 2; } -fn three(value: i32) i32 { return value + 3; } +fn one(value: i32) i32 { + return value + 1; +} +fn two(value: i32) i32 { + return value + 2; +} +fn three(value: i32) i32 { + return value + 3; +} fn performFn(comptime prefix_char: u8, start_value: i32) i32 { var result: i32 = start_value; @@ -229,7 +266,7 @@ test "eval @setRuntimeSafety at compile-time" { assert(result == 1234); } -fn fnWithSetRuntimeSafety() i32{ +fn fnWithSetRuntimeSafety() i32 { @setRuntimeSafety(true); return 1234; } @@ -244,7 +281,6 @@ fn fnWithFloatMode() f32 { return 1234.0; } - const SimpleStruct = struct { field: i32, @@ -253,7 +289,9 @@ const SimpleStruct = struct { } }; -var simple_struct = SimpleStruct{ .field = 1234, }; +var simple_struct = SimpleStruct { + .field = 1234, +}; const bound_fn = simple_struct.method; @@ -261,8 +299,6 @@ test "call method on bound fn referring to var instance" { assert(bound_fn() == 1237); } - - test "ptr to local array argument at comptime" { comptime { var bytes: [10]u8 = undefined; @@ -277,7 +313,6 @@ fn modifySomeBytes(bytes: []u8) void { bytes[9] = 'b'; } - test "comparisons 0 <= uint and 0 > uint should be comptime" { testCompTimeUIntComparisons(1234); } @@ -296,8 +331,6 @@ fn testCompTimeUIntComparisons(x: u32) void { } } - - test "const ptr to variable data changes at runtime" { assert(foo_ref.name[0] == 'a'); foo_ref.name = "b"; @@ -308,11 +341,11 @@ const Foo = struct { name: []const u8, }; -var foo_contents = Foo { .name = "a", }; +var foo_contents = Foo { + .name = "a", +}; const foo_ref = &foo_contents; - - test "create global array with for loop" { assert(global_array[5] == 5 * 5); assert(global_array[9] == 9 * 9); @@ -321,7 +354,7 @@ test "create global array with for loop" { const global_array = x: { var result: [10]usize = undefined; for (result) |*item, index| { - *item = index * index; + item.* = index * index; } break :x result; }; @@ -379,7 +412,7 @@ test "f128 at compile time is lossy" { pub fn TypeWithCompTimeSlice(comptime field_name: []const u8) type { return struct { - pub const Node = struct { }; + pub const Node = struct {}; }; } @@ -401,10 +434,10 @@ fn copyWithPartialInline(s: []u32, b: []u8) void { comptime var i: usize = 0; inline while (i < 4) : (i += 1) { s[i] = 0; - s[i] |= u32(b[i*4+0]) << 24; - s[i] |= u32(b[i*4+1]) << 16; - s[i] |= u32(b[i*4+2]) << 8; - s[i] |= u32(b[i*4+3]) << 0; + s[i] |= u32(b[i * 4 + 0]) << 24; + s[i] |= u32(b[i * 4 + 1]) << 16; + s[i] |= u32(b[i * 4 + 2]) << 8; + s[i] |= u32(b[i * 4 + 3]) << 0; } } @@ -413,7 +446,7 @@ test "binary math operator in partially inlined function" { var b: [16]u8 = undefined; for (b) |*r, i| - *r = u8(i + 1); + r.* = u8(i + 1); copyWithPartialInline(s[0..], b[0..]); assert(s[0] == 0x1020304); @@ -422,7 +455,6 @@ test "binary math operator in partially inlined function" { assert(s[3] == 0xd0e0f10); } - test "comptime function with the same args is memoized" { comptime { assert(MakeType(i32) == MakeType(i32)); @@ -447,12 +479,12 @@ test "comptime function with mutable pointer is not memoized" { } fn increment(value: &i32) void { - *value += 1; + value.* += 1; } fn generateTable(comptime T: type) [1010]T { - var res : [1010]T = undefined; - var i : usize = 0; + var res: [1010]T = undefined; + var i: usize = 0; while (i < 1010) : (i += 1) { res[i] = T(i); } @@ -496,9 +528,10 @@ const SingleFieldStruct = struct { } }; test "const ptr to comptime mutable data is not memoized" { - comptime { - var foo = SingleFieldStruct {.x = 1}; + var foo = SingleFieldStruct { + .x = 1, + }; assert(foo.read_x() == 1); foo.x = 2; assert(foo.read_x() == 2); diff --git a/test/cases/fn.zig b/test/cases/fn.zig index 5388deac10..6d47dafad4 100644 --- a/test/cases/fn.zig +++ b/test/cases/fn.zig @@ -7,7 +7,6 @@ fn testParamsAdd(a: i32, b: i32) i32 { return a + b; } - test "local variables" { testLocVars(2); } @@ -16,7 +15,6 @@ fn testLocVars(b: i32) void { if (a + b != 3) unreachable; } - test "void parameters" { voidFun(1, void{}, 2, {}); } @@ -27,9 +25,8 @@ fn voidFun(a: i32, b: void, c: i32, d: void) void { return vv; } - test "mutable local variables" { - var zero : i32 = 0; + var zero: i32 = 0; assert(zero == 0); var i = i32(0); @@ -41,7 +38,7 @@ test "mutable local variables" { test "separate block scopes" { { - const no_conflict : i32 = 5; + const no_conflict: i32 = 5; assert(no_conflict == 5); } @@ -56,8 +53,7 @@ test "call function with empty string" { acceptsString(""); } -fn acceptsString(foo: []u8) void { } - +fn acceptsString(foo: []u8) void {} fn @"weird function name"() i32 { return 1234; @@ -70,31 +66,43 @@ test "implicit cast function unreachable return" { wantsFnWithVoid(fnWithUnreachable); } -fn wantsFnWithVoid(f: fn() void) void { } +fn wantsFnWithVoid(f: fn() void) void {} fn fnWithUnreachable() noreturn { unreachable; } - test "function pointers" { - const fns = []@typeOf(fn1) { fn1, fn2, fn3, fn4, }; + const fns = []@typeOf(fn1) { + fn1, + fn2, + fn3, + fn4, + }; for (fns) |f, i| { assert(f() == u32(i) + 5); } } -fn fn1() u32 {return 5;} -fn fn2() u32 {return 6;} -fn fn3() u32 {return 7;} -fn fn4() u32 {return 8;} - +fn fn1() u32 { + return 5; +} +fn fn2() u32 { + return 6; +} +fn fn3() u32 { + return 7; +} +fn fn4() u32 { + return 8; +} test "inline function call" { assert(@inlineCall(add, 3, 9) == 12); } -fn add(a: i32, b: i32) i32 { return a + b; } - +fn add(a: i32, b: i32) i32 { + return a + b; +} test "number literal as an argument" { numberLiteralArg(3); @@ -110,4 +118,4 @@ test "assign inline fn to const variable" { a(); } -inline fn inlineFn() void { } +inline fn inlineFn() void {} diff --git a/test/cases/for.zig b/test/cases/for.zig index 7bb0d7c9fa..f13e6ec6e5 100644 --- a/test/cases/for.zig +++ b/test/cases/for.zig @@ -3,8 +3,14 @@ const assert = std.debug.assert; const mem = std.mem; test "continue in for loop" { - const array = []i32 {1, 2, 3, 4, 5}; - var sum : i32 = 0; + const array = []i32 { + 1, + 2, + 3, + 4, + 5, + }; + var sum: i32 = 0; for (array) |x| { sum += x; if (x < 3) { @@ -24,17 +30,39 @@ test "for loop with pointer elem var" { } fn mangleString(s: []u8) void { for (s) |*c| { - *c += 1; + c.* += 1; } } test "basic for loop" { - const expected_result = []u8{9, 8, 7, 6, 0, 1, 2, 3, 9, 8, 7, 6, 0, 1, 2, 3 }; + const expected_result = []u8 { + 9, + 8, + 7, + 6, + 0, + 1, + 2, + 3, + 9, + 8, + 7, + 6, + 0, + 1, + 2, + 3, + }; var buffer: [expected_result.len]u8 = undefined; var buf_index: usize = 0; - const array = []u8 {9, 8, 7, 6}; + const array = []u8 { + 9, + 8, + 7, + 6, + }; for (array) |item| { buffer[buf_index] = item; buf_index += 1; @@ -65,7 +93,8 @@ fn testBreakOuter() void { var array = "aoeu"; var count: usize = 0; outer: for (array) |_| { - for (array) |_2| { // TODO shouldn't get error for redeclaring "_" + // TODO shouldn't get error for redeclaring "_" + for (array) |_2| { count += 1; break :outer; } @@ -82,7 +111,8 @@ fn testContinueOuter() void { var array = "aoeu"; var counter: usize = 0; outer: for (array) |_| { - for (array) |_2| { // TODO shouldn't get error for redeclaring "_" + // TODO shouldn't get error for redeclaring "_" + for (array) |_2| { counter += 1; continue :outer; } diff --git a/test/cases/generics.zig b/test/cases/generics.zig index 19b4a598d8..da8a7dcad6 100644 --- a/test/cases/generics.zig +++ b/test/cases/generics.zig @@ -37,7 +37,6 @@ test "fn with comptime args" { assert(sameButWithFloats(0.43, 0.49) == 0.49); } - test "var params" { assert(max_i32(12, 34) == 34); assert(max_f64(1.2, 3.4) == 3.4); @@ -60,7 +59,6 @@ fn max_f64(a: f64, b: f64) f64 { return max_var(a, b); } - pub fn List(comptime T: type) type { return SmallList(T, 8); } @@ -82,10 +80,15 @@ test "function with return type type" { assert(list2.prealloc_items.len == 8); } - test "generic struct" { - var a1 = GenNode(i32) {.value = 13, .next = null,}; - var b1 = GenNode(bool) {.value = true, .next = null,}; + var a1 = GenNode(i32) { + .value = 13, + .next = null, + }; + var b1 = GenNode(bool) { + .value = true, + .next = null, + }; assert(a1.value == 13); assert(a1.value == a1.getVal()); assert(b1.getVal()); @@ -94,7 +97,9 @@ fn GenNode(comptime T: type) type { return struct { value: T, next: ?&GenNode(T), - fn getVal(n: &const GenNode(T)) T { return n.value; } + fn getVal(n: &const GenNode(T)) T { + return n.value; + } }; } @@ -107,7 +112,6 @@ fn GenericDataThing(comptime count: isize) type { }; } - test "use generic param in generic param" { assert(aGenericFn(i32, 3, 4) == 7); } @@ -115,21 +119,31 @@ fn aGenericFn(comptime T: type, comptime a: T, b: T) T { return a + b; } - test "generic fn with implicit cast" { assert(getFirstByte(u8, []u8 {13}) == 13); - assert(getFirstByte(u16, []u16 {0, 13}) == 0); + assert(getFirstByte(u16, []u16 { + 0, + 13, + }) == 0); +} +fn getByte(ptr: ?&const u8) u8 { + return ??ptr.*; } -fn getByte(ptr: ?&const u8) u8 {return *??ptr;} fn getFirstByte(comptime T: type, mem: []const T) u8 { return getByte(@ptrCast(&const u8, &mem[0])); } +const foos = []fn(var) bool { + foo1, + foo2, +}; -const foos = []fn(var) bool { foo1, foo2 }; - -fn foo1(arg: var) bool { return arg; } -fn foo2(arg: var) bool { return !arg; } +fn foo1(arg: var) bool { + return arg; +} +fn foo2(arg: var) bool { + return !arg; +} test "array of generic fns" { assert(foos[0](true)); diff --git a/test/cases/if.zig b/test/cases/if.zig index 2caae7448c..808936bfa5 100644 --- a/test/cases/if.zig +++ b/test/cases/if.zig @@ -23,7 +23,6 @@ fn firstEqlThird(a: i32, b: i32, c: i32) void { } } - test "else if expression" { assert(elseIfExpressionF(1) == 1); } diff --git a/test/cases/import/a_namespace.zig b/test/cases/import/a_namespace.zig index 5cf906cf91..042f1867a5 100644 --- a/test/cases/import/a_namespace.zig +++ b/test/cases/import/a_namespace.zig @@ -1 +1,3 @@ -pub fn foo() i32 { return 1234; } +pub fn foo() i32 { + return 1234; +} diff --git a/test/cases/ir_block_deps.zig b/test/cases/ir_block_deps.zig index 202df19f62..c017eca508 100644 --- a/test/cases/ir_block_deps.zig +++ b/test/cases/ir_block_deps.zig @@ -11,7 +11,9 @@ fn foo(id: u64) !i32 { }; } -fn getErrInt() error!i32 { return 0; } +fn getErrInt() error!i32 { + return 0; +} test "ir block deps" { assert((foo(1) catch unreachable) == 0); diff --git a/test/cases/math.zig b/test/cases/math.zig index 47d001a590..dfc5946fdb 100644 --- a/test/cases/math.zig +++ b/test/cases/math.zig @@ -28,25 +28,12 @@ fn testDivision() void { assert(divTrunc(f32, -5.0, 3.0) == -1.0); comptime { - assert( - 1194735857077236777412821811143690633098347576 % - 508740759824825164163191790951174292733114988 == - 177254337427586449086438229241342047632117600); - assert(@rem(-1194735857077236777412821811143690633098347576, - 508740759824825164163191790951174292733114988) == - -177254337427586449086438229241342047632117600); - assert(1194735857077236777412821811143690633098347576 / - 508740759824825164163191790951174292733114988 == - 2); - assert(@divTrunc(-1194735857077236777412821811143690633098347576, - 508740759824825164163191790951174292733114988) == - -2); - assert(@divTrunc(1194735857077236777412821811143690633098347576, - -508740759824825164163191790951174292733114988) == - -2); - assert(@divTrunc(-1194735857077236777412821811143690633098347576, - -508740759824825164163191790951174292733114988) == - 2); + assert(1194735857077236777412821811143690633098347576 % 508740759824825164163191790951174292733114988 == 177254337427586449086438229241342047632117600); + assert(@rem(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -177254337427586449086438229241342047632117600); + assert(1194735857077236777412821811143690633098347576 / 508740759824825164163191790951174292733114988 == 2); + assert(@divTrunc(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -2); + assert(@divTrunc(1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == -2); + assert(@divTrunc(-1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == 2); assert(4126227191251978491697987544882340798050766755606969681711 % 10 == 1); } } @@ -114,18 +101,28 @@ fn ctz(x: var) usize { test "assignment operators" { var i: u32 = 0; - i += 5; assert(i == 5); - i -= 2; assert(i == 3); - i *= 20; assert(i == 60); - i /= 3; assert(i == 20); - i %= 11; assert(i == 9); - i <<= 1; assert(i == 18); - i >>= 2; assert(i == 4); + i += 5; + assert(i == 5); + i -= 2; + assert(i == 3); + i *= 20; + assert(i == 60); + i /= 3; + assert(i == 20); + i %= 11; + assert(i == 9); + i <<= 1; + assert(i == 18); + i >>= 2; + assert(i == 4); i = 6; - i &= 5; assert(i == 4); - i ^= 6; assert(i == 2); + i &= 5; + assert(i == 4); + i ^= 6; + assert(i == 2); i = 6; - i |= 3; assert(i == 7); + i |= 3; + assert(i == 7); } test "three expr in a row" { @@ -138,7 +135,7 @@ fn testThreeExprInARow(f: bool, t: bool) void { assertFalse(1 | 2 | 4 != 7); assertFalse(3 ^ 6 ^ 8 != 13); assertFalse(7 & 14 & 28 != 4); - assertFalse(9 << 1 << 2 != 9 << 3); + assertFalse(9 << 1 << 2 != 9 << 3); assertFalse(90 >> 1 >> 2 != 90 >> 3); assertFalse(100 - 1 + 1000 != 1099); assertFalse(5 * 4 / 2 % 3 != 1); @@ -150,7 +147,6 @@ fn assertFalse(b: bool) void { assert(!b); } - test "const number literal" { const one = 1; const eleven = ten + one; @@ -159,8 +155,6 @@ test "const number literal" { } const ten = 10; - - test "unsigned wrapping" { testUnsignedWrappingEval(@maxValue(u32)); comptime testUnsignedWrappingEval(@maxValue(u32)); @@ -214,8 +208,12 @@ const DivResult = struct { }; test "binary not" { - assert(comptime x: {break :x ~u16(0b1010101010101010) == 0b0101010101010101;}); - assert(comptime x: {break :x ~u64(2147483647) == 18446744071562067968;}); + assert(comptime x: { + break :x ~u16(0b1010101010101010) == 0b0101010101010101; + }); + assert(comptime x: { + break :x ~u64(2147483647) == 18446744071562067968; + }); testBinaryNot(0b1010101010101010); } @@ -319,27 +317,15 @@ fn testShrExact(x: u8) void { test "big number addition" { comptime { - assert( - 35361831660712422535336160538497375248 + - 101752735581729509668353361206450473702 == - 137114567242441932203689521744947848950); - assert( - 594491908217841670578297176641415611445982232488944558774612 + - 390603545391089362063884922208143568023166603618446395589768 == - 985095453608931032642182098849559179469148836107390954364380); + assert(35361831660712422535336160538497375248 + 101752735581729509668353361206450473702 == 137114567242441932203689521744947848950); + assert(594491908217841670578297176641415611445982232488944558774612 + 390603545391089362063884922208143568023166603618446395589768 == 985095453608931032642182098849559179469148836107390954364380); } } test "big number multiplication" { comptime { - assert( - 45960427431263824329884196484953148229 * - 128339149605334697009938835852565949723 == - 5898522172026096622534201617172456926982464453350084962781392314016180490567); - assert( - 594491908217841670578297176641415611445982232488944558774612 * - 390603545391089362063884922208143568023166603618446395589768 == - 232210647056203049913662402532976186578842425262306016094292237500303028346593132411865381225871291702600263463125370016); + assert(45960427431263824329884196484953148229 * 128339149605334697009938835852565949723 == 5898522172026096622534201617172456926982464453350084962781392314016180490567); + assert(594491908217841670578297176641415611445982232488944558774612 * 390603545391089362063884922208143568023166603618446395589768 == 232210647056203049913662402532976186578842425262306016094292237500303028346593132411865381225871291702600263463125370016); } } @@ -380,7 +366,9 @@ test "f128" { comptime test_f128(); } -fn make_f128(x: f128) f128 { return x; } +fn make_f128(x: f128) f128 { + return x; +} fn test_f128() void { assert(@sizeOf(f128) == 16); diff --git a/test/cases/misc.zig b/test/cases/misc.zig index 95a9a46bff..66487a4946 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -4,6 +4,7 @@ const cstr = @import("std").cstr; const builtin = @import("builtin"); // normal comment + /// this is a documentation comment /// doc comment line 2 fn emptyFunctionWithComments() void {} @@ -16,8 +17,7 @@ comptime { @export("disabledExternFn", disabledExternFn, builtin.GlobalLinkage.Internal); } -extern fn disabledExternFn() void { -} +extern fn disabledExternFn() void {} test "call disabled extern fn" { disabledExternFn(); @@ -110,17 +110,29 @@ fn testShortCircuit(f: bool, t: bool) void { var hit_3 = f; var hit_4 = f; - if (t or x: {assert(f); break :x f;}) { + if (t or x: { + assert(f); + break :x f; + }) { hit_1 = t; } - if (f or x: { hit_2 = t; break :x f; }) { + if (f or x: { + hit_2 = t; + break :x f; + }) { assert(f); } - if (t and x: { hit_3 = t; break :x f; }) { + if (t and x: { + hit_3 = t; + break :x f; + }) { assert(f); } - if (f and x: {assert(f); break :x f;}) { + if (f and x: { + assert(f); + break :x f; + }) { assert(f); } else { hit_4 = t; @@ -146,8 +158,8 @@ test "return string from function" { assert(mem.eql(u8, first4KeysOfHomeRow(), "aoeu")); } -const g1 : i32 = 1233 + 1; -var g2 : i32 = 0; +const g1: i32 = 1233 + 1; +var g2: i32 = 0; test "global variables" { assert(g2 == 0); @@ -155,10 +167,9 @@ test "global variables" { assert(g2 == 1234); } - test "memcpy and memset intrinsics" { - var foo : [20]u8 = undefined; - var bar : [20]u8 = undefined; + var foo: [20]u8 = undefined; + var bar: [20]u8 = undefined; @memset(&foo[0], 'A', foo.len); @memcpy(&bar[0], &foo[0], bar.len); @@ -167,12 +178,14 @@ test "memcpy and memset intrinsics" { } test "builtin static eval" { - const x : i32 = comptime x: {break :x 1 + 2 + 3;}; + const x: i32 = comptime x: { + break :x 1 + 2 + 3; + }; assert(x == comptime 6); } test "slicing" { - var array : [20]i32 = undefined; + var array: [20]i32 = undefined; array[5] = 1234; @@ -187,15 +200,15 @@ test "slicing" { if (slice_rest.len != 10) unreachable; } - test "constant equal function pointers" { const alias = emptyFn; - assert(comptime x: {break :x emptyFn == alias;}); + assert(comptime x: { + break :x emptyFn == alias; + }); } fn emptyFn() void {} - test "hex escape" { assert(mem.eql(u8, "\x68\x65\x6c\x6c\x6f", "hello")); } @@ -219,7 +232,7 @@ test "string escapes" { } test "multiline string" { - const s1 = + const s1 = \\one \\two) \\three @@ -229,7 +242,7 @@ test "multiline string" { } test "multiline C string" { - const s1 = + const s1 = c\\one c\\two) c\\three @@ -238,18 +251,16 @@ test "multiline C string" { assert(cstr.cmp(s1, s2) == 0); } - test "type equality" { assert(&const u8 != &u8); } - const global_a: i32 = 1234; const global_b: &const i32 = &global_a; const global_c: &const f32 = @ptrCast(&const f32, global_b); test "compile time global reinterpret" { const d = @ptrCast(&const i32, global_c); - assert(*d == 1234); + assert(d.* == 1234); } test "explicit cast maybe pointers" { @@ -261,12 +272,11 @@ test "generic malloc free" { const a = memAlloc(u8, 10) catch unreachable; memFree(u8, a); } -var some_mem : [100]u8 = undefined; +var some_mem: [100]u8 = undefined; fn memAlloc(comptime T: type, n: usize) error![]T { return @ptrCast(&T, &some_mem[0])[0..n]; } -fn memFree(comptime T: type, memory: []T) void { } - +fn memFree(comptime T: type, memory: []T) void {} test "cast undefined" { const array: [100]u8 = undefined; @@ -275,32 +285,35 @@ test "cast undefined" { } fn testCastUndefined(x: []const u8) void {} - test "cast small unsigned to larger signed" { assert(castSmallUnsignedToLargerSigned1(200) == i16(200)); assert(castSmallUnsignedToLargerSigned2(9999) == i64(9999)); } -fn castSmallUnsignedToLargerSigned1(x: u8) i16 { return x; } -fn castSmallUnsignedToLargerSigned2(x: u16) i64 { return x; } - +fn castSmallUnsignedToLargerSigned1(x: u8) i16 { + return x; +} +fn castSmallUnsignedToLargerSigned2(x: u16) i64 { + return x; +} test "implicit cast after unreachable" { assert(outer() == 1234); } -fn inner() i32 { return 1234; } +fn inner() i32 { + return 1234; +} fn outer() i64 { return inner(); } - test "pointer dereferencing" { var x = i32(3); const y = &x; - *y += 1; + y.* += 1; assert(x == 4); - assert(*y == 4); + assert(y.* == 4); } test "call result of if else expression" { @@ -310,9 +323,12 @@ test "call result of if else expression" { fn f2(x: bool) []const u8 { return (if (x) fA else fB)(); } -fn fA() []const u8 { return "a"; } -fn fB() []const u8 { return "b"; } - +fn fA() []const u8 { + return "a"; +} +fn fB() []const u8 { + return "b"; +} test "const expression eval handling of variables" { var x = true; @@ -321,8 +337,6 @@ test "const expression eval handling of variables" { } } - - test "constant enum initialization with differing sizes" { test3_1(test3_foo); test3_2(test3_bar); @@ -336,10 +350,17 @@ const Test3Point = struct { x: i32, y: i32, }; -const test3_foo = Test3Foo { .Three = Test3Point {.x = 3, .y = 4}}; -const test3_bar = Test3Foo { .Two = 13}; +const test3_foo = Test3Foo { + .Three = Test3Point { + .x = 3, + .y = 4, + }, +}; +const test3_bar = Test3Foo { + .Two = 13, +}; fn test3_1(f: &const Test3Foo) void { - switch (*f) { + switch (f.*) { Test3Foo.Three => |pt| { assert(pt.x == 3); assert(pt.y == 4); @@ -348,7 +369,7 @@ fn test3_1(f: &const Test3Foo) void { } } fn test3_2(f: &const Test3Foo) void { - switch (*f) { + switch (f.*) { Test3Foo.Two => |x| { assert(x == 13); }, @@ -356,23 +377,19 @@ fn test3_2(f: &const Test3Foo) void { } } - test "character literals" { assert('\'' == single_quote); } const single_quote = '\''; - - test "take address of parameter" { testTakeAddressOfParameter(12.34); } fn testTakeAddressOfParameter(f: f32) void { const f_ptr = &f; - assert(*f_ptr == 12.34); + assert(f_ptr.* == 12.34); } - test "pointer comparison" { const a = ([]const u8)("a"); const b = &a; @@ -382,23 +399,30 @@ fn ptrEql(a: &const []const u8, b: &const []const u8) bool { return a == b; } - test "C string concatenation" { const a = c"OK" ++ c" IT " ++ c"WORKED"; const b = c"OK IT WORKED"; const len = cstr.len(b); const len_with_null = len + 1; - {var i: u32 = 0; while (i < len_with_null) : (i += 1) { - assert(a[i] == b[i]); - }} + { + var i: u32 = 0; + while (i < len_with_null) : (i += 1) { + assert(a[i] == b[i]); + } + } assert(a[len] == 0); assert(b[len] == 0); } test "cast slice to u8 slice" { assert(@sizeOf(i32) == 4); - var big_thing_array = []i32{1, 2, 3, 4}; + var big_thing_array = []i32 { + 1, + 2, + 3, + 4, + }; const big_thing_slice: []i32 = big_thing_array[0..]; const bytes = ([]u8)(big_thing_slice); assert(bytes.len == 4 * 4); @@ -421,25 +445,22 @@ test "pointer to void return type" { } fn testPointerToVoidReturnType() error!void { const a = testPointerToVoidReturnType2(); - return *a; + return a.*; } const test_pointer_to_void_return_type_x = void{}; fn testPointerToVoidReturnType2() &const void { return &test_pointer_to_void_return_type_x; } - test "non const ptr to aliased type" { const int = i32; assert(?&int == ?&i32); } - - test "array 2D const double ptr" { const rect_2d_vertexes = [][1]f32 { - []f32{1.0}, - []f32{2.0}, + []f32 {1.0}, + []f32 {2.0}, }; testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]); } @@ -450,10 +471,21 @@ fn testArray2DConstDoublePtr(ptr: &const f32) void { } const Tid = builtin.TypeId; -const AStruct = struct { x: i32, }; -const AnEnum = enum { One, Two, }; -const AUnionEnum = union(enum) { One: i32, Two: void, }; -const AUnion = union { One: void, Two: void }; +const AStruct = struct { + x: i32, +}; +const AnEnum = enum { + One, + Two, +}; +const AUnionEnum = union(enum) { + One: i32, + Two: void, +}; +const AUnion = union { + One: void, + Two: void, +}; test "@typeId" { comptime { @@ -481,9 +513,11 @@ test "@typeId" { assert(@typeId(@typeOf(AUnionEnum.One)) == Tid.Enum); assert(@typeId(AUnionEnum) == Tid.Union); assert(@typeId(AUnion) == Tid.Union); - assert(@typeId(fn()void) == Tid.Fn); + assert(@typeId(fn() void) == Tid.Fn); assert(@typeId(@typeOf(builtin)) == Tid.Namespace); - assert(@typeId(@typeOf(x: {break :x this;})) == Tid.Block); + assert(@typeId(@typeOf(x: { + break :x this; + })) == Tid.Block); // TODO bound fn // TODO arg tuple // TODO opaque @@ -499,8 +533,7 @@ test "@canImplicitCast" { } test "@typeName" { - const Struct = struct { - }; + const Struct = struct {}; const Union = union { unused: u8, }; @@ -525,14 +558,19 @@ fn TypeFromFn(comptime T: type) type { test "volatile load and store" { var number: i32 = 1234; const ptr = (&volatile i32)(&number); - *ptr += 1; - assert(*ptr == 1235); + ptr.* += 1; + assert(ptr.* == 1235); } test "slice string literal has type []const u8" { comptime { assert(@typeOf("aoeu"[0..]) == []const u8); - const array = []i32{1, 2, 3, 4}; + const array = []i32 { + 1, + 2, + 3, + 4, + }; assert(@typeOf(array[0..]) == []const i32); } } @@ -544,12 +582,15 @@ const GDTEntry = struct { field: i32, }; var gdt = []GDTEntry { - GDTEntry {.field = 1}, - GDTEntry {.field = 2}, + GDTEntry { + .field = 1, + }, + GDTEntry { + .field = 2, + }, }; var global_ptr = &gdt[0]; - // can't really run this test but we can make sure it has no compile error // and generates code const vram = @intToPtr(&volatile u8, 0x20000000)[0..0x8000]; @@ -584,7 +625,7 @@ test "comptime if inside runtime while which unconditionally breaks" { } fn testComptimeIfInsideRuntimeWhileWhichUnconditionallyBreaks(cond: bool) void { while (cond) { - if (false) { } + if (false) {} break; } } @@ -607,7 +648,9 @@ fn testStructInFn() void { kind: BlockKind, }; - var block = Block { .kind = 1234 }; + var block = Block { + .kind = 1234, + }; block.kind += 1; @@ -617,7 +660,9 @@ fn testStructInFn() void { fn fnThatClosesOverLocalConst() type { const c = 1; return struct { - fn g() i32 { return c; } + fn g() i32 { + return c; + } }; } @@ -635,22 +680,29 @@ fn thisIsAColdFn() void { @setCold(true); } - -const PackedStruct = packed struct { a: u8, b: u8, }; -const PackedUnion = packed union { a: u8, b: u32, }; -const PackedEnum = packed enum { A, B, }; +const PackedStruct = packed struct { + a: u8, + b: u8, +}; +const PackedUnion = packed union { + a: u8, + b: u32, +}; +const PackedEnum = packed enum { + A, + B, +}; test "packed struct, enum, union parameters in extern function" { - testPackedStuff( - PackedStruct{.a = 1, .b = 2}, - PackedUnion{.a = 1}, - PackedEnum.A, - ); -} - -export fn testPackedStuff(a: &const PackedStruct, b: &const PackedUnion, c: PackedEnum) void { + testPackedStuff(PackedStruct { + .a = 1, + .b = 2, + }, PackedUnion { + .a = 1, + }, PackedEnum.A); } +export fn testPackedStuff(a: &const PackedStruct, b: &const PackedUnion, c: PackedEnum) void {} test "slicing zero length array" { const s1 = ""[0..]; @@ -661,7 +713,6 @@ test "slicing zero length array" { assert(mem.eql(u32, s2, []u32{})); } - const addr1 = @ptrCast(&const u8, emptyFn); test "comptime cast fn to ptr" { const addr2 = @ptrCast(&const u8, emptyFn); diff --git a/test/cases/namespace_depends_on_compile_var/index.zig b/test/cases/namespace_depends_on_compile_var/index.zig index 95209dcef3..ccc49d9367 100644 --- a/test/cases/namespace_depends_on_compile_var/index.zig +++ b/test/cases/namespace_depends_on_compile_var/index.zig @@ -8,7 +8,7 @@ test "namespace depends on compile var" { assert(!some_namespace.a_bool); } } -const some_namespace = switch(builtin.os) { +const some_namespace = switch (builtin.os) { builtin.Os.linux => @import("a.zig"), else => @import("b.zig"), }; diff --git a/test/cases/null.zig b/test/cases/null.zig index 35d72b729c..96a62ab1ed 100644 --- a/test/cases/null.zig +++ b/test/cases/null.zig @@ -1,7 +1,7 @@ const assert = @import("std").debug.assert; test "nullable type" { - const x : ?bool = true; + const x: ?bool = true; if (x) |y| { if (y) { @@ -13,13 +13,13 @@ test "nullable type" { unreachable; } - const next_x : ?i32 = null; + const next_x: ?i32 = null; const z = next_x ?? 1234; assert(z == 1234); - const final_x : ?i32 = 13; + const final_x: ?i32 = 13; const num = final_x ?? unreachable; @@ -30,19 +30,17 @@ test "test maybe object and get a pointer to the inner value" { var maybe_bool: ?bool = true; if (maybe_bool) |*b| { - *b = false; + b.* = false; } assert(??maybe_bool == false); } - test "rhs maybe unwrap return" { const x: ?bool = true; const y = x ?? return; } - test "maybe return" { maybeReturnImpl(); comptime maybeReturnImpl(); @@ -50,8 +48,7 @@ test "maybe return" { fn maybeReturnImpl() void { assert(??foo(1235)); - if (foo(null) != null) - unreachable; + if (foo(null) != null) unreachable; assert(!??foo(1234)); } @@ -60,12 +57,16 @@ fn foo(x: ?i32) ?bool { return value > 1234; } - test "if var maybe pointer" { - assert(shouldBeAPlus1(Particle {.a = 14, .b = 1, .c = 1, .d = 1}) == 15); + assert(shouldBeAPlus1(Particle { + .a = 14, + .b = 1, + .c = 1, + .d = 1, + }) == 15); } fn shouldBeAPlus1(p: &const Particle) u64 { - var maybe_particle: ?Particle = *p; + var maybe_particle: ?Particle = p.*; if (maybe_particle) |*particle| { particle.a += 1; } @@ -81,7 +82,6 @@ const Particle = struct { d: u64, }; - test "null literal outside function" { const is_null = here_is_a_null_literal.context == null; assert(is_null); @@ -96,7 +96,6 @@ const here_is_a_null_literal = SillyStruct { .context = null, }; - test "test null runtime" { testTestNullRuntime(null); } @@ -123,8 +122,6 @@ fn bar(x: ?void) ?void { } } - - const StructWithNullable = struct { field: ?i32, }; diff --git a/test/cases/ref_var_in_if_after_if_2nd_switch_prong.zig b/test/cases/ref_var_in_if_after_if_2nd_switch_prong.zig index 76cff3731a..3c94bb0d49 100644 --- a/test/cases/ref_var_in_if_after_if_2nd_switch_prong.zig +++ b/test/cases/ref_var_in_if_after_if_2nd_switch_prong.zig @@ -23,7 +23,7 @@ fn foo(c: bool, k: Num, c2: bool, b: []const u8) void { if (c) { const output_path = b; - if (c2) { } + if (c2) {} a(output_path); } diff --git a/test/cases/reflection.zig b/test/cases/reflection.zig index 0abc46c9de..f9b64c80eb 100644 --- a/test/cases/reflection.zig +++ b/test/cases/reflection.zig @@ -23,7 +23,9 @@ test "reflection: function return type, var args, and param types" { } } -fn dummy(a: bool, b: i32, c: f32) i32 { return 1234; } +fn dummy(a: bool, b: i32, c: f32) i32 { + return 1234; +} fn dummy_varargs(args: ...) void {} test "reflection: struct member types and names" { @@ -54,7 +56,6 @@ test "reflection: enum member types and names" { assert(mem.eql(u8, @memberName(Bar, 2), "Three")); assert(mem.eql(u8, @memberName(Bar, 3), "Four")); } - } test "reflection: @field" { diff --git a/test/cases/slice.zig b/test/cases/slice.zig index ea708ba3b5..4ca194672c 100644 --- a/test/cases/slice.zig +++ b/test/cases/slice.zig @@ -18,7 +18,11 @@ test "slice child property" { } test "runtime safety lets us slice from len..len" { - var an_array = []u8{1, 2, 3}; + var an_array = []u8 { + 1, + 2, + 3, + }; assert(mem.eql(u8, sliceFromLenToLen(an_array[0..], 3, 3), "")); } @@ -27,7 +31,7 @@ fn sliceFromLenToLen(a_slice: []u8, start: usize, end: usize) []u8 { } test "implicitly cast array of size 0 to slice" { - var msg = []u8 {}; + var msg = []u8{}; assertLenIsZero(msg); } diff --git a/test/cases/struct.zig b/test/cases/struct.zig index c3df97678b..c474d99f2b 100644 --- a/test/cases/struct.zig +++ b/test/cases/struct.zig @@ -2,9 +2,11 @@ const assert = @import("std").debug.assert; const builtin = @import("builtin"); const StructWithNoFields = struct { - fn add(a: i32, b: i32) i32 { return a + b; } + fn add(a: i32, b: i32) i32 { + return a + b; + } }; -const empty_global_instance = StructWithNoFields {}; +const empty_global_instance = StructWithNoFields{}; test "call struct static method" { const result = StructWithNoFields.add(3, 4); @@ -34,12 +36,11 @@ test "void struct fields" { assert(@sizeOf(VoidStructFieldsFoo) == 4); } const VoidStructFieldsFoo = struct { - a : void, - b : i32, - c : void, + a: void, + b: i32, + c: void, }; - test "structs" { var foo: StructFoo = undefined; @memset(@ptrCast(&u8, &foo), 0, @sizeOf(StructFoo)); @@ -50,9 +51,9 @@ test "structs" { assert(foo.c == 100); } const StructFoo = struct { - a : i32, - b : bool, - c : f32, + a: i32, + b: bool, + c: f32, }; fn testFoo(foo: &const StructFoo) void { assert(foo.b); @@ -61,7 +62,6 @@ fn testMutation(foo: &StructFoo) void { foo.c = 100; } - const Node = struct { val: Val, next: &Node, @@ -72,10 +72,10 @@ const Val = struct { }; test "struct point to self" { - var root : Node = undefined; + var root: Node = undefined; root.val.x = 1; - var node : Node = undefined; + var node: Node = undefined; node.next = &root; node.val.x = 2; @@ -85,8 +85,8 @@ test "struct point to self" { } test "struct byval assign" { - var foo1 : StructFoo = undefined; - var foo2 : StructFoo = undefined; + var foo1: StructFoo = undefined; + var foo2: StructFoo = undefined; foo1.a = 1234; foo2.a = 0; @@ -96,46 +96,57 @@ test "struct byval assign" { } fn structInitializer() void { - const val = Val { .x = 42 }; + const val = Val { + .x = 42, + }; assert(val.x == 42); } - test "fn call of struct field" { - assert(callStructField(Foo {.ptr = aFunc,}) == 13); + assert(callStructField(Foo { + .ptr = aFunc, + }) == 13); } const Foo = struct { ptr: fn() i32, }; -fn aFunc() i32 { return 13; } +fn aFunc() i32 { + return 13; +} fn callStructField(foo: &const Foo) i32 { return foo.ptr(); } - test "store member function in variable" { - const instance = MemberFnTestFoo { .x = 1234, }; + const instance = MemberFnTestFoo { + .x = 1234, + }; const memberFn = MemberFnTestFoo.member; const result = memberFn(instance); assert(result == 1234); } const MemberFnTestFoo = struct { x: i32, - fn member(foo: &const MemberFnTestFoo) i32 { return foo.x; } + fn member(foo: &const MemberFnTestFoo) i32 { + return foo.x; + } }; - test "call member function directly" { - const instance = MemberFnTestFoo { .x = 1234, }; + const instance = MemberFnTestFoo { + .x = 1234, + }; const result = MemberFnTestFoo.member(instance); assert(result == 1234); } test "member functions" { - const r = MemberFnRand {.seed = 1234}; + const r = MemberFnRand { + .seed = 1234, + }; assert(r.getSeed() == 1234); } const MemberFnRand = struct { @@ -170,17 +181,16 @@ const EmptyStruct = struct { } }; - test "return empty struct from fn" { _ = testReturnEmptyStructFromFn(); } const EmptyStruct2 = struct {}; fn testReturnEmptyStructFromFn() EmptyStruct2 { - return EmptyStruct2 {}; + return EmptyStruct2{}; } test "pass slice of empty struct to fn" { - assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2{ EmptyStruct2{} }) == 1); + assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2 {EmptyStruct2{}}) == 1); } fn testPassSliceOfEmptyStructToFn(slice: []const EmptyStruct2) usize { return slice.len; @@ -201,7 +211,6 @@ test "packed struct" { assert(four == 4); } - const BitField1 = packed struct { a: u3, b: u3, @@ -301,7 +310,7 @@ test "packed array 24bits" { assert(@sizeOf(FooArray24Bits) == 2 + 2 * 3 + 2); } - var bytes = []u8{0} ** (@sizeOf(FooArray24Bits) + 1); + var bytes = []u8 {0} ** (@sizeOf(FooArray24Bits) + 1); bytes[bytes.len - 1] = 0xaa; const ptr = &([]FooArray24Bits)(bytes[0..bytes.len - 1])[0]; assert(ptr.a == 0); @@ -351,7 +360,7 @@ test "aligned array of packed struct" { assert(@sizeOf(FooArrayOfAligned) == 2 * 2); } - var bytes = []u8{0xbb} ** @sizeOf(FooArrayOfAligned); + var bytes = []u8 {0xbb} ** @sizeOf(FooArrayOfAligned); const ptr = &([]FooArrayOfAligned)(bytes[0..bytes.len])[0]; assert(ptr.a[0].a == 0xbb); @@ -360,11 +369,15 @@ test "aligned array of packed struct" { assert(ptr.a[1].b == 0xbb); } - - test "runtime struct initialization of bitfield" { - const s1 = Nibbles { .x = x1, .y = x1 }; - const s2 = Nibbles { .x = u4(x2), .y = u4(x2) }; + const s1 = Nibbles { + .x = x1, + .y = x1, + }; + const s2 = Nibbles { + .x = u4(x2), + .y = u4(x2), + }; assert(s1.x == x1); assert(s1.y == x1); @@ -394,7 +407,7 @@ test "native bit field understands endianness" { var all: u64 = 0x7765443322221111; var bytes: [8]u8 = undefined; @memcpy(&bytes[0], @ptrCast(&u8, &all), 8); - var bitfields = *@ptrCast(&Bitfields, &bytes[0]); + var bitfields = @ptrCast(&Bitfields, &bytes[0]).*; assert(bitfields.f1 == 0x1111); assert(bitfields.f2 == 0x2222); diff --git a/test/cases/struct_contains_null_ptr_itself.zig b/test/cases/struct_contains_null_ptr_itself.zig index 5864ef4038..b6cb1a94cc 100644 --- a/test/cases/struct_contains_null_ptr_itself.zig +++ b/test/cases/struct_contains_null_ptr_itself.zig @@ -19,4 +19,3 @@ pub const Node = struct { pub const NodeLineComment = struct { base: Node, }; - diff --git a/test/cases/struct_contains_slice_of_itself.zig b/test/cases/struct_contains_slice_of_itself.zig index 45ec56c1e2..ee34c16baf 100644 --- a/test/cases/struct_contains_slice_of_itself.zig +++ b/test/cases/struct_contains_slice_of_itself.zig @@ -6,7 +6,7 @@ const Node = struct { }; test "struct contains slice of itself" { - var other_nodes = []Node{ + var other_nodes = []Node { Node { .payload = 31, .children = []Node{}, diff --git a/test/cases/switch.zig b/test/cases/switch.zig index a0ac646160..b870297f18 100644 --- a/test/cases/switch.zig +++ b/test/cases/switch.zig @@ -6,7 +6,10 @@ test "switch with numbers" { fn testSwitchWithNumbers(x: u32) void { const result = switch (x) { - 1, 2, 3, 4 ... 8 => false, + 1, + 2, + 3, + 4 ... 8 => false, 13 => true, else => false, }; @@ -34,8 +37,10 @@ test "implicit comptime switch" { const result = switch (x) { 3 => 10, 4 => 11, - 5, 6 => 12, - 7, 8 => 13, + 5, + 6 => 12, + 7, + 8 => 13, else => 14, }; @@ -61,7 +66,6 @@ fn nonConstSwitchOnEnum(fruit: Fruit) void { } } - test "switch statement" { nonConstSwitch(SwitchStatmentFoo.C); } @@ -81,11 +85,16 @@ const SwitchStatmentFoo = enum { D, }; - test "switch prong with variable" { - switchProngWithVarFn(SwitchProngWithVarEnum { .One = 13}); - switchProngWithVarFn(SwitchProngWithVarEnum { .Two = 13.0}); - switchProngWithVarFn(SwitchProngWithVarEnum { .Meh = {}}); + switchProngWithVarFn(SwitchProngWithVarEnum { + .One = 13, + }); + switchProngWithVarFn(SwitchProngWithVarEnum { + .Two = 13.0, + }); + switchProngWithVarFn(SwitchProngWithVarEnum { + .Meh = {}, + }); } const SwitchProngWithVarEnum = union(enum) { One: i32, @@ -93,7 +102,7 @@ const SwitchProngWithVarEnum = union(enum) { Meh: void, }; fn switchProngWithVarFn(a: &const SwitchProngWithVarEnum) void { - switch(*a) { + switch (a.*) { SwitchProngWithVarEnum.One => |x| { assert(x == 13); }, @@ -112,9 +121,11 @@ test "switch on enum using pointer capture" { } fn testSwitchEnumPtrCapture() void { - var value = SwitchProngWithVarEnum { .One = 1234 }; + var value = SwitchProngWithVarEnum { + .One = 1234, + }; switch (value) { - SwitchProngWithVarEnum.One => |*x| *x += 1, + SwitchProngWithVarEnum.One => |*x| x.* += 1, else => unreachable, } switch (value) { @@ -125,8 +136,12 @@ fn testSwitchEnumPtrCapture() void { test "switch with multiple expressions" { const x = switch (returnsFive()) { - 1, 2, 3 => 1, - 4, 5, 6 => 2, + 1, + 2, + 3 => 1, + 4, + 5, + 6 => 2, else => i32(3), }; assert(x == 2); @@ -135,14 +150,15 @@ fn returnsFive() i32 { return 5; } - const Number = union(enum) { One: u64, Two: u8, Three: f32, }; -const number = Number { .Three = 1.23 }; +const number = Number { + .Three = 1.23, +}; fn returnsFalse() bool { switch (number) { @@ -198,7 +214,8 @@ fn testSwitchHandleAllCasesRange(x: u8) u8 { return switch (x) { 0 ... 100 => u8(0), 101 ... 200 => 1, - 201, 203 => 2, + 201, + 203 => 2, 202 => 4, 204 ... 255 => 3, }; diff --git a/test/cases/switch_prong_err_enum.zig b/test/cases/switch_prong_err_enum.zig index 136e8834e6..2d28d2f4c7 100644 --- a/test/cases/switch_prong_err_enum.zig +++ b/test/cases/switch_prong_err_enum.zig @@ -14,14 +14,18 @@ const FormValue = union(enum) { fn doThing(form_id: u64) error!FormValue { return switch (form_id) { - 17 => FormValue { .Address = try readOnce() }, + 17 => FormValue { + .Address = try readOnce(), + }, else => error.InvalidDebugInfo, }; } test "switch prong returns error enum" { switch (doThing(17) catch unreachable) { - FormValue.Address => |payload| { assert(payload == 1); }, + FormValue.Address => |payload| { + assert(payload == 1); + }, else => unreachable, } assert(read_count == 1); diff --git a/test/cases/switch_prong_implicit_cast.zig b/test/cases/switch_prong_implicit_cast.zig index 335feeef43..3d80f3fdb2 100644 --- a/test/cases/switch_prong_implicit_cast.zig +++ b/test/cases/switch_prong_implicit_cast.zig @@ -7,8 +7,12 @@ const FormValue = union(enum) { fn foo(id: u64) !FormValue { return switch (id) { - 2 => FormValue { .Two = true }, - 1 => FormValue { .One = {} }, + 2 => FormValue { + .Two = true, + }, + 1 => FormValue { + .One = {}, + }, else => return error.Whatever, }; } diff --git a/test/cases/try.zig b/test/cases/try.zig index 4a0425e22e..483bf6a915 100644 --- a/test/cases/try.zig +++ b/test/cases/try.zig @@ -3,14 +3,12 @@ const assert = @import("std").debug.assert; test "try on error union" { tryOnErrorUnionImpl(); comptime tryOnErrorUnionImpl(); - } fn tryOnErrorUnionImpl() void { - const x = if (returnsTen()) |val| - val + 1 - else |err| switch (err) { - error.ItBroke, error.NoMem => 1, + const x = if (returnsTen()) |val| val + 1 else |err| switch (err) { + error.ItBroke, + error.NoMem => 1, error.CrappedOut => i32(2), else => unreachable, }; diff --git a/test/cases/undefined.zig b/test/cases/undefined.zig index bc81f9cf84..f1af10e532 100644 --- a/test/cases/undefined.zig +++ b/test/cases/undefined.zig @@ -63,6 +63,6 @@ test "assign undefined to struct with method" { } test "type name of undefined" { - const x = undefined; - assert(mem.eql(u8, @typeName(@typeOf(x)), "(undefined)")); + const x = undefined; + assert(mem.eql(u8, @typeName(@typeOf(x)), "(undefined)")); } diff --git a/test/cases/union.zig b/test/cases/union.zig index dc2a7c3414..50cf8004b9 100644 --- a/test/cases/union.zig +++ b/test/cases/union.zig @@ -10,38 +10,41 @@ const Agg = struct { val2: Value, }; -const v1 = Value { .Int = 1234 }; -const v2 = Value { .Array = []u8{3} ** 9 }; +const v1 = Value{ .Int = 1234 }; +const v2 = Value{ .Array = []u8{3} ** 9 }; -const err = (error!Agg)(Agg { +const err = (error!Agg)(Agg{ .val1 = v1, .val2 = v2, }); -const array = []Value { v1, v2, v1, v2}; - +const array = []Value{ + v1, + v2, + v1, + v2, +}; test "unions embedded in aggregate types" { switch (array[1]) { Value.Array => |arr| assert(arr[4] == 3), else => unreachable, } - switch((err catch unreachable).val1) { + switch ((err catch unreachable).val1) { Value.Int => |x| assert(x == 1234), else => unreachable, } } - const Foo = union { float: f64, int: i32, }; test "basic unions" { - var foo = Foo { .int = 1 }; + var foo = Foo{ .int = 1 }; assert(foo.int == 1); - foo = Foo {.float = 12.34}; + foo = Foo{ .float = 12.34 }; assert(foo.float == 12.34); } @@ -56,11 +59,11 @@ test "init union with runtime value" { } fn setFloat(foo: &Foo, x: f64) void { - *foo = Foo { .float = x }; + foo.* = Foo{ .float = x }; } fn setInt(foo: &Foo, x: i32) void { - *foo = Foo { .int = x }; + foo.* = Foo{ .int = x }; } const FooExtern = extern union { @@ -69,13 +72,12 @@ const FooExtern = extern union { }; test "basic extern unions" { - var foo = FooExtern { .int = 1 }; + var foo = FooExtern{ .int = 1 }; assert(foo.int == 1); foo.float = 12.34; assert(foo.float == 12.34); } - const Letter = enum { A, B, @@ -93,12 +95,12 @@ test "union with specified enum tag" { } fn doTest() void { - assert(bar(Payload {.A = 1234}) == -10); + assert(bar(Payload{ .A = 1234 }) == -10); } fn bar(value: &const Payload) i32 { - assert(Letter(*value) == Letter.A); - return switch (*value) { + assert(Letter(value.*) == Letter.A); + return switch (value.*) { Payload.A => |x| return x - 1244, Payload.B => |x| if (x == 12.34) i32(20) else 21, Payload.C => |x| if (x) i32(30) else 31, @@ -131,13 +133,13 @@ const MultipleChoice2 = union(enum(u32)) { test "union(enum(u32)) with specified and unspecified tag values" { comptime assert(@TagType(@TagType(MultipleChoice2)) == u32); - testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2 {.C = 123}); - comptime testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2 { .C = 123} ); + testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 }); + comptime testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 }); } fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: &const MultipleChoice2) void { - assert(u32(@TagType(MultipleChoice2)(*x)) == 60); - assert(1123 == switch (*x) { + assert(u32(@TagType(MultipleChoice2)(x.*)) == 60); + assert(1123 == switch (x.*) { MultipleChoice2.A => 1, MultipleChoice2.B => 2, MultipleChoice2.C => |v| i32(1000) + v, @@ -150,10 +152,9 @@ fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: &const MultipleChoice2) void }); } - const ExternPtrOrInt = extern union { ptr: &u8, - int: u64 + int: u64, }; test "extern union size" { comptime assert(@sizeOf(ExternPtrOrInt) == 8); @@ -161,7 +162,7 @@ test "extern union size" { const PackedPtrOrInt = packed union { ptr: &u8, - int: u64 + int: u64, }; test "extern union size" { comptime assert(@sizeOf(PackedPtrOrInt) == 8); @@ -174,8 +175,16 @@ test "union with only 1 field which is void should be zero bits" { comptime assert(@sizeOf(ZeroBits) == 0); } -const TheTag = enum {A, B, C}; -const TheUnion = union(TheTag) { A: i32, B: i32, C: i32 }; +const TheTag = enum { + A, + B, + C, +}; +const TheUnion = union(TheTag) { + A: i32, + B: i32, + C: i32, +}; test "union field access gives the enum values" { assert(TheUnion.A == TheTag.A); assert(TheUnion.B == TheTag.B); @@ -183,20 +192,28 @@ test "union field access gives the enum values" { } test "cast union to tag type of union" { - testCastUnionToTagType(TheUnion {.B = 1234}); - comptime testCastUnionToTagType(TheUnion {.B = 1234}); + testCastUnionToTagType(TheUnion{ .B = 1234 }); + comptime testCastUnionToTagType(TheUnion{ .B = 1234 }); } fn testCastUnionToTagType(x: &const TheUnion) void { - assert(TheTag(*x) == TheTag.B); + assert(TheTag(x.*) == TheTag.B); } test "cast tag type of union to union" { var x: Value2 = Letter2.B; assert(Letter2(x) == Letter2.B); } -const Letter2 = enum { A, B, C }; -const Value2 = union(Letter2) { A: i32, B, C, }; +const Letter2 = enum { + A, + B, + C, +}; +const Value2 = union(Letter2) { + A: i32, + B, + C, +}; test "implicit cast union to its tag type" { var x: Value2 = Letter2.B; @@ -217,19 +234,16 @@ const TheUnion2 = union(enum) { }; fn assertIsTheUnion2Item1(value: &const TheUnion2) void { - assert(*value == TheUnion2.Item1); + assert(value.* == TheUnion2.Item1); } - pub const PackThis = union(enum) { Invalid: bool, StringLiteral: u2, }; test "constant packed union" { - testConstPackedUnion([]PackThis { - PackThis { .StringLiteral = 1 }, - }); + testConstPackedUnion([]PackThis{PackThis{ .StringLiteral = 1 }}); } fn testConstPackedUnion(expected_tokens: []const PackThis) void { @@ -242,7 +256,7 @@ test "switch on union with only 1 field" { switch (r) { PartialInst.Compiled => { var z: PartialInstWithPayload = undefined; - z = PartialInstWithPayload { .Compiled = 1234 }; + z = PartialInstWithPayload{ .Compiled = 1234 }; switch (z) { PartialInstWithPayload.Compiled => |x| { assert(x == 1234); @@ -261,4 +275,3 @@ const PartialInst = union(enum) { const PartialInstWithPayload = union(enum) { Compiled: i32, }; - diff --git a/test/cases/var_args.zig b/test/cases/var_args.zig index cead9eb8bf..81f800568c 100644 --- a/test/cases/var_args.zig +++ b/test/cases/var_args.zig @@ -2,9 +2,12 @@ const assert = @import("std").debug.assert; fn add(args: ...) i32 { var sum = i32(0); - {comptime var i: usize = 0; inline while (i < args.len) : (i += 1) { - sum += args[i]; - }} + { + comptime var i: usize = 0; + inline while (i < args.len) : (i += 1) { + sum += args[i]; + } + } return sum; } @@ -55,18 +58,23 @@ fn extraFn(extra: u32, args: ...) usize { return args.len; } +const foos = []fn(...) bool { + foo1, + foo2, +}; -const foos = []fn(...) bool { foo1, foo2 }; - -fn foo1(args: ...) bool { return true; } -fn foo2(args: ...) bool { return false; } +fn foo1(args: ...) bool { + return true; +} +fn foo2(args: ...) bool { + return false; +} test "array of var args functions" { assert(foos[0]()); assert(!foos[1]()); } - test "pass array and slice of same array to var args should have same pointers" { const array = "hi"; const slice: []const u8 = array; @@ -79,7 +87,6 @@ fn assertSlicePtrsEql(args: ...) void { assert(s1.ptr == s2.ptr); } - test "pass zero length array to var args param" { doNothingWithFirstArg(""); } diff --git a/test/cases/while.zig b/test/cases/while.zig index 33d5a5623a..574a7b7e76 100644 --- a/test/cases/while.zig +++ b/test/cases/while.zig @@ -1,7 +1,7 @@ const assert = @import("std").debug.assert; test "while loop" { - var i : i32 = 0; + var i: i32 = 0; while (i < 4) { i += 1; } @@ -35,7 +35,7 @@ test "continue and break" { } var continue_and_break_counter: i32 = 0; fn runContinueAndBreakTest() void { - var i : i32 = 0; + var i: i32 = 0; while (true) { continue_and_break_counter += 2; i += 1; @@ -58,10 +58,13 @@ fn returnWithImplicitCastFromWhileLoopTest() error!void { test "while with continue expression" { var sum: i32 = 0; - {var i: i32 = 0; while (i < 10) : (i += 1) { - if (i == 5) continue; - sum += i; - }} + { + var i: i32 = 0; + while (i < 10) : (i += 1) { + if (i == 5) continue; + sum += i; + } + } assert(sum == 40); } @@ -117,17 +120,13 @@ test "while with error union condition" { var numbers_left: i32 = undefined; fn getNumberOrErr() error!i32 { - return if (numbers_left == 0) - error.OutOfNumbers - else x: { + return if (numbers_left == 0) error.OutOfNumbers else x: { numbers_left -= 1; break :x numbers_left; }; } fn getNumberOrNull() ?i32 { - return if (numbers_left == 0) - null - else x: { + return if (numbers_left == 0) null else x: { numbers_left -= 1; break :x numbers_left; }; @@ -136,42 +135,48 @@ fn getNumberOrNull() ?i32 { test "while on nullable with else result follow else prong" { const result = while (returnNull()) |value| { break value; - } else i32(2); + } else + i32(2); assert(result == 2); } test "while on nullable with else result follow break prong" { const result = while (returnMaybe(10)) |value| { break value; - } else i32(2); + } else + i32(2); assert(result == 10); } test "while on error union with else result follow else prong" { const result = while (returnError()) |value| { break value; - } else |err| i32(2); + } else|err| + i32(2); assert(result == 2); } test "while on error union with else result follow break prong" { const result = while (returnSuccess(10)) |value| { break value; - } else |err| i32(2); + } else|err| + i32(2); assert(result == 10); } test "while on bool with else result follow else prong" { const result = while (returnFalse()) { break i32(10); - } else i32(2); + } else + i32(2); assert(result == 2); } test "while on bool with else result follow break prong" { const result = while (returnTrue()) { break i32(10); - } else i32(2); + } else + i32(2); assert(result == 10); } @@ -202,9 +207,21 @@ fn testContinueOuter() void { } } -fn returnNull() ?i32 { return null; } -fn returnMaybe(x: i32) ?i32 { return x; } -fn returnError() error!i32 { return error.YouWantedAnError; } -fn returnSuccess(x: i32) error!i32 { return x; } -fn returnFalse() bool { return false; } -fn returnTrue() bool { return true; } +fn returnNull() ?i32 { + return null; +} +fn returnMaybe(x: i32) ?i32 { + return x; +} +fn returnError() error!i32 { + return error.YouWantedAnError; +} +fn returnSuccess(x: i32) error!i32 { + return x; +} +fn returnFalse() bool { + return false; +} +fn returnTrue() bool { + return true; +} From ac4d55dec1e32ddef945bfa246eb78f20f31ec44 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 1 May 2018 01:53:04 -0400 Subject: [PATCH 03/75] behavior tests passing with new pointer deref syntax --- std/array_list.zig | 54 +- std/fmt/index.zig | 93 ++- std/heap.zig | 106 ++-- std/io.zig | 65 +- std/linked_list.zig | 95 +-- std/os/index.zig | 80 ++- std/os/linux/index.zig | 371 ++++++----- std/special/bootstrap.zig | 8 +- std/special/compiler_rt/fixuint.zig | 6 +- std/special/compiler_rt/fixunsdfdi.zig | 1 - std/special/compiler_rt/fixunsdfsi.zig | 1 - std/special/compiler_rt/fixunssfti.zig | 1 - std/special/compiler_rt/fixunstfti.zig | 1 - std/special/compiler_rt/index.zig | 818 ++++++++++++++++++++----- std/special/compiler_rt/udivmod.zig | 43 +- std/special/compiler_rt/udivmodti4.zig | 2 +- std/special/compiler_rt/umodti3.zig | 2 +- test/cases/cast.zig | 6 +- test/cases/generics.zig | 2 +- 19 files changed, 1128 insertions(+), 627 deletions(-) diff --git a/std/array_list.zig b/std/array_list.zig index 2a44b66518..8c8426e1e5 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -8,7 +8,7 @@ pub fn ArrayList(comptime T: type) type { return AlignedArrayList(T, @alignOf(T)); } -pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ +pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { return struct { const Self = this; @@ -21,7 +21,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ /// Deinitialize with `deinit` or use `toOwnedSlice`. pub fn init(allocator: &Allocator) Self { - return Self { + return Self{ .items = []align(A) T{}, .len = 0, .allocator = allocator, @@ -48,7 +48,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ /// allocated with `allocator`. /// Deinitialize with `deinit` or use `toOwnedSlice`. pub fn fromOwnedSlice(allocator: &Allocator, slice: []align(A) T) Self { - return Self { + return Self{ .items = slice, .len = slice.len, .allocator = allocator, @@ -59,7 +59,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ pub fn toOwnedSlice(self: &Self) []align(A) T { const allocator = self.allocator; const result = allocator.alignedShrink(T, A, self.items, self.len); - *self = init(allocator); + self.* = init(allocator); return result; } @@ -67,21 +67,21 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ try l.ensureCapacity(l.len + 1); l.len += 1; - mem.copy(T, l.items[n+1..l.len], l.items[n..l.len-1]); - l.items[n] = *item; + mem.copy(T, l.items[n + 1..l.len], l.items[n..l.len - 1]); + l.items[n] = item.*; } pub fn insertSlice(l: &Self, n: usize, items: []align(A) const T) !void { try l.ensureCapacity(l.len + items.len); l.len += items.len; - mem.copy(T, l.items[n+items.len..l.len], l.items[n..l.len-items.len]); - mem.copy(T, l.items[n..n+items.len], items); + mem.copy(T, l.items[n + items.len..l.len], l.items[n..l.len - items.len]); + mem.copy(T, l.items[n..n + items.len], items); } pub fn append(l: &Self, item: &const T) !void { const new_item_ptr = try l.addOne(); - *new_item_ptr = *item; + new_item_ptr.* = item.*; } pub fn appendSlice(l: &Self, items: []align(A) const T) !void { @@ -124,8 +124,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ } pub fn popOrNull(self: &Self) ?T { - if (self.len == 0) - return null; + if (self.len == 0) return null; return self.pop(); } }; @@ -135,25 +134,35 @@ test "basic ArrayList test" { var list = ArrayList(i32).init(debug.global_allocator); defer list.deinit(); - {var i: usize = 0; while (i < 10) : (i += 1) { - list.append(i32(i + 1)) catch unreachable; - }} + { + var i: usize = 0; + while (i < 10) : (i += 1) { + list.append(i32(i + 1)) catch unreachable; + } + } - {var i: usize = 0; while (i < 10) : (i += 1) { - assert(list.items[i] == i32(i + 1)); - }} + { + var i: usize = 0; + while (i < 10) : (i += 1) { + assert(list.items[i] == i32(i + 1)); + } + } assert(list.pop() == 10); assert(list.len == 9); - list.appendSlice([]const i32 { 1, 2, 3 }) catch unreachable; + list.appendSlice([]const i32{ + 1, + 2, + 3, + }) catch unreachable; assert(list.len == 12); assert(list.pop() == 3); assert(list.pop() == 2); assert(list.pop() == 1); assert(list.len == 9); - list.appendSlice([]const i32 {}) catch unreachable; + list.appendSlice([]const i32{}) catch unreachable; assert(list.len == 9); } @@ -166,12 +175,15 @@ test "insert ArrayList test" { assert(list.items[0] == 5); assert(list.items[1] == 1); - try list.insertSlice(1, []const i32 { 9, 8 }); + try list.insertSlice(1, []const i32{ + 9, + 8, + }); assert(list.items[0] == 5); assert(list.items[1] == 9); assert(list.items[2] == 8); - const items = []const i32 { 1 }; + const items = []const i32{1}; try list.insertSlice(0, items[0..0]); assert(list.items[0] == 5); } diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 43e758038f..804fd802f1 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -11,9 +11,7 @@ const max_int_digits = 65; /// Renders fmt string with args, calling output with slices of bytes. /// If `output` returns an error, the error is returned from `format` and /// `output` is not called again. -pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void, - comptime fmt: []const u8, args: ...) Errors!void -{ +pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void, comptime fmt: []const u8, args: ...) Errors!void { const State = enum { Start, OpenBrace, @@ -221,7 +219,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), } } -pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { +pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { const T = @typeOf(value); switch (@typeId(T)) { builtin.TypeId.Int => { @@ -256,7 +254,7 @@ pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@ }, builtin.TypeId.Pointer => { if (@typeId(T.Child) == builtin.TypeId.Array and T.Child.Child == u8) { - return output(context, (*value)[0..]); + return output(context, (value.*)[0..]); } else { return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value)); } @@ -270,13 +268,11 @@ pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@ } } -pub fn formatAsciiChar(c: u8, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { +pub fn formatAsciiChar(c: u8, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { return output(context, (&c)[0..1]); } -pub fn formatBuf(buf: []const u8, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +pub fn formatBuf(buf: []const u8, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { try output(context, buf); var leftover_padding = if (width > buf.len) (width - buf.len) else return; @@ -289,7 +285,7 @@ pub fn formatBuf(buf: []const u8, width: usize, // Print a float in scientific notation to the specified precision. Null uses full precision. // It should be the case that every full precision, printed value can be re-parsed back to the // same type unambiguously. -pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { +pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { var x = f64(value); // Errol doesn't handle these special cases. @@ -338,7 +334,7 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, var printed: usize = 0; if (float_decimal.digits.len > 1) { const num_digits = math.min(float_decimal.digits.len, precision + 1); - try output(context, float_decimal.digits[1 .. num_digits]); + try output(context, float_decimal.digits[1..num_digits]); printed += num_digits - 1; } @@ -350,12 +346,9 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, try output(context, float_decimal.digits[0..1]); try output(context, "."); if (float_decimal.digits.len > 1) { - const num_digits = if (@typeOf(value) == f32) - math.min(usize(9), float_decimal.digits.len) - else - float_decimal.digits.len; + const num_digits = if (@typeOf(value) == f32) math.min(usize(9), float_decimal.digits.len) else float_decimal.digits.len; - try output(context, float_decimal.digits[1 .. num_digits]); + try output(context, float_decimal.digits[1..num_digits]); } else { try output(context, "0"); } @@ -381,7 +374,7 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, // Print a float of the format x.yyyyy where the number of y is specified by the precision argument. // By default floats are printed at full precision (no rounding). -pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { +pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { var x = f64(value); // Errol doesn't handle these special cases. @@ -431,14 +424,14 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com if (num_digits_whole > 0) { // We may have to zero pad, for instance 1e4 requires zero padding. - try output(context, float_decimal.digits[0 .. num_digits_whole_no_pad]); + try output(context, float_decimal.digits[0..num_digits_whole_no_pad]); var i = num_digits_whole_no_pad; while (i < num_digits_whole) : (i += 1) { try output(context, "0"); } } else { - try output(context , "0"); + try output(context, "0"); } // {.0} special case doesn't want a trailing '.' @@ -470,10 +463,10 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com // Remaining fractional portion, zero-padding if insufficient. debug.assert(precision >= printed); if (num_digits_whole_no_pad + precision - printed < float_decimal.digits.len) { - try output(context, float_decimal.digits[num_digits_whole_no_pad .. num_digits_whole_no_pad + precision - printed]); + try output(context, float_decimal.digits[num_digits_whole_no_pad..num_digits_whole_no_pad + precision - printed]); return; } else { - try output(context, float_decimal.digits[num_digits_whole_no_pad ..]); + try output(context, float_decimal.digits[num_digits_whole_no_pad..]); printed += float_decimal.digits.len - num_digits_whole_no_pad; while (printed < precision) : (printed += 1) { @@ -489,14 +482,14 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com if (num_digits_whole > 0) { // We may have to zero pad, for instance 1e4 requires zero padding. - try output(context, float_decimal.digits[0 .. num_digits_whole_no_pad]); + try output(context, float_decimal.digits[0..num_digits_whole_no_pad]); var i = num_digits_whole_no_pad; while (i < num_digits_whole) : (i += 1) { try output(context, "0"); } } else { - try output(context , "0"); + try output(context, "0"); } // Omit `.` if no fractional portion @@ -516,14 +509,11 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com } } - try output(context, float_decimal.digits[num_digits_whole_no_pad ..]); + try output(context, float_decimal.digits[num_digits_whole_no_pad..]); } } - -pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { if (@typeOf(value).is_signed) { return formatIntSigned(value, base, uppercase, width, context, Errors, output); } else { @@ -531,9 +521,7 @@ pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, } } -fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { const uint = @IntType(false, @typeOf(value).bit_count); if (value < 0) { const minus_sign: u8 = '-'; @@ -552,9 +540,7 @@ fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, } } -fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { // max_int_digits accounts for the minus sign. when printing an unsigned // number we don't need to do that. var buf: [max_int_digits - 1]u8 = undefined; @@ -566,8 +552,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, index -= 1; buf[index] = digitToChar(u8(digit), uppercase); a /= base; - if (a == 0) - break; + if (a == 0) break; } const digits_buf = buf[index..]; @@ -579,8 +564,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, while (true) { try output(context, (&zero_byte)[0..1]); leftover_padding -= 1; - if (leftover_padding == 0) - break; + if (leftover_padding == 0) break; } mem.set(u8, buf[0..index], '0'); return output(context, buf); @@ -592,7 +576,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, } pub fn formatIntBuf(out_buf: []u8, value: var, base: u8, uppercase: bool, width: usize) usize { - var context = FormatIntBuf { + var context = FormatIntBuf{ .out_buf = out_buf, .index = 0, }; @@ -609,10 +593,8 @@ fn formatIntCallback(context: &FormatIntBuf, bytes: []const u8) (error{}!void) { } pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) !T { - if (!T.is_signed) - return parseUnsigned(T, buf, radix); - if (buf.len == 0) - return T(0); + if (!T.is_signed) return parseUnsigned(T, buf, radix); + if (buf.len == 0) return T(0); if (buf[0] == '-') { return math.negate(try parseUnsigned(T, buf[1..], radix)); } else if (buf[0] == '+') { @@ -632,9 +614,10 @@ test "fmt.parseInt" { assert(if (parseInt(u8, "256", 10)) |_| false else |err| err == error.Overflow); } -const ParseUnsignedError = error { +const ParseUnsignedError = error{ /// The result cannot fit in the type specified Overflow, + /// The input had a byte that was not a digit InvalidCharacter, }; @@ -659,8 +642,7 @@ pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) { else => return error.InvalidCharacter, }; - if (value >= radix) - return error.InvalidCharacter; + if (value >= radix) return error.InvalidCharacter; return value; } @@ -684,20 +666,21 @@ fn bufPrintWrite(context: &BufPrintContext, bytes: []const u8) !void { } pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) ![]u8 { - var context = BufPrintContext { .remaining = buf, }; + var context = BufPrintContext{ .remaining = buf }; try format(&context, error{BufferTooSmall}, bufPrintWrite, fmt, args); return buf[0..buf.len - context.remaining.len]; } pub fn allocPrint(allocator: &mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 { var size: usize = 0; - format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {}; + format(&size, error{}, countSize, fmt, args) catch |err| switch (err) { + }; const buf = try allocator.alloc(u8, size); return bufPrint(buf, fmt, args); } fn countSize(size: &usize, bytes: []const u8) (error{}!void) { - *size += bytes.len; + size.* += bytes.len; } test "buf print int" { @@ -773,9 +756,7 @@ test "fmt.format" { unused: u8, }; var buf1: [32]u8 = undefined; - const value = Struct { - .unused = 42, - }; + const value = Struct{ .unused = 42 }; const result = try bufPrint(buf1[0..], "pointer: {}\n", &value); assert(mem.startsWith(u8, result, "pointer: Struct@")); } @@ -988,7 +969,7 @@ test "fmt.format" { pub fn trim(buf: []const u8) []const u8 { var start: usize = 0; - while (start < buf.len and isWhiteSpace(buf[start])) : (start += 1) { } + while (start < buf.len and isWhiteSpace(buf[start])) : (start += 1) {} var end: usize = buf.len; while (true) { @@ -1000,7 +981,6 @@ pub fn trim(buf: []const u8) []const u8 { } } break; - } return buf[start..end]; } @@ -1015,7 +995,10 @@ test "fmt.trim" { pub fn isWhiteSpace(byte: u8) bool { return switch (byte) { - ' ', '\t', '\n', '\r' => true, + ' ', + '\t', + '\n', + '\r' => true, else => false, }; } diff --git a/std/heap.zig b/std/heap.zig index bfdf62f658..7b753524a6 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -10,7 +10,7 @@ const c = std.c; const Allocator = mem.Allocator; pub const c_allocator = &c_allocator_state; -var c_allocator_state = Allocator { +var c_allocator_state = Allocator{ .allocFn = cAlloc, .reallocFn = cRealloc, .freeFn = cFree, @@ -18,10 +18,7 @@ var c_allocator_state = Allocator { fn cAlloc(self: &Allocator, n: usize, alignment: u29) ![]u8 { assert(alignment <= @alignOf(c_longdouble)); - return if (c.malloc(n)) |buf| - @ptrCast(&u8, buf)[0..n] - else - error.OutOfMemory; + return if (c.malloc(n)) |buf| @ptrCast(&u8, buf)[0..n] else error.OutOfMemory; } fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { @@ -48,8 +45,8 @@ pub const DirectAllocator = struct { const HeapHandle = if (builtin.os == Os.windows) os.windows.HANDLE else void; pub fn init() DirectAllocator { - return DirectAllocator { - .allocator = Allocator { + return DirectAllocator{ + .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, @@ -71,39 +68,39 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, Os.macosx, Os.ios => { + Os.linux, + Os.macosx, + Os.ios => { const p = os.posix; - const alloc_size = if(alignment <= os.page_size) n else n + alignment; - const addr = p.mmap(null, alloc_size, p.PROT_READ|p.PROT_WRITE, - p.MAP_PRIVATE|p.MAP_ANONYMOUS, -1, 0); - if(addr == p.MAP_FAILED) return error.OutOfMemory; - - if(alloc_size == n) return @intToPtr(&u8, addr)[0..n]; - + const alloc_size = if (alignment <= os.page_size) n else n + alignment; + const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0); + if (addr == p.MAP_FAILED) return error.OutOfMemory; + + if (alloc_size == n) return @intToPtr(&u8, addr)[0..n]; + var aligned_addr = addr & ~usize(alignment - 1); aligned_addr += alignment; - + //We can unmap the unused portions of our mmap, but we must only // pass munmap bytes that exist outside our allocated pages or it // will happily eat us too - + //Since alignment > page_size, we are by definition on a page boundry const unused_start = addr; const unused_len = aligned_addr - 1 - unused_start; var err = p.munmap(unused_start, unused_len); debug.assert(p.getErrno(err) == 0); - + //It is impossible that there is an unoccupied page at the top of our // mmap. - + return @intToPtr(&u8, aligned_addr)[0..n]; }, Os.windows => { const amt = n + alignment + @sizeOf(usize); const heap_handle = self.heap_handle ?? blk: { - const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) - ?? return error.OutOfMemory; + const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) ?? return error.OutOfMemory; self.heap_handle = hh; break :blk hh; }; @@ -113,7 +110,7 @@ pub const DirectAllocator = struct { const march_forward_bytes = if (rem == 0) 0 else (alignment - rem); const adjusted_addr = root_addr + march_forward_bytes; const record_addr = adjusted_addr + n; - *@intToPtr(&align(1) usize, record_addr) = root_addr; + @intToPtr(&align(1) usize, record_addr).* = root_addr; return @intToPtr(&u8, adjusted_addr)[0..n]; }, else => @compileError("Unsupported OS"), @@ -124,7 +121,9 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, Os.macosx, Os.ios => { + Os.linux, + Os.macosx, + Os.ios => { if (new_size <= old_mem.len) { const base_addr = @ptrToInt(old_mem.ptr); const old_addr_end = base_addr + old_mem.len; @@ -144,13 +143,13 @@ pub const DirectAllocator = struct { Os.windows => { const old_adjusted_addr = @ptrToInt(old_mem.ptr); const old_record_addr = old_adjusted_addr + old_mem.len; - const root_addr = *@intToPtr(&align(1) usize, old_record_addr); + const root_addr = @intToPtr(&align(1) usize, old_record_addr).*; const old_ptr = @intToPtr(os.windows.LPVOID, root_addr); const amt = new_size + alignment + @sizeOf(usize); const new_ptr = os.windows.HeapReAlloc(??self.heap_handle, 0, old_ptr, amt) ?? blk: { if (new_size > old_mem.len) return error.OutOfMemory; const new_record_addr = old_record_addr - new_size + old_mem.len; - *@intToPtr(&align(1) usize, new_record_addr) = root_addr; + @intToPtr(&align(1) usize, new_record_addr).* = root_addr; return old_mem[0..new_size]; }; const offset = old_adjusted_addr - root_addr; @@ -158,7 +157,7 @@ pub const DirectAllocator = struct { const new_adjusted_addr = new_root_addr + offset; assert(new_adjusted_addr % alignment == 0); const new_record_addr = new_adjusted_addr + new_size; - *@intToPtr(&align(1) usize, new_record_addr) = new_root_addr; + @intToPtr(&align(1) usize, new_record_addr).* = new_root_addr; return @intToPtr(&u8, new_adjusted_addr)[0..new_size]; }, else => @compileError("Unsupported OS"), @@ -169,12 +168,14 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, Os.macosx, Os.ios => { + Os.linux, + Os.macosx, + Os.ios => { _ = os.posix.munmap(@ptrToInt(bytes.ptr), bytes.len); }, Os.windows => { const record_addr = @ptrToInt(bytes.ptr) + bytes.len; - const root_addr = *@intToPtr(&align(1) usize, record_addr); + const root_addr = @intToPtr(&align(1) usize, record_addr).*; const ptr = @intToPtr(os.windows.LPVOID, root_addr); _ = os.windows.HeapFree(??self.heap_handle, 0, ptr); }, @@ -195,8 +196,8 @@ pub const ArenaAllocator = struct { const BufNode = std.LinkedList([]u8).Node; pub fn init(child_allocator: &Allocator) ArenaAllocator { - return ArenaAllocator { - .allocator = Allocator { + return ArenaAllocator{ + .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, @@ -228,7 +229,7 @@ pub const ArenaAllocator = struct { const buf = try self.child_allocator.alignedAlloc(u8, @alignOf(BufNode), len); const buf_node_slice = ([]BufNode)(buf[0..@sizeOf(BufNode)]); const buf_node = &buf_node_slice[0]; - *buf_node = BufNode { + buf_node.* = BufNode{ .data = buf, .prev = null, .next = null, @@ -253,7 +254,7 @@ pub const ArenaAllocator = struct { cur_node = try self.createNode(cur_buf.len, n + alignment); continue; } - const result = cur_buf[adjusted_index .. new_end_index]; + const result = cur_buf[adjusted_index..new_end_index]; self.end_index = new_end_index; return result; } @@ -269,7 +270,7 @@ pub const ArenaAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void { } + fn free(allocator: &Allocator, bytes: []u8) void {} }; pub const FixedBufferAllocator = struct { @@ -278,8 +279,8 @@ pub const FixedBufferAllocator = struct { buffer: []u8, pub fn init(buffer: []u8) FixedBufferAllocator { - return FixedBufferAllocator { - .allocator = Allocator { + return FixedBufferAllocator{ + .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, @@ -299,7 +300,7 @@ pub const FixedBufferAllocator = struct { if (new_end_index > self.buffer.len) { return error.OutOfMemory; } - const result = self.buffer[adjusted_index .. new_end_index]; + const result = self.buffer[adjusted_index..new_end_index]; self.end_index = new_end_index; return result; @@ -315,7 +316,7 @@ pub const FixedBufferAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void { } + fn free(allocator: &Allocator, bytes: []u8) void {} }; /// lock free @@ -325,8 +326,8 @@ pub const ThreadSafeFixedBufferAllocator = struct { buffer: []u8, pub fn init(buffer: []u8) ThreadSafeFixedBufferAllocator { - return ThreadSafeFixedBufferAllocator { - .allocator = Allocator { + return ThreadSafeFixedBufferAllocator{ + .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, @@ -348,8 +349,7 @@ pub const ThreadSafeFixedBufferAllocator = struct { if (new_end_index > self.buffer.len) { return error.OutOfMemory; } - end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, - builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) ?? return self.buffer[adjusted_index .. new_end_index]; + end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) ?? return self.buffer[adjusted_index..new_end_index]; } } @@ -363,11 +363,9 @@ pub const ThreadSafeFixedBufferAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void { } + fn free(allocator: &Allocator, bytes: []u8) void {} }; - - test "c_allocator" { if (builtin.link_libc) { var slice = c_allocator.alloc(u8, 50) catch return; @@ -415,8 +413,8 @@ fn testAllocator(allocator: &mem.Allocator) !void { var slice = try allocator.alloc(&i32, 100); for (slice) |*item, i| { - *item = try allocator.create(i32); - **item = i32(i); + item.* = try allocator.create(i32); + item.*.* = i32(i); } for (slice) |item, i| { @@ -434,26 +432,26 @@ fn testAllocator(allocator: &mem.Allocator) !void { fn testAllocatorLargeAlignment(allocator: &mem.Allocator) mem.Allocator.Error!void { //Maybe a platform's page_size is actually the same as or // very near usize? - if(os.page_size << 2 > @maxValue(usize)) return; - + if (os.page_size << 2 > @maxValue(usize)) return; + const USizeShift = @IntType(false, std.math.log2(usize.bit_count)); const large_align = u29(os.page_size << 2); - + var align_mask: usize = undefined; _ = @shlWithOverflow(usize, ~usize(0), USizeShift(@ctz(large_align)), &align_mask); - + var slice = try allocator.allocFn(allocator, 500, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); - + slice = try allocator.reallocFn(allocator, slice, 100, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); - + slice = try allocator.reallocFn(allocator, slice, 5000, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); - + slice = try allocator.reallocFn(allocator, slice, 10, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); - + slice = try allocator.reallocFn(allocator, slice, 20000, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); diff --git a/std/io.zig b/std/io.zig index 7b72af15e4..7c997fdf42 100644 --- a/std/io.zig +++ b/std/io.zig @@ -18,32 +18,17 @@ const is_windows = builtin.os == builtin.Os.windows; const GetStdIoErrs = os.WindowsGetStdHandleErrs; pub fn getStdErr() GetStdIoErrs!File { - const handle = if (is_windows) - try os.windowsGetStdHandle(os.windows.STD_ERROR_HANDLE) - else if (is_posix) - os.posix.STDERR_FILENO - else - unreachable; + const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_ERROR_HANDLE) else if (is_posix) os.posix.STDERR_FILENO else unreachable; return File.openHandle(handle); } pub fn getStdOut() GetStdIoErrs!File { - const handle = if (is_windows) - try os.windowsGetStdHandle(os.windows.STD_OUTPUT_HANDLE) - else if (is_posix) - os.posix.STDOUT_FILENO - else - unreachable; + const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_OUTPUT_HANDLE) else if (is_posix) os.posix.STDOUT_FILENO else unreachable; return File.openHandle(handle); } pub fn getStdIn() GetStdIoErrs!File { - const handle = if (is_windows) - try os.windowsGetStdHandle(os.windows.STD_INPUT_HANDLE) - else if (is_posix) - os.posix.STDIN_FILENO - else - unreachable; + const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_INPUT_HANDLE) else if (is_posix) os.posix.STDIN_FILENO else unreachable; return File.openHandle(handle); } @@ -56,11 +41,9 @@ pub const FileInStream = struct { pub const Stream = InStream(Error); pub fn init(file: &File) FileInStream { - return FileInStream { + return FileInStream{ .file = file, - .stream = Stream { - .readFn = readFn, - }, + .stream = Stream{ .readFn = readFn }, }; } @@ -79,11 +62,9 @@ pub const FileOutStream = struct { pub const Stream = OutStream(Error); pub fn init(file: &File) FileOutStream { - return FileOutStream { + return FileOutStream{ .file = file, - .stream = Stream { - .writeFn = writeFn, - }, + .stream = Stream{ .writeFn = writeFn }, }; } @@ -121,8 +102,7 @@ pub fn InStream(comptime ReadError: type) type { } const new_buf_size = math.min(max_size, actual_buf_len + os.page_size); - if (new_buf_size == actual_buf_len) - return error.StreamTooLong; + if (new_buf_size == actual_buf_len) return error.StreamTooLong; try buffer.resize(new_buf_size); } } @@ -165,9 +145,7 @@ pub fn InStream(comptime ReadError: type) type { /// memory would be greater than `max_size`, returns `error.StreamTooLong`. /// Caller owns returned memory. /// If this function returns an error, the contents from the stream read so far are lost. - pub fn readUntilDelimiterAlloc(self: &Self, allocator: &mem.Allocator, - delimiter: u8, max_size: usize) ![]u8 - { + pub fn readUntilDelimiterAlloc(self: &Self, allocator: &mem.Allocator, delimiter: u8, max_size: usize) ![]u8 { var buf = Buffer.initNull(allocator); defer buf.deinit(); @@ -283,7 +261,7 @@ pub fn BufferedInStream(comptime Error: type) type { pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) type { return struct { const Self = this; - const Stream = InStream(Error); + const Stream = InStream(Error); pub stream: Stream, @@ -294,7 +272,7 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) end_index: usize, pub fn init(unbuffered_in_stream: &Stream) Self { - return Self { + return Self{ .unbuffered_in_stream = unbuffered_in_stream, .buffer = undefined, @@ -305,9 +283,7 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) .start_index = buffer_size, .end_index = buffer_size, - .stream = Stream { - .readFn = readFn, - }, + .stream = Stream{ .readFn = readFn }, }; } @@ -368,13 +344,11 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr index: usize, pub fn init(unbuffered_out_stream: &Stream) Self { - return Self { + return Self{ .unbuffered_out_stream = unbuffered_out_stream, .buffer = undefined, .index = 0, - .stream = Stream { - .writeFn = writeFn, - }, + .stream = Stream{ .writeFn = writeFn }, }; } @@ -416,11 +390,9 @@ pub const BufferOutStream = struct { pub const Stream = OutStream(Error); pub fn init(buffer: &Buffer) BufferOutStream { - return BufferOutStream { + return BufferOutStream{ .buffer = buffer, - .stream = Stream { - .writeFn = writeFn, - }, + .stream = Stream{ .writeFn = writeFn }, }; } @@ -430,7 +402,6 @@ pub const BufferOutStream = struct { } }; - pub const BufferedAtomicFile = struct { atomic_file: os.AtomicFile, file_stream: FileOutStream, @@ -441,7 +412,7 @@ pub const BufferedAtomicFile = struct { var self = try allocator.create(BufferedAtomicFile); errdefer allocator.destroy(self); - *self = BufferedAtomicFile { + self.* = BufferedAtomicFile{ .atomic_file = undefined, .file_stream = undefined, .buffered_stream = undefined, @@ -489,7 +460,7 @@ pub fn readLine(buf: []u8) !usize { '\r' => { // trash the following \n _ = stream.readByte() catch return error.EndOfFile; - return index; + return index; }, '\n' => return index, else => { diff --git a/std/linked_list.zig b/std/linked_list.zig index 45595f3efb..c6be08171e 100644 --- a/std/linked_list.zig +++ b/std/linked_list.zig @@ -26,10 +26,10 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na data: T, pub fn init(value: &const T) Node { - return Node { + return Node{ .prev = null, .next = null, - .data = *value, + .data = value.*, }; } @@ -45,18 +45,18 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na }; first: ?&Node, - last: ?&Node, - len: usize, + last: ?&Node, + len: usize, /// Initialize a linked list. /// /// Returns: /// An empty linked list. pub fn init() Self { - return Self { + return Self{ .first = null, - .last = null, - .len = 0, + .last = null, + .len = 0, }; } @@ -131,7 +131,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na } else { // Empty list. list.first = new_node; - list.last = new_node; + list.last = new_node; new_node.prev = null; new_node.next = null; @@ -217,7 +217,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na pub fn createNode(list: &Self, data: &const T, allocator: &Allocator) !&Node { comptime assert(!isIntrusive()); var node = try list.allocateNode(allocator); - *node = Node.init(data); + node.* = Node.init(data); return node; } }; @@ -227,11 +227,11 @@ test "basic linked list test" { const allocator = debug.global_allocator; var list = LinkedList(u32).init(); - var one = try list.createNode(1, allocator); - var two = try list.createNode(2, allocator); + var one = try list.createNode(1, allocator); + var two = try list.createNode(2, allocator); var three = try list.createNode(3, allocator); - var four = try list.createNode(4, allocator); - var five = try list.createNode(5, allocator); + var four = try list.createNode(4, allocator); + var five = try list.createNode(5, allocator); defer { list.destroyNode(one, allocator); list.destroyNode(two, allocator); @@ -240,11 +240,11 @@ test "basic linked list test" { list.destroyNode(five, allocator); } - list.append(two); // {2} - list.append(five); // {2, 5} - list.prepend(one); // {1, 2, 5} - list.insertBefore(five, four); // {1, 2, 4, 5} - list.insertAfter(two, three); // {1, 2, 3, 4, 5} + list.append(two); // {2} + list.append(five); // {2, 5} + list.prepend(one); // {1, 2, 5} + list.insertBefore(five, four); // {1, 2, 4, 5} + list.insertAfter(two, three); // {1, 2, 3, 4, 5} // Traverse forwards. { @@ -266,13 +266,13 @@ test "basic linked list test" { } } - var first = list.popFirst(); // {2, 3, 4, 5} - var last = list.pop(); // {2, 3, 4} - list.remove(three); // {2, 4} + var first = list.popFirst(); // {2, 3, 4, 5} + var last = list.pop(); // {2, 3, 4} + list.remove(three); // {2, 4} - assert ((??list.first).data == 2); - assert ((??list.last ).data == 4); - assert (list.len == 2); + assert((??list.first).data == 2); + assert((??list.last).data == 4); + assert(list.len == 2); } const ElementList = IntrusiveLinkedList(Element, "link"); @@ -285,17 +285,32 @@ test "basic intrusive linked list test" { const allocator = debug.global_allocator; var list = ElementList.init(); - var one = Element { .value = 1, .link = ElementList.Node.initIntrusive() }; - var two = Element { .value = 2, .link = ElementList.Node.initIntrusive() }; - var three = Element { .value = 3, .link = ElementList.Node.initIntrusive() }; - var four = Element { .value = 4, .link = ElementList.Node.initIntrusive() }; - var five = Element { .value = 5, .link = ElementList.Node.initIntrusive() }; + var one = Element{ + .value = 1, + .link = ElementList.Node.initIntrusive(), + }; + var two = Element{ + .value = 2, + .link = ElementList.Node.initIntrusive(), + }; + var three = Element{ + .value = 3, + .link = ElementList.Node.initIntrusive(), + }; + var four = Element{ + .value = 4, + .link = ElementList.Node.initIntrusive(), + }; + var five = Element{ + .value = 5, + .link = ElementList.Node.initIntrusive(), + }; - list.append(&two.link); // {2} - list.append(&five.link); // {2, 5} - list.prepend(&one.link); // {1, 2, 5} - list.insertBefore(&five.link, &four.link); // {1, 2, 4, 5} - list.insertAfter(&two.link, &three.link); // {1, 2, 3, 4, 5} + list.append(&two.link); // {2} + list.append(&five.link); // {2, 5} + list.prepend(&one.link); // {1, 2, 5} + list.insertBefore(&five.link, &four.link); // {1, 2, 4, 5} + list.insertAfter(&two.link, &three.link); // {1, 2, 3, 4, 5} // Traverse forwards. { @@ -317,11 +332,11 @@ test "basic intrusive linked list test" { } } - var first = list.popFirst(); // {2, 3, 4, 5} - var last = list.pop(); // {2, 3, 4} - list.remove(&three.link); // {2, 4} + var first = list.popFirst(); // {2, 3, 4, 5} + var last = list.pop(); // {2, 3, 4} + list.remove(&three.link); // {2, 4} - assert ((??list.first).toData().value == 2); - assert ((??list.last ).toData().value == 4); - assert (list.len == 2); + assert((??list.first).toData().value == 2); + assert((??list.last).toData().value == 4); + assert(list.len == 2); } diff --git a/std/os/index.zig b/std/os/index.zig index 4f1826021f..8728f4a6f6 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -137,7 +137,7 @@ pub fn getRandomBytes(buf: []u8) !void { } }, Os.zen => { - const randomness = []u8 { + const randomness = []u8{ 42, 1, 7, @@ -265,7 +265,7 @@ pub fn posixRead(fd: i32, buf: []u8) !void { } } -pub const PosixWriteError = error { +pub const PosixWriteError = error{ WouldBlock, FileClosed, DestinationAddressRequired, @@ -310,7 +310,7 @@ pub fn posixWrite(fd: i32, bytes: []const u8) !void { } } -pub const PosixOpenError = error { +pub const PosixOpenError = error{ OutOfMemory, AccessDenied, FileTooBig, @@ -477,7 +477,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator: return posixExecveErrnoToErr(err); } -pub const PosixExecveError = error { +pub const PosixExecveError = error{ SystemResources, AccessDenied, InvalidExe, @@ -512,7 +512,7 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError { }; } -pub var linux_aux_raw = []usize {0} ** 38; +pub var linux_aux_raw = []usize{0} ** 38; pub var posix_environ_raw: []&u8 = undefined; /// Caller must free result when done. @@ -667,7 +667,7 @@ pub fn symLink(allocator: &Allocator, existing_path: []const u8, new_path: []con } } -pub const WindowsSymLinkError = error { +pub const WindowsSymLinkError = error{ OutOfMemory, Unexpected, }; @@ -686,7 +686,7 @@ pub fn symLinkWindows(allocator: &Allocator, existing_path: []const u8, new_path } } -pub const PosixSymLinkError = error { +pub const PosixSymLinkError = error{ OutOfMemory, AccessDenied, DiskQuota, @@ -895,7 +895,7 @@ pub const AtomicFile = struct { else => return err, }; - return AtomicFile { + return AtomicFile{ .allocator = allocator, .file = file, .tmp_path = tmp_path, @@ -1087,7 +1087,7 @@ pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) !void { /// removes it. If it cannot be removed because it is a non-empty directory, /// this function recursively removes its entries and then tries again. /// TODO non-recursive implementation -const DeleteTreeError = error { +const DeleteTreeError = error{ OutOfMemory, AccessDenied, FileTooBig, @@ -1217,7 +1217,7 @@ pub const Dir = struct { Os.ios => 0, else => {}, }; - return Dir { + return Dir{ .allocator = allocator, .fd = fd, .darwin_seek = darwin_seek_init, @@ -1294,7 +1294,7 @@ pub const Dir = struct { posix.DT_WHT => Entry.Kind.Whiteout, else => Entry.Kind.Unknown, }; - return Entry { + return Entry{ .name = name, .kind = entry_kind, }; @@ -1355,7 +1355,7 @@ pub const Dir = struct { posix.DT_SOCK => Entry.Kind.UnixDomainSocket, else => Entry.Kind.Unknown, }; - return Entry { + return Entry{ .name = name, .kind = entry_kind, }; @@ -1465,7 +1465,7 @@ pub fn posix_setregid(rgid: u32, egid: u32) !void { }; } -pub const WindowsGetStdHandleErrs = error { +pub const WindowsGetStdHandleErrs = error{ NoStdHandles, Unexpected, }; @@ -1489,7 +1489,7 @@ pub const ArgIteratorPosix = struct { count: usize, pub fn init() ArgIteratorPosix { - return ArgIteratorPosix { + return ArgIteratorPosix{ .index = 0, .count = raw.len, }; @@ -1522,16 +1522,14 @@ pub const ArgIteratorWindows = struct { quote_count: usize, seen_quote_count: usize, - pub const NextError = error { - OutOfMemory, - }; + pub const NextError = error{OutOfMemory}; pub fn init() ArgIteratorWindows { return initWithCmdLine(windows.GetCommandLineA()); } pub fn initWithCmdLine(cmd_line: &const u8) ArgIteratorWindows { - return ArgIteratorWindows { + return ArgIteratorWindows{ .index = 0, .cmd_line = cmd_line, .in_quote = false, @@ -1676,9 +1674,7 @@ pub const ArgIterator = struct { inner: InnerType, pub fn init() ArgIterator { - return ArgIterator { - .inner = InnerType.init(), - }; + return ArgIterator{ .inner = InnerType.init() }; } pub const NextError = ArgIteratorWindows.NextError; @@ -1757,33 +1753,33 @@ pub fn argsFree(allocator: &mem.Allocator, args_alloc: []const []u8) void { } test "windows arg parsing" { - testWindowsCmdLine(c"a b\tc d", [][]const u8 { + testWindowsCmdLine(c"a b\tc d", [][]const u8{ "a", "b", "c", "d", }); - testWindowsCmdLine(c"\"abc\" d e", [][]const u8 { + testWindowsCmdLine(c"\"abc\" d e", [][]const u8{ "abc", "d", "e", }); - testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8 { + testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8{ "a\\\\\\b", "de fg", "h", }); - testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8 { + testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8{ "a\\\"b", "c", "d", }); - testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8 { + testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8{ "a\\\\b c", "d", "e", }); - testWindowsCmdLine(c"a b\tc \"d f", [][]const u8 { + testWindowsCmdLine(c"a b\tc \"d f", [][]const u8{ "a", "b", "c", @@ -1791,7 +1787,7 @@ test "windows arg parsing" { "f", }); - testWindowsCmdLine(c"\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", [][]const u8 { + testWindowsCmdLine(c"\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", [][]const u8{ ".\\..\\zig-cache\\build", "bin\\zig.exe", ".\\..", @@ -1811,7 +1807,7 @@ fn testWindowsCmdLine(input_cmd_line: &const u8, expected_args: []const []const // TODO make this a build variable that you can set const unexpected_error_tracing = false; -const UnexpectedError = error { +const UnexpectedError = error{ /// The Operating System returned an undocumented error code. Unexpected, }; @@ -1950,7 +1946,7 @@ pub fn isTty(handle: FileHandle) bool { } } -pub const PosixSocketError = error { +pub const PosixSocketError = error{ /// Permission to create a socket of the specified type and/or /// pro‐tocol is denied. PermissionDenied, @@ -1992,7 +1988,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 { } } -pub const PosixBindError = error { +pub const PosixBindError = error{ /// The address is protected, and the user is not the superuser. /// For UNIX domain sockets: Search permission is denied on a component /// of the path prefix. @@ -2065,7 +2061,7 @@ pub fn posixBind(fd: i32, addr: &const posix.sockaddr) PosixBindError!void { } } -const PosixListenError = error { +const PosixListenError = error{ /// Another socket is already listening on the same port. /// For Internet domain sockets, the socket referred to by sockfd had not previously /// been bound to an address and, upon attempting to bind it to an ephemeral port, it @@ -2098,7 +2094,7 @@ pub fn posixListen(sockfd: i32, backlog: u32) PosixListenError!void { } } -pub const PosixAcceptError = error { +pub const PosixAcceptError = error{ /// The socket is marked nonblocking and no connections are present to be accepted. WouldBlock, @@ -2165,7 +2161,7 @@ pub fn posixAccept(fd: i32, addr: &posix.sockaddr, flags: u32) PosixAcceptError! } } -pub const LinuxEpollCreateError = error { +pub const LinuxEpollCreateError = error{ /// Invalid value specified in flags. InvalidSyscall, @@ -2198,7 +2194,7 @@ pub fn linuxEpollCreate(flags: u32) LinuxEpollCreateError!i32 { } } -pub const LinuxEpollCtlError = error { +pub const LinuxEpollCtlError = error{ /// epfd or fd is not a valid file descriptor. InvalidFileDescriptor, @@ -2271,7 +2267,7 @@ pub fn linuxEpollWait(epfd: i32, events: []linux.epoll_event, timeout: i32) usiz } } -pub const PosixGetSockNameError = error { +pub const PosixGetSockNameError = error{ /// Insufficient resources were available in the system to perform the operation. SystemResources, @@ -2295,7 +2291,7 @@ pub fn posixGetSockName(sockfd: i32) PosixGetSockNameError!posix.sockaddr { } } -pub const PosixConnectError = error { +pub const PosixConnectError = error{ /// For UNIX domain sockets, which are identified by pathname: Write permission is denied on the socket /// file, or search permission is denied for one of the directories in the path prefix. /// or @@ -2484,7 +2480,7 @@ pub const Thread = struct { } }; -pub const SpawnThreadError = error { +pub const SpawnThreadError = error{ /// A system-imposed limit on the number of threads was encountered. /// There are a number of limits that may trigger this error: /// * the RLIMIT_NPROC soft resource limit (set via setrlimit(2)), @@ -2532,7 +2528,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread if (@sizeOf(Context) == 0) { return startFn({}); } else { - return startFn(*@ptrCast(&Context, @alignCast(@alignOf(Context), arg))); + return startFn(@ptrCast(&Context, @alignCast(@alignOf(Context), arg)).*); } } }; @@ -2562,7 +2558,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread if (@sizeOf(Context) == 0) { return startFn({}); } else { - return startFn(*@intToPtr(&const Context, ctx_addr)); + return startFn(@intToPtr(&const Context, ctx_addr).*); } } extern fn posixThreadMain(ctx: ?&c_void) ?&c_void { @@ -2570,7 +2566,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread _ = startFn({}); return null; } else { - _ = startFn(*@ptrCast(&const Context, @alignCast(@alignOf(Context), ctx))); + _ = startFn(@ptrCast(&const Context, @alignCast(@alignOf(Context), ctx)).*); return null; } } @@ -2590,7 +2586,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread stack_end -= stack_end % @alignOf(Context); assert(stack_end >= stack_addr); const context_ptr = @alignCast(@alignOf(Context), @intToPtr(&Context, stack_end)); - *context_ptr = context; + context_ptr.* = context; arg = stack_end; } diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 368f074b9b..4e0e9ee5d5 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -30,96 +30,95 @@ pub const FUTEX_PRIVATE_FLAG = 128; pub const FUTEX_CLOCK_REALTIME = 256; - -pub const PROT_NONE = 0; -pub const PROT_READ = 1; -pub const PROT_WRITE = 2; -pub const PROT_EXEC = 4; +pub const PROT_NONE = 0; +pub const PROT_READ = 1; +pub const PROT_WRITE = 2; +pub const PROT_EXEC = 4; pub const PROT_GROWSDOWN = 0x01000000; -pub const PROT_GROWSUP = 0x02000000; +pub const PROT_GROWSUP = 0x02000000; -pub const MAP_FAILED = @maxValue(usize); -pub const MAP_SHARED = 0x01; -pub const MAP_PRIVATE = 0x02; -pub const MAP_TYPE = 0x0f; -pub const MAP_FIXED = 0x10; -pub const MAP_ANONYMOUS = 0x20; -pub const MAP_NORESERVE = 0x4000; -pub const MAP_GROWSDOWN = 0x0100; -pub const MAP_DENYWRITE = 0x0800; +pub const MAP_FAILED = @maxValue(usize); +pub const MAP_SHARED = 0x01; +pub const MAP_PRIVATE = 0x02; +pub const MAP_TYPE = 0x0f; +pub const MAP_FIXED = 0x10; +pub const MAP_ANONYMOUS = 0x20; +pub const MAP_NORESERVE = 0x4000; +pub const MAP_GROWSDOWN = 0x0100; +pub const MAP_DENYWRITE = 0x0800; pub const MAP_EXECUTABLE = 0x1000; -pub const MAP_LOCKED = 0x2000; -pub const MAP_POPULATE = 0x8000; -pub const MAP_NONBLOCK = 0x10000; -pub const MAP_STACK = 0x20000; -pub const MAP_HUGETLB = 0x40000; -pub const MAP_FILE = 0; +pub const MAP_LOCKED = 0x2000; +pub const MAP_POPULATE = 0x8000; +pub const MAP_NONBLOCK = 0x10000; +pub const MAP_STACK = 0x20000; +pub const MAP_HUGETLB = 0x40000; +pub const MAP_FILE = 0; pub const F_OK = 0; pub const X_OK = 1; pub const W_OK = 2; pub const R_OK = 4; -pub const WNOHANG = 1; -pub const WUNTRACED = 2; -pub const WSTOPPED = 2; -pub const WEXITED = 4; +pub const WNOHANG = 1; +pub const WUNTRACED = 2; +pub const WSTOPPED = 2; +pub const WEXITED = 4; pub const WCONTINUED = 8; -pub const WNOWAIT = 0x1000000; +pub const WNOWAIT = 0x1000000; -pub const SA_NOCLDSTOP = 1; -pub const SA_NOCLDWAIT = 2; -pub const SA_SIGINFO = 4; -pub const SA_ONSTACK = 0x08000000; -pub const SA_RESTART = 0x10000000; -pub const SA_NODEFER = 0x40000000; -pub const SA_RESETHAND = 0x80000000; -pub const SA_RESTORER = 0x04000000; +pub const SA_NOCLDSTOP = 1; +pub const SA_NOCLDWAIT = 2; +pub const SA_SIGINFO = 4; +pub const SA_ONSTACK = 0x08000000; +pub const SA_RESTART = 0x10000000; +pub const SA_NODEFER = 0x40000000; +pub const SA_RESETHAND = 0x80000000; +pub const SA_RESTORER = 0x04000000; -pub const SIGHUP = 1; -pub const SIGINT = 2; -pub const SIGQUIT = 3; -pub const SIGILL = 4; -pub const SIGTRAP = 5; -pub const SIGABRT = 6; -pub const SIGIOT = SIGABRT; -pub const SIGBUS = 7; -pub const SIGFPE = 8; -pub const SIGKILL = 9; -pub const SIGUSR1 = 10; -pub const SIGSEGV = 11; -pub const SIGUSR2 = 12; -pub const SIGPIPE = 13; -pub const SIGALRM = 14; -pub const SIGTERM = 15; +pub const SIGHUP = 1; +pub const SIGINT = 2; +pub const SIGQUIT = 3; +pub const SIGILL = 4; +pub const SIGTRAP = 5; +pub const SIGABRT = 6; +pub const SIGIOT = SIGABRT; +pub const SIGBUS = 7; +pub const SIGFPE = 8; +pub const SIGKILL = 9; +pub const SIGUSR1 = 10; +pub const SIGSEGV = 11; +pub const SIGUSR2 = 12; +pub const SIGPIPE = 13; +pub const SIGALRM = 14; +pub const SIGTERM = 15; pub const SIGSTKFLT = 16; -pub const SIGCHLD = 17; -pub const SIGCONT = 18; -pub const SIGSTOP = 19; -pub const SIGTSTP = 20; -pub const SIGTTIN = 21; -pub const SIGTTOU = 22; -pub const SIGURG = 23; -pub const SIGXCPU = 24; -pub const SIGXFSZ = 25; +pub const SIGCHLD = 17; +pub const SIGCONT = 18; +pub const SIGSTOP = 19; +pub const SIGTSTP = 20; +pub const SIGTTIN = 21; +pub const SIGTTOU = 22; +pub const SIGURG = 23; +pub const SIGXCPU = 24; +pub const SIGXFSZ = 25; pub const SIGVTALRM = 26; -pub const SIGPROF = 27; -pub const SIGWINCH = 28; -pub const SIGIO = 29; -pub const SIGPOLL = 29; -pub const SIGPWR = 30; -pub const SIGSYS = 31; +pub const SIGPROF = 27; +pub const SIGWINCH = 28; +pub const SIGIO = 29; +pub const SIGPOLL = 29; +pub const SIGPWR = 30; +pub const SIGSYS = 31; pub const SIGUNUSED = SIGSYS; pub const O_RDONLY = 0o0; pub const O_WRONLY = 0o1; -pub const O_RDWR = 0o2; +pub const O_RDWR = 0o2; pub const SEEK_SET = 0; pub const SEEK_CUR = 1; pub const SEEK_END = 2; -pub const SIG_BLOCK = 0; +pub const SIG_BLOCK = 0; pub const SIG_UNBLOCK = 1; pub const SIG_SETMASK = 2; @@ -408,7 +407,6 @@ pub const DT_LNK = 10; pub const DT_SOCK = 12; pub const DT_WHT = 14; - pub const TCGETS = 0x5401; pub const TCSETS = 0x5402; pub const TCSETSW = 0x5403; @@ -539,23 +537,23 @@ pub const MS_BIND = 4096; pub const MS_MOVE = 8192; pub const MS_REC = 16384; pub const MS_SILENT = 32768; -pub const MS_POSIXACL = (1<<16); -pub const MS_UNBINDABLE = (1<<17); -pub const MS_PRIVATE = (1<<18); -pub const MS_SLAVE = (1<<19); -pub const MS_SHARED = (1<<20); -pub const MS_RELATIME = (1<<21); -pub const MS_KERNMOUNT = (1<<22); -pub const MS_I_VERSION = (1<<23); -pub const MS_STRICTATIME = (1<<24); -pub const MS_LAZYTIME = (1<<25); -pub const MS_NOREMOTELOCK = (1<<27); -pub const MS_NOSEC = (1<<28); -pub const MS_BORN = (1<<29); -pub const MS_ACTIVE = (1<<30); -pub const MS_NOUSER = (1<<31); +pub const MS_POSIXACL = (1 << 16); +pub const MS_UNBINDABLE = (1 << 17); +pub const MS_PRIVATE = (1 << 18); +pub const MS_SLAVE = (1 << 19); +pub const MS_SHARED = (1 << 20); +pub const MS_RELATIME = (1 << 21); +pub const MS_KERNMOUNT = (1 << 22); +pub const MS_I_VERSION = (1 << 23); +pub const MS_STRICTATIME = (1 << 24); +pub const MS_LAZYTIME = (1 << 25); +pub const MS_NOREMOTELOCK = (1 << 27); +pub const MS_NOSEC = (1 << 28); +pub const MS_BORN = (1 << 29); +pub const MS_ACTIVE = (1 << 30); +pub const MS_NOUSER = (1 << 31); -pub const MS_RMT_MASK = (MS_RDONLY|MS_SYNCHRONOUS|MS_MANDLOCK|MS_I_VERSION|MS_LAZYTIME); +pub const MS_RMT_MASK = (MS_RDONLY | MS_SYNCHRONOUS | MS_MANDLOCK | MS_I_VERSION | MS_LAZYTIME); pub const MS_MGC_VAL = 0xc0ed0000; pub const MS_MGC_MSK = 0xffff0000; @@ -565,7 +563,6 @@ pub const MNT_DETACH = 2; pub const MNT_EXPIRE = 4; pub const UMOUNT_NOFOLLOW = 8; - pub const S_IFMT = 0o170000; pub const S_IFDIR = 0o040000; @@ -626,15 +623,30 @@ pub const TFD_CLOEXEC = O_CLOEXEC; pub const TFD_TIMER_ABSTIME = 1; pub const TFD_TIMER_CANCEL_ON_SET = (1 << 1); -fn unsigned(s: i32) u32 { return @bitCast(u32, s); } -fn signed(s: u32) i32 { return @bitCast(i32, s); } -pub fn WEXITSTATUS(s: i32) i32 { return signed((unsigned(s) & 0xff00) >> 8); } -pub fn WTERMSIG(s: i32) i32 { return signed(unsigned(s) & 0x7f); } -pub fn WSTOPSIG(s: i32) i32 { return WEXITSTATUS(s); } -pub fn WIFEXITED(s: i32) bool { return WTERMSIG(s) == 0; } -pub fn WIFSTOPPED(s: i32) bool { return (u16)(((unsigned(s)&0xffff)*%0x10001)>>8) > 0x7f00; } -pub fn WIFSIGNALED(s: i32) bool { return (unsigned(s)&0xffff)-%1 < 0xff; } - +fn unsigned(s: i32) u32 { + return @bitCast(u32, s); +} +fn signed(s: u32) i32 { + return @bitCast(i32, s); +} +pub fn WEXITSTATUS(s: i32) i32 { + return signed((unsigned(s) & 0xff00) >> 8); +} +pub fn WTERMSIG(s: i32) i32 { + return signed(unsigned(s) & 0x7f); +} +pub fn WSTOPSIG(s: i32) i32 { + return WEXITSTATUS(s); +} +pub fn WIFEXITED(s: i32) bool { + return WTERMSIG(s) == 0; +} +pub fn WIFSTOPPED(s: i32) bool { + return (u16)(((unsigned(s) & 0xffff) *% 0x10001) >> 8) > 0x7f00; +} +pub fn WIFSIGNALED(s: i32) bool { + return (unsigned(s) & 0xffff) -% 1 < 0xff; +} pub const winsize = extern struct { ws_row: u16, @@ -707,8 +719,7 @@ pub fn umount2(special: &const u8, flags: u32) usize { } pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { - return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), - @bitCast(usize, offset)); + return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset)); } pub fn munmap(address: usize, length: usize) usize { @@ -812,7 +823,8 @@ pub fn clock_gettime(clk_id: i32, tp: ×pec) usize { if (@ptrToInt(f) != 0) { const rc = f(clk_id, tp); switch (rc) { - 0, @bitCast(usize, isize(-EINVAL)) => return rc, + 0, + @bitCast(usize, isize(-EINVAL)) => return rc, else => {}, } } @@ -823,8 +835,7 @@ var vdso_clock_gettime = init_vdso_clock_gettime; extern fn init_vdso_clock_gettime(clk: i32, ts: ×pec) usize { const addr = vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM); var f = @intToPtr(@typeOf(init_vdso_clock_gettime), addr); - _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, - builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic); + _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic); if (@ptrToInt(f) == 0) return @bitCast(usize, isize(-ENOSYS)); return f(clk, ts); } @@ -918,18 +929,18 @@ pub fn getpid() i32 { } pub fn sigprocmask(flags: u32, noalias set: &const sigset_t, noalias oldset: ?&sigset_t) usize { - return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG/8); + return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8); } pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigaction) usize { assert(sig >= 1); assert(sig != SIGKILL); assert(sig != SIGSTOP); - var ksa = k_sigaction { + var ksa = k_sigaction{ .handler = act.handler, .flags = act.flags | SA_RESTORER, .mask = undefined, - .restorer = @ptrCast(extern fn()void, restore_rt), + .restorer = @ptrCast(extern fn() void, restore_rt), }; var ksa_old: k_sigaction = undefined; @memcpy(@ptrCast(&u8, &ksa.mask), @ptrCast(&const u8, &act.mask), 8); @@ -952,22 +963,22 @@ const all_mask = []usize{@maxValue(usize)}; const app_mask = []usize{0xfffffffc7fffffff}; const k_sigaction = extern struct { - handler: extern fn(i32)void, + handler: extern fn(i32) void, flags: usize, - restorer: extern fn()void, + restorer: extern fn() void, mask: [2]u32, }; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = struct { - handler: extern fn(i32)void, + handler: extern fn(i32) void, mask: sigset_t, flags: u32, }; -pub const SIG_ERR = @intToPtr(extern fn(i32)void, @maxValue(usize)); -pub const SIG_DFL = @intToPtr(extern fn(i32)void, 0); -pub const SIG_IGN = @intToPtr(extern fn(i32)void, 1); +pub const SIG_ERR = @intToPtr(extern fn(i32) void, @maxValue(usize)); +pub const SIG_DFL = @intToPtr(extern fn(i32) void, 0); +pub const SIG_IGN = @intToPtr(extern fn(i32) void, 1); pub const empty_sigset = []usize{0} ** sigset_t.len; pub fn raise(sig: i32) usize { @@ -980,25 +991,25 @@ pub fn raise(sig: i32) usize { } fn blockAllSignals(set: &sigset_t) void { - _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG/8); + _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG / 8); } fn blockAppSignals(set: &sigset_t) void { - _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG/8); + _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG / 8); } fn restoreSignals(set: &sigset_t) void { - _ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG/8); + _ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG / 8); } pub fn sigaddset(set: &sigset_t, sig: u6) void { const s = sig - 1; - (*set)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1)); + (set.*)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1)); } pub fn sigismember(set: &const sigset_t, sig: u6) bool { const s = sig - 1; - return ((*set)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0; + return ((set.*)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0; } pub const in_port_t = u16; @@ -1062,9 +1073,7 @@ pub fn recvmsg(fd: i32, msg: &msghdr, flags: u32) usize { return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags); } -pub fn recvfrom(fd: i32, noalias buf: &u8, len: usize, flags: u32, - noalias addr: ?&sockaddr, noalias alen: ?&socklen_t) usize -{ +pub fn recvfrom(fd: i32, noalias buf: &u8, len: usize, flags: u32, noalias addr: ?&sockaddr, noalias alen: ?&socklen_t) usize { return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } @@ -1132,25 +1141,16 @@ pub fn fgetxattr(fd: usize, name: &const u8, value: &void, size: usize) usize { return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size); } -pub fn setxattr(path: &const u8, name: &const u8, value: &const void, - size: usize, flags: usize) usize { - - return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), - size, flags); +pub fn setxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize { + return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn lsetxattr(path: &const u8, name: &const u8, value: &const void, - size: usize, flags: usize) usize { - - return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), - size, flags); +pub fn lsetxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize { + return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn fsetxattr(fd: usize, name: &const u8, value: &const void, - size: usize, flags: usize) usize { - - return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), - size, flags); +pub fn fsetxattr(fd: usize, name: &const u8, value: &const void, size: usize, flags: usize) usize { + return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn removexattr(path: &const u8, name: &const u8) usize { @@ -1199,7 +1199,7 @@ pub fn timerfd_create(clockid: i32, flags: u32) usize { pub const itimerspec = extern struct { it_interval: timespec, - it_value: timespec + it_value: timespec, }; pub fn timerfd_gettime(fd: i32, curr_value: &itimerspec) usize { @@ -1211,30 +1211,30 @@ pub fn timerfd_settime(fd: i32, flags: u32, new_value: &const itimerspec, old_va } pub const _LINUX_CAPABILITY_VERSION_1 = 0x19980330; -pub const _LINUX_CAPABILITY_U32S_1 = 1; +pub const _LINUX_CAPABILITY_U32S_1 = 1; pub const _LINUX_CAPABILITY_VERSION_2 = 0x20071026; -pub const _LINUX_CAPABILITY_U32S_2 = 2; +pub const _LINUX_CAPABILITY_U32S_2 = 2; pub const _LINUX_CAPABILITY_VERSION_3 = 0x20080522; -pub const _LINUX_CAPABILITY_U32S_3 = 2; +pub const _LINUX_CAPABILITY_U32S_3 = 2; -pub const VFS_CAP_REVISION_MASK = 0xFF000000; -pub const VFS_CAP_REVISION_SHIFT = 24; -pub const VFS_CAP_FLAGS_MASK = ~VFS_CAP_REVISION_MASK; +pub const VFS_CAP_REVISION_MASK = 0xFF000000; +pub const VFS_CAP_REVISION_SHIFT = 24; +pub const VFS_CAP_FLAGS_MASK = ~VFS_CAP_REVISION_MASK; pub const VFS_CAP_FLAGS_EFFECTIVE = 0x000001; pub const VFS_CAP_REVISION_1 = 0x01000000; -pub const VFS_CAP_U32_1 = 1; -pub const XATTR_CAPS_SZ_1 = @sizeOf(u32)*(1 + 2*VFS_CAP_U32_1); +pub const VFS_CAP_U32_1 = 1; +pub const XATTR_CAPS_SZ_1 = @sizeOf(u32) * (1 + 2 * VFS_CAP_U32_1); pub const VFS_CAP_REVISION_2 = 0x02000000; -pub const VFS_CAP_U32_2 = 2; -pub const XATTR_CAPS_SZ_2 = @sizeOf(u32)*(1 + 2*VFS_CAP_U32_2); +pub const VFS_CAP_U32_2 = 2; +pub const XATTR_CAPS_SZ_2 = @sizeOf(u32) * (1 + 2 * VFS_CAP_U32_2); -pub const XATTR_CAPS_SZ = XATTR_CAPS_SZ_2; -pub const VFS_CAP_U32 = VFS_CAP_U32_2; -pub const VFS_CAP_REVISION = VFS_CAP_REVISION_2; +pub const XATTR_CAPS_SZ = XATTR_CAPS_SZ_2; +pub const VFS_CAP_U32 = VFS_CAP_U32_2; +pub const VFS_CAP_REVISION = VFS_CAP_REVISION_2; pub const vfs_cap_data = extern struct { //all of these are mandated as little endian @@ -1245,49 +1245,48 @@ pub const vfs_cap_data = extern struct { }; magic_etc: u32, - data: [VFS_CAP_U32]Data, + data: [VFS_CAP_U32]Data, }; - -pub const CAP_CHOWN = 0; -pub const CAP_DAC_OVERRIDE = 1; -pub const CAP_DAC_READ_SEARCH = 2; -pub const CAP_FOWNER = 3; -pub const CAP_FSETID = 4; -pub const CAP_KILL = 5; -pub const CAP_SETGID = 6; -pub const CAP_SETUID = 7; -pub const CAP_SETPCAP = 8; -pub const CAP_LINUX_IMMUTABLE = 9; -pub const CAP_NET_BIND_SERVICE = 10; -pub const CAP_NET_BROADCAST = 11; -pub const CAP_NET_ADMIN = 12; -pub const CAP_NET_RAW = 13; -pub const CAP_IPC_LOCK = 14; -pub const CAP_IPC_OWNER = 15; -pub const CAP_SYS_MODULE = 16; -pub const CAP_SYS_RAWIO = 17; -pub const CAP_SYS_CHROOT = 18; -pub const CAP_SYS_PTRACE = 19; -pub const CAP_SYS_PACCT = 20; -pub const CAP_SYS_ADMIN = 21; -pub const CAP_SYS_BOOT = 22; -pub const CAP_SYS_NICE = 23; -pub const CAP_SYS_RESOURCE = 24; -pub const CAP_SYS_TIME = 25; -pub const CAP_SYS_TTY_CONFIG = 26; -pub const CAP_MKNOD = 27; -pub const CAP_LEASE = 28; -pub const CAP_AUDIT_WRITE = 29; -pub const CAP_AUDIT_CONTROL = 30; -pub const CAP_SETFCAP = 31; -pub const CAP_MAC_OVERRIDE = 32; -pub const CAP_MAC_ADMIN = 33; -pub const CAP_SYSLOG = 34; -pub const CAP_WAKE_ALARM = 35; -pub const CAP_BLOCK_SUSPEND = 36; -pub const CAP_AUDIT_READ = 37; -pub const CAP_LAST_CAP = CAP_AUDIT_READ; +pub const CAP_CHOWN = 0; +pub const CAP_DAC_OVERRIDE = 1; +pub const CAP_DAC_READ_SEARCH = 2; +pub const CAP_FOWNER = 3; +pub const CAP_FSETID = 4; +pub const CAP_KILL = 5; +pub const CAP_SETGID = 6; +pub const CAP_SETUID = 7; +pub const CAP_SETPCAP = 8; +pub const CAP_LINUX_IMMUTABLE = 9; +pub const CAP_NET_BIND_SERVICE = 10; +pub const CAP_NET_BROADCAST = 11; +pub const CAP_NET_ADMIN = 12; +pub const CAP_NET_RAW = 13; +pub const CAP_IPC_LOCK = 14; +pub const CAP_IPC_OWNER = 15; +pub const CAP_SYS_MODULE = 16; +pub const CAP_SYS_RAWIO = 17; +pub const CAP_SYS_CHROOT = 18; +pub const CAP_SYS_PTRACE = 19; +pub const CAP_SYS_PACCT = 20; +pub const CAP_SYS_ADMIN = 21; +pub const CAP_SYS_BOOT = 22; +pub const CAP_SYS_NICE = 23; +pub const CAP_SYS_RESOURCE = 24; +pub const CAP_SYS_TIME = 25; +pub const CAP_SYS_TTY_CONFIG = 26; +pub const CAP_MKNOD = 27; +pub const CAP_LEASE = 28; +pub const CAP_AUDIT_WRITE = 29; +pub const CAP_AUDIT_CONTROL = 30; +pub const CAP_SETFCAP = 31; +pub const CAP_MAC_OVERRIDE = 32; +pub const CAP_MAC_ADMIN = 33; +pub const CAP_SYSLOG = 34; +pub const CAP_WAKE_ALARM = 35; +pub const CAP_BLOCK_SUSPEND = 36; +pub const CAP_AUDIT_READ = 37; +pub const CAP_LAST_CAP = CAP_AUDIT_READ; pub fn cap_valid(u8: x) bool { return x >= 0 and x <= CAP_LAST_CAP; diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index 1dc7e24869..056ab35003 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -27,10 +27,10 @@ extern fn zen_start() noreturn { nakedcc fn _start() noreturn { switch (builtin.arch) { builtin.Arch.x86_64 => { - argc_ptr = asm("lea (%%rsp), %[argc]": [argc] "=r" (-> &usize)); + argc_ptr = asm ("lea (%%rsp), %[argc]" : [argc] "=r" (-> &usize)); }, builtin.Arch.i386 => { - argc_ptr = asm("lea (%%esp), %[argc]": [argc] "=r" (-> &usize)); + argc_ptr = asm ("lea (%%esp), %[argc]" : [argc] "=r" (-> &usize)); }, else => @compileError("unsupported arch"), } @@ -46,7 +46,7 @@ extern fn WinMainCRTStartup() noreturn { } fn posixCallMainAndExit() noreturn { - const argc = *argc_ptr; + const argc = argc_ptr.*; const argv = @ptrCast(&&u8, &argc_ptr[1]); const envp_nullable = @ptrCast(&?&u8, &argv[argc + 1]); var envp_count: usize = 0; @@ -56,7 +56,7 @@ fn posixCallMainAndExit() noreturn { const auxv = &@ptrCast(&usize, envp.ptr)[envp_count + 1]; var i: usize = 0; while (auxv[i] != 0) : (i += 2) { - if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i+1]; + if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i + 1]; } std.debug.assert(std.os.linux_aux_raw[std.elf.AT_PAGESZ] == std.os.page_size); } diff --git a/std/special/compiler_rt/fixuint.zig b/std/special/compiler_rt/fixuint.zig index b01bc48118..d9a7393fe4 100644 --- a/std/special/compiler_rt/fixuint.zig +++ b/std/special/compiler_rt/fixuint.zig @@ -36,12 +36,10 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t const significand: rep_t = (aAbs & significandMask) | implicitBit; // If either the value or the exponent is negative, the result is zero. - if (sign == -1 or exponent < 0) - return 0; + if (sign == -1 or exponent < 0) return 0; // If the value is too large for the integer type, saturate. - if (c_uint(exponent) >= fixuint_t.bit_count) - return ~fixuint_t(0); + if (c_uint(exponent) >= fixuint_t.bit_count) return ~fixuint_t(0); // If 0 <= exponent < significandBits, right shift to get the result. // Otherwise, shift left. diff --git a/std/special/compiler_rt/fixunsdfdi.zig b/std/special/compiler_rt/fixunsdfdi.zig index 37a8a01a50..1fa7ed758e 100644 --- a/std/special/compiler_rt/fixunsdfdi.zig +++ b/std/special/compiler_rt/fixunsdfdi.zig @@ -9,4 +9,3 @@ pub extern fn __fixunsdfdi(a: f64) u64 { test "import fixunsdfdi" { _ = @import("fixunsdfdi_test.zig"); } - diff --git a/std/special/compiler_rt/fixunsdfsi.zig b/std/special/compiler_rt/fixunsdfsi.zig index 0b5aebb7f6..a77cb8df89 100644 --- a/std/special/compiler_rt/fixunsdfsi.zig +++ b/std/special/compiler_rt/fixunsdfsi.zig @@ -9,4 +9,3 @@ pub extern fn __fixunsdfsi(a: f64) u32 { test "import fixunsdfsi" { _ = @import("fixunsdfsi_test.zig"); } - diff --git a/std/special/compiler_rt/fixunssfti.zig b/std/special/compiler_rt/fixunssfti.zig index 0abd73fe76..f0cd788d2e 100644 --- a/std/special/compiler_rt/fixunssfti.zig +++ b/std/special/compiler_rt/fixunssfti.zig @@ -9,4 +9,3 @@ pub extern fn __fixunssfti(a: f32) u128 { test "import fixunssfti" { _ = @import("fixunssfti_test.zig"); } - diff --git a/std/special/compiler_rt/fixunstfti.zig b/std/special/compiler_rt/fixunstfti.zig index fea99eb6e8..cd6178164a 100644 --- a/std/special/compiler_rt/fixunstfti.zig +++ b/std/special/compiler_rt/fixunstfti.zig @@ -9,4 +9,3 @@ pub extern fn __fixunstfti(a: f128) u128 { test "import fixunstfti" { _ = @import("fixunstfti_test.zig"); } - diff --git a/std/special/compiler_rt/index.zig b/std/special/compiler_rt/index.zig index 6ef43c4fed..44466a407d 100644 --- a/std/special/compiler_rt/index.zig +++ b/std/special/compiler_rt/index.zig @@ -91,9 +91,10 @@ pub fn setXmm0(comptime T: type, value: T) void { const aligned_value: T align(16) = value; asm volatile ( \\movaps (%[ptr]), %%xmm0 - : - : [ptr] "r" (&aligned_value) - : "xmm0"); + + : + : [ptr] "r" (&aligned_value) + : "xmm0"); } extern fn __udivdi3(a: u64, b: u64) u64 { @@ -282,26 +283,27 @@ extern fn __udivmodsi4(a: u32, b: u32, rem: &u32) u32 { @setRuntimeSafety(is_test); const d = __udivsi3(a, b); - *rem = u32(i32(a) -% (i32(d) * i32(b))); + rem.* = u32(i32(a) -% (i32(d) * i32(b))); return d; } - extern fn __udivsi3(n: u32, d: u32) u32 { @setRuntimeSafety(is_test); const n_uword_bits: c_uint = u32.bit_count; // special cases - if (d == 0) - return 0; // ?! - if (n == 0) - return 0; + if (d == 0) return 0; // ?! + if (n == 0) return 0; var sr = @bitCast(c_uint, c_int(@clz(d)) - c_int(@clz(n))); // 0 <= sr <= n_uword_bits - 1 or sr large - if (sr > n_uword_bits - 1) // d > r + if (sr > n_uword_bits - 1) { + // d > r return 0; - if (sr == n_uword_bits - 1) // d == 1 + } + if (sr == n_uword_bits - 1) { + // d == 1 return n; + } sr += 1; // 1 <= sr <= n_uword_bits - 1 // Not a special case @@ -340,139 +342,667 @@ fn test_one_umoddi3(a: u64, b: u64, expected_r: u64) void { } test "test_udivsi3" { - const cases = [][3]u32 { - []u32{0x00000000, 0x00000001, 0x00000000}, - []u32{0x00000000, 0x00000002, 0x00000000}, - []u32{0x00000000, 0x00000003, 0x00000000}, - []u32{0x00000000, 0x00000010, 0x00000000}, - []u32{0x00000000, 0x078644FA, 0x00000000}, - []u32{0x00000000, 0x0747AE14, 0x00000000}, - []u32{0x00000000, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000000, 0x80000000, 0x00000000}, - []u32{0x00000000, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000000, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000000, 0xFFFFFFFF, 0x00000000}, - []u32{0x00000001, 0x00000001, 0x00000001}, - []u32{0x00000001, 0x00000002, 0x00000000}, - []u32{0x00000001, 0x00000003, 0x00000000}, - []u32{0x00000001, 0x00000010, 0x00000000}, - []u32{0x00000001, 0x078644FA, 0x00000000}, - []u32{0x00000001, 0x0747AE14, 0x00000000}, - []u32{0x00000001, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000001, 0x80000000, 0x00000000}, - []u32{0x00000001, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000001, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000001, 0xFFFFFFFF, 0x00000000}, - []u32{0x00000002, 0x00000001, 0x00000002}, - []u32{0x00000002, 0x00000002, 0x00000001}, - []u32{0x00000002, 0x00000003, 0x00000000}, - []u32{0x00000002, 0x00000010, 0x00000000}, - []u32{0x00000002, 0x078644FA, 0x00000000}, - []u32{0x00000002, 0x0747AE14, 0x00000000}, - []u32{0x00000002, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000002, 0x80000000, 0x00000000}, - []u32{0x00000002, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000002, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000002, 0xFFFFFFFF, 0x00000000}, - []u32{0x00000003, 0x00000001, 0x00000003}, - []u32{0x00000003, 0x00000002, 0x00000001}, - []u32{0x00000003, 0x00000003, 0x00000001}, - []u32{0x00000003, 0x00000010, 0x00000000}, - []u32{0x00000003, 0x078644FA, 0x00000000}, - []u32{0x00000003, 0x0747AE14, 0x00000000}, - []u32{0x00000003, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000003, 0x80000000, 0x00000000}, - []u32{0x00000003, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000003, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000003, 0xFFFFFFFF, 0x00000000}, - []u32{0x00000010, 0x00000001, 0x00000010}, - []u32{0x00000010, 0x00000002, 0x00000008}, - []u32{0x00000010, 0x00000003, 0x00000005}, - []u32{0x00000010, 0x00000010, 0x00000001}, - []u32{0x00000010, 0x078644FA, 0x00000000}, - []u32{0x00000010, 0x0747AE14, 0x00000000}, - []u32{0x00000010, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000010, 0x80000000, 0x00000000}, - []u32{0x00000010, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000010, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000010, 0xFFFFFFFF, 0x00000000}, - []u32{0x078644FA, 0x00000001, 0x078644FA}, - []u32{0x078644FA, 0x00000002, 0x03C3227D}, - []u32{0x078644FA, 0x00000003, 0x028216FE}, - []u32{0x078644FA, 0x00000010, 0x0078644F}, - []u32{0x078644FA, 0x078644FA, 0x00000001}, - []u32{0x078644FA, 0x0747AE14, 0x00000001}, - []u32{0x078644FA, 0x7FFFFFFF, 0x00000000}, - []u32{0x078644FA, 0x80000000, 0x00000000}, - []u32{0x078644FA, 0xFFFFFFFD, 0x00000000}, - []u32{0x078644FA, 0xFFFFFFFE, 0x00000000}, - []u32{0x078644FA, 0xFFFFFFFF, 0x00000000}, - []u32{0x0747AE14, 0x00000001, 0x0747AE14}, - []u32{0x0747AE14, 0x00000002, 0x03A3D70A}, - []u32{0x0747AE14, 0x00000003, 0x026D3A06}, - []u32{0x0747AE14, 0x00000010, 0x00747AE1}, - []u32{0x0747AE14, 0x078644FA, 0x00000000}, - []u32{0x0747AE14, 0x0747AE14, 0x00000001}, - []u32{0x0747AE14, 0x7FFFFFFF, 0x00000000}, - []u32{0x0747AE14, 0x80000000, 0x00000000}, - []u32{0x0747AE14, 0xFFFFFFFD, 0x00000000}, - []u32{0x0747AE14, 0xFFFFFFFE, 0x00000000}, - []u32{0x0747AE14, 0xFFFFFFFF, 0x00000000}, - []u32{0x7FFFFFFF, 0x00000001, 0x7FFFFFFF}, - []u32{0x7FFFFFFF, 0x00000002, 0x3FFFFFFF}, - []u32{0x7FFFFFFF, 0x00000003, 0x2AAAAAAA}, - []u32{0x7FFFFFFF, 0x00000010, 0x07FFFFFF}, - []u32{0x7FFFFFFF, 0x078644FA, 0x00000011}, - []u32{0x7FFFFFFF, 0x0747AE14, 0x00000011}, - []u32{0x7FFFFFFF, 0x7FFFFFFF, 0x00000001}, - []u32{0x7FFFFFFF, 0x80000000, 0x00000000}, - []u32{0x7FFFFFFF, 0xFFFFFFFD, 0x00000000}, - []u32{0x7FFFFFFF, 0xFFFFFFFE, 0x00000000}, - []u32{0x7FFFFFFF, 0xFFFFFFFF, 0x00000000}, - []u32{0x80000000, 0x00000001, 0x80000000}, - []u32{0x80000000, 0x00000002, 0x40000000}, - []u32{0x80000000, 0x00000003, 0x2AAAAAAA}, - []u32{0x80000000, 0x00000010, 0x08000000}, - []u32{0x80000000, 0x078644FA, 0x00000011}, - []u32{0x80000000, 0x0747AE14, 0x00000011}, - []u32{0x80000000, 0x7FFFFFFF, 0x00000001}, - []u32{0x80000000, 0x80000000, 0x00000001}, - []u32{0x80000000, 0xFFFFFFFD, 0x00000000}, - []u32{0x80000000, 0xFFFFFFFE, 0x00000000}, - []u32{0x80000000, 0xFFFFFFFF, 0x00000000}, - []u32{0xFFFFFFFD, 0x00000001, 0xFFFFFFFD}, - []u32{0xFFFFFFFD, 0x00000002, 0x7FFFFFFE}, - []u32{0xFFFFFFFD, 0x00000003, 0x55555554}, - []u32{0xFFFFFFFD, 0x00000010, 0x0FFFFFFF}, - []u32{0xFFFFFFFD, 0x078644FA, 0x00000022}, - []u32{0xFFFFFFFD, 0x0747AE14, 0x00000023}, - []u32{0xFFFFFFFD, 0x7FFFFFFF, 0x00000001}, - []u32{0xFFFFFFFD, 0x80000000, 0x00000001}, - []u32{0xFFFFFFFD, 0xFFFFFFFD, 0x00000001}, - []u32{0xFFFFFFFD, 0xFFFFFFFE, 0x00000000}, - []u32{0xFFFFFFFD, 0xFFFFFFFF, 0x00000000}, - []u32{0xFFFFFFFE, 0x00000001, 0xFFFFFFFE}, - []u32{0xFFFFFFFE, 0x00000002, 0x7FFFFFFF}, - []u32{0xFFFFFFFE, 0x00000003, 0x55555554}, - []u32{0xFFFFFFFE, 0x00000010, 0x0FFFFFFF}, - []u32{0xFFFFFFFE, 0x078644FA, 0x00000022}, - []u32{0xFFFFFFFE, 0x0747AE14, 0x00000023}, - []u32{0xFFFFFFFE, 0x7FFFFFFF, 0x00000002}, - []u32{0xFFFFFFFE, 0x80000000, 0x00000001}, - []u32{0xFFFFFFFE, 0xFFFFFFFD, 0x00000001}, - []u32{0xFFFFFFFE, 0xFFFFFFFE, 0x00000001}, - []u32{0xFFFFFFFE, 0xFFFFFFFF, 0x00000000}, - []u32{0xFFFFFFFF, 0x00000001, 0xFFFFFFFF}, - []u32{0xFFFFFFFF, 0x00000002, 0x7FFFFFFF}, - []u32{0xFFFFFFFF, 0x00000003, 0x55555555}, - []u32{0xFFFFFFFF, 0x00000010, 0x0FFFFFFF}, - []u32{0xFFFFFFFF, 0x078644FA, 0x00000022}, - []u32{0xFFFFFFFF, 0x0747AE14, 0x00000023}, - []u32{0xFFFFFFFF, 0x7FFFFFFF, 0x00000002}, - []u32{0xFFFFFFFF, 0x80000000, 0x00000001}, - []u32{0xFFFFFFFF, 0xFFFFFFFD, 0x00000001}, - []u32{0xFFFFFFFF, 0xFFFFFFFE, 0x00000001}, - []u32{0xFFFFFFFF, 0xFFFFFFFF, 0x00000001}, + const cases = [][3]u32{ + []u32{ + 0x00000000, + 0x00000001, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x00000002, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x00000003, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x00000010, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000000, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000000, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x00000001, + 0x00000001, + }, + []u32{ + 0x00000001, + 0x00000002, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x00000003, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x00000010, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000001, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000001, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000001, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x00000001, + 0x00000002, + }, + []u32{ + 0x00000002, + 0x00000002, + 0x00000001, + }, + []u32{ + 0x00000002, + 0x00000003, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x00000010, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000002, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000002, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000002, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x00000001, + 0x00000003, + }, + []u32{ + 0x00000003, + 0x00000002, + 0x00000001, + }, + []u32{ + 0x00000003, + 0x00000003, + 0x00000001, + }, + []u32{ + 0x00000003, + 0x00000010, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000003, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000003, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000003, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000010, + 0x00000001, + 0x00000010, + }, + []u32{ + 0x00000010, + 0x00000002, + 0x00000008, + }, + []u32{ + 0x00000010, + 0x00000003, + 0x00000005, + }, + []u32{ + 0x00000010, + 0x00000010, + 0x00000001, + }, + []u32{ + 0x00000010, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000010, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000010, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000010, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000010, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000010, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000010, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0x00000001, + 0x078644FA, + }, + []u32{ + 0x078644FA, + 0x00000002, + 0x03C3227D, + }, + []u32{ + 0x078644FA, + 0x00000003, + 0x028216FE, + }, + []u32{ + 0x078644FA, + 0x00000010, + 0x0078644F, + }, + []u32{ + 0x078644FA, + 0x078644FA, + 0x00000001, + }, + []u32{ + 0x078644FA, + 0x0747AE14, + 0x00000001, + }, + []u32{ + 0x078644FA, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0x00000001, + 0x0747AE14, + }, + []u32{ + 0x0747AE14, + 0x00000002, + 0x03A3D70A, + }, + []u32{ + 0x0747AE14, + 0x00000003, + 0x026D3A06, + }, + []u32{ + 0x0747AE14, + 0x00000010, + 0x00747AE1, + }, + []u32{ + 0x0747AE14, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0x0747AE14, + 0x00000001, + }, + []u32{ + 0x0747AE14, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x7FFFFFFF, + 0x00000001, + 0x7FFFFFFF, + }, + []u32{ + 0x7FFFFFFF, + 0x00000002, + 0x3FFFFFFF, + }, + []u32{ + 0x7FFFFFFF, + 0x00000003, + 0x2AAAAAAA, + }, + []u32{ + 0x7FFFFFFF, + 0x00000010, + 0x07FFFFFF, + }, + []u32{ + 0x7FFFFFFF, + 0x078644FA, + 0x00000011, + }, + []u32{ + 0x7FFFFFFF, + 0x0747AE14, + 0x00000011, + }, + []u32{ + 0x7FFFFFFF, + 0x7FFFFFFF, + 0x00000001, + }, + []u32{ + 0x7FFFFFFF, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x7FFFFFFF, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x7FFFFFFF, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x7FFFFFFF, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x80000000, + 0x00000001, + 0x80000000, + }, + []u32{ + 0x80000000, + 0x00000002, + 0x40000000, + }, + []u32{ + 0x80000000, + 0x00000003, + 0x2AAAAAAA, + }, + []u32{ + 0x80000000, + 0x00000010, + 0x08000000, + }, + []u32{ + 0x80000000, + 0x078644FA, + 0x00000011, + }, + []u32{ + 0x80000000, + 0x0747AE14, + 0x00000011, + }, + []u32{ + 0x80000000, + 0x7FFFFFFF, + 0x00000001, + }, + []u32{ + 0x80000000, + 0x80000000, + 0x00000001, + }, + []u32{ + 0x80000000, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x80000000, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x80000000, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0xFFFFFFFD, + 0x00000001, + 0xFFFFFFFD, + }, + []u32{ + 0xFFFFFFFD, + 0x00000002, + 0x7FFFFFFE, + }, + []u32{ + 0xFFFFFFFD, + 0x00000003, + 0x55555554, + }, + []u32{ + 0xFFFFFFFD, + 0x00000010, + 0x0FFFFFFF, + }, + []u32{ + 0xFFFFFFFD, + 0x078644FA, + 0x00000022, + }, + []u32{ + 0xFFFFFFFD, + 0x0747AE14, + 0x00000023, + }, + []u32{ + 0xFFFFFFFD, + 0x7FFFFFFF, + 0x00000001, + }, + []u32{ + 0xFFFFFFFD, + 0x80000000, + 0x00000001, + }, + []u32{ + 0xFFFFFFFD, + 0xFFFFFFFD, + 0x00000001, + }, + []u32{ + 0xFFFFFFFD, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0xFFFFFFFD, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0xFFFFFFFE, + 0x00000001, + 0xFFFFFFFE, + }, + []u32{ + 0xFFFFFFFE, + 0x00000002, + 0x7FFFFFFF, + }, + []u32{ + 0xFFFFFFFE, + 0x00000003, + 0x55555554, + }, + []u32{ + 0xFFFFFFFE, + 0x00000010, + 0x0FFFFFFF, + }, + []u32{ + 0xFFFFFFFE, + 0x078644FA, + 0x00000022, + }, + []u32{ + 0xFFFFFFFE, + 0x0747AE14, + 0x00000023, + }, + []u32{ + 0xFFFFFFFE, + 0x7FFFFFFF, + 0x00000002, + }, + []u32{ + 0xFFFFFFFE, + 0x80000000, + 0x00000001, + }, + []u32{ + 0xFFFFFFFE, + 0xFFFFFFFD, + 0x00000001, + }, + []u32{ + 0xFFFFFFFE, + 0xFFFFFFFE, + 0x00000001, + }, + []u32{ + 0xFFFFFFFE, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0xFFFFFFFF, + 0x00000001, + 0xFFFFFFFF, + }, + []u32{ + 0xFFFFFFFF, + 0x00000002, + 0x7FFFFFFF, + }, + []u32{ + 0xFFFFFFFF, + 0x00000003, + 0x55555555, + }, + []u32{ + 0xFFFFFFFF, + 0x00000010, + 0x0FFFFFFF, + }, + []u32{ + 0xFFFFFFFF, + 0x078644FA, + 0x00000022, + }, + []u32{ + 0xFFFFFFFF, + 0x0747AE14, + 0x00000023, + }, + []u32{ + 0xFFFFFFFF, + 0x7FFFFFFF, + 0x00000002, + }, + []u32{ + 0xFFFFFFFF, + 0x80000000, + 0x00000001, + }, + []u32{ + 0xFFFFFFFF, + 0xFFFFFFFD, + 0x00000001, + }, + []u32{ + 0xFFFFFFFF, + 0xFFFFFFFE, + 0x00000001, + }, + []u32{ + 0xFFFFFFFF, + 0xFFFFFFFF, + 0x00000001, + }, }; for (cases) |case| { diff --git a/std/special/compiler_rt/udivmod.zig b/std/special/compiler_rt/udivmod.zig index 07eaef583c..e8a86c5c44 100644 --- a/std/special/compiler_rt/udivmod.zig +++ b/std/special/compiler_rt/udivmod.zig @@ -1,7 +1,10 @@ const builtin = @import("builtin"); const is_test = builtin.is_test; -const low = switch (builtin.endian) { builtin.Endian.Big => 1, builtin.Endian.Little => 0 }; +const low = switch (builtin.endian) { + builtin.Endian.Big => 1, + builtin.Endian.Little => 0, +}; const high = 1 - low; pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: ?&DoubleInt) DoubleInt { @@ -11,8 +14,8 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: const SignedDoubleInt = @IntType(true, DoubleInt.bit_count); const Log2SingleInt = @import("../../math/index.zig").Log2Int(SingleInt); - const n = *@ptrCast(&const [2]SingleInt, &a); // TODO issue #421 - const d = *@ptrCast(&const [2]SingleInt, &b); // TODO issue #421 + const n = @ptrCast(&const [2]SingleInt, &a).*; // TODO issue #421 + const d = @ptrCast(&const [2]SingleInt, &b).*; // TODO issue #421 var q: [2]SingleInt = undefined; var r: [2]SingleInt = undefined; var sr: c_uint = undefined; @@ -23,7 +26,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // --- // 0 X if (maybe_rem) |rem| { - *rem = n[low] % d[low]; + rem.* = n[low] % d[low]; } return n[low] / d[low]; } @@ -31,7 +34,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // --- // K X if (maybe_rem) |rem| { - *rem = n[low]; + rem.* = n[low]; } return 0; } @@ -42,7 +45,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // --- // 0 0 if (maybe_rem) |rem| { - *rem = n[high] % d[low]; + rem.* = n[high] % d[low]; } return n[high] / d[low]; } @@ -54,7 +57,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: if (maybe_rem) |rem| { r[high] = n[high] % d[high]; r[low] = 0; - *rem = *@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]); // TODO issue #421 + rem.* = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 } return n[high] / d[high]; } @@ -66,7 +69,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: if (maybe_rem) |rem| { r[low] = n[low]; r[high] = n[high] & (d[high] - 1); - *rem = *@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]); // TODO issue #421 + rem.* = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 } return n[high] >> Log2SingleInt(@ctz(d[high])); } @@ -77,7 +80,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // 0 <= sr <= SingleInt.bit_count - 2 or sr large if (sr > SingleInt.bit_count - 2) { if (maybe_rem) |rem| { - *rem = a; + rem.* = a; } return 0; } @@ -98,7 +101,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: if ((d[low] & (d[low] - 1)) == 0) { // d is a power of 2 if (maybe_rem) |rem| { - *rem = n[low] & (d[low] - 1); + rem.* = n[low] & (d[low] - 1); } if (d[low] == 1) { return a; @@ -106,7 +109,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: sr = @ctz(d[low]); q[high] = n[high] >> Log2SingleInt(sr); q[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); - return *@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]); // TODO issue #421 + return @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]).*; // TODO issue #421 } // K X // --- @@ -141,7 +144,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // 0 <= sr <= SingleInt.bit_count - 1 or sr large if (sr > SingleInt.bit_count - 1) { if (maybe_rem) |rem| { - *rem = a; + rem.* = a; } return 0; } @@ -170,25 +173,25 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: var r_all: DoubleInt = undefined; while (sr > 0) : (sr -= 1) { // r:q = ((r:q) << 1) | carry - r[high] = (r[high] << 1) | (r[low] >> (SingleInt.bit_count - 1)); - r[low] = (r[low] << 1) | (q[high] >> (SingleInt.bit_count - 1)); - q[high] = (q[high] << 1) | (q[low] >> (SingleInt.bit_count - 1)); - q[low] = (q[low] << 1) | carry; + r[high] = (r[high] << 1) | (r[low] >> (SingleInt.bit_count - 1)); + r[low] = (r[low] << 1) | (q[high] >> (SingleInt.bit_count - 1)); + q[high] = (q[high] << 1) | (q[low] >> (SingleInt.bit_count - 1)); + q[low] = (q[low] << 1) | carry; // carry = 0; // if (r.all >= b) // { // r.all -= b; // carry = 1; // } - r_all = *@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]); // TODO issue #421 + r_all = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 const s: SignedDoubleInt = SignedDoubleInt(b -% r_all -% 1) >> (DoubleInt.bit_count - 1); carry = u32(s & 1); r_all -= b & @bitCast(DoubleInt, s); - r = *@ptrCast(&[2]SingleInt, &r_all); // TODO issue #421 + r = @ptrCast(&[2]SingleInt, &r_all).*; // TODO issue #421 } - const q_all = ((*@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0])) << 1) | carry; // TODO issue #421 + const q_all = ((@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]).*) << 1) | carry; // TODO issue #421 if (maybe_rem) |rem| { - *rem = r_all; + rem.* = r_all; } return q_all; } diff --git a/std/special/compiler_rt/udivmodti4.zig b/std/special/compiler_rt/udivmodti4.zig index f8fdebe4db..816f82b900 100644 --- a/std/special/compiler_rt/udivmodti4.zig +++ b/std/special/compiler_rt/udivmodti4.zig @@ -9,7 +9,7 @@ pub extern fn __udivmodti4(a: u128, b: u128, maybe_rem: ?&u128) u128 { pub extern fn __udivmodti4_windows_x86_64(a: &const u128, b: &const u128, maybe_rem: ?&u128) void { @setRuntimeSafety(builtin.is_test); - compiler_rt.setXmm0(u128, udivmod(u128, *a, *b, maybe_rem)); + compiler_rt.setXmm0(u128, udivmod(u128, a.*, b.*, maybe_rem)); } test "import udivmodti4" { diff --git a/std/special/compiler_rt/umodti3.zig b/std/special/compiler_rt/umodti3.zig index 3e8b80058e..11e2955bb3 100644 --- a/std/special/compiler_rt/umodti3.zig +++ b/std/special/compiler_rt/umodti3.zig @@ -11,5 +11,5 @@ pub extern fn __umodti3(a: u128, b: u128) u128 { pub extern fn __umodti3_windows_x86_64(a: &const u128, b: &const u128) void { @setRuntimeSafety(builtin.is_test); - compiler_rt.setXmm0(u128, __umodti3(*a, *b)); + compiler_rt.setXmm0(u128, __umodti3(a.*, b.*)); } diff --git a/test/cases/cast.zig b/test/cases/cast.zig index 547cca5797..8b6afb4310 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -14,7 +14,7 @@ test "integer literal to pointer cast" { } test "pointer reinterpret const float to int" { - const float: f64 = 5.99999999999994648725e - 01; + const float: f64 = 5.99999999999994648725e-01; const float_ptr = &float; const int_ptr = @ptrCast(&const i32, float_ptr); const int_val = int_ptr.*; @@ -121,13 +121,13 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" { return (p.*).x; } fn maybeConstConst(p: ?&const &const Self) u8 { - return (??p.*).x; + return ((??p).*).x; } fn constConstConst(p: &const &const &const Self) u8 { return (p.*.*).x; } fn maybeConstConstConst(p: ?&const &const &const Self) u8 { - return (??p.*.*).x; + return ((??p).*.*).x; } }; const s = S { diff --git a/test/cases/generics.zig b/test/cases/generics.zig index da8a7dcad6..3fb33d0495 100644 --- a/test/cases/generics.zig +++ b/test/cases/generics.zig @@ -127,7 +127,7 @@ test "generic fn with implicit cast" { }) == 0); } fn getByte(ptr: ?&const u8) u8 { - return ??ptr.*; + return (??ptr).*; } fn getFirstByte(comptime T: type, mem: []const T) u8 { return getByte(@ptrCast(&const u8, &mem[0])); From 4787127cf6418f7a819c9d6f07a9046d76e0de65 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 10 May 2018 00:29:49 -0400 Subject: [PATCH 04/75] partial conversion to post-fix pointer deref using zig fmt --- std/atomic/queue.zig | 12 +- std/atomic/stack.zig | 16 +- std/buffer.zig | 11 +- std/build.zig | 207 +++++------- std/crypto/blake2.zig | 705 ++++++++++++++++++++++++++------------- std/crypto/hmac.zig | 4 +- std/crypto/sha3.zig | 287 ++++++++++------ std/event.zig | 53 ++- std/hash/crc.zig | 32 +- std/hash_map.zig | 94 +++--- std/json.zig | 207 +++++++----- std/math/acos.zig | 14 +- std/math/asin.zig | 18 +- std/math/atan2.zig | 66 ++-- std/math/cbrt.zig | 10 +- std/math/ceil.zig | 4 +- std/math/cos.zig | 12 +- std/math/floor.zig | 4 +- std/math/fma.zig | 7 +- std/math/hypot.zig | 8 +- std/math/ln.zig | 6 +- std/math/log10.zig | 18 +- std/math/log2.zig | 7 +- std/math/round.zig | 8 +- std/math/sin.zig | 12 +- std/math/tan.zig | 6 +- std/net.zig | 40 +-- std/os/child_process.zig | 192 ++++++----- std/segmented_list.zig | 54 +-- std/sort.zig | 564 ++++++++++++++++++++++--------- 30 files changed, 1617 insertions(+), 1061 deletions(-) diff --git a/std/atomic/queue.zig b/std/atomic/queue.zig index e25c8e6b17..288a2b3b48 100644 --- a/std/atomic/queue.zig +++ b/std/atomic/queue.zig @@ -70,7 +70,7 @@ test "std.atomic.queue" { var queue: Queue(i32) = undefined; queue.init(); - var context = Context { + var context = Context{ .allocator = a, .queue = &queue, .put_sum = 0, @@ -81,16 +81,18 @@ test "std.atomic.queue" { var putters: [put_thread_count]&std.os.Thread = undefined; for (putters) |*t| { - *t = try std.os.spawnThread(&context, startPuts); + t.* = try std.os.spawnThread(&context, startPuts); } var getters: [put_thread_count]&std.os.Thread = undefined; for (getters) |*t| { - *t = try std.os.spawnThread(&context, startGets); + t.* = try std.os.spawnThread(&context, startGets); } - for (putters) |t| t.wait(); + for (putters) |t| + t.wait(); _ = @atomicRmw(u8, &context.puts_done, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); - for (getters) |t| t.wait(); + for (getters) |t| + t.wait(); std.debug.assert(context.put_sum == context.get_sum); std.debug.assert(context.get_count == puts_per_thread * put_thread_count); diff --git a/std/atomic/stack.zig b/std/atomic/stack.zig index 4a3dbef32b..400a1a3c4f 100644 --- a/std/atomic/stack.zig +++ b/std/atomic/stack.zig @@ -14,9 +14,7 @@ pub fn Stack(comptime T: type) type { }; pub fn init() Self { - return Self { - .root = null, - }; + return Self{ .root = null }; } /// push operation, but only if you are the first item in the stack. if you did not succeed in @@ -75,7 +73,7 @@ test "std.atomic.stack" { var a = &fixed_buffer_allocator.allocator; var stack = Stack(i32).init(); - var context = Context { + var context = Context{ .allocator = a, .stack = &stack, .put_sum = 0, @@ -86,16 +84,18 @@ test "std.atomic.stack" { var putters: [put_thread_count]&std.os.Thread = undefined; for (putters) |*t| { - *t = try std.os.spawnThread(&context, startPuts); + t.* = try std.os.spawnThread(&context, startPuts); } var getters: [put_thread_count]&std.os.Thread = undefined; for (getters) |*t| { - *t = try std.os.spawnThread(&context, startGets); + t.* = try std.os.spawnThread(&context, startGets); } - for (putters) |t| t.wait(); + for (putters) |t| + t.wait(); _ = @atomicRmw(u8, &context.puts_done, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); - for (getters) |t| t.wait(); + for (getters) |t| + t.wait(); std.debug.assert(context.put_sum == context.get_sum); std.debug.assert(context.get_count == puts_per_thread * put_thread_count); diff --git a/std/buffer.zig b/std/buffer.zig index 041d891dec..cf530c3c9e 100644 --- a/std/buffer.zig +++ b/std/buffer.zig @@ -31,9 +31,7 @@ pub const Buffer = struct { /// * ::replaceContentsBuffer /// * ::resize pub fn initNull(allocator: &Allocator) Buffer { - return Buffer { - .list = ArrayList(u8).init(allocator), - }; + return Buffer{ .list = ArrayList(u8).init(allocator) }; } /// Must deinitialize with deinit. @@ -45,9 +43,7 @@ pub const Buffer = struct { /// allocated with `allocator`. /// Must deinitialize with deinit. pub fn fromOwnedSlice(allocator: &Allocator, slice: []u8) Buffer { - var self = Buffer { - .list = ArrayList(u8).fromOwnedSlice(allocator, slice), - }; + var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) }; self.list.append(0); return self; } @@ -57,11 +53,10 @@ pub const Buffer = struct { pub fn toOwnedSlice(self: &Buffer) []u8 { const allocator = self.list.allocator; const result = allocator.shrink(u8, self.list.items, self.len()); - *self = initNull(allocator); + self.* = initNull(allocator); return result; } - pub fn deinit(self: &Buffer) void { self.list.deinit(); } diff --git a/std/build.zig b/std/build.zig index a312b28a6f..276176c63c 100644 --- a/std/build.zig +++ b/std/build.zig @@ -82,10 +82,8 @@ pub const Builder = struct { description: []const u8, }; - pub fn init(allocator: &Allocator, zig_exe: []const u8, build_root: []const u8, - cache_root: []const u8) Builder - { - var self = Builder { + pub fn init(allocator: &Allocator, zig_exe: []const u8, build_root: []const u8, cache_root: []const u8) Builder { + var self = Builder{ .zig_exe = zig_exe, .build_root = build_root, .cache_root = os.path.relative(allocator, build_root, cache_root) catch unreachable, @@ -112,12 +110,12 @@ pub const Builder = struct { .lib_dir = undefined, .exe_dir = undefined, .installed_files = ArrayList([]const u8).init(allocator), - .uninstall_tls = TopLevelStep { + .uninstall_tls = TopLevelStep{ .step = Step.init("uninstall", allocator, makeUninstall), .description = "Remove build artifacts from prefix path", }, .have_uninstall_step = false, - .install_tls = TopLevelStep { + .install_tls = TopLevelStep{ .step = Step.initNoOp("install", allocator), .description = "Copy build artifacts to prefix path", }, @@ -151,9 +149,7 @@ pub const Builder = struct { return LibExeObjStep.createObject(self, name, root_src); } - pub fn addSharedLibrary(self: &Builder, name: []const u8, root_src: ?[]const u8, - ver: &const Version) &LibExeObjStep - { + pub fn addSharedLibrary(self: &Builder, name: []const u8, root_src: ?[]const u8, ver: &const Version) &LibExeObjStep { return LibExeObjStep.createSharedLibrary(self, name, root_src, ver); } @@ -163,7 +159,7 @@ pub const Builder = struct { pub fn addTest(self: &Builder, root_src: []const u8) &TestStep { const test_step = self.allocator.create(TestStep) catch unreachable; - *test_step = TestStep.init(self, root_src); + test_step.* = TestStep.init(self, root_src); return test_step; } @@ -190,33 +186,31 @@ pub const Builder = struct { } /// ::argv is copied. - pub fn addCommand(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, - argv: []const []const u8) &CommandStep - { + pub fn addCommand(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) &CommandStep { return CommandStep.create(self, cwd, env_map, argv); } pub fn addWriteFile(self: &Builder, file_path: []const u8, data: []const u8) &WriteFileStep { const write_file_step = self.allocator.create(WriteFileStep) catch unreachable; - *write_file_step = WriteFileStep.init(self, file_path, data); + write_file_step.* = WriteFileStep.init(self, file_path, data); return write_file_step; } pub fn addLog(self: &Builder, comptime format: []const u8, args: ...) &LogStep { const data = self.fmt(format, args); const log_step = self.allocator.create(LogStep) catch unreachable; - *log_step = LogStep.init(self, data); + log_step.* = LogStep.init(self, data); return log_step; } pub fn addRemoveDirTree(self: &Builder, dir_path: []const u8) &RemoveDirStep { const remove_dir_step = self.allocator.create(RemoveDirStep) catch unreachable; - *remove_dir_step = RemoveDirStep.init(self, dir_path); + remove_dir_step.* = RemoveDirStep.init(self, dir_path); return remove_dir_step; } pub fn version(self: &const Builder, major: u32, minor: u32, patch: u32) Version { - return Version { + return Version{ .major = major, .minor = minor, .patch = patch, @@ -254,8 +248,7 @@ pub const Builder = struct { } pub fn getInstallStep(self: &Builder) &Step { - if (self.have_install_step) - return &self.install_tls.step; + if (self.have_install_step) return &self.install_tls.step; self.top_level_steps.append(&self.install_tls) catch unreachable; self.have_install_step = true; @@ -263,8 +256,7 @@ pub const Builder = struct { } pub fn getUninstallStep(self: &Builder) &Step { - if (self.have_uninstall_step) - return &self.uninstall_tls.step; + if (self.have_uninstall_step) return &self.uninstall_tls.step; self.top_level_steps.append(&self.uninstall_tls) catch unreachable; self.have_uninstall_step = true; @@ -360,7 +352,7 @@ pub const Builder = struct { pub fn option(self: &Builder, comptime T: type, name: []const u8, description: []const u8) ?T { const type_id = comptime typeToEnum(T); - const available_option = AvailableOption { + const available_option = AvailableOption{ .name = name, .type_id = type_id, .description = description, @@ -413,7 +405,7 @@ pub const Builder = struct { pub fn step(self: &Builder, name: []const u8, description: []const u8) &Step { const step_info = self.allocator.create(TopLevelStep) catch unreachable; - *step_info = TopLevelStep { + step_info.* = TopLevelStep{ .step = Step.initNoOp(name, self.allocator), .description = description, }; @@ -446,9 +438,9 @@ pub const Builder = struct { } pub fn addUserInputOption(self: &Builder, name: []const u8, value: []const u8) bool { - if (self.user_input_options.put(name, UserInputOption { + if (self.user_input_options.put(name, UserInputOption{ .name = name, - .value = UserValue { .Scalar = value }, + .value = UserValue{ .Scalar = value }, .used = false, }) catch unreachable) |*prev_value| { // option already exists @@ -458,18 +450,18 @@ pub const Builder = struct { var list = ArrayList([]const u8).init(self.allocator); list.append(s) catch unreachable; list.append(value) catch unreachable; - _ = self.user_input_options.put(name, UserInputOption { + _ = self.user_input_options.put(name, UserInputOption{ .name = name, - .value = UserValue { .List = list }, + .value = UserValue{ .List = list }, .used = false, }) catch unreachable; }, UserValue.List => |*list| { // append to the list list.append(value) catch unreachable; - _ = self.user_input_options.put(name, UserInputOption { + _ = self.user_input_options.put(name, UserInputOption{ .name = name, - .value = UserValue { .List = *list }, + .value = UserValue{ .List = list.* }, .used = false, }) catch unreachable; }, @@ -483,9 +475,9 @@ pub const Builder = struct { } pub fn addUserInputFlag(self: &Builder, name: []const u8) bool { - if (self.user_input_options.put(name, UserInputOption { + if (self.user_input_options.put(name, UserInputOption{ .name = name, - .value = UserValue {.Flag = {} }, + .value = UserValue{ .Flag = {} }, .used = false, }) catch unreachable) |*prev_value| { switch (prev_value.value) { @@ -556,9 +548,7 @@ pub const Builder = struct { warn("\n"); } - fn spawnChildEnvMap(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, - argv: []const []const u8) !void - { + fn spawnChildEnvMap(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) !void { if (self.verbose) { printCmd(cwd, argv); } @@ -617,7 +607,7 @@ pub const Builder = struct { self.pushInstalledFile(full_dest_path); const install_step = self.allocator.create(InstallFileStep) catch unreachable; - *install_step = InstallFileStep.init(self, src_path, full_dest_path); + install_step.* = InstallFileStep.init(self, src_path, full_dest_path); return install_step; } @@ -659,25 +649,23 @@ pub const Builder = struct { if (builtin.environ == builtin.Environ.msvc) { return "cl.exe"; } else { - return os.getEnvVarOwned(self.allocator, "CC") catch |err| + return os.getEnvVarOwned(self.allocator, "CC") catch |err| if (err == error.EnvironmentVariableNotFound) ([]const u8)("cc") else - debug.panic("Unable to get environment variable: {}", err) - ; + debug.panic("Unable to get environment variable: {}", err); } } pub fn findProgram(self: &Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 { // TODO report error for ambiguous situations - const exe_extension = (Target { .Native = {}}).exeFileExt(); + const exe_extension = (Target{ .Native = {} }).exeFileExt(); for (self.search_prefixes.toSliceConst()) |search_prefix| { for (names) |name| { if (os.path.isAbsolute(name)) { return name; } - const full_path = try os.path.join(self.allocator, search_prefix, "bin", - self.fmt("{}{}", name, exe_extension)); + const full_path = try os.path.join(self.allocator, search_prefix, "bin", self.fmt("{}{}", name, exe_extension)); if (os.path.real(self.allocator, full_path)) |real_path| { return real_path; } else |_| { @@ -761,7 +749,7 @@ pub const Target = union(enum) { Cross: CrossTarget, pub fn oFileExt(self: &const Target) []const u8 { - const environ = switch (*self) { + const environ = switch (self.*) { Target.Native => builtin.environ, Target.Cross => |t| t.environ, }; @@ -786,7 +774,7 @@ pub const Target = union(enum) { } pub fn getOs(self: &const Target) builtin.Os { - return switch (*self) { + return switch (self.*) { Target.Native => builtin.os, Target.Cross => |t| t.os, }; @@ -794,7 +782,8 @@ pub const Target = union(enum) { pub fn isDarwin(self: &const Target) bool { return switch (self.getOs()) { - builtin.Os.ios, builtin.Os.macosx => true, + builtin.Os.ios, + builtin.Os.macosx => true, else => false, }; } @@ -860,61 +849,57 @@ pub const LibExeObjStep = struct { Obj, }; - pub fn createSharedLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8, - ver: &const Version) &LibExeObjStep - { + pub fn createSharedLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8, ver: &const Version) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initExtraArgs(builder, name, root_src, Kind.Lib, false, ver); + self.* = initExtraArgs(builder, name, root_src, Kind.Lib, false, ver); return self; } pub fn createCSharedLibrary(builder: &Builder, name: []const u8, version: &const Version) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initC(builder, name, Kind.Lib, version, false); + self.* = initC(builder, name, Kind.Lib, version, false); return self; } pub fn createStaticLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initExtraArgs(builder, name, root_src, Kind.Lib, true, builder.version(0, 0, 0)); + self.* = initExtraArgs(builder, name, root_src, Kind.Lib, true, builder.version(0, 0, 0)); return self; } pub fn createCStaticLibrary(builder: &Builder, name: []const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initC(builder, name, Kind.Lib, builder.version(0, 0, 0), true); + self.* = initC(builder, name, Kind.Lib, builder.version(0, 0, 0), true); return self; } pub fn createObject(builder: &Builder, name: []const u8, root_src: []const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initExtraArgs(builder, name, root_src, Kind.Obj, false, builder.version(0, 0, 0)); + self.* = initExtraArgs(builder, name, root_src, Kind.Obj, false, builder.version(0, 0, 0)); return self; } pub fn createCObject(builder: &Builder, name: []const u8, src: []const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initC(builder, name, Kind.Obj, builder.version(0, 0, 0), false); + self.* = initC(builder, name, Kind.Obj, builder.version(0, 0, 0), false); self.object_src = src; return self; } pub fn createExecutable(builder: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initExtraArgs(builder, name, root_src, Kind.Exe, false, builder.version(0, 0, 0)); + self.* = initExtraArgs(builder, name, root_src, Kind.Exe, false, builder.version(0, 0, 0)); return self; } pub fn createCExecutable(builder: &Builder, name: []const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initC(builder, name, Kind.Exe, builder.version(0, 0, 0), false); + self.* = initC(builder, name, Kind.Exe, builder.version(0, 0, 0), false); return self; } - fn initExtraArgs(builder: &Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, - static: bool, ver: &const Version) LibExeObjStep - { - var self = LibExeObjStep { + fn initExtraArgs(builder: &Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, static: bool, ver: &const Version) LibExeObjStep { + var self = LibExeObjStep{ .strip = false, .builder = builder, .verbose_link = false, @@ -930,7 +915,7 @@ pub const LibExeObjStep = struct { .step = Step.init(name, builder.allocator, make), .output_path = null, .output_h_path = null, - .version = *ver, + .version = ver.*, .out_filename = undefined, .out_h_filename = builder.fmt("{}.h", name), .major_only_filename = undefined, @@ -953,11 +938,11 @@ pub const LibExeObjStep = struct { } fn initC(builder: &Builder, name: []const u8, kind: Kind, version: &const Version, static: bool) LibExeObjStep { - var self = LibExeObjStep { + var self = LibExeObjStep{ .builder = builder, .name = name, .kind = kind, - .version = *version, + .version = version.*, .static = static, .target = Target.Native, .cflags = ArrayList([]const u8).init(builder.allocator), @@ -1005,9 +990,9 @@ pub const LibExeObjStep = struct { self.out_filename = self.builder.fmt("lib{}.a", self.name); } else { switch (self.target.getOs()) { - builtin.Os.ios, builtin.Os.macosx => { - self.out_filename = self.builder.fmt("lib{}.{d}.{d}.{d}.dylib", - self.name, self.version.major, self.version.minor, self.version.patch); + builtin.Os.ios, + builtin.Os.macosx => { + self.out_filename = self.builder.fmt("lib{}.{d}.{d}.{d}.dylib", self.name, self.version.major, self.version.minor, self.version.patch); self.major_only_filename = self.builder.fmt("lib{}.{d}.dylib", self.name, self.version.major); self.name_only_filename = self.builder.fmt("lib{}.dylib", self.name); }, @@ -1015,8 +1000,7 @@ pub const LibExeObjStep = struct { self.out_filename = self.builder.fmt("{}.dll", self.name); }, else => { - self.out_filename = self.builder.fmt("lib{}.so.{d}.{d}.{d}", - self.name, self.version.major, self.version.minor, self.version.patch); + self.out_filename = self.builder.fmt("lib{}.so.{d}.{d}.{d}", self.name, self.version.major, self.version.minor, self.version.patch); self.major_only_filename = self.builder.fmt("lib{}.so.{d}", self.name, self.version.major); self.name_only_filename = self.builder.fmt("lib{}.so", self.name); }, @@ -1026,16 +1010,12 @@ pub const LibExeObjStep = struct { } } - pub fn setTarget(self: &LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, - target_environ: builtin.Environ) void - { - self.target = Target { - .Cross = CrossTarget { - .arch = target_arch, - .os = target_os, - .environ = target_environ, - } - }; + pub fn setTarget(self: &LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { + self.target = Target{ .Cross = CrossTarget{ + .arch = target_arch, + .os = target_os, + .environ = target_environ, + } }; self.computeOutFileNames(); } @@ -1159,7 +1139,7 @@ pub const LibExeObjStep = struct { pub fn addPackagePath(self: &LibExeObjStep, name: []const u8, pkg_index_path: []const u8) void { assert(self.is_zig); - self.packages.append(Pkg { + self.packages.append(Pkg{ .name = name, .path = pkg_index_path, }) catch unreachable; @@ -1343,8 +1323,7 @@ pub const LibExeObjStep = struct { try builder.spawnChild(zig_args.toSliceConst()); if (self.kind == Kind.Lib and !self.static and self.target.wantSharedLibSymLinks()) { - try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename, - self.name_only_filename); + try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename, self.name_only_filename); } } @@ -1373,7 +1352,8 @@ pub const LibExeObjStep = struct { args.append("ssp-buffer-size=4") catch unreachable; } }, - builtin.Mode.ReleaseFast, builtin.Mode.ReleaseSmall => { + builtin.Mode.ReleaseFast, + builtin.Mode.ReleaseSmall => { args.append("-O2") catch unreachable; args.append("-fno-stack-protector") catch unreachable; }, @@ -1505,8 +1485,7 @@ pub const LibExeObjStep = struct { } if (!is_darwin) { - const rpath_arg = builder.fmt("-Wl,-rpath,{}", - os.path.real(builder.allocator, builder.pathFromRoot(builder.cache_root)) catch unreachable); + const rpath_arg = builder.fmt("-Wl,-rpath,{}", os.path.real(builder.allocator, builder.pathFromRoot(builder.cache_root)) catch unreachable); defer builder.allocator.free(rpath_arg); cc_args.append(rpath_arg) catch unreachable; @@ -1535,8 +1514,7 @@ pub const LibExeObjStep = struct { try builder.spawnChild(cc_args.toSliceConst()); if (self.target.wantSharedLibSymLinks()) { - try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename, - self.name_only_filename); + try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename, self.name_only_filename); } } }, @@ -1581,8 +1559,7 @@ pub const LibExeObjStep = struct { cc_args.append("-o") catch unreachable; cc_args.append(output_path) catch unreachable; - const rpath_arg = builder.fmt("-Wl,-rpath,{}", - os.path.real(builder.allocator, builder.pathFromRoot(builder.cache_root)) catch unreachable); + const rpath_arg = builder.fmt("-Wl,-rpath,{}", os.path.real(builder.allocator, builder.pathFromRoot(builder.cache_root)) catch unreachable); defer builder.allocator.free(rpath_arg); cc_args.append(rpath_arg) catch unreachable; @@ -1635,7 +1612,7 @@ pub const TestStep = struct { pub fn init(builder: &Builder, root_src: []const u8) TestStep { const step_name = builder.fmt("test {}", root_src); - return TestStep { + return TestStep{ .step = Step.init(step_name, builder.allocator, make), .builder = builder, .root_src = root_src, @@ -1644,7 +1621,7 @@ pub const TestStep = struct { .name_prefix = "", .filter = null, .link_libs = BufSet.init(builder.allocator), - .target = Target { .Native = {} }, + .target = Target{ .Native = {} }, .exec_cmd_args = null, .include_dirs = ArrayList([]const u8).init(builder.allocator), }; @@ -1674,16 +1651,12 @@ pub const TestStep = struct { self.filter = text; } - pub fn setTarget(self: &TestStep, target_arch: builtin.Arch, target_os: builtin.Os, - target_environ: builtin.Environ) void - { - self.target = Target { - .Cross = CrossTarget { - .arch = target_arch, - .os = target_os, - .environ = target_environ, - } - }; + pub fn setTarget(self: &TestStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { + self.target = Target{ .Cross = CrossTarget{ + .arch = target_arch, + .os = target_os, + .environ = target_environ, + } }; } pub fn setExecCmd(self: &TestStep, args: []const ?[]const u8) void { @@ -1789,11 +1762,9 @@ pub const CommandStep = struct { env_map: &const BufMap, /// ::argv is copied. - pub fn create(builder: &Builder, cwd: ?[]const u8, env_map: &const BufMap, - argv: []const []const u8) &CommandStep - { + pub fn create(builder: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) &CommandStep { const self = builder.allocator.create(CommandStep) catch unreachable; - *self = CommandStep { + self.* = CommandStep{ .builder = builder, .step = Step.init(argv[0], builder.allocator, make), .argv = builder.allocator.alloc([]u8, argv.len) catch unreachable, @@ -1828,7 +1799,7 @@ const InstallArtifactStep = struct { LibExeObjStep.Kind.Exe => builder.exe_dir, LibExeObjStep.Kind.Lib => builder.lib_dir, }; - *self = Self { + self.* = Self{ .builder = builder, .step = Step.init(builder.fmt("install {}", artifact.step.name), builder.allocator, make), .artifact = artifact, @@ -1837,10 +1808,8 @@ const InstallArtifactStep = struct { self.step.dependOn(&artifact.step); builder.pushInstalledFile(self.dest_file); if (self.artifact.kind == LibExeObjStep.Kind.Lib and !self.artifact.static) { - builder.pushInstalledFile(os.path.join(builder.allocator, builder.lib_dir, - artifact.major_only_filename) catch unreachable); - builder.pushInstalledFile(os.path.join(builder.allocator, builder.lib_dir, - artifact.name_only_filename) catch unreachable); + builder.pushInstalledFile(os.path.join(builder.allocator, builder.lib_dir, artifact.major_only_filename) catch unreachable); + builder.pushInstalledFile(os.path.join(builder.allocator, builder.lib_dir, artifact.name_only_filename) catch unreachable); } return self; } @@ -1859,8 +1828,7 @@ const InstallArtifactStep = struct { }; try builder.copyFileMode(self.artifact.getOutputPath(), self.dest_file, mode); if (self.artifact.kind == LibExeObjStep.Kind.Lib and !self.artifact.static) { - try doAtomicSymLinks(builder.allocator, self.dest_file, - self.artifact.major_only_filename, self.artifact.name_only_filename); + try doAtomicSymLinks(builder.allocator, self.dest_file, self.artifact.major_only_filename, self.artifact.name_only_filename); } } }; @@ -1872,7 +1840,7 @@ pub const InstallFileStep = struct { dest_path: []const u8, pub fn init(builder: &Builder, src_path: []const u8, dest_path: []const u8) InstallFileStep { - return InstallFileStep { + return InstallFileStep{ .builder = builder, .step = Step.init(builder.fmt("install {}", src_path), builder.allocator, make), .src_path = src_path, @@ -1893,7 +1861,7 @@ pub const WriteFileStep = struct { data: []const u8, pub fn init(builder: &Builder, file_path: []const u8, data: []const u8) WriteFileStep { - return WriteFileStep { + return WriteFileStep{ .builder = builder, .step = Step.init(builder.fmt("writefile {}", file_path), builder.allocator, make), .file_path = file_path, @@ -1922,7 +1890,7 @@ pub const LogStep = struct { data: []const u8, pub fn init(builder: &Builder, data: []const u8) LogStep { - return LogStep { + return LogStep{ .builder = builder, .step = Step.init(builder.fmt("log {}", data), builder.allocator, make), .data = data, @@ -1941,7 +1909,7 @@ pub const RemoveDirStep = struct { dir_path: []const u8, pub fn init(builder: &Builder, dir_path: []const u8) RemoveDirStep { - return RemoveDirStep { + return RemoveDirStep{ .builder = builder, .step = Step.init(builder.fmt("RemoveDir {}", dir_path), builder.allocator, make), .dir_path = dir_path, @@ -1966,8 +1934,8 @@ pub const Step = struct { loop_flag: bool, done_flag: bool, - pub fn init(name: []const u8, allocator: &Allocator, makeFn: fn (&Step)error!void) Step { - return Step { + pub fn init(name: []const u8, allocator: &Allocator, makeFn: fn(&Step) error!void) Step { + return Step{ .name = name, .makeFn = makeFn, .dependencies = ArrayList(&Step).init(allocator), @@ -1980,8 +1948,7 @@ pub const Step = struct { } pub fn make(self: &Step) !void { - if (self.done_flag) - return; + if (self.done_flag) return; try self.makeFn(self); self.done_flag = true; @@ -1994,9 +1961,7 @@ pub const Step = struct { fn makeNoOp(self: &Step) error!void {} }; -fn doAtomicSymLinks(allocator: &Allocator, output_path: []const u8, filename_major_only: []const u8, - filename_name_only: []const u8) !void -{ +fn doAtomicSymLinks(allocator: &Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void { const out_dir = os.path.dirname(output_path); const out_basename = os.path.basename(output_path); // sym link for libfoo.so.1 to libfoo.so.1.2.3 diff --git a/std/crypto/blake2.zig b/std/crypto/blake2.zig index 99f0e629cd..18025d08eb 100644 --- a/std/crypto/blake2.zig +++ b/std/crypto/blake2.zig @@ -6,11 +6,23 @@ const builtin = @import("builtin"); const htest = @import("test.zig"); const RoundParam = struct { - a: usize, b: usize, c: usize, d: usize, x: usize, y: usize, + a: usize, + b: usize, + c: usize, + d: usize, + x: usize, + y: usize, }; fn Rp(a: usize, b: usize, c: usize, d: usize, x: usize, y: usize) RoundParam { - return RoundParam { .a = a, .b = b, .c = c, .d = d, .x = x, .y = y, }; + return RoundParam{ + .a = a, + .b = b, + .c = c, + .d = d, + .x = x, + .y = y, + }; } ///////////////////// @@ -19,145 +31,153 @@ fn Rp(a: usize, b: usize, c: usize, d: usize, x: usize, y: usize) RoundParam { pub const Blake2s224 = Blake2s(224); pub const Blake2s256 = Blake2s(256); -fn Blake2s(comptime out_len: usize) type { return struct { - const Self = this; - const block_size = 64; - const digest_size = out_len / 8; +fn Blake2s(comptime out_len: usize) type { + return struct { + const Self = this; + const block_size = 64; + const digest_size = out_len / 8; - const iv = [8]u32 { - 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, - 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, - }; + const iv = [8]u32{ + 0x6A09E667, + 0xBB67AE85, + 0x3C6EF372, + 0xA54FF53A, + 0x510E527F, + 0x9B05688C, + 0x1F83D9AB, + 0x5BE0CD19, + }; - const sigma = [10][16]u8 { - []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, - []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, - []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, - []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, - []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, - []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, - []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, - []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, - }; + const sigma = [10][16]u8{ + []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + }; - h: [8]u32, - t: u64, - // Streaming cache - buf: [64]u8, - buf_len: u8, + h: [8]u32, + t: u64, + // Streaming cache + buf: [64]u8, + buf_len: u8, - pub fn init() Self { - debug.assert(8 <= out_len and out_len <= 512); + pub fn init() Self { + debug.assert(8 <= out_len and out_len <= 512); - var s: Self = undefined; - s.reset(); - return s; - } + var s: Self = undefined; + s.reset(); + return s; + } - pub fn reset(d: &Self) void { - mem.copy(u32, d.h[0..], iv[0..]); + pub fn reset(d: &Self) void { + mem.copy(u32, d.h[0..], iv[0..]); - // No key plus default parameters - d.h[0] ^= 0x01010000 ^ u32(out_len >> 3); - d.t = 0; - d.buf_len = 0; - } - - pub fn hash(b: []const u8, out: []u8) void { - var d = Self.init(); - d.update(b); - d.final(out); - } - - pub fn update(d: &Self, b: []const u8) void { - var off: usize = 0; - - // Partial buffer exists from previous update. Copy into buffer then hash. - if (d.buf_len != 0 and d.buf_len + b.len > 64) { - off += 64 - d.buf_len; - mem.copy(u8, d.buf[d.buf_len..], b[0..off]); - d.t += 64; - d.round(d.buf[0..], false); + // No key plus default parameters + d.h[0] ^= 0x01010000 ^ u32(out_len >> 3); + d.t = 0; d.buf_len = 0; } - // Full middle blocks. - while (off + 64 <= b.len) : (off += 64) { - d.t += 64; - d.round(b[off..off + 64], false); + pub fn hash(b: []const u8, out: []u8) void { + var d = Self.init(); + d.update(b); + d.final(out); } - // Copy any remainder for next pass. - mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); - } + pub fn update(d: &Self, b: []const u8) void { + var off: usize = 0; - pub fn final(d: &Self, out: []u8) void { - debug.assert(out.len >= out_len / 8); + // Partial buffer exists from previous update. Copy into buffer then hash. + if (d.buf_len != 0 and d.buf_len + b.len > 64) { + off += 64 - d.buf_len; + mem.copy(u8, d.buf[d.buf_len..], b[0..off]); + d.t += 64; + d.round(d.buf[0..], false); + d.buf_len = 0; + } - mem.set(u8, d.buf[d.buf_len..], 0); - d.t += d.buf_len; - d.round(d.buf[0..], true); + // Full middle blocks. + while (off + 64 <= b.len) : (off += 64) { + d.t += 64; + d.round(b[off..off + 64], false); + } - const rr = d.h[0 .. out_len / 32]; - - for (rr) |s, j| { - mem.writeInt(out[4*j .. 4*j + 4], s, builtin.Endian.Little); - } - } - - fn round(d: &Self, b: []const u8, last: bool) void { - debug.assert(b.len == 64); - - var m: [16]u32 = undefined; - var v: [16]u32 = undefined; - - for (m) |*r, i| { - *r = mem.readIntLE(u32, b[4*i .. 4*i + 4]); + // Copy any remainder for next pass. + mem.copy(u8, d.buf[d.buf_len..], b[off..]); + d.buf_len += u8(b[off..].len); } - var k: usize = 0; - while (k < 8) : (k += 1) { - v[k] = d.h[k]; - v[k+8] = iv[k]; - } + pub fn final(d: &Self, out: []u8) void { + debug.assert(out.len >= out_len / 8); - v[12] ^= @truncate(u32, d.t); - v[13] ^= u32(d.t >> 32); - if (last) v[14] = ~v[14]; + mem.set(u8, d.buf[d.buf_len..], 0); + d.t += d.buf_len; + d.round(d.buf[0..], true); - const rounds = comptime []RoundParam { - Rp(0, 4, 8, 12, 0, 1), - Rp(1, 5, 9, 13, 2, 3), - Rp(2, 6, 10, 14, 4, 5), - Rp(3, 7, 11, 15, 6, 7), - Rp(0, 5, 10, 15, 8, 9), - Rp(1, 6, 11, 12, 10, 11), - Rp(2, 7, 8, 13, 12, 13), - Rp(3, 4, 9, 14, 14, 15), - }; + const rr = d.h[0..out_len / 32]; - comptime var j: usize = 0; - inline while (j < 10) : (j += 1) { - inline for (rounds) |r| { - v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; - v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(16)); - v[r.c] = v[r.c] +% v[r.d]; - v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(12)); - v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; - v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(8)); - v[r.c] = v[r.c] +% v[r.d]; - v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(7)); + for (rr) |s, j| { + mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Little); } } - for (d.h) |*r, i| { - *r ^= v[i] ^ v[i + 8]; + fn round(d: &Self, b: []const u8, last: bool) void { + debug.assert(b.len == 64); + + var m: [16]u32 = undefined; + var v: [16]u32 = undefined; + + for (m) |*r, i| { + r.* = mem.readIntLE(u32, b[4 * i..4 * i + 4]); + } + + var k: usize = 0; + while (k < 8) : (k += 1) { + v[k] = d.h[k]; + v[k + 8] = iv[k]; + } + + v[12] ^= @truncate(u32, d.t); + v[13] ^= u32(d.t >> 32); + if (last) v[14] = ~v[14]; + + const rounds = comptime []RoundParam{ + Rp(0, 4, 8, 12, 0, 1), + Rp(1, 5, 9, 13, 2, 3), + Rp(2, 6, 10, 14, 4, 5), + Rp(3, 7, 11, 15, 6, 7), + Rp(0, 5, 10, 15, 8, 9), + Rp(1, 6, 11, 12, 10, 11), + Rp(2, 7, 8, 13, 12, 13), + Rp(3, 4, 9, 14, 14, 15), + }; + + comptime var j: usize = 0; + inline while (j < 10) : (j += 1) { + inline for (rounds) |r| { + v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; + v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(16)); + v[r.c] = v[r.c] +% v[r.d]; + v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(12)); + v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; + v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(8)); + v[r.c] = v[r.c] +% v[r.d]; + v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(7)); + } + } + + for (d.h) |*r, i| { + r.* ^= v[i] ^ v[i + 8]; + } } - } -};} + }; +} test "blake2s224 single" { const h1 = "1fa1291e65248b37b3433475b2a0dd63d54a11ecc4e3e034e7bc1ef4"; @@ -230,7 +250,7 @@ test "blake2s256 streaming" { } test "blake2s256 aligned final" { - var block = []u8 {0} ** Blake2s256.block_size; + var block = []u8{0} ** Blake2s256.block_size; var out: [Blake2s256.digest_size]u8 = undefined; var h = Blake2s256.init(); @@ -238,154 +258,363 @@ test "blake2s256 aligned final" { h.final(out[0..]); } - ///////////////////// // Blake2b pub const Blake2b384 = Blake2b(384); pub const Blake2b512 = Blake2b(512); -fn Blake2b(comptime out_len: usize) type { return struct { - const Self = this; - const block_size = 128; - const digest_size = out_len / 8; +fn Blake2b(comptime out_len: usize) type { + return struct { + const Self = this; + const block_size = 128; + const digest_size = out_len / 8; - const iv = [8]u64 { - 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, - 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, - 0x510e527fade682d1, 0x9b05688c2b3e6c1f, - 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, - }; + const iv = [8]u64{ + 0x6a09e667f3bcc908, + 0xbb67ae8584caa73b, + 0x3c6ef372fe94f82b, + 0xa54ff53a5f1d36f1, + 0x510e527fade682d1, + 0x9b05688c2b3e6c1f, + 0x1f83d9abfb41bd6b, + 0x5be0cd19137e2179, + }; - const sigma = [12][16]u8 { - []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, - []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, - []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, - []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, - []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, - []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, - []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, - []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 }, - []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - }; + const sigma = [12][16]u8{ + []const u8{ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }, + []const u8{ + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3, + }, + []const u8{ + 11, + 8, + 12, + 0, + 5, + 2, + 15, + 13, + 10, + 14, + 3, + 6, + 7, + 1, + 9, + 4, + }, + []const u8{ + 7, + 9, + 3, + 1, + 13, + 12, + 11, + 14, + 2, + 6, + 5, + 10, + 4, + 0, + 15, + 8, + }, + []const u8{ + 9, + 0, + 5, + 7, + 2, + 4, + 10, + 15, + 14, + 1, + 11, + 12, + 6, + 8, + 3, + 13, + }, + []const u8{ + 2, + 12, + 6, + 10, + 0, + 11, + 8, + 3, + 4, + 13, + 7, + 5, + 15, + 14, + 1, + 9, + }, + []const u8{ + 12, + 5, + 1, + 15, + 14, + 13, + 4, + 10, + 0, + 7, + 6, + 3, + 9, + 2, + 8, + 11, + }, + []const u8{ + 13, + 11, + 7, + 14, + 12, + 1, + 3, + 9, + 5, + 0, + 15, + 4, + 8, + 6, + 2, + 10, + }, + []const u8{ + 6, + 15, + 14, + 9, + 11, + 3, + 0, + 8, + 12, + 2, + 13, + 7, + 1, + 4, + 10, + 5, + }, + []const u8{ + 10, + 2, + 8, + 4, + 7, + 6, + 1, + 5, + 15, + 11, + 9, + 14, + 3, + 12, + 13, + 0, + }, + []const u8{ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }, + []const u8{ + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3, + }, + }; - h: [8]u64, - t: u128, - // Streaming cache - buf: [128]u8, - buf_len: u8, + h: [8]u64, + t: u128, + // Streaming cache + buf: [128]u8, + buf_len: u8, - pub fn init() Self { - debug.assert(8 <= out_len and out_len <= 512); + pub fn init() Self { + debug.assert(8 <= out_len and out_len <= 512); - var s: Self = undefined; - s.reset(); - return s; - } + var s: Self = undefined; + s.reset(); + return s; + } - pub fn reset(d: &Self) void { - mem.copy(u64, d.h[0..], iv[0..]); + pub fn reset(d: &Self) void { + mem.copy(u64, d.h[0..], iv[0..]); - // No key plus default parameters - d.h[0] ^= 0x01010000 ^ (out_len >> 3); - d.t = 0; - d.buf_len = 0; - } - - pub fn hash(b: []const u8, out: []u8) void { - var d = Self.init(); - d.update(b); - d.final(out); - } - - pub fn update(d: &Self, b: []const u8) void { - var off: usize = 0; - - // Partial buffer exists from previous update. Copy into buffer then hash. - if (d.buf_len != 0 and d.buf_len + b.len > 128) { - off += 128 - d.buf_len; - mem.copy(u8, d.buf[d.buf_len..], b[0..off]); - d.t += 128; - d.round(d.buf[0..], false); + // No key plus default parameters + d.h[0] ^= 0x01010000 ^ (out_len >> 3); + d.t = 0; d.buf_len = 0; } - // Full middle blocks. - while (off + 128 <= b.len) : (off += 128) { - d.t += 128; - d.round(b[off..off + 128], false); + pub fn hash(b: []const u8, out: []u8) void { + var d = Self.init(); + d.update(b); + d.final(out); } - // Copy any remainder for next pass. - mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); - } + pub fn update(d: &Self, b: []const u8) void { + var off: usize = 0; - pub fn final(d: &Self, out: []u8) void { - mem.set(u8, d.buf[d.buf_len..], 0); - d.t += d.buf_len; - d.round(d.buf[0..], true); + // Partial buffer exists from previous update. Copy into buffer then hash. + if (d.buf_len != 0 and d.buf_len + b.len > 128) { + off += 128 - d.buf_len; + mem.copy(u8, d.buf[d.buf_len..], b[0..off]); + d.t += 128; + d.round(d.buf[0..], false); + d.buf_len = 0; + } - const rr = d.h[0 .. out_len / 64]; + // Full middle blocks. + while (off + 128 <= b.len) : (off += 128) { + d.t += 128; + d.round(b[off..off + 128], false); + } - for (rr) |s, j| { - mem.writeInt(out[8*j .. 8*j + 8], s, builtin.Endian.Little); - } - } - - fn round(d: &Self, b: []const u8, last: bool) void { - debug.assert(b.len == 128); - - var m: [16]u64 = undefined; - var v: [16]u64 = undefined; - - for (m) |*r, i| { - *r = mem.readIntLE(u64, b[8*i .. 8*i + 8]); + // Copy any remainder for next pass. + mem.copy(u8, d.buf[d.buf_len..], b[off..]); + d.buf_len += u8(b[off..].len); } - var k: usize = 0; - while (k < 8) : (k += 1) { - v[k] = d.h[k]; - v[k+8] = iv[k]; - } + pub fn final(d: &Self, out: []u8) void { + mem.set(u8, d.buf[d.buf_len..], 0); + d.t += d.buf_len; + d.round(d.buf[0..], true); - v[12] ^= @truncate(u64, d.t); - v[13] ^= u64(d.t >> 64); - if (last) v[14] = ~v[14]; + const rr = d.h[0..out_len / 64]; - const rounds = comptime []RoundParam { - Rp(0, 4, 8, 12, 0, 1), - Rp(1, 5, 9, 13, 2, 3), - Rp(2, 6, 10, 14, 4, 5), - Rp(3, 7, 11, 15, 6, 7), - Rp(0, 5, 10, 15, 8, 9), - Rp(1, 6, 11, 12, 10, 11), - Rp(2, 7, 8, 13, 12, 13), - Rp(3, 4, 9, 14, 14, 15), - }; - - comptime var j: usize = 0; - inline while (j < 12) : (j += 1) { - inline for (rounds) |r| { - v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; - v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(32)); - v[r.c] = v[r.c] +% v[r.d]; - v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(24)); - v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; - v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(16)); - v[r.c] = v[r.c] +% v[r.d]; - v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(63)); + for (rr) |s, j| { + mem.writeInt(out[8 * j..8 * j + 8], s, builtin.Endian.Little); } } - for (d.h) |*r, i| { - *r ^= v[i] ^ v[i + 8]; + fn round(d: &Self, b: []const u8, last: bool) void { + debug.assert(b.len == 128); + + var m: [16]u64 = undefined; + var v: [16]u64 = undefined; + + for (m) |*r, i| { + r.* = mem.readIntLE(u64, b[8 * i..8 * i + 8]); + } + + var k: usize = 0; + while (k < 8) : (k += 1) { + v[k] = d.h[k]; + v[k + 8] = iv[k]; + } + + v[12] ^= @truncate(u64, d.t); + v[13] ^= u64(d.t >> 64); + if (last) v[14] = ~v[14]; + + const rounds = comptime []RoundParam{ + Rp(0, 4, 8, 12, 0, 1), + Rp(1, 5, 9, 13, 2, 3), + Rp(2, 6, 10, 14, 4, 5), + Rp(3, 7, 11, 15, 6, 7), + Rp(0, 5, 10, 15, 8, 9), + Rp(1, 6, 11, 12, 10, 11), + Rp(2, 7, 8, 13, 12, 13), + Rp(3, 4, 9, 14, 14, 15), + }; + + comptime var j: usize = 0; + inline while (j < 12) : (j += 1) { + inline for (rounds) |r| { + v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; + v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(32)); + v[r.c] = v[r.c] +% v[r.d]; + v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(24)); + v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; + v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(16)); + v[r.c] = v[r.c] +% v[r.d]; + v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(63)); + } + } + + for (d.h) |*r, i| { + r.* ^= v[i] ^ v[i + 8]; + } } - } -};} + }; +} test "blake2b384 single" { const h1 = "b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100"; @@ -458,7 +687,7 @@ test "blake2b512 streaming" { } test "blake2b512 aligned final" { - var block = []u8 {0} ** Blake2b512.block_size; + var block = []u8{0} ** Blake2b512.block_size; var out: [Blake2b512.digest_size]u8 = undefined; var h = Blake2b512.init(); diff --git a/std/crypto/hmac.zig b/std/crypto/hmac.zig index 2a36f15b71..1415e88cf4 100644 --- a/std/crypto/hmac.zig +++ b/std/crypto/hmac.zig @@ -29,12 +29,12 @@ pub fn Hmac(comptime H: type) type { var o_key_pad: [H.block_size]u8 = undefined; for (o_key_pad) |*b, i| { - *b = scratch[i] ^ 0x5c; + b.* = scratch[i] ^ 0x5c; } var i_key_pad: [H.block_size]u8 = undefined; for (i_key_pad) |*b, i| { - *b = scratch[i] ^ 0x36; + b.* = scratch[i] ^ 0x36; } // HMAC(k, m) = H(o_key_pad | H(i_key_pad | message)) where | is concatenation diff --git a/std/crypto/sha3.zig b/std/crypto/sha3.zig index f92f56d68f..73b6415e1d 100644 --- a/std/crypto/sha3.zig +++ b/std/crypto/sha3.zig @@ -10,148 +10,228 @@ pub const Sha3_256 = Keccak(256, 0x06); pub const Sha3_384 = Keccak(384, 0x06); pub const Sha3_512 = Keccak(512, 0x06); -fn Keccak(comptime bits: usize, comptime delim: u8) type { return struct { - const Self = this; - const block_size = 200; - const digest_size = bits / 8; +fn Keccak(comptime bits: usize, comptime delim: u8) type { + return struct { + const Self = this; + const block_size = 200; + const digest_size = bits / 8; - s: [200]u8, - offset: usize, - rate: usize, + s: [200]u8, + offset: usize, + rate: usize, - pub fn init() Self { - var d: Self = undefined; - d.reset(); - return d; - } + pub fn init() Self { + var d: Self = undefined; + d.reset(); + return d; + } - pub fn reset(d: &Self) void { - mem.set(u8, d.s[0..], 0); - d.offset = 0; - d.rate = 200 - (bits / 4); - } + pub fn reset(d: &Self) void { + mem.set(u8, d.s[0..], 0); + d.offset = 0; + d.rate = 200 - (bits / 4); + } - pub fn hash(b: []const u8, out: []u8) void { - var d = Self.init(); - d.update(b); - d.final(out); - } + pub fn hash(b: []const u8, out: []u8) void { + var d = Self.init(); + d.update(b); + d.final(out); + } - pub fn update(d: &Self, b: []const u8) void { - var ip: usize = 0; - var len = b.len; - var rate = d.rate - d.offset; - var offset = d.offset; + pub fn update(d: &Self, b: []const u8) void { + var ip: usize = 0; + var len = b.len; + var rate = d.rate - d.offset; + var offset = d.offset; - // absorb - while (len >= rate) { - for (d.s[offset .. offset + rate]) |*r, i| - *r ^= b[ip..][i]; + // absorb + while (len >= rate) { + for (d.s[offset..offset + rate]) |*r, i| + r.* ^= b[ip..][i]; + + keccak_f(1600, d.s[0..]); + + ip += rate; + len -= rate; + rate = d.rate; + offset = 0; + } + + for (d.s[offset..offset + len]) |*r, i| + r.* ^= b[ip..][i]; + + d.offset = offset + len; + } + + pub fn final(d: &Self, out: []u8) void { + // padding + d.s[d.offset] ^= delim; + d.s[d.rate - 1] ^= 0x80; keccak_f(1600, d.s[0..]); - ip += rate; - len -= rate; - rate = d.rate; - offset = 0; + // squeeze + var op: usize = 0; + var len: usize = bits / 8; + + while (len >= d.rate) { + mem.copy(u8, out[op..], d.s[0..d.rate]); + keccak_f(1600, d.s[0..]); + op += d.rate; + len -= d.rate; + } + + mem.copy(u8, out[op..], d.s[0..len]); } + }; +} - for (d.s[offset .. offset + len]) |*r, i| - *r ^= b[ip..][i]; - - d.offset = offset + len; - } - - pub fn final(d: &Self, out: []u8) void { - // padding - d.s[d.offset] ^= delim; - d.s[d.rate - 1] ^= 0x80; - - keccak_f(1600, d.s[0..]); - - // squeeze - var op: usize = 0; - var len: usize = bits / 8; - - while (len >= d.rate) { - mem.copy(u8, out[op..], d.s[0..d.rate]); - keccak_f(1600, d.s[0..]); - op += d.rate; - len -= d.rate; - } - - mem.copy(u8, out[op..], d.s[0..len]); - } -};} - -const RC = []const u64 { - 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, - 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, - 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, - 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, - 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, - 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, +const RC = []const u64{ + 0x0000000000000001, + 0x0000000000008082, + 0x800000000000808a, + 0x8000000080008000, + 0x000000000000808b, + 0x0000000080000001, + 0x8000000080008081, + 0x8000000000008009, + 0x000000000000008a, + 0x0000000000000088, + 0x0000000080008009, + 0x000000008000000a, + 0x000000008000808b, + 0x800000000000008b, + 0x8000000000008089, + 0x8000000000008003, + 0x8000000000008002, + 0x8000000000000080, + 0x000000000000800a, + 0x800000008000000a, + 0x8000000080008081, + 0x8000000000008080, + 0x0000000080000001, + 0x8000000080008008, }; -const ROTC = []const usize { - 1, 3, 6, 10, 15, 21, 28, 36, - 45, 55, 2, 14, 27, 41, 56, 8, - 25, 43, 62, 18, 39, 61, 20, 44 +const ROTC = []const usize{ + 1, + 3, + 6, + 10, + 15, + 21, + 28, + 36, + 45, + 55, + 2, + 14, + 27, + 41, + 56, + 8, + 25, + 43, + 62, + 18, + 39, + 61, + 20, + 44, }; -const PIL = []const usize { - 10, 7, 11, 17, 18, 3, 5, 16, - 8, 21, 24, 4, 15, 23, 19, 13, - 12, 2, 20, 14, 22, 9, 6, 1 +const PIL = []const usize{ + 10, + 7, + 11, + 17, + 18, + 3, + 5, + 16, + 8, + 21, + 24, + 4, + 15, + 23, + 19, + 13, + 12, + 2, + 20, + 14, + 22, + 9, + 6, + 1, }; -const M5 = []const usize { - 0, 1, 2, 3, 4, 0, 1, 2, 3, 4 +const M5 = []const usize{ + 0, + 1, + 2, + 3, + 4, + 0, + 1, + 2, + 3, + 4, }; fn keccak_f(comptime F: usize, d: []u8) void { debug.assert(d.len == F / 8); const B = F / 25; - const no_rounds = comptime x: { break :x 12 + 2 * math.log2(B); }; + const no_rounds = comptime x: { + break :x 12 + 2 * math.log2(B); + }; - var s = []const u64 {0} ** 25; - var t = []const u64 {0} ** 1; - var c = []const u64 {0} ** 5; + var s = []const u64{0} ** 25; + var t = []const u64{0} ** 1; + var c = []const u64{0} ** 5; for (s) |*r, i| { - *r = mem.readIntLE(u64, d[8*i .. 8*i + 8]); + r.* = mem.readIntLE(u64, d[8 * i..8 * i + 8]); } comptime var x: usize = 0; comptime var y: usize = 0; for (RC[0..no_rounds]) |round| { // theta - x = 0; inline while (x < 5) : (x += 1) { - c[x] = s[x] ^ s[x+5] ^ s[x+10] ^ s[x+15] ^ s[x+20]; + x = 0; + inline while (x < 5) : (x += 1) { + c[x] = s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]; } - x = 0; inline while (x < 5) : (x += 1) { - t[0] = c[M5[x+4]] ^ math.rotl(u64, c[M5[x+1]], usize(1)); - y = 0; inline while (y < 5) : (y += 1) { - s[x + y*5] ^= t[0]; + x = 0; + inline while (x < 5) : (x += 1) { + t[0] = c[M5[x + 4]] ^ math.rotl(u64, c[M5[x + 1]], usize(1)); + y = 0; + inline while (y < 5) : (y += 1) { + s[x + y * 5] ^= t[0]; } } // rho+pi t[0] = s[1]; - x = 0; inline while (x < 24) : (x += 1) { + x = 0; + inline while (x < 24) : (x += 1) { c[0] = s[PIL[x]]; s[PIL[x]] = math.rotl(u64, t[0], ROTC[x]); t[0] = c[0]; } // chi - y = 0; inline while (y < 5) : (y += 1) { - x = 0; inline while (x < 5) : (x += 1) { - c[x] = s[x + y*5]; + y = 0; + inline while (y < 5) : (y += 1) { + x = 0; + inline while (x < 5) : (x += 1) { + c[x] = s[x + y * 5]; } - x = 0; inline while (x < 5) : (x += 1) { - s[x + y*5] = c[x] ^ (~c[M5[x+1]] & c[M5[x+2]]); + x = 0; + inline while (x < 5) : (x += 1) { + s[x + y * 5] = c[x] ^ (~c[M5[x + 1]] & c[M5[x + 2]]); } } @@ -160,11 +240,10 @@ fn keccak_f(comptime F: usize, d: []u8) void { } for (s) |r, i| { - mem.writeInt(d[8*i .. 8*i + 8], r, builtin.Endian.Little); + mem.writeInt(d[8 * i..8 * i + 8], r, builtin.Endian.Little); } } - test "sha3-224 single" { htest.assertEqualHash(Sha3_224, "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", ""); htest.assertEqualHash(Sha3_224, "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", "abc"); @@ -192,7 +271,7 @@ test "sha3-224 streaming" { } test "sha3-256 single" { - htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a" , ""); + htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", ""); htest.assertEqualHash(Sha3_256, "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", "abc"); htest.assertEqualHash(Sha3_256, "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } @@ -218,7 +297,7 @@ test "sha3-256 streaming" { } test "sha3-256 aligned final" { - var block = []u8 {0} ** Sha3_256.block_size; + var block = []u8{0} ** Sha3_256.block_size; var out: [Sha3_256.digest_size]u8 = undefined; var h = Sha3_256.init(); @@ -228,7 +307,7 @@ test "sha3-256 aligned final" { test "sha3-384 single" { const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004"; - htest.assertEqualHash(Sha3_384, h1 , ""); + htest.assertEqualHash(Sha3_384, h1, ""); const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25"; htest.assertEqualHash(Sha3_384, h2, "abc"); const h3 = "79407d3b5916b59c3e30b09822974791c313fb9ecc849e406f23592d04f625dc8c709b98b43b3852b337216179aa7fc7"; @@ -259,7 +338,7 @@ test "sha3-384 streaming" { test "sha3-512 single" { const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"; - htest.assertEqualHash(Sha3_512, h1 , ""); + htest.assertEqualHash(Sha3_512, h1, ""); const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"; htest.assertEqualHash(Sha3_512, h2, "abc"); const h3 = "afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185"; @@ -289,7 +368,7 @@ test "sha3-512 streaming" { } test "sha3-512 aligned final" { - var block = []u8 {0} ** Sha3_512.block_size; + var block = []u8{0} ** Sha3_512.block_size; var out: [Sha3_512.digest_size]u8 = undefined; var h = Sha3_512.init(); diff --git a/std/event.zig b/std/event.zig index bdad7fcc18..b2e7e3ae38 100644 --- a/std/event.zig +++ b/std/event.zig @@ -6,7 +6,7 @@ const mem = std.mem; const posix = std.os.posix; pub const TcpServer = struct { - handleRequestFn: async<&mem.Allocator> fn (&TcpServer, &const std.net.Address, &const std.os.File) void, + handleRequestFn: async<&mem.Allocator> fn(&TcpServer, &const std.net.Address, &const std.os.File) void, loop: &Loop, sockfd: i32, @@ -18,13 +18,11 @@ pub const TcpServer = struct { const PromiseNode = std.LinkedList(promise).Node; pub fn init(loop: &Loop) !TcpServer { - const sockfd = try std.os.posixSocket(posix.AF_INET, - posix.SOCK_STREAM|posix.SOCK_CLOEXEC|posix.SOCK_NONBLOCK, - posix.PROTO_tcp); + const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); errdefer std.os.close(sockfd); // TODO can't initialize handler coroutine here because we need well defined copy elision - return TcpServer { + return TcpServer{ .loop = loop, .sockfd = sockfd, .accept_coro = null, @@ -34,9 +32,7 @@ pub const TcpServer = struct { }; } - pub fn listen(self: &TcpServer, address: &const std.net.Address, - handleRequestFn: async<&mem.Allocator> fn (&TcpServer, &const std.net.Address, &const std.os.File)void) !void - { + pub fn listen(self: &TcpServer, address: &const std.net.Address, handleRequestFn: async<&mem.Allocator> fn(&TcpServer, &const std.net.Address, &const std.os.File) void) !void { self.handleRequestFn = handleRequestFn; try std.os.posixBind(self.sockfd, &address.os_addr); @@ -48,7 +44,6 @@ pub const TcpServer = struct { try self.loop.addFd(self.sockfd, ??self.accept_coro); errdefer self.loop.removeFd(self.sockfd); - } pub fn deinit(self: &TcpServer) void { @@ -60,9 +55,7 @@ pub const TcpServer = struct { pub async fn handler(self: &TcpServer) void { while (true) { var accepted_addr: std.net.Address = undefined; - if (std.os.posixAccept(self.sockfd, &accepted_addr.os_addr, - posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| - { + if (std.os.posixAccept(self.sockfd, &accepted_addr.os_addr, posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| { var socket = std.os.File.openHandle(accepted_fd); _ = async self.handleRequestFn(self, accepted_addr, socket) catch |err| switch (err) { error.OutOfMemory => { @@ -110,7 +103,7 @@ pub const Loop = struct { fn init(allocator: &mem.Allocator) !Loop { const epollfd = try std.os.linuxEpollCreate(std.os.linux.EPOLL_CLOEXEC); - return Loop { + return Loop{ .keep_running = true, .allocator = allocator, .epollfd = epollfd, @@ -118,11 +111,9 @@ pub const Loop = struct { } pub fn addFd(self: &Loop, fd: i32, prom: promise) !void { - var ev = std.os.linux.epoll_event { - .events = std.os.linux.EPOLLIN|std.os.linux.EPOLLOUT|std.os.linux.EPOLLET, - .data = std.os.linux.epoll_data { - .ptr = @ptrToInt(prom), - }, + var ev = std.os.linux.epoll_event{ + .events = std.os.linux.EPOLLIN | std.os.linux.EPOLLOUT | std.os.linux.EPOLLET, + .data = std.os.linux.epoll_data{ .ptr = @ptrToInt(prom) }, }; try std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_ADD, fd, &ev); } @@ -157,9 +148,9 @@ pub const Loop = struct { }; pub async fn connect(loop: &Loop, _address: &const std.net.Address) !std.os.File { - var address = *_address; // TODO https://github.com/zig-lang/zig/issues/733 + var address = _address.*; // TODO https://github.com/zig-lang/zig/issues/733 - const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM|posix.SOCK_CLOEXEC|posix.SOCK_NONBLOCK, posix.PROTO_tcp); + const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); errdefer std.os.close(sockfd); try std.os.posixConnectAsync(sockfd, &address.os_addr); @@ -179,11 +170,9 @@ test "listen on a port, send bytes, receive bytes" { const Self = this; - async<&mem.Allocator> fn handler(tcp_server: &TcpServer, _addr: &const std.net.Address, - _socket: &const std.os.File) void - { + async<&mem.Allocator> fn handler(tcp_server: &TcpServer, _addr: &const std.net.Address, _socket: &const std.os.File) void { const self = @fieldParentPtr(Self, "tcp_server", tcp_server); - var socket = *_socket; // TODO https://github.com/zig-lang/zig/issues/733 + var socket = _socket.*; // TODO https://github.com/zig-lang/zig/issues/733 defer socket.close(); const next_handler = async errorableHandler(self, _addr, socket) catch |err| switch (err) { error.OutOfMemory => @panic("unable to handle connection: out of memory"), @@ -191,14 +180,14 @@ test "listen on a port, send bytes, receive bytes" { (await next_handler) catch |err| { std.debug.panic("unable to handle connection: {}\n", err); }; - suspend |p| { cancel p; } + suspend |p| { + cancel p; + } } - async fn errorableHandler(self: &Self, _addr: &const std.net.Address, - _socket: &const std.os.File) !void - { - const addr = *_addr; // TODO https://github.com/zig-lang/zig/issues/733 - var socket = *_socket; // TODO https://github.com/zig-lang/zig/issues/733 + async fn errorableHandler(self: &Self, _addr: &const std.net.Address, _socket: &const std.os.File) !void { + const addr = _addr.*; // TODO https://github.com/zig-lang/zig/issues/733 + var socket = _socket.*; // TODO https://github.com/zig-lang/zig/issues/733 var adapter = std.io.FileOutStream.init(&socket); var stream = &adapter.stream; @@ -210,9 +199,7 @@ test "listen on a port, send bytes, receive bytes" { const addr = std.net.Address.initIp4(ip4addr, 0); var loop = try Loop.init(std.debug.global_allocator); - var server = MyServer { - .tcp_server = try TcpServer.init(&loop), - }; + var server = MyServer{ .tcp_server = try TcpServer.init(&loop) }; defer server.tcp_server.deinit(); try server.tcp_server.listen(addr, MyServer.handler); diff --git a/std/hash/crc.zig b/std/hash/crc.zig index f88069ce3c..e4c1405a1c 100644 --- a/std/hash/crc.zig +++ b/std/hash/crc.zig @@ -9,9 +9,9 @@ const std = @import("../index.zig"); const debug = std.debug; pub const Polynomial = struct { - const IEEE = 0xedb88320; + const IEEE = 0xedb88320; const Castagnoli = 0x82f63b78; - const Koopman = 0xeb31d82e; + const Koopman = 0xeb31d82e; }; // IEEE is by far the most common CRC and so is aliased by default. @@ -27,20 +27,22 @@ pub fn Crc32WithPoly(comptime poly: u32) type { for (tables[0]) |*e, i| { var crc = u32(i); - var j: usize = 0; while (j < 8) : (j += 1) { + var j: usize = 0; + while (j < 8) : (j += 1) { if (crc & 1 == 1) { crc = (crc >> 1) ^ poly; } else { crc = (crc >> 1); } } - *e = crc; + e.* = crc; } var i: usize = 0; while (i < 256) : (i += 1) { var crc = tables[0][i]; - var j: usize = 1; while (j < 8) : (j += 1) { + var j: usize = 1; + while (j < 8) : (j += 1) { const index = @truncate(u8, crc); crc = tables[0][index] ^ (crc >> 8); tables[j][i] = crc; @@ -53,22 +55,21 @@ pub fn Crc32WithPoly(comptime poly: u32) type { crc: u32, pub fn init() Self { - return Self { - .crc = 0xffffffff, - }; + return Self{ .crc = 0xffffffff }; } pub fn update(self: &Self, input: []const u8) void { var i: usize = 0; while (i + 8 <= input.len) : (i += 8) { - const p = input[i..i+8]; + const p = input[i..i + 8]; // Unrolling this way gives ~50Mb/s increase - self.crc ^= (u32(p[0]) << 0); - self.crc ^= (u32(p[1]) << 8); + self.crc ^= (u32(p[0]) << 0); + self.crc ^= (u32(p[1]) << 8); self.crc ^= (u32(p[2]) << 16); self.crc ^= (u32(p[3]) << 24); + self.crc = lookup_tables[0][p[7]] ^ lookup_tables[1][p[6]] ^ @@ -123,14 +124,15 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type { for (table) |*e, i| { var crc = u32(i * 16); - var j: usize = 0; while (j < 8) : (j += 1) { + var j: usize = 0; + while (j < 8) : (j += 1) { if (crc & 1 == 1) { crc = (crc >> 1) ^ poly; } else { crc = (crc >> 1); } } - *e = crc; + e.* = crc; } break :block table; @@ -139,9 +141,7 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type { crc: u32, pub fn init() Self { - return Self { - .crc = 0xffffffff, - }; + return Self{ .crc = 0xffffffff }; } pub fn update(self: &Self, input: []const u8) void { diff --git a/std/hash_map.zig b/std/hash_map.zig index 2a178d9d44..e3b86f8a3b 100644 --- a/std/hash_map.zig +++ b/std/hash_map.zig @@ -9,10 +9,7 @@ const builtin = @import("builtin"); const want_modification_safety = builtin.mode != builtin.Mode.ReleaseFast; const debug_u32 = if (want_modification_safety) u32 else void; -pub fn HashMap(comptime K: type, comptime V: type, - comptime hash: fn(key: K)u32, - comptime eql: fn(a: K, b: K)bool) type -{ +pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32, comptime eql: fn(a: K, b: K) bool) type { return struct { entries: []Entry, size: usize, @@ -65,7 +62,7 @@ pub fn HashMap(comptime K: type, comptime V: type, }; pub fn init(allocator: &Allocator) Self { - return Self { + return Self{ .entries = []Entry{}, .allocator = allocator, .size = 0, @@ -129,34 +126,36 @@ pub fn HashMap(comptime K: type, comptime V: type, if (hm.entries.len == 0) return null; hm.incrementModificationCount(); const start_index = hm.keyToIndex(key); - {var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { - const index = (start_index + roll_over) % hm.entries.len; - var entry = &hm.entries[index]; + { + var roll_over: usize = 0; + while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { + const index = (start_index + roll_over) % hm.entries.len; + var entry = &hm.entries[index]; - if (!entry.used) - return null; + if (!entry.used) return null; - if (!eql(entry.key, key)) continue; + if (!eql(entry.key, key)) continue; - while (roll_over < hm.entries.len) : (roll_over += 1) { - const next_index = (start_index + roll_over + 1) % hm.entries.len; - const next_entry = &hm.entries[next_index]; - if (!next_entry.used or next_entry.distance_from_start_index == 0) { - entry.used = false; - hm.size -= 1; - return entry; + while (roll_over < hm.entries.len) : (roll_over += 1) { + const next_index = (start_index + roll_over + 1) % hm.entries.len; + const next_entry = &hm.entries[next_index]; + if (!next_entry.used or next_entry.distance_from_start_index == 0) { + entry.used = false; + hm.size -= 1; + return entry; + } + entry.* = next_entry.*; + entry.distance_from_start_index -= 1; + entry = next_entry; } - *entry = *next_entry; - entry.distance_from_start_index -= 1; - entry = next_entry; + unreachable; // shifting everything in the table } - unreachable; // shifting everything in the table - }} + } return null; } pub fn iterator(hm: &const Self) Iterator { - return Iterator { + return Iterator{ .hm = hm, .count = 0, .index = 0, @@ -182,21 +181,23 @@ pub fn HashMap(comptime K: type, comptime V: type, /// Returns the value that was already there. fn internalPut(hm: &Self, orig_key: K, orig_value: &const V) ?V { var key = orig_key; - var value = *orig_value; + var value = orig_value.*; const start_index = hm.keyToIndex(key); var roll_over: usize = 0; var distance_from_start_index: usize = 0; - while (roll_over < hm.entries.len) : ({roll_over += 1; distance_from_start_index += 1;}) { + while (roll_over < hm.entries.len) : ({ + roll_over += 1; + distance_from_start_index += 1; + }) { const index = (start_index + roll_over) % hm.entries.len; const entry = &hm.entries[index]; if (entry.used and !eql(entry.key, key)) { if (entry.distance_from_start_index < distance_from_start_index) { // robin hood to the rescue - const tmp = *entry; - hm.max_distance_from_start_index = math.max(hm.max_distance_from_start_index, - distance_from_start_index); - *entry = Entry { + const tmp = entry.*; + hm.max_distance_from_start_index = math.max(hm.max_distance_from_start_index, distance_from_start_index); + entry.* = Entry{ .used = true, .distance_from_start_index = distance_from_start_index, .key = key, @@ -219,7 +220,7 @@ pub fn HashMap(comptime K: type, comptime V: type, } hm.max_distance_from_start_index = math.max(distance_from_start_index, hm.max_distance_from_start_index); - *entry = Entry { + entry.* = Entry{ .used = true, .distance_from_start_index = distance_from_start_index, .key = key, @@ -232,13 +233,16 @@ pub fn HashMap(comptime K: type, comptime V: type, fn internalGet(hm: &const Self, key: K) ?&Entry { const start_index = hm.keyToIndex(key); - {var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { - const index = (start_index + roll_over) % hm.entries.len; - const entry = &hm.entries[index]; + { + var roll_over: usize = 0; + while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { + const index = (start_index + roll_over) % hm.entries.len; + const entry = &hm.entries[index]; - if (!entry.used) return null; - if (eql(entry.key, key)) return entry; - }} + if (!entry.used) return null; + if (eql(entry.key, key)) return entry; + } + } return null; } @@ -282,11 +286,19 @@ test "iterator hash map" { assert((reset_map.put(2, 22) catch unreachable) == null); assert((reset_map.put(3, 33) catch unreachable) == null); - var keys = []i32 { 1, 2, 3 }; - var values = []i32 { 11, 22, 33 }; + var keys = []i32{ + 1, + 2, + 3, + }; + var values = []i32{ + 11, + 22, + 33, + }; var it = reset_map.iterator(); - var count : usize = 0; + var count: usize = 0; while (it.next()) |next| { assert(next.key == keys[count]); assert(next.value == values[count]); @@ -305,7 +317,7 @@ test "iterator hash map" { } it.reset(); - var entry = ?? it.next(); + var entry = ??it.next(); assert(entry.key == keys[0]); assert(entry.value == values[0]); } diff --git a/std/json.zig b/std/json.zig index 6f853501ed..2ea9083e2f 100644 --- a/std/json.zig +++ b/std/json.zig @@ -35,7 +35,7 @@ pub const Token = struct { }; pub fn init(id: Id, count: usize, offset: u1) Token { - return Token { + return Token{ .id = id, .offset = offset, .string_has_escape = false, @@ -45,7 +45,7 @@ pub const Token = struct { } pub fn initString(count: usize, has_unicode_escape: bool) Token { - return Token { + return Token{ .id = Id.String, .offset = 0, .string_has_escape = has_unicode_escape, @@ -55,7 +55,7 @@ pub const Token = struct { } pub fn initNumber(count: usize, number_is_integer: bool) Token { - return Token { + return Token{ .id = Id.Number, .offset = 0, .string_has_escape = false, @@ -66,7 +66,7 @@ pub const Token = struct { // A marker token is a zero-length pub fn initMarker(id: Id) Token { - return Token { + return Token{ .id = id, .offset = 0, .string_has_escape = false, @@ -77,7 +77,7 @@ pub const Token = struct { // Slice into the underlying input string. pub fn slice(self: &const Token, input: []const u8, i: usize) []const u8 { - return input[i + self.offset - self.count .. i + self.offset]; + return input[i + self.offset - self.count..i + self.offset]; } }; @@ -105,8 +105,8 @@ const StreamingJsonParser = struct { stack: u256, stack_used: u8, - const object_bit = 0; - const array_bit = 1; + const object_bit = 0; + const array_bit = 1; const max_stack_size = @maxValue(u8); pub fn init() StreamingJsonParser { @@ -120,7 +120,7 @@ const StreamingJsonParser = struct { p.count = 0; // Set before ever read in main transition function p.after_string_state = undefined; - p.after_value_state = State.ValueEnd; // handle end of values normally + p.after_value_state = State.ValueEnd; // handle end of values normally p.stack = 0; p.stack_used = 0; p.complete = false; @@ -181,7 +181,7 @@ const StreamingJsonParser = struct { } }; - pub const Error = error { + pub const Error = error{ InvalidTopLevel, TooManyNestedItems, TooManyClosingItems, @@ -206,8 +206,8 @@ const StreamingJsonParser = struct { // // There is currently no error recovery on a bad stream. pub fn feed(p: &StreamingJsonParser, c: u8, token1: &?Token, token2: &?Token) Error!void { - *token1 = null; - *token2 = null; + token1.* = null; + token2.* = null; p.count += 1; // unlikely @@ -228,7 +228,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; - *token = Token.initMarker(Token.Id.ObjectBegin); + token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { p.stack <<= 1; @@ -238,7 +238,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; - *token = Token.initMarker(Token.Id.ArrayBegin); + token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.number_is_integer = true; @@ -281,7 +281,10 @@ const StreamingJsonParser = struct { p.after_value_state = State.TopLevelEnd; p.count = 0; }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -290,7 +293,10 @@ const StreamingJsonParser = struct { }, State.TopLevelEnd => switch (c) { - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -324,7 +330,7 @@ const StreamingJsonParser = struct { else => {}, } - *token = Token.initMarker(Token.Id.ObjectEnd); + token.* = Token.initMarker(Token.Id.ObjectEnd); }, ']' => { if (p.stack & 1 != array_bit) { @@ -348,7 +354,7 @@ const StreamingJsonParser = struct { else => {}, } - *token = Token.initMarker(Token.Id.ArrayEnd); + token.* = Token.initMarker(Token.Id.ArrayEnd); }, '{' => { if (p.stack_used == max_stack_size) { @@ -362,7 +368,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; - *token = Token.initMarker(Token.Id.ObjectBegin); + token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { if (p.stack_used == max_stack_size) { @@ -376,7 +382,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; - *token = Token.initMarker(Token.Id.ArrayBegin); + token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.state = State.Number; @@ -406,7 +412,10 @@ const StreamingJsonParser = struct { p.state = State.NullLiteral1; p.count = 0; }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -428,7 +437,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; - *token = Token.initMarker(Token.Id.ObjectBegin); + token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { if (p.stack_used == max_stack_size) { @@ -442,7 +451,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; - *token = Token.initMarker(Token.Id.ArrayBegin); + token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.state = State.Number; @@ -472,7 +481,10 @@ const StreamingJsonParser = struct { p.state = State.NullLiteral1; p.count = 0; }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -501,7 +513,7 @@ const StreamingJsonParser = struct { p.state = State.TopLevelEnd; } - *token = Token.initMarker(Token.Id.ArrayEnd); + token.* = Token.initMarker(Token.Id.ArrayEnd); }, '}' => { if (p.stack_used == 0) { @@ -519,9 +531,12 @@ const StreamingJsonParser = struct { p.state = State.TopLevelEnd; } - *token = Token.initMarker(Token.Id.ObjectEnd); + token.* = Token.initMarker(Token.Id.ObjectEnd); }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -534,7 +549,10 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -553,12 +571,15 @@ const StreamingJsonParser = struct { p.complete = true; } - *token = Token.initString(p.count - 1, p.string_has_escape); + token.* = Token.initString(p.count - 1, p.string_has_escape); }, '\\' => { p.state = State.StringEscapeCharacter; }, - 0x20, 0x21, 0x23 ... 0x5B, 0x5D ... 0x7F => { + 0x20, + 0x21, + 0x23 ... 0x5B, + 0x5D ... 0x7F => { // non-control ascii }, 0xC0 ... 0xDF => { @@ -599,7 +620,14 @@ const StreamingJsonParser = struct { // The current JSONTestSuite tests rely on both of this behaviour being present // however, so we default to the status quo where both are accepted until this // is further clarified. - '"', '\\', '/', 'b', 'f', 'n', 'r', 't' => { + '"', + '\\', + '/', + 'b', + 'f', + 'n', + 'r', + 't' => { p.string_has_escape = true; p.state = State.String; }, @@ -613,28 +641,36 @@ const StreamingJsonParser = struct { }, State.StringEscapeHexUnicode4 => switch (c) { - '0' ... '9', 'A' ... 'F', 'a' ... 'f' => { + '0' ... '9', + 'A' ... 'F', + 'a' ... 'f' => { p.state = State.StringEscapeHexUnicode3; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode3 => switch (c) { - '0' ... '9', 'A' ... 'F', 'a' ... 'f' => { + '0' ... '9', + 'A' ... 'F', + 'a' ... 'f' => { p.state = State.StringEscapeHexUnicode2; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode2 => switch (c) { - '0' ... '9', 'A' ... 'F', 'a' ... 'f' => { + '0' ... '9', + 'A' ... 'F', + 'a' ... 'f' => { p.state = State.StringEscapeHexUnicode1; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode1 => switch (c) { - '0' ... '9', 'A' ... 'F', 'a' ... 'f' => { + '0' ... '9', + 'A' ... 'F', + 'a' ... 'f' => { p.state = State.String; }, else => return error.InvalidUnicodeHexSymbol, @@ -662,13 +698,14 @@ const StreamingJsonParser = struct { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, - 'e', 'E' => { + 'e', + 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } @@ -681,7 +718,8 @@ const StreamingJsonParser = struct { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, - 'e', 'E' => { + 'e', + 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, @@ -690,7 +728,7 @@ const StreamingJsonParser = struct { }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } @@ -714,13 +752,14 @@ const StreamingJsonParser = struct { '0' ... '9' => { // another digit }, - 'e', 'E' => { + 'e', + 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } @@ -729,20 +768,22 @@ const StreamingJsonParser = struct { State.NumberMaybeExponent => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - 'e', 'E' => { + 'e', + 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } }, State.NumberExponent => switch (c) { - '-', '+', => { + '-', + '+' => { p.complete = false; p.state = State.NumberExponentDigitsRequired; }, @@ -773,7 +814,7 @@ const StreamingJsonParser = struct { }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } @@ -793,7 +834,7 @@ const StreamingJsonParser = struct { 'e' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; - *token = Token.init(Token.Id.True, p.count + 1, 1); + token.* = Token.init(Token.Id.True, p.count + 1, 1); }, else => { return error.InvalidLiteral; @@ -819,7 +860,7 @@ const StreamingJsonParser = struct { 'e' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; - *token = Token.init(Token.Id.False, p.count + 1, 1); + token.* = Token.init(Token.Id.False, p.count + 1, 1); }, else => { return error.InvalidLiteral; @@ -840,7 +881,7 @@ const StreamingJsonParser = struct { 'l' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; - *token = Token.init(Token.Id.Null, p.count + 1, 1); + token.* = Token.init(Token.Id.Null, p.count + 1, 1); }, else => { return error.InvalidLiteral; @@ -895,7 +936,7 @@ pub const Value = union(enum) { Object: ObjectMap, pub fn dump(self: &const Value) void { - switch (*self) { + switch (self.*) { Value.Null => { std.debug.warn("null"); }, @@ -950,7 +991,7 @@ pub const Value = union(enum) { } fn dumpIndentLevel(self: &const Value, indent: usize, level: usize) void { - switch (*self) { + switch (self.*) { Value.Null => { std.debug.warn("null"); }, @@ -1027,7 +1068,7 @@ const JsonParser = struct { }; pub fn init(allocator: &Allocator, copy_strings: bool) JsonParser { - return JsonParser { + return JsonParser{ .allocator = allocator, .state = State.Simple, .copy_strings = copy_strings, @@ -1082,7 +1123,7 @@ const JsonParser = struct { std.debug.assert(p.stack.len == 1); - return ValueTree { + return ValueTree{ .arena = arena, .root = p.stack.at(0), }; @@ -1115,11 +1156,11 @@ const JsonParser = struct { switch (token.id) { Token.Id.ObjectBegin => { - try p.stack.append(Value { .Object = ObjectMap.init(allocator) }); + try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { - try p.stack.append(Value { .Array = ArrayList(Value).init(allocator) }); + try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { @@ -1133,12 +1174,12 @@ const JsonParser = struct { p.state = State.ObjectKey; }, Token.Id.True => { - _ = try object.put(key, Value { .Bool = true }); + _ = try object.put(key, Value{ .Bool = true }); _ = p.stack.pop(); p.state = State.ObjectKey; }, Token.Id.False => { - _ = try object.put(key, Value { .Bool = false }); + _ = try object.put(key, Value{ .Bool = false }); _ = p.stack.pop(); p.state = State.ObjectKey; }, @@ -1165,11 +1206,11 @@ const JsonParser = struct { try p.pushToParent(value); }, Token.Id.ObjectBegin => { - try p.stack.append(Value { .Object = ObjectMap.init(allocator) }); + try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { - try p.stack.append(Value { .Array = ArrayList(Value).init(allocator) }); + try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { @@ -1179,10 +1220,10 @@ const JsonParser = struct { try array.append(try p.parseNumber(token, input, i)); }, Token.Id.True => { - try array.append(Value { .Bool = true }); + try array.append(Value{ .Bool = true }); }, Token.Id.False => { - try array.append(Value { .Bool = false }); + try array.append(Value{ .Bool = false }); }, Token.Id.Null => { try array.append(Value.Null); @@ -1194,11 +1235,11 @@ const JsonParser = struct { }, State.Simple => switch (token.id) { Token.Id.ObjectBegin => { - try p.stack.append(Value { .Object = ObjectMap.init(allocator) }); + try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { - try p.stack.append(Value { .Array = ArrayList(Value).init(allocator) }); + try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { @@ -1208,15 +1249,16 @@ const JsonParser = struct { try p.stack.append(try p.parseNumber(token, input, i)); }, Token.Id.True => { - try p.stack.append(Value { .Bool = true }); + try p.stack.append(Value{ .Bool = true }); }, Token.Id.False => { - try p.stack.append(Value { .Bool = false }); + try p.stack.append(Value{ .Bool = false }); }, Token.Id.Null => { try p.stack.append(Value.Null); }, - Token.Id.ObjectEnd, Token.Id.ArrayEnd => { + Token.Id.ObjectEnd, + Token.Id.ArrayEnd => { unreachable; }, }, @@ -1248,15 +1290,14 @@ const JsonParser = struct { // TODO: We don't strictly have to copy values which do not contain any escape // characters if flagged with the option. const slice = token.slice(input, i); - return Value { .String = try mem.dupe(p.allocator, u8, slice) }; + return Value{ .String = try mem.dupe(p.allocator, u8, slice) }; } fn parseNumber(p: &JsonParser, token: &const Token, input: []const u8, i: usize) !Value { return if (token.number_is_integer) - Value { .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) } + Value{ .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) } else - @panic("TODO: fmt.parseFloat not yet implemented") - ; + @panic("TODO: fmt.parseFloat not yet implemented"); } }; @@ -1267,21 +1308,21 @@ test "json parser dynamic" { defer p.deinit(); const s = - \\{ - \\ "Image": { - \\ "Width": 800, - \\ "Height": 600, - \\ "Title": "View from 15th Floor", - \\ "Thumbnail": { - \\ "Url": "http://www.example.com/image/481989943", - \\ "Height": 125, - \\ "Width": 100 - \\ }, - \\ "Animated" : false, - \\ "IDs": [116, 943, 234, 38793] - \\ } - \\} - ; + \\{ + \\ "Image": { + \\ "Width": 800, + \\ "Height": 600, + \\ "Title": "View from 15th Floor", + \\ "Thumbnail": { + \\ "Url": "http://www.example.com/image/481989943", + \\ "Height": 125, + \\ "Width": 100 + \\ }, + \\ "Animated" : false, + \\ "IDs": [116, 943, 234, 38793] + \\ } + \\} + ; var tree = try p.parse(s); defer tree.deinit(); diff --git a/std/math/acos.zig b/std/math/acos.zig index a4f08af306..284f73fc91 100644 --- a/std/math/acos.zig +++ b/std/math/acos.zig @@ -16,7 +16,7 @@ pub fn acos(x: var) @typeOf(x) { } fn r32(z: f32) f32 { - const pS0 = 1.6666586697e-01; + const pS0 = 1.6666586697e-01; const pS1 = -4.2743422091e-02; const pS2 = -8.6563630030e-03; const qS1 = -7.0662963390e-01; @@ -74,16 +74,16 @@ fn acos32(x: f32) f32 { } fn r64(z: f64) f64 { - const pS0: f64 = 1.66666666666666657415e-01; + const pS0: f64 = 1.66666666666666657415e-01; const pS1: f64 = -3.25565818622400915405e-01; - const pS2: f64 = 2.01212532134862925881e-01; + const pS2: f64 = 2.01212532134862925881e-01; const pS3: f64 = -4.00555345006794114027e-02; - const pS4: f64 = 7.91534994289814532176e-04; - const pS5: f64 = 3.47933107596021167570e-05; + const pS4: f64 = 7.91534994289814532176e-04; + const pS5: f64 = 3.47933107596021167570e-05; const qS1: f64 = -2.40339491173441421878e+00; - const qS2: f64 = 2.02094576023350569471e+00; + const qS2: f64 = 2.02094576023350569471e+00; const qS3: f64 = -6.88283971605453293030e-01; - const qS4: f64 = 7.70381505559019352791e-02; + const qS4: f64 = 7.70381505559019352791e-02; const p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); const q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); diff --git a/std/math/asin.zig b/std/math/asin.zig index 9fa5a80ea5..2ee3aa6048 100644 --- a/std/math/asin.zig +++ b/std/math/asin.zig @@ -17,7 +17,7 @@ pub fn asin(x: var) @typeOf(x) { } fn r32(z: f32) f32 { - const pS0 = 1.6666586697e-01; + const pS0 = 1.6666586697e-01; const pS1 = -4.2743422091e-02; const pS2 = -8.6563630030e-03; const qS1 = -7.0662963390e-01; @@ -37,9 +37,9 @@ fn asin32(x: f32) f32 { if (ix >= 0x3F800000) { // |x| >= 1 if (ix == 0x3F800000) { - return x * pio2 + 0x1.0p-120; // asin(+-1) = +-pi/2 with inexact + return x * pio2 + 0x1.0p-120; // asin(+-1) = +-pi/2 with inexact } else { - return math.nan(f32); // asin(|x| > 1) is nan + return math.nan(f32); // asin(|x| > 1) is nan } } @@ -66,16 +66,16 @@ fn asin32(x: f32) f32 { } fn r64(z: f64) f64 { - const pS0: f64 = 1.66666666666666657415e-01; + const pS0: f64 = 1.66666666666666657415e-01; const pS1: f64 = -3.25565818622400915405e-01; - const pS2: f64 = 2.01212532134862925881e-01; + const pS2: f64 = 2.01212532134862925881e-01; const pS3: f64 = -4.00555345006794114027e-02; - const pS4: f64 = 7.91534994289814532176e-04; - const pS5: f64 = 3.47933107596021167570e-05; + const pS4: f64 = 7.91534994289814532176e-04; + const pS5: f64 = 3.47933107596021167570e-05; const qS1: f64 = -2.40339491173441421878e+00; - const qS2: f64 = 2.02094576023350569471e+00; + const qS2: f64 = 2.02094576023350569471e+00; const qS3: f64 = -6.88283971605453293030e-01; - const qS4: f64 = 7.70381505559019352791e-02; + const qS4: f64 = 7.70381505559019352791e-02; const p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); const q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); diff --git a/std/math/atan2.zig b/std/math/atan2.zig index 37c520da46..0892f0b438 100644 --- a/std/math/atan2.zig +++ b/std/math/atan2.zig @@ -31,7 +31,7 @@ pub fn atan2(comptime T: type, x: T, y: T) T { } fn atan2_32(y: f32, x: f32) f32 { - const pi: f32 = 3.1415927410e+00; + const pi: f32 = 3.1415927410e+00; const pi_lo: f32 = -8.7422776573e-08; if (math.isNan(x) or math.isNan(y)) { @@ -53,9 +53,10 @@ fn atan2_32(y: f32, x: f32) f32 { if (iy == 0) { switch (m) { - 0, 1 => return y, // atan(+-0, +...) - 2 => return pi, // atan(+0, -...) - 3 => return -pi, // atan(-0, -...) + 0, + 1 => return y, // atan(+-0, +...) + 2 => return pi, // atan(+0, -...) + 3 => return -pi, // atan(-0, -...) else => unreachable, } } @@ -71,18 +72,18 @@ fn atan2_32(y: f32, x: f32) f32 { if (ix == 0x7F800000) { if (iy == 0x7F800000) { switch (m) { - 0 => return pi / 4, // atan(+inf, +inf) - 1 => return -pi / 4, // atan(-inf, +inf) - 2 => return 3*pi / 4, // atan(+inf, -inf) - 3 => return -3*pi / 4, // atan(-inf, -inf) + 0 => return pi / 4, // atan(+inf, +inf) + 1 => return -pi / 4, // atan(-inf, +inf) + 2 => return 3 * pi / 4, // atan(+inf, -inf) + 3 => return -3 * pi / 4, // atan(-inf, -inf) else => unreachable, } } else { switch (m) { - 0 => return 0.0, // atan(+..., +inf) - 1 => return -0.0, // atan(-..., +inf) - 2 => return pi, // atan(+..., -inf) - 3 => return -pi, // atan(-...f, -inf) + 0 => return 0.0, // atan(+..., +inf) + 1 => return -0.0, // atan(-..., +inf) + 2 => return pi, // atan(+..., -inf) + 3 => return -pi, // atan(-...f, -inf) else => unreachable, } } @@ -107,16 +108,16 @@ fn atan2_32(y: f32, x: f32) f32 { }; switch (m) { - 0 => return z, // atan(+, +) - 1 => return -z, // atan(-, +) - 2 => return pi - (z - pi_lo), // atan(+, -) - 3 => return (z - pi_lo) - pi, // atan(-, -) + 0 => return z, // atan(+, +) + 1 => return -z, // atan(-, +) + 2 => return pi - (z - pi_lo), // atan(+, -) + 3 => return (z - pi_lo) - pi, // atan(-, -) else => unreachable, } } fn atan2_64(y: f64, x: f64) f64 { - const pi: f64 = 3.1415926535897931160E+00; + const pi: f64 = 3.1415926535897931160E+00; const pi_lo: f64 = 1.2246467991473531772E-16; if (math.isNan(x) or math.isNan(y)) { @@ -143,9 +144,10 @@ fn atan2_64(y: f64, x: f64) f64 { if (iy | ly == 0) { switch (m) { - 0, 1 => return y, // atan(+-0, +...) - 2 => return pi, // atan(+0, -...) - 3 => return -pi, // atan(-0, -...) + 0, + 1 => return y, // atan(+-0, +...) + 2 => return pi, // atan(+0, -...) + 3 => return -pi, // atan(-0, -...) else => unreachable, } } @@ -161,18 +163,18 @@ fn atan2_64(y: f64, x: f64) f64 { if (ix == 0x7FF00000) { if (iy == 0x7FF00000) { switch (m) { - 0 => return pi / 4, // atan(+inf, +inf) - 1 => return -pi / 4, // atan(-inf, +inf) - 2 => return 3*pi / 4, // atan(+inf, -inf) - 3 => return -3*pi / 4, // atan(-inf, -inf) + 0 => return pi / 4, // atan(+inf, +inf) + 1 => return -pi / 4, // atan(-inf, +inf) + 2 => return 3 * pi / 4, // atan(+inf, -inf) + 3 => return -3 * pi / 4, // atan(-inf, -inf) else => unreachable, } } else { switch (m) { - 0 => return 0.0, // atan(+..., +inf) - 1 => return -0.0, // atan(-..., +inf) - 2 => return pi, // atan(+..., -inf) - 3 => return -pi, // atan(-...f, -inf) + 0 => return 0.0, // atan(+..., +inf) + 1 => return -0.0, // atan(-..., +inf) + 2 => return pi, // atan(+..., -inf) + 3 => return -pi, // atan(-...f, -inf) else => unreachable, } } @@ -197,10 +199,10 @@ fn atan2_64(y: f64, x: f64) f64 { }; switch (m) { - 0 => return z, // atan(+, +) - 1 => return -z, // atan(-, +) - 2 => return pi - (z - pi_lo), // atan(+, -) - 3 => return (z - pi_lo) - pi, // atan(-, -) + 0 => return z, // atan(+, +) + 1 => return -z, // atan(-, +) + 2 => return pi - (z - pi_lo), // atan(+, -) + 3 => return (z - pi_lo) - pi, // atan(-, -) else => unreachable, } } diff --git a/std/math/cbrt.zig b/std/math/cbrt.zig index a265392ff7..cd3b71ca8a 100644 --- a/std/math/cbrt.zig +++ b/std/math/cbrt.zig @@ -58,15 +58,15 @@ fn cbrt32(x: f32) f32 { } fn cbrt64(x: f64) f64 { - const B1: u32 = 715094163; // (1023 - 1023 / 3 - 0.03306235651 * 2^20 - const B2: u32 = 696219795; // (1023 - 1023 / 3 - 54 / 3 - 0.03306235651 * 2^20 + const B1: u32 = 715094163; // (1023 - 1023 / 3 - 0.03306235651 * 2^20 + const B2: u32 = 696219795; // (1023 - 1023 / 3 - 54 / 3 - 0.03306235651 * 2^20 // |1 / cbrt(x) - p(x)| < 2^(23.5) - const P0: f64 = 1.87595182427177009643; + const P0: f64 = 1.87595182427177009643; const P1: f64 = -1.88497979543377169875; - const P2: f64 = 1.621429720105354466140; + const P2: f64 = 1.621429720105354466140; const P3: f64 = -0.758397934778766047437; - const P4: f64 = 0.145996192886612446982; + const P4: f64 = 0.145996192886612446982; var u = @bitCast(u64, x); var hx = u32(u >> 32) & 0x7FFFFFFF; diff --git a/std/math/ceil.zig b/std/math/ceil.zig index 5bdb84ca00..a189bb66d2 100644 --- a/std/math/ceil.zig +++ b/std/math/ceil.zig @@ -56,7 +56,7 @@ fn ceil64(x: f64) f64 { const e = (u >> 52) & 0x7FF; var y: f64 = undefined; - if (e >= 0x3FF+52 or x == 0) { + if (e >= 0x3FF + 52 or x == 0) { return x; } @@ -68,7 +68,7 @@ fn ceil64(x: f64) f64 { y = x + math.f64_toint - math.f64_toint - x; } - if (e <= 0x3FF-1) { + if (e <= 0x3FF - 1) { math.forceEval(y); if (u >> 63 != 0) { return -0.0; diff --git a/std/math/cos.zig b/std/math/cos.zig index bb405b0d10..5e5ec4f1cb 100644 --- a/std/math/cos.zig +++ b/std/math/cos.zig @@ -18,20 +18,20 @@ pub fn cos(x: var) @typeOf(x) { } // sin polynomial coefficients -const S0 = 1.58962301576546568060E-10; +const S0 = 1.58962301576546568060E-10; const S1 = -2.50507477628578072866E-8; -const S2 = 2.75573136213857245213E-6; +const S2 = 2.75573136213857245213E-6; const S3 = -1.98412698295895385996E-4; -const S4 = 8.33333333332211858878E-3; +const S4 = 8.33333333332211858878E-3; const S5 = -1.66666666666666307295E-1; // cos polynomial coeffiecients const C0 = -1.13585365213876817300E-11; -const C1 = 2.08757008419747316778E-9; +const C1 = 2.08757008419747316778E-9; const C2 = -2.75573141792967388112E-7; -const C3 = 2.48015872888517045348E-5; +const C3 = 2.48015872888517045348E-5; const C4 = -1.38888888888730564116E-3; -const C5 = 4.16666666666665929218E-2; +const C5 = 4.16666666666665929218E-2; // NOTE: This is taken from the go stdlib. The musl implementation is much more complex. // diff --git a/std/math/floor.zig b/std/math/floor.zig index 1b8e2dfeed..7d5364787f 100644 --- a/std/math/floor.zig +++ b/std/math/floor.zig @@ -57,7 +57,7 @@ fn floor64(x: f64) f64 { const e = (u >> 52) & 0x7FF; var y: f64 = undefined; - if (e >= 0x3FF+52 or x == 0) { + if (e >= 0x3FF + 52 or x == 0) { return x; } @@ -69,7 +69,7 @@ fn floor64(x: f64) f64 { y = x + math.f64_toint - math.f64_toint - x; } - if (e <= 0x3FF-1) { + if (e <= 0x3FF - 1) { math.forceEval(y); if (u >> 63 != 0) { return -1.0; diff --git a/std/math/fma.zig b/std/math/fma.zig index e8d146db34..3e9214f35b 100644 --- a/std/math/fma.zig +++ b/std/math/fma.zig @@ -5,7 +5,7 @@ const assert = std.debug.assert; pub fn fma(comptime T: type, x: T, y: T, z: T) T { return switch (T) { f32 => fma32(x, y, z), - f64 => fma64(x, y ,z), + f64 => fma64(x, y, z), else => @compileError("fma not implemented for " ++ @typeName(T)), }; } @@ -71,7 +71,10 @@ fn fma64(x: f64, y: f64, z: f64) f64 { } } -const dd = struct { hi: f64, lo: f64, }; +const dd = struct { + hi: f64, + lo: f64, +}; fn dd_add(a: f64, b: f64) dd { var ret: dd = undefined; diff --git a/std/math/hypot.zig b/std/math/hypot.zig index 06427d0865..fe0de3a1ea 100644 --- a/std/math/hypot.zig +++ b/std/math/hypot.zig @@ -39,11 +39,11 @@ fn hypot32(x: f32, y: f32) f32 { } var z: f32 = 1.0; - if (ux >= (0x7F+60) << 23) { + if (ux >= (0x7F + 60) << 23) { z = 0x1.0p90; xx *= 0x1.0p-90; yy *= 0x1.0p-90; - } else if (uy < (0x7F-60) << 23) { + } else if (uy < (0x7F - 60) << 23) { z = 0x1.0p-90; xx *= 0x1.0p-90; yy *= 0x1.0p-90; @@ -57,8 +57,8 @@ fn sq(hi: &f64, lo: &f64, x: f64) void { const xc = x * split; const xh = x - xc + xc; const xl = x - xh; - *hi = x * x; - *lo = xh * xh - *hi + 2 * xh * xl + xl * xl; + hi.* = x * x; + lo.* = xh * xh - hi.* + 2 * xh * xl + xl * xl; } fn hypot64(x: f64, y: f64) f64 { diff --git a/std/math/ln.zig b/std/math/ln.zig index d09494b998..263e5955cb 100644 --- a/std/math/ln.zig +++ b/std/math/ln.zig @@ -120,11 +120,9 @@ pub fn ln_64(x_: f64) f64 { k -= 54; x *= 0x1.0p54; hx = u32(@bitCast(u64, ix) >> 32); - } - else if (hx >= 0x7FF00000) { + } else if (hx >= 0x7FF00000) { return x; - } - else if (hx == 0x3FF00000 and ix << 32 == 0) { + } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } diff --git a/std/math/log10.zig b/std/math/log10.zig index aa74caa901..d9fa1dcb02 100644 --- a/std/math/log10.zig +++ b/std/math/log10.zig @@ -35,10 +35,10 @@ pub fn log10(x: var) @typeOf(x) { } pub fn log10_32(x_: f32) f32 { - const ivln10hi: f32 = 4.3432617188e-01; - const ivln10lo: f32 = -3.1689971365e-05; - const log10_2hi: f32 = 3.0102920532e-01; - const log10_2lo: f32 = 7.9034151668e-07; + const ivln10hi: f32 = 4.3432617188e-01; + const ivln10lo: f32 = -3.1689971365e-05; + const log10_2hi: f32 = 3.0102920532e-01; + const log10_2lo: f32 = 7.9034151668e-07; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; @@ -95,8 +95,8 @@ pub fn log10_32(x_: f32) f32 { } pub fn log10_64(x_: f64) f64 { - const ivln10hi: f64 = 4.34294481878168880939e-01; - const ivln10lo: f64 = 2.50829467116452752298e-11; + const ivln10hi: f64 = 4.34294481878168880939e-01; + const ivln10lo: f64 = 2.50829467116452752298e-11; const log10_2hi: f64 = 3.01029995663611771306e-01; const log10_2lo: f64 = 3.69423907715893078616e-13; const Lg1: f64 = 6.666666666666735130e-01; @@ -126,11 +126,9 @@ pub fn log10_64(x_: f64) f64 { k -= 54; x *= 0x1.0p54; hx = u32(@bitCast(u64, x) >> 32); - } - else if (hx >= 0x7FF00000) { + } else if (hx >= 0x7FF00000) { return x; - } - else if (hx == 0x3FF00000 and ix << 32 == 0) { + } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } diff --git a/std/math/log2.zig b/std/math/log2.zig index d5bbe385c2..22cc8082b3 100644 --- a/std/math/log2.zig +++ b/std/math/log2.zig @@ -27,7 +27,10 @@ pub fn log2(x: var) @typeOf(x) { TypeId.IntLiteral => comptime { var result = 0; var x_shifted = x; - while (b: {x_shifted >>= 1; break :b x_shifted != 0;}) : (result += 1) {} + while (b: { + x_shifted >>= 1; + break :b x_shifted != 0; + }) : (result += 1) {} return result; }, TypeId.Int => { @@ -38,7 +41,7 @@ pub fn log2(x: var) @typeOf(x) { } pub fn log2_32(x_: f32) f32 { - const ivln2hi: f32 = 1.4428710938e+00; + const ivln2hi: f32 = 1.4428710938e+00; const ivln2lo: f32 = -1.7605285393e-04; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; diff --git a/std/math/round.zig b/std/math/round.zig index c16190da21..c8d9eb4fd4 100644 --- a/std/math/round.zig +++ b/std/math/round.zig @@ -24,13 +24,13 @@ fn round32(x_: f32) f32 { const e = (u >> 23) & 0xFF; var y: f32 = undefined; - if (e >= 0x7F+23) { + if (e >= 0x7F + 23) { return x; } if (u >> 31 != 0) { x = -x; } - if (e < 0x7F-1) { + if (e < 0x7F - 1) { math.forceEval(x + math.f32_toint); return 0 * @bitCast(f32, u); } @@ -61,13 +61,13 @@ fn round64(x_: f64) f64 { const e = (u >> 52) & 0x7FF; var y: f64 = undefined; - if (e >= 0x3FF+52) { + if (e >= 0x3FF + 52) { return x; } if (u >> 63 != 0) { x = -x; } - if (e < 0x3ff-1) { + if (e < 0x3ff - 1) { math.forceEval(x + math.f64_toint); return 0 * @bitCast(f64, u); } diff --git a/std/math/sin.zig b/std/math/sin.zig index 5dd869545b..21c324e444 100644 --- a/std/math/sin.zig +++ b/std/math/sin.zig @@ -19,20 +19,20 @@ pub fn sin(x: var) @typeOf(x) { } // sin polynomial coefficients -const S0 = 1.58962301576546568060E-10; +const S0 = 1.58962301576546568060E-10; const S1 = -2.50507477628578072866E-8; -const S2 = 2.75573136213857245213E-6; +const S2 = 2.75573136213857245213E-6; const S3 = -1.98412698295895385996E-4; -const S4 = 8.33333333332211858878E-3; +const S4 = 8.33333333332211858878E-3; const S5 = -1.66666666666666307295E-1; // cos polynomial coeffiecients const C0 = -1.13585365213876817300E-11; -const C1 = 2.08757008419747316778E-9; +const C1 = 2.08757008419747316778E-9; const C2 = -2.75573141792967388112E-7; -const C3 = 2.48015872888517045348E-5; +const C3 = 2.48015872888517045348E-5; const C4 = -1.38888888888730564116E-3; -const C5 = 4.16666666666665929218E-2; +const C5 = 4.16666666666665929218E-2; // NOTE: This is taken from the go stdlib. The musl implementation is much more complex. // diff --git a/std/math/tan.zig b/std/math/tan.zig index 11428b6e8b..f578cf8156 100644 --- a/std/math/tan.zig +++ b/std/math/tan.zig @@ -19,12 +19,12 @@ pub fn tan(x: var) @typeOf(x) { } const Tp0 = -1.30936939181383777646E4; -const Tp1 = 1.15351664838587416140E6; +const Tp1 = 1.15351664838587416140E6; const Tp2 = -1.79565251976484877988E7; -const Tq1 = 1.36812963470692954678E4; +const Tq1 = 1.36812963470692954678E4; const Tq2 = -1.32089234440210967447E6; -const Tq3 = 2.50083801823357915839E7; +const Tq3 = 2.50083801823357915839E7; const Tq4 = -5.38695755929454629881E7; // NOTE: This is taken from the go stdlib. The musl implementation is much more complex. diff --git a/std/net.zig b/std/net.zig index 8e1b8d97b2..b1e291ab92 100644 --- a/std/net.zig +++ b/std/net.zig @@ -19,37 +19,29 @@ pub const Address = struct { os_addr: OsAddress, pub fn initIp4(ip4: u32, port: u16) Address { - return Address { - .os_addr = posix.sockaddr { - .in = posix.sockaddr_in { - .family = posix.AF_INET, - .port = std.mem.endianSwapIfLe(u16, port), - .addr = ip4, - .zero = []u8{0} ** 8, - }, - }, - }; + return Address{ .os_addr = posix.sockaddr{ .in = posix.sockaddr_in{ + .family = posix.AF_INET, + .port = std.mem.endianSwapIfLe(u16, port), + .addr = ip4, + .zero = []u8{0} ** 8, + } } }; } pub fn initIp6(ip6: &const Ip6Addr, port: u16) Address { - return Address { + return Address{ .family = posix.AF_INET6, - .os_addr = posix.sockaddr { - .in6 = posix.sockaddr_in6 { - .family = posix.AF_INET6, - .port = std.mem.endianSwapIfLe(u16, port), - .flowinfo = 0, - .addr = ip6.addr, - .scope_id = ip6.scope_id, - }, - }, + .os_addr = posix.sockaddr{ .in6 = posix.sockaddr_in6{ + .family = posix.AF_INET6, + .port = std.mem.endianSwapIfLe(u16, port), + .flowinfo = 0, + .addr = ip6.addr, + .scope_id = ip6.scope_id, + } }, }; } pub fn initPosix(addr: &const posix.sockaddr) Address { - return Address { - .os_addr = *addr, - }; + return Address{ .os_addr = addr.* }; } pub fn format(self: &const Address, out_stream: var) !void { @@ -98,7 +90,7 @@ pub fn parseIp4(buf: []const u8) !u32 { } } else { return error.InvalidCharacter; - } + } } if (index == 3 and saw_any_digits) { out_ptr[index] = x; diff --git a/std/os/child_process.zig b/std/os/child_process.zig index 8bb8b2d7e7..6c0c21f64a 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -49,7 +49,7 @@ pub const ChildProcess = struct { err_pipe: if (is_windows) void else [2]i32, llnode: if (is_windows) void else LinkedList(&ChildProcess).Node, - pub const SpawnError = error { + pub const SpawnError = error{ ProcessFdQuotaExceeded, Unexpected, NotDir, @@ -88,7 +88,7 @@ pub const ChildProcess = struct { const child = try allocator.create(ChildProcess); errdefer allocator.destroy(child); - *child = ChildProcess { + child.* = ChildProcess{ .allocator = allocator, .argv = argv, .pid = undefined, @@ -99,8 +99,10 @@ pub const ChildProcess = struct { .term = null, .env_map = null, .cwd = null, - .uid = if (is_windows) {} else null, - .gid = if (is_windows) {} else null, + .uid = if (is_windows) {} else + null, + .gid = if (is_windows) {} else + null, .stdin = null, .stdout = null, .stderr = null, @@ -193,9 +195,7 @@ pub const ChildProcess = struct { /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns. /// If it succeeds, the caller owns result.stdout and result.stderr memory. - pub fn exec(allocator: &mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, - env_map: ?&const BufMap, max_output_size: usize) !ExecResult - { + pub fn exec(allocator: &mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, env_map: ?&const BufMap, max_output_size: usize) !ExecResult { const child = try ChildProcess.init(argv, allocator); defer child.deinit(); @@ -218,7 +218,7 @@ pub const ChildProcess = struct { try stdout_file_in_stream.stream.readAllBuffer(&stdout, max_output_size); try stderr_file_in_stream.stream.readAllBuffer(&stderr, max_output_size); - return ExecResult { + return ExecResult{ .term = try child.wait(), .stdout = stdout.toOwnedSlice(), .stderr = stderr.toOwnedSlice(), @@ -255,9 +255,9 @@ pub const ChildProcess = struct { self.term = (SpawnError!Term)(x: { var exit_code: windows.DWORD = undefined; if (windows.GetExitCodeProcess(self.handle, &exit_code) == 0) { - break :x Term { .Unknown = 0 }; + break :x Term{ .Unknown = 0 }; } else { - break :x Term { .Exited = @bitCast(i32, exit_code)}; + break :x Term{ .Exited = @bitCast(i32, exit_code) }; } }); @@ -288,9 +288,18 @@ pub const ChildProcess = struct { } fn cleanupStreams(self: &ChildProcess) void { - if (self.stdin) |*stdin| { stdin.close(); self.stdin = null; } - if (self.stdout) |*stdout| { stdout.close(); self.stdout = null; } - if (self.stderr) |*stderr| { stderr.close(); self.stderr = null; } + if (self.stdin) |*stdin| { + stdin.close(); + self.stdin = null; + } + if (self.stdout) |*stdout| { + stdout.close(); + self.stdout = null; + } + if (self.stderr) |*stderr| { + stderr.close(); + self.stderr = null; + } } fn cleanupAfterWait(self: &ChildProcess, status: i32) !Term { @@ -317,25 +326,30 @@ pub const ChildProcess = struct { fn statusToTerm(status: i32) Term { return if (posix.WIFEXITED(status)) - Term { .Exited = posix.WEXITSTATUS(status) } + Term{ .Exited = posix.WEXITSTATUS(status) } else if (posix.WIFSIGNALED(status)) - Term { .Signal = posix.WTERMSIG(status) } + Term{ .Signal = posix.WTERMSIG(status) } else if (posix.WIFSTOPPED(status)) - Term { .Stopped = posix.WSTOPSIG(status) } + Term{ .Stopped = posix.WSTOPSIG(status) } else - Term { .Unknown = status } - ; + Term{ .Unknown = status }; } fn spawnPosix(self: &ChildProcess) !void { const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try makePipe() else undefined; - errdefer if (self.stdin_behavior == StdIo.Pipe) { destroyPipe(stdin_pipe); }; + errdefer if (self.stdin_behavior == StdIo.Pipe) { + destroyPipe(stdin_pipe); + }; const stdout_pipe = if (self.stdout_behavior == StdIo.Pipe) try makePipe() else undefined; - errdefer if (self.stdout_behavior == StdIo.Pipe) { destroyPipe(stdout_pipe); }; + errdefer if (self.stdout_behavior == StdIo.Pipe) { + destroyPipe(stdout_pipe); + }; const stderr_pipe = if (self.stderr_behavior == StdIo.Pipe) try makePipe() else undefined; - errdefer if (self.stderr_behavior == StdIo.Pipe) { destroyPipe(stderr_pipe); }; + errdefer if (self.stderr_behavior == StdIo.Pipe) { + destroyPipe(stderr_pipe); + }; const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const dev_null_fd = if (any_ignore) blk: { @@ -346,7 +360,9 @@ pub const ChildProcess = struct { } else blk: { break :blk undefined; }; - defer { if (any_ignore) os.close(dev_null_fd); } + defer { + if (any_ignore) os.close(dev_null_fd); + } var env_map_owned: BufMap = undefined; var we_own_env_map: bool = undefined; @@ -358,7 +374,9 @@ pub const ChildProcess = struct { env_map_owned = try os.getEnvMap(self.allocator); break :x &env_map_owned; }; - defer { if (we_own_env_map) env_map_owned.deinit(); } + defer { + if (we_own_env_map) env_map_owned.deinit(); + } // This pipe is used to communicate errors between the time of fork // and execve from the child process to the parent process. @@ -369,23 +387,21 @@ pub const ChildProcess = struct { const pid_err = posix.getErrno(pid_result); if (pid_err > 0) { return switch (pid_err) { - posix.EAGAIN, posix.ENOMEM, posix.ENOSYS => error.SystemResources, + posix.EAGAIN, + posix.ENOMEM, + posix.ENOSYS => error.SystemResources, else => os.unexpectedErrorPosix(pid_err), }; } if (pid_result == 0) { // we are the child - setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch - |err| forkChildErrReport(err_pipe[1], err); - setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch - |err| forkChildErrReport(err_pipe[1], err); - setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch - |err| forkChildErrReport(err_pipe[1], err); + setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); + setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); + setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); if (self.cwd) |cwd| { - os.changeCurDir(self.allocator, cwd) catch - |err| forkChildErrReport(err_pipe[1], err); + os.changeCurDir(self.allocator, cwd) catch |err| forkChildErrReport(err_pipe[1], err); } if (self.gid) |gid| { @@ -396,8 +412,7 @@ pub const ChildProcess = struct { os.posix_setreuid(uid, uid) catch |err| forkChildErrReport(err_pipe[1], err); } - os.posixExecve(self.argv, env_map, self.allocator) catch - |err| forkChildErrReport(err_pipe[1], err); + os.posixExecve(self.argv, env_map, self.allocator) catch |err| forkChildErrReport(err_pipe[1], err); } // we are the parent @@ -423,37 +438,41 @@ pub const ChildProcess = struct { self.llnode = LinkedList(&ChildProcess).Node.init(self); self.term = null; - if (self.stdin_behavior == StdIo.Pipe) { os.close(stdin_pipe[0]); } - if (self.stdout_behavior == StdIo.Pipe) { os.close(stdout_pipe[1]); } - if (self.stderr_behavior == StdIo.Pipe) { os.close(stderr_pipe[1]); } + if (self.stdin_behavior == StdIo.Pipe) { + os.close(stdin_pipe[0]); + } + if (self.stdout_behavior == StdIo.Pipe) { + os.close(stdout_pipe[1]); + } + if (self.stderr_behavior == StdIo.Pipe) { + os.close(stderr_pipe[1]); + } } fn spawnWindows(self: &ChildProcess) !void { - const saAttr = windows.SECURITY_ATTRIBUTES { + const saAttr = windows.SECURITY_ATTRIBUTES{ .nLength = @sizeOf(windows.SECURITY_ATTRIBUTES), .bInheritHandle = windows.TRUE, .lpSecurityDescriptor = null, }; - const any_ignore = (self.stdin_behavior == StdIo.Ignore or - self.stdout_behavior == StdIo.Ignore or - self.stderr_behavior == StdIo.Ignore); + const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const nul_handle = if (any_ignore) blk: { const nul_file_path = "NUL"; var fixed_buffer_mem: [nul_file_path.len + 1]u8 = undefined; var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]); - break :blk try os.windowsOpen(&fixed_allocator.allocator, "NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ, - windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL); + break :blk try os.windowsOpen(&fixed_allocator.allocator, "NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL); } else blk: { break :blk undefined; }; - defer { if (any_ignore) os.close(nul_handle); } + defer { + if (any_ignore) os.close(nul_handle); + } if (any_ignore) { try windowsSetHandleInfo(nul_handle, windows.HANDLE_FLAG_INHERIT, 0); } - var g_hChildStd_IN_Rd: ?windows.HANDLE = null; var g_hChildStd_IN_Wr: ?windows.HANDLE = null; switch (self.stdin_behavior) { @@ -470,7 +489,9 @@ pub const ChildProcess = struct { g_hChildStd_IN_Rd = null; }, } - errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_IN_Rd, g_hChildStd_IN_Wr); }; + errdefer if (self.stdin_behavior == StdIo.Pipe) { + windowsDestroyPipe(g_hChildStd_IN_Rd, g_hChildStd_IN_Wr); + }; var g_hChildStd_OUT_Rd: ?windows.HANDLE = null; var g_hChildStd_OUT_Wr: ?windows.HANDLE = null; @@ -488,7 +509,9 @@ pub const ChildProcess = struct { g_hChildStd_OUT_Wr = null; }, } - errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_OUT_Rd, g_hChildStd_OUT_Wr); }; + errdefer if (self.stdin_behavior == StdIo.Pipe) { + windowsDestroyPipe(g_hChildStd_OUT_Rd, g_hChildStd_OUT_Wr); + }; var g_hChildStd_ERR_Rd: ?windows.HANDLE = null; var g_hChildStd_ERR_Wr: ?windows.HANDLE = null; @@ -506,12 +529,14 @@ pub const ChildProcess = struct { g_hChildStd_ERR_Wr = null; }, } - errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_ERR_Rd, g_hChildStd_ERR_Wr); }; + errdefer if (self.stdin_behavior == StdIo.Pipe) { + windowsDestroyPipe(g_hChildStd_ERR_Rd, g_hChildStd_ERR_Wr); + }; const cmd_line = try windowsCreateCommandLine(self.allocator, self.argv); defer self.allocator.free(cmd_line); - var siStartInfo = windows.STARTUPINFOA { + var siStartInfo = windows.STARTUPINFOA{ .cb = @sizeOf(windows.STARTUPINFOA), .hStdError = g_hChildStd_ERR_Wr, .hStdOutput = g_hChildStd_OUT_Wr, @@ -534,19 +559,11 @@ pub const ChildProcess = struct { }; var piProcInfo: windows.PROCESS_INFORMATION = undefined; - const cwd_slice = if (self.cwd) |cwd| - try cstr.addNullByte(self.allocator, cwd) - else - null - ; + const cwd_slice = if (self.cwd) |cwd| try cstr.addNullByte(self.allocator, cwd) else null; defer if (cwd_slice) |cwd| self.allocator.free(cwd); const cwd_ptr = if (cwd_slice) |cwd| cwd.ptr else null; - const maybe_envp_buf = if (self.env_map) |env_map| - try os.createWindowsEnvBlock(self.allocator, env_map) - else - null - ; + const maybe_envp_buf = if (self.env_map) |env_map| try os.createWindowsEnvBlock(self.allocator, env_map) else null; defer if (maybe_envp_buf) |envp_buf| self.allocator.free(envp_buf); const envp_ptr = if (maybe_envp_buf) |envp_buf| envp_buf.ptr else null; @@ -563,11 +580,8 @@ pub const ChildProcess = struct { }; defer self.allocator.free(app_name); - windowsCreateProcess(app_name.ptr, cmd_line.ptr, envp_ptr, cwd_ptr, - &siStartInfo, &piProcInfo) catch |no_path_err| - { - if (no_path_err != error.FileNotFound) - return no_path_err; + windowsCreateProcess(app_name.ptr, cmd_line.ptr, envp_ptr, cwd_ptr, &siStartInfo, &piProcInfo) catch |no_path_err| { + if (no_path_err != error.FileNotFound) return no_path_err; const PATH = try os.getEnvVarOwned(self.allocator, "PATH"); defer self.allocator.free(PATH); @@ -577,9 +591,7 @@ pub const ChildProcess = struct { const joined_path = try os.path.join(self.allocator, search_path, app_name); defer self.allocator.free(joined_path); - if (windowsCreateProcess(joined_path.ptr, cmd_line.ptr, envp_ptr, cwd_ptr, - &siStartInfo, &piProcInfo)) |_| - { + if (windowsCreateProcess(joined_path.ptr, cmd_line.ptr, envp_ptr, cwd_ptr, &siStartInfo, &piProcInfo)) |_| { break; } else |err| if (err == error.FileNotFound) { continue; @@ -609,9 +621,15 @@ pub const ChildProcess = struct { self.thread_handle = piProcInfo.hThread; self.term = null; - if (self.stdin_behavior == StdIo.Pipe) { os.close(??g_hChildStd_IN_Rd); } - if (self.stderr_behavior == StdIo.Pipe) { os.close(??g_hChildStd_ERR_Wr); } - if (self.stdout_behavior == StdIo.Pipe) { os.close(??g_hChildStd_OUT_Wr); } + if (self.stdin_behavior == StdIo.Pipe) { + os.close(??g_hChildStd_IN_Rd); + } + if (self.stderr_behavior == StdIo.Pipe) { + os.close(??g_hChildStd_ERR_Wr); + } + if (self.stdout_behavior == StdIo.Pipe) { + os.close(??g_hChildStd_OUT_Wr); + } } fn setUpChildIo(stdio: StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) !void { @@ -622,18 +640,14 @@ pub const ChildProcess = struct { StdIo.Ignore => try os.posixDup2(dev_null_fd, std_fileno), } } - }; -fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?&u8, - lpStartupInfo: &windows.STARTUPINFOA, lpProcessInformation: &windows.PROCESS_INFORMATION) !void -{ - if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, - @ptrCast(?&c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) - { +fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?&u8, lpStartupInfo: &windows.STARTUPINFOA, lpProcessInformation: &windows.PROCESS_INFORMATION) !void { + if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?&c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) { const err = windows.GetLastError(); return switch (err) { - windows.ERROR.FILE_NOT_FOUND, windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, + windows.ERROR.FILE_NOT_FOUND, + windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, windows.ERROR.INVALID_PARAMETER => unreachable, windows.ERROR.INVALID_NAME => error.InvalidName, else => os.unexpectedErrorWindows(err), @@ -641,9 +655,6 @@ fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ? } } - - - /// Caller must dealloc. /// Guarantees a null byte at result[result.len]. fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) ![]u8 { @@ -651,8 +662,7 @@ fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) defer buf.deinit(); for (argv) |arg, arg_i| { - if (arg_i != 0) - try buf.appendByte(' '); + if (arg_i != 0) try buf.appendByte(' '); if (mem.indexOfAny(u8, arg, " \t\n\"") == null) { try buf.append(arg); continue; @@ -686,7 +696,6 @@ fn windowsDestroyPipe(rd: ?windows.HANDLE, wr: ?windows.HANDLE) void { if (wr) |h| os.close(h); } - // TODO: workaround for bug where the `const` from `&const` is dropped when the type is // a namespace field lookup const SECURITY_ATTRIBUTES = windows.SECURITY_ATTRIBUTES; @@ -715,8 +724,8 @@ fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const S try windowsMakePipe(&rd_h, &wr_h, sattr); errdefer windowsDestroyPipe(rd_h, wr_h); try windowsSetHandleInfo(wr_h, windows.HANDLE_FLAG_INHERIT, 0); - *rd = rd_h; - *wr = wr_h; + rd.* = rd_h; + wr.* = wr_h; } fn windowsMakePipeOut(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) !void { @@ -725,8 +734,8 @@ fn windowsMakePipeOut(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const try windowsMakePipe(&rd_h, &wr_h, sattr); errdefer windowsDestroyPipe(rd_h, wr_h); try windowsSetHandleInfo(rd_h, windows.HANDLE_FLAG_INHERIT, 0); - *rd = rd_h; - *wr = wr_h; + rd.* = rd_h; + wr.* = wr_h; } fn makePipe() ![2]i32 { @@ -734,7 +743,8 @@ fn makePipe() ![2]i32 { const err = posix.getErrno(posix.pipe(&fds)); if (err > 0) { return switch (err) { - posix.EMFILE, posix.ENFILE => error.SystemResources, + posix.EMFILE, + posix.ENFILE => error.SystemResources, else => os.unexpectedErrorPosix(err), }; } @@ -742,8 +752,8 @@ fn makePipe() ![2]i32 { } fn destroyPipe(pipe: &const [2]i32) void { - os.close((*pipe)[0]); - os.close((*pipe)[1]); + os.close((pipe.*)[0]); + os.close((pipe.*)[1]); } // Child of fork calls this to report an error to the fork parent. diff --git a/std/segmented_list.zig b/std/segmented_list.zig index 6c7c879919..e9abc7adf9 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -93,7 +93,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type /// Deinitialize with `deinit` pub fn init(allocator: &Allocator) Self { - return Self { + return Self{ .allocator = allocator, .len = 0, .prealloc_segment = undefined, @@ -104,7 +104,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type pub fn deinit(self: &Self) void { self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0); self.allocator.free(self.dynamic_segments); - *self = undefined; + self.* = undefined; } pub fn at(self: &Self, i: usize) &T { @@ -118,7 +118,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type pub fn push(self: &Self, item: &const T) !void { const new_item_ptr = try self.addOne(); - *new_item_ptr = *item; + new_item_ptr.* = item.*; } pub fn pushMany(self: &Self, items: []const T) !void { @@ -128,11 +128,10 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } pub fn pop(self: &Self) ?T { - if (self.len == 0) - return null; + if (self.len == 0) return null; const index = self.len - 1; - const result = *self.uncheckedAt(index); + const result = self.uncheckedAt(index).*; self.len = index; return result; } @@ -245,8 +244,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type shelf_size: usize, pub fn next(it: &Iterator) ?&T { - if (it.index >= it.list.len) - return null; + if (it.index >= it.list.len) return null; if (it.index < prealloc_item_count) { const ptr = &it.list.prealloc_segment[it.index]; it.index += 1; @@ -270,12 +268,10 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } pub fn prev(it: &Iterator) ?&T { - if (it.index == 0) - return null; + if (it.index == 0) return null; it.index -= 1; - if (it.index < prealloc_item_count) - return &it.list.prealloc_segment[it.index]; + if (it.index < prealloc_item_count) return &it.list.prealloc_segment[it.index]; if (it.box_index == 0) { it.shelf_index -= 1; @@ -290,7 +286,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type }; pub fn iterator(self: &Self, start_index: usize) Iterator { - var it = Iterator { + var it = Iterator{ .list = self, .index = start_index, .shelf_index = undefined, @@ -324,25 +320,31 @@ fn testSegmentedList(comptime prealloc: usize, allocator: &Allocator) !void { var list = SegmentedList(i32, prealloc).init(allocator); defer list.deinit(); - {var i: usize = 0; while (i < 100) : (i += 1) { - try list.push(i32(i + 1)); - assert(list.len == i + 1); - }} + { + var i: usize = 0; + while (i < 100) : (i += 1) { + try list.push(i32(i + 1)); + assert(list.len == i + 1); + } + } - {var i: usize = 0; while (i < 100) : (i += 1) { - assert(*list.at(i) == i32(i + 1)); - }} + { + var i: usize = 0; + while (i < 100) : (i += 1) { + assert(list.at(i).* == i32(i + 1)); + } + } { var it = list.iterator(0); var x: i32 = 0; while (it.next()) |item| { x += 1; - assert(*item == x); + assert(item.* == x); } assert(x == 100); while (it.prev()) |item| : (x -= 1) { - assert(*item == x); + assert(item.* == x); } assert(x == 0); } @@ -350,14 +352,18 @@ fn testSegmentedList(comptime prealloc: usize, allocator: &Allocator) !void { assert(??list.pop() == 100); assert(list.len == 99); - try list.pushMany([]i32 { 1, 2, 3 }); + try list.pushMany([]i32{ + 1, + 2, + 3, + }); assert(list.len == 102); assert(??list.pop() == 3); assert(??list.pop() == 2); assert(??list.pop() == 1); assert(list.len == 99); - try list.pushMany([]const i32 {}); + try list.pushMany([]const i32{}); assert(list.len == 99); var i: i32 = 99; diff --git a/std/sort.zig b/std/sort.zig index 0f83df7bb4..4cc7ad503a 100644 --- a/std/sort.zig +++ b/std/sort.zig @@ -5,15 +5,18 @@ const math = std.math; const builtin = @import("builtin"); /// Stable in-place sort. O(n) best case, O(pow(n, 2)) worst case. O(1) memory (no allocator required). -pub fn insertionSort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool) void { - {var i: usize = 1; while (i < items.len) : (i += 1) { - const x = items[i]; - var j: usize = i; - while (j > 0 and lessThan(x, items[j - 1])) : (j -= 1) { - items[j] = items[j - 1]; +pub fn insertionSort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) void { + { + var i: usize = 1; + while (i < items.len) : (i += 1) { + const x = items[i]; + var j: usize = i; + while (j > 0 and lessThan(x, items[j - 1])) : (j -= 1) { + items[j] = items[j - 1]; + } + items[j] = x; } - items[j] = x; - }} + } } const Range = struct { @@ -21,7 +24,10 @@ const Range = struct { end: usize, fn init(start: usize, end: usize) Range { - return Range { .start = start, .end = end }; + return Range{ + .start = start, + .end = end, + }; } fn length(self: &const Range) usize { @@ -29,7 +35,6 @@ const Range = struct { } }; - const Iterator = struct { size: usize, power_of_two: usize, @@ -42,7 +47,7 @@ const Iterator = struct { fn init(size2: usize, min_level: usize) Iterator { const power_of_two = math.floorPowerOfTwo(usize, size2); const denominator = power_of_two / min_level; - return Iterator { + return Iterator{ .numerator = 0, .decimal = 0, .size = size2, @@ -68,7 +73,10 @@ const Iterator = struct { self.decimal += 1; } - return Range {.start = start, .end = self.decimal}; + return Range{ + .start = start, + .end = self.decimal, + }; } fn finished(self: &Iterator) bool { @@ -100,7 +108,7 @@ const Pull = struct { /// Stable in-place sort. O(n) best case, O(n*log(n)) worst case and average case. O(1) memory (no allocator required). /// Currently implemented as block sort. -pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool) void { +pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) void { // Implementation ported from https://github.com/BonzaiThePenguin/WikiSort/blob/master/WikiSort.c var cache: [512]T = undefined; @@ -123,7 +131,16 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // http://pages.ripco.net/~jgamble/nw.html var iterator = Iterator.init(items.len, 4); while (!iterator.finished()) { - var order = []u8{0, 1, 2, 3, 4, 5, 6, 7}; + var order = []u8{ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; const range = iterator.nextRange(); const sliced_items = items[range.start..]; @@ -149,56 +166,56 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons swap(T, sliced_items, lessThan, &order, 3, 5); swap(T, sliced_items, lessThan, &order, 3, 4); }, - 7 => { - swap(T, sliced_items, lessThan, &order, 1, 2); - swap(T, sliced_items, lessThan, &order, 3, 4); - swap(T, sliced_items, lessThan, &order, 5, 6); - swap(T, sliced_items, lessThan, &order, 0, 2); - swap(T, sliced_items, lessThan, &order, 3, 5); - swap(T, sliced_items, lessThan, &order, 4, 6); - swap(T, sliced_items, lessThan, &order, 0, 1); - swap(T, sliced_items, lessThan, &order, 4, 5); - swap(T, sliced_items, lessThan, &order, 2, 6); - swap(T, sliced_items, lessThan, &order, 0, 4); - swap(T, sliced_items, lessThan, &order, 1, 5); - swap(T, sliced_items, lessThan, &order, 0, 3); - swap(T, sliced_items, lessThan, &order, 2, 5); - swap(T, sliced_items, lessThan, &order, 1, 3); - swap(T, sliced_items, lessThan, &order, 2, 4); - swap(T, sliced_items, lessThan, &order, 2, 3); - }, - 6 => { - swap(T, sliced_items, lessThan, &order, 1, 2); - swap(T, sliced_items, lessThan, &order, 4, 5); - swap(T, sliced_items, lessThan, &order, 0, 2); - swap(T, sliced_items, lessThan, &order, 3, 5); - swap(T, sliced_items, lessThan, &order, 0, 1); - swap(T, sliced_items, lessThan, &order, 3, 4); - swap(T, sliced_items, lessThan, &order, 2, 5); - swap(T, sliced_items, lessThan, &order, 0, 3); - swap(T, sliced_items, lessThan, &order, 1, 4); - swap(T, sliced_items, lessThan, &order, 2, 4); - swap(T, sliced_items, lessThan, &order, 1, 3); - swap(T, sliced_items, lessThan, &order, 2, 3); - }, - 5 => { - swap(T, sliced_items, lessThan, &order, 0, 1); - swap(T, sliced_items, lessThan, &order, 3, 4); - swap(T, sliced_items, lessThan, &order, 2, 4); - swap(T, sliced_items, lessThan, &order, 2, 3); - swap(T, sliced_items, lessThan, &order, 1, 4); - swap(T, sliced_items, lessThan, &order, 0, 3); - swap(T, sliced_items, lessThan, &order, 0, 2); - swap(T, sliced_items, lessThan, &order, 1, 3); - swap(T, sliced_items, lessThan, &order, 1, 2); - }, - 4 => { - swap(T, sliced_items, lessThan, &order, 0, 1); - swap(T, sliced_items, lessThan, &order, 2, 3); - swap(T, sliced_items, lessThan, &order, 0, 2); - swap(T, sliced_items, lessThan, &order, 1, 3); - swap(T, sliced_items, lessThan, &order, 1, 2); - }, + 7 => { + swap(T, sliced_items, lessThan, &order, 1, 2); + swap(T, sliced_items, lessThan, &order, 3, 4); + swap(T, sliced_items, lessThan, &order, 5, 6); + swap(T, sliced_items, lessThan, &order, 0, 2); + swap(T, sliced_items, lessThan, &order, 3, 5); + swap(T, sliced_items, lessThan, &order, 4, 6); + swap(T, sliced_items, lessThan, &order, 0, 1); + swap(T, sliced_items, lessThan, &order, 4, 5); + swap(T, sliced_items, lessThan, &order, 2, 6); + swap(T, sliced_items, lessThan, &order, 0, 4); + swap(T, sliced_items, lessThan, &order, 1, 5); + swap(T, sliced_items, lessThan, &order, 0, 3); + swap(T, sliced_items, lessThan, &order, 2, 5); + swap(T, sliced_items, lessThan, &order, 1, 3); + swap(T, sliced_items, lessThan, &order, 2, 4); + swap(T, sliced_items, lessThan, &order, 2, 3); + }, + 6 => { + swap(T, sliced_items, lessThan, &order, 1, 2); + swap(T, sliced_items, lessThan, &order, 4, 5); + swap(T, sliced_items, lessThan, &order, 0, 2); + swap(T, sliced_items, lessThan, &order, 3, 5); + swap(T, sliced_items, lessThan, &order, 0, 1); + swap(T, sliced_items, lessThan, &order, 3, 4); + swap(T, sliced_items, lessThan, &order, 2, 5); + swap(T, sliced_items, lessThan, &order, 0, 3); + swap(T, sliced_items, lessThan, &order, 1, 4); + swap(T, sliced_items, lessThan, &order, 2, 4); + swap(T, sliced_items, lessThan, &order, 1, 3); + swap(T, sliced_items, lessThan, &order, 2, 3); + }, + 5 => { + swap(T, sliced_items, lessThan, &order, 0, 1); + swap(T, sliced_items, lessThan, &order, 3, 4); + swap(T, sliced_items, lessThan, &order, 2, 4); + swap(T, sliced_items, lessThan, &order, 2, 3); + swap(T, sliced_items, lessThan, &order, 1, 4); + swap(T, sliced_items, lessThan, &order, 0, 3); + swap(T, sliced_items, lessThan, &order, 0, 2); + swap(T, sliced_items, lessThan, &order, 1, 3); + swap(T, sliced_items, lessThan, &order, 1, 2); + }, + 4 => { + swap(T, sliced_items, lessThan, &order, 0, 1); + swap(T, sliced_items, lessThan, &order, 2, 3); + swap(T, sliced_items, lessThan, &order, 0, 2); + swap(T, sliced_items, lessThan, &order, 1, 3); + swap(T, sliced_items, lessThan, &order, 1, 2); + }, else => {}, } } @@ -273,7 +290,6 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // we merged two levels at the same time, so we're done with this level already // (iterator.nextLevel() is called again at the bottom of this outer merge loop) _ = iterator.nextLevel(); - } else { iterator.begin(); while (!iterator.finished()) { @@ -303,7 +319,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // 8. redistribute the two internal buffers back into the items var block_size: usize = math.sqrt(iterator.length()); - var buffer_size = iterator.length()/block_size + 1; + var buffer_size = iterator.length() / block_size + 1; // as an optimization, we really only need to pull out the internal buffers once for each level of merges // after that we can reuse the same buffers over and over, then redistribute it when we're finished with this level @@ -316,8 +332,18 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons var start: usize = 0; var pull_index: usize = 0; var pull = []Pull{ - Pull {.from = 0, .to = 0, .count = 0, .range = Range.init(0, 0),}, - Pull {.from = 0, .to = 0, .count = 0, .range = Range.init(0, 0),}, + Pull{ + .from = 0, + .to = 0, + .count = 0, + .range = Range.init(0, 0), + }, + Pull{ + .from = 0, + .to = 0, + .count = 0, + .range = Range.init(0, 0), + }, }; var buffer1 = Range.init(0, 0); @@ -355,7 +381,10 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // these values will be pulled out to the start of A last = A.start; count = 1; - while (count < find) : ({last = index; count += 1;}) { + while (count < find) : ({ + last = index; + count += 1; + }) { index = findLastForward(T, items, items[last], Range.init(last + 1, A.end), lessThan, find - count); if (index == A.end) break; } @@ -363,7 +392,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons if (count >= buffer_size) { // keep track of the range within the items where we'll need to "pull out" these values to create the internal buffer - pull[pull_index] = Pull { + pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, @@ -398,7 +427,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons } else if (pull_index == 0 and count > buffer1.length()) { // keep track of the largest buffer we were able to find buffer1 = Range.init(A.start, A.start + count); - pull[pull_index] = Pull { + pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, @@ -410,7 +439,10 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // these values will be pulled out to the end of B last = B.end - 1; count = 1; - while (count < find) : ({last = index - 1; count += 1;}) { + while (count < find) : ({ + last = index - 1; + count += 1; + }) { index = findFirstBackward(T, items, items[last], Range.init(B.start, last), lessThan, find - count); if (index == B.start) break; } @@ -418,7 +450,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons if (count >= buffer_size) { // keep track of the range within the items where we'll need to "pull out" these values to create the internal buffe - pull[pull_index] = Pull { + pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, @@ -457,7 +489,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons } else if (pull_index == 0 and count > buffer1.length()) { // keep track of the largest buffer we were able to find buffer1 = Range.init(B.end - count, B.end); - pull[pull_index] = Pull { + pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, @@ -496,7 +528,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // adjust block_size and buffer_size based on the values we were able to pull out buffer_size = buffer1.length(); - block_size = iterator.length()/buffer_size + 1; + block_size = iterator.length() / buffer_size + 1; // the first buffer NEEDS to be large enough to tag each of the evenly sized A blocks, // so this was originally here to test the math for adjusting block_size above @@ -547,7 +579,10 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // swap the first value of each A block with the value in buffer1 var indexA = buffer1.start; index = firstA.end; - while (index < blockA.end) : ({indexA += 1; index += block_size;}) { + while (index < blockA.end) : ({ + indexA += 1; + index += block_size; + }) { mem.swap(T, &items[indexA], &items[index]); } @@ -626,9 +661,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // if there are no more A blocks remaining, this step is finished! blockA.start += block_size; - if (blockA.length() == 0) - break; - + if (blockA.length() == 0) break; } else if (blockB.length() < block_size) { // move the last B block, which is unevenly sized, to before the remaining A blocks, by using a rotation // the cache is disabled here since it might contain the contents of the previous A block @@ -709,7 +742,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons } // merge operation without a buffer -fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const Range, lessThan: fn(&const T,&const T)bool) void { +fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const Range, lessThan: fn(&const T, &const T) bool) void { if (A_arg.length() == 0 or B_arg.length() == 0) return; // this just repeatedly binary searches into B and rotates A into position. @@ -730,8 +763,8 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const // again, this is NOT a general-purpose solution – it only works well in this case! // kind of like how the O(n^2) insertion sort is used in some places - var A = *A_arg; - var B = *B_arg; + var A = A_arg.*; + var B = B_arg.*; while (true) { // find the first place in B where the first item in A needs to be inserted @@ -751,7 +784,7 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const } // merge operation using an internal buffer -fn mergeInternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T,&const T)bool, buffer: &const Range) void { +fn mergeInternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, buffer: &const Range) void { // whenever we find a value to add to the final array, swap it with the value that's already in that spot // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order var A_count: usize = 0; @@ -787,9 +820,9 @@ fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_s // combine a linear search with a binary search to reduce the number of comparisons in situations // where have some idea as to how many unique values there are and where the next value might be -fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool, unique: usize) usize { +fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length()/unique, usize(1)); + const skip = math.max(range.length() / unique, usize(1)); var index = range.start + skip; while (lessThan(items[index - 1], value)) : (index += skip) { @@ -801,9 +834,9 @@ fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const return binaryFirst(T, items, value, Range.init(index - skip, index), lessThan); } -fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool, unique: usize) usize { +fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length()/unique, usize(1)); + const skip = math.max(range.length() / unique, usize(1)); var index = range.end - skip; while (index > range.start and !lessThan(items[index - 1], value)) : (index -= skip) { @@ -815,9 +848,9 @@ fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &cons return binaryFirst(T, items, value, Range.init(index, index + skip), lessThan); } -fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool, unique: usize) usize { +fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length()/unique, usize(1)); + const skip = math.max(range.length() / unique, usize(1)); var index = range.start + skip; while (!lessThan(value, items[index - 1])) : (index += skip) { @@ -829,9 +862,9 @@ fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const return binaryLast(T, items, value, Range.init(index - skip, index), lessThan); } -fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool, unique: usize) usize { +fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length()/unique, usize(1)); + const skip = math.max(range.length() / unique, usize(1)); var index = range.end - skip; while (index > range.start and lessThan(value, items[index - 1])) : (index -= skip) { @@ -843,12 +876,12 @@ fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const return binaryLast(T, items, value, Range.init(index, index + skip), lessThan); } -fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool) usize { +fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool) usize { var start = range.start; var end = range.end - 1; if (range.start >= range.end) return range.end; while (start < end) { - const mid = start + (end - start)/2; + const mid = start + (end - start) / 2; if (lessThan(items[mid], value)) { start = mid + 1; } else { @@ -861,12 +894,12 @@ fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Rang return start; } -fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool) usize { +fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool) usize { var start = range.start; var end = range.end - 1; if (range.start >= range.end) return range.end; while (start < end) { - const mid = start + (end - start)/2; + const mid = start + (end - start) / 2; if (!lessThan(value, items[mid])) { start = mid + 1; } else { @@ -879,7 +912,7 @@ fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range return start; } -fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, lessThan: fn(&const T,&const T)bool, into: []T) void { +fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, into: []T) void { var A_index: usize = A.start; var B_index: usize = B.start; const A_last = A.end; @@ -909,7 +942,7 @@ fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, less } } -fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T,&const T)bool, cache: []T) void { +fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, cache: []T) void { // A fits into the cache, so use that instead of the internal buffer var A_index: usize = 0; var B_index: usize = B.start; @@ -937,29 +970,27 @@ fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, mem.copy(T, items[insert_index..], cache[A_index..A_last]); } -fn swap(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool, order: &[8]u8, x: usize, y: usize) void { - if (lessThan(items[y], items[x]) or - ((*order)[x] > (*order)[y] and !lessThan(items[x], items[y]))) - { +fn swap(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool, order: &[8]u8, x: usize, y: usize) void { + if (lessThan(items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(items[x], items[y]))) { mem.swap(T, &items[x], &items[y]); - mem.swap(u8, &(*order)[x], &(*order)[y]); + mem.swap(u8, &(order.*)[x], &(order.*)[y]); } } fn i32asc(lhs: &const i32, rhs: &const i32) bool { - return *lhs < *rhs; + return lhs.* < rhs.*; } fn i32desc(lhs: &const i32, rhs: &const i32) bool { - return *rhs < *lhs; + return rhs.* < lhs.*; } fn u8asc(lhs: &const u8, rhs: &const u8) bool { - return *lhs < *rhs; + return lhs.* < rhs.*; } fn u8desc(lhs: &const u8, rhs: &const u8) bool { - return *rhs < *lhs; + return rhs.* < lhs.*; } test "stable sort" { @@ -967,44 +998,125 @@ test "stable sort" { comptime testStableSort(); } fn testStableSort() void { - var expected = []IdAndValue { - IdAndValue{.id = 0, .value = 0}, - IdAndValue{.id = 1, .value = 0}, - IdAndValue{.id = 2, .value = 0}, - IdAndValue{.id = 0, .value = 1}, - IdAndValue{.id = 1, .value = 1}, - IdAndValue{.id = 2, .value = 1}, - IdAndValue{.id = 0, .value = 2}, - IdAndValue{.id = 1, .value = 2}, - IdAndValue{.id = 2, .value = 2}, - }; - var cases = [][9]IdAndValue { - []IdAndValue { - IdAndValue{.id = 0, .value = 0}, - IdAndValue{.id = 0, .value = 1}, - IdAndValue{.id = 0, .value = 2}, - IdAndValue{.id = 1, .value = 0}, - IdAndValue{.id = 1, .value = 1}, - IdAndValue{.id = 1, .value = 2}, - IdAndValue{.id = 2, .value = 0}, - IdAndValue{.id = 2, .value = 1}, - IdAndValue{.id = 2, .value = 2}, + var expected = []IdAndValue{ + IdAndValue{ + .id = 0, + .value = 0, }, - []IdAndValue { - IdAndValue{.id = 0, .value = 2}, - IdAndValue{.id = 0, .value = 1}, - IdAndValue{.id = 0, .value = 0}, - IdAndValue{.id = 1, .value = 2}, - IdAndValue{.id = 1, .value = 1}, - IdAndValue{.id = 1, .value = 0}, - IdAndValue{.id = 2, .value = 2}, - IdAndValue{.id = 2, .value = 1}, - IdAndValue{.id = 2, .value = 0}, + IdAndValue{ + .id = 1, + .value = 0, + }, + IdAndValue{ + .id = 2, + .value = 0, + }, + IdAndValue{ + .id = 0, + .value = 1, + }, + IdAndValue{ + .id = 1, + .value = 1, + }, + IdAndValue{ + .id = 2, + .value = 1, + }, + IdAndValue{ + .id = 0, + .value = 2, + }, + IdAndValue{ + .id = 1, + .value = 2, + }, + IdAndValue{ + .id = 2, + .value = 2, + }, + }; + var cases = [][9]IdAndValue{ + []IdAndValue{ + IdAndValue{ + .id = 0, + .value = 0, + }, + IdAndValue{ + .id = 0, + .value = 1, + }, + IdAndValue{ + .id = 0, + .value = 2, + }, + IdAndValue{ + .id = 1, + .value = 0, + }, + IdAndValue{ + .id = 1, + .value = 1, + }, + IdAndValue{ + .id = 1, + .value = 2, + }, + IdAndValue{ + .id = 2, + .value = 0, + }, + IdAndValue{ + .id = 2, + .value = 1, + }, + IdAndValue{ + .id = 2, + .value = 2, + }, + }, + []IdAndValue{ + IdAndValue{ + .id = 0, + .value = 2, + }, + IdAndValue{ + .id = 0, + .value = 1, + }, + IdAndValue{ + .id = 0, + .value = 0, + }, + IdAndValue{ + .id = 1, + .value = 2, + }, + IdAndValue{ + .id = 1, + .value = 1, + }, + IdAndValue{ + .id = 1, + .value = 0, + }, + IdAndValue{ + .id = 2, + .value = 2, + }, + IdAndValue{ + .id = 2, + .value = 1, + }, + IdAndValue{ + .id = 2, + .value = 0, + }, }, }; for (cases) |*case| { - insertionSort(IdAndValue, (*case)[0..], cmpByValue); - for (*case) |item, i| { + insertionSort(IdAndValue, (case.*)[0..], cmpByValue); + for (case.*) |item, i| { assert(item.id == expected[i].id); assert(item.value == expected[i].value); } @@ -1019,13 +1131,31 @@ fn cmpByValue(a: &const IdAndValue, b: &const IdAndValue) bool { } test "std.sort" { - const u8cases = [][]const []const u8 { - [][]const u8{"", ""}, - [][]const u8{"a", "a"}, - [][]const u8{"az", "az"}, - [][]const u8{"za", "az"}, - [][]const u8{"asdf", "adfs"}, - [][]const u8{"one", "eno"}, + const u8cases = [][]const []const u8{ + [][]const u8{ + "", + "", + }, + [][]const u8{ + "a", + "a", + }, + [][]const u8{ + "az", + "az", + }, + [][]const u8{ + "za", + "az", + }, + [][]const u8{ + "asdf", + "adfs", + }, + [][]const u8{ + "one", + "eno", + }, }; for (u8cases) |case| { @@ -1036,13 +1166,59 @@ test "std.sort" { assert(mem.eql(u8, slice, case[1])); } - const i32cases = [][]const []const i32 { - [][]const i32{[]i32{}, []i32{}}, - [][]const i32{[]i32{1}, []i32{1}}, - [][]const i32{[]i32{0, 1}, []i32{0, 1}}, - [][]const i32{[]i32{1, 0}, []i32{0, 1}}, - [][]const i32{[]i32{1, -1, 0}, []i32{-1, 0, 1}}, - [][]const i32{[]i32{2, 1, 3}, []i32{1, 2, 3}}, + const i32cases = [][]const []const i32{ + [][]const i32{ + []i32{}, + []i32{}, + }, + [][]const i32{ + []i32{1}, + []i32{1}, + }, + [][]const i32{ + []i32{ + 0, + 1, + }, + []i32{ + 0, + 1, + }, + }, + [][]const i32{ + []i32{ + 1, + 0, + }, + []i32{ + 0, + 1, + }, + }, + [][]const i32{ + []i32{ + 1, + -1, + 0, + }, + []i32{ + -1, + 0, + 1, + }, + }, + [][]const i32{ + []i32{ + 2, + 1, + 3, + }, + []i32{ + 1, + 2, + 3, + }, + }, }; for (i32cases) |case| { @@ -1055,13 +1231,59 @@ test "std.sort" { } test "std.sort descending" { - const rev_cases = [][]const []const i32 { - [][]const i32{[]i32{}, []i32{}}, - [][]const i32{[]i32{1}, []i32{1}}, - [][]const i32{[]i32{0, 1}, []i32{1, 0}}, - [][]const i32{[]i32{1, 0}, []i32{1, 0}}, - [][]const i32{[]i32{1, -1, 0}, []i32{1, 0, -1}}, - [][]const i32{[]i32{2, 1, 3}, []i32{3, 2, 1}}, + const rev_cases = [][]const []const i32{ + [][]const i32{ + []i32{}, + []i32{}, + }, + [][]const i32{ + []i32{1}, + []i32{1}, + }, + [][]const i32{ + []i32{ + 0, + 1, + }, + []i32{ + 1, + 0, + }, + }, + [][]const i32{ + []i32{ + 1, + 0, + }, + []i32{ + 1, + 0, + }, + }, + [][]const i32{ + []i32{ + 1, + -1, + 0, + }, + []i32{ + 1, + 0, + -1, + }, + }, + [][]const i32{ + []i32{ + 2, + 1, + 3, + }, + []i32{ + 3, + 2, + 1, + }, + }, }; for (rev_cases) |case| { @@ -1074,10 +1296,22 @@ test "std.sort descending" { } test "another sort case" { - var arr = []i32{ 5, 3, 1, 2, 4 }; + var arr = []i32{ + 5, + 3, + 1, + 2, + 4, + }; sort(i32, arr[0..], i32asc); - assert(mem.eql(i32, arr, []i32{ 1, 2, 3, 4, 5 })); + assert(mem.eql(i32, arr, []i32{ + 1, + 2, + 3, + 4, + 5, + })); } test "sort fuzz testing" { @@ -1112,7 +1346,7 @@ fn fuzzTest(rng: &std.rand.Random) void { } } -pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool) T { +pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) T { var i: usize = 0; var smallest = items[0]; for (items[1..]) |item| { @@ -1123,7 +1357,7 @@ pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const return smallest; } -pub fn max(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool) T { +pub fn max(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) T { var i: usize = 0; var biggest = items[0]; for (items[1..]) |item| { From 277b9cf8788f340f387e63029ad9fc12664cafff Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Fri, 11 May 2018 22:41:44 -0400 Subject: [PATCH 05/75] fix comptime code modification of global const closes #1008 --- src/ir.cpp | 7 ++++++- test/cases/eval.zig | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/ir.cpp b/src/ir.cpp index 1e6a7d7b8b..c251f30320 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -8686,6 +8686,10 @@ static void copy_const_val(ConstExprValue *dest, ConstExprValue *src, bool same_ *dest = *src; if (!same_global_refs) { dest->global_refs = global_refs; + if (dest->type->id == TypeTableEntryIdStruct) { + dest->data.x_struct.fields = allocate_nonzero(dest->type->data.structure.src_field_count); + memcpy(dest->data.x_struct.fields, src->data.x_struct.fields, sizeof(ConstExprValue) * dest->type->data.structure.src_field_count); + } } } @@ -11670,7 +11674,8 @@ static TypeTableEntry *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstruc if (var->mem_slot_index != SIZE_MAX) { assert(var->mem_slot_index < ira->exec_context.mem_slot_count); ConstExprValue *mem_slot = &ira->exec_context.mem_slot_list[var->mem_slot_index]; - *mem_slot = casted_init_value->value; + copy_const_val(mem_slot, &casted_init_value->value, + !is_comptime_var || var->gen_is_const); if (is_comptime_var || (var_class_requires_const && var->gen_is_const)) { ir_build_const_from(ira, &decl_var_instruction->base); diff --git a/test/cases/eval.zig b/test/cases/eval.zig index 364db5e152..1ed30872e0 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -536,3 +536,20 @@ test "runtime 128 bit integer division" { var c = a / b; assert(c == 15231399999); } + +pub const Info = struct { + version: u8, +}; + +pub const diamond_info = Info { + .version = 0, +}; + +test "comptime modification of const struct field" { + comptime { + var res = diamond_info; + res.version = 1; + assert(diamond_info.version == 0); + assert(res.version == 1); + } +} From 4277762b742216d4dd44bfe7490947e69527fbc7 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Fri, 11 May 2018 23:04:41 -0400 Subject: [PATCH 06/75] fix windows build system broken by 6e821078f625a03eb8b7794c983da0f7793366ab --- std/os/child_process.zig | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/std/os/child_process.zig b/std/os/child_process.zig index 8bb8b2d7e7..ebc8a38cd1 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -650,6 +650,8 @@ fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) var buf = try Buffer.initSize(allocator, 0); defer buf.deinit(); + var buf_stream = &io.BufferOutStream.init(&buf).stream; + for (argv) |arg, arg_i| { if (arg_i != 0) try buf.appendByte(' '); @@ -663,18 +665,18 @@ fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) switch (byte) { '\\' => backslash_count += 1, '"' => { - try buf.appendByteNTimes('\\', backslash_count * 2 + 1); + try buf_stream.writeByteNTimes('\\', backslash_count * 2 + 1); try buf.appendByte('"'); backslash_count = 0; }, else => { - try buf.appendByteNTimes('\\', backslash_count); + try buf_stream.writeByteNTimes('\\', backslash_count); try buf.appendByte(byte); backslash_count = 0; }, } } - try buf.appendByteNTimes('\\', backslash_count * 2); + try buf_stream.writeByteNTimes('\\', backslash_count * 2); try buf.appendByte('"'); } From a6ae45145f5814963cfdff4e18c1f984729588b9 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 12 May 2018 17:35:15 -0400 Subject: [PATCH 07/75] add @newStackCall builtin function See #1006 --- doc/langref.html.in | 47 +++++++++++++++-- src/all_types.hpp | 7 +++ src/codegen.cpp | 99 ++++++++++++++++++++++++++++++++++- src/ir.cpp | 66 +++++++++++++++++++---- src/target.cpp | 62 ++++++++++++++++++++++ src/target.hpp | 2 + test/behavior.zig | 5 +- test/cases/new_stack_call.zig | 26 +++++++++ 8 files changed, 298 insertions(+), 16 deletions(-) create mode 100644 test/cases/new_stack_call.zig diff --git a/doc/langref.html.in b/doc/langref.html.in index b867ff0b35..4ae98abbd2 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -4485,17 +4485,58 @@ mem.set(u8, dest, c); If no overflow or underflow occurs, returns false.

{#header_close#} + {#header_open|@newStackCall#} +
@newStackCall(new_stack: []u8, function: var, args: ...) -> var
+

+ This calls a function, in the same way that invoking an expression with parentheses does. However, + instead of using the same stack as the caller, the function uses the stack provided in the new_stack + parameter. +

+ {#code_begin|test#} +const std = @import("std"); +const assert = std.debug.assert; + +var new_stack_bytes: [1024]u8 = undefined; + +test "calling a function with a new stack" { + const arg = 1234; + + const a = @newStackCall(new_stack_bytes[0..512], targetFunction, arg); + const b = @newStackCall(new_stack_bytes[512..], targetFunction, arg); + _ = targetFunction(arg); + + assert(arg == 1234); + assert(a < b); +} + +fn targetFunction(x: i32) usize { + assert(x == 1234); + + var local_variable: i32 = 42; + const ptr = &local_variable; + *ptr += 1; + + assert(local_variable == 43); + return @ptrToInt(ptr); +} + {#code_end#} + {#header_close#} {#header_open|@noInlineCall#}
@noInlineCall(function: var, args: ...) -> var

This calls a function, in the same way that invoking an expression with parentheses does:

-
const assert = @import("std").debug.assert;
+      {#code_begin|test#}
+const assert = @import("std").debug.assert;
+
 test "noinline function call" {
     assert(@noInlineCall(add, 3, 9) == 12);
 }
 
-fn add(a: i32, b: i32) -> i32 { a + b }
+fn add(a: i32, b: i32) i32 { + return a + b; +} + {#code_end#}

Unlike a normal function call, however, @noInlineCall guarantees that the call will not be inlined. If the call must be inlined, a compile error is emitted. @@ -6451,7 +6492,7 @@ hljs.registerLanguage("zig", function(t) { a = t.IR + "\\s*\\(", c = { keyword: "const align var extern stdcallcc nakedcc volatile export pub noalias inline struct packed enum union break return try catch test continue unreachable comptime and or asm defer errdefer if else switch while for fn use bool f32 f64 void type noreturn error i8 u8 i16 u16 i32 u32 i64 u64 isize usize i8w u8w i16w i32w u32w i64w u64w isizew usizew c_short c_ushort c_int c_uint c_long c_ulong c_longlong c_ulonglong", - built_in: "atomicLoad breakpoint returnAddress frameAddress fieldParentPtr setFloatMode IntType OpaqueType compileError compileLog setCold setRuntimeSafety setEvalBranchQuota offsetOf memcpy inlineCall setGlobalLinkage setGlobalSection divTrunc divFloor enumTagName intToPtr ptrToInt panic canImplicitCast ptrCast bitCast rem mod memset sizeOf alignOf alignCast maxValue minValue memberCount memberName memberType typeOf addWithOverflow subWithOverflow mulWithOverflow shlWithOverflow shlExact shrExact cInclude cDefine cUndef ctz clz import cImport errorName embedFile cmpxchgStrong cmpxchgWeak fence divExact truncate atomicRmw sqrt field typeInfo", + built_in: "atomicLoad breakpoint returnAddress frameAddress fieldParentPtr setFloatMode IntType OpaqueType compileError compileLog setCold setRuntimeSafety setEvalBranchQuota offsetOf memcpy inlineCall setGlobalLinkage setGlobalSection divTrunc divFloor enumTagName intToPtr ptrToInt panic canImplicitCast ptrCast bitCast rem mod memset sizeOf alignOf alignCast maxValue minValue memberCount memberName memberType typeOf addWithOverflow subWithOverflow mulWithOverflow shlWithOverflow shlExact shrExact cInclude cDefine cUndef ctz clz import cImport errorName embedFile cmpxchgStrong cmpxchgWeak fence divExact truncate atomicRmw sqrt field typeInfo newStackCall", literal: "true false null undefined" }, n = [e, t.CLCM, t.CBCM, s, r]; diff --git a/src/all_types.hpp b/src/all_types.hpp index c1c6c9a1a5..dc61c8235f 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -1340,6 +1340,7 @@ enum BuiltinFnId { BuiltinFnIdOffsetOf, BuiltinFnIdInlineCall, BuiltinFnIdNoInlineCall, + BuiltinFnIdNewStackCall, BuiltinFnIdTypeId, BuiltinFnIdShlExact, BuiltinFnIdShrExact, @@ -1656,8 +1657,13 @@ struct CodeGen { LLVMValueRef coro_alloc_helper_fn_val; LLVMValueRef merge_err_ret_traces_fn_val; LLVMValueRef add_error_return_trace_addr_fn_val; + LLVMValueRef stacksave_fn_val; + LLVMValueRef stackrestore_fn_val; + LLVMValueRef write_register_fn_val; bool error_during_imports; + LLVMValueRef sp_md_node; + const char **clang_argv; size_t clang_argv_len; ZigList lib_dirs; @@ -2280,6 +2286,7 @@ struct IrInstructionCall { bool is_async; IrInstruction *async_allocator; + IrInstruction *new_stack; }; struct IrInstructionConst { diff --git a/src/codegen.cpp b/src/codegen.cpp index 4e58f86d4b..f1e102392a 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -938,6 +938,53 @@ static LLVMValueRef get_memcpy_fn_val(CodeGen *g) { return g->memcpy_fn_val; } +static LLVMValueRef get_stacksave_fn_val(CodeGen *g) { + if (g->stacksave_fn_val) + return g->stacksave_fn_val; + + // declare i8* @llvm.stacksave() + + LLVMTypeRef fn_type = LLVMFunctionType(LLVMPointerType(LLVMInt8Type(), 0), nullptr, 0, false); + g->stacksave_fn_val = LLVMAddFunction(g->module, "llvm.stacksave", fn_type); + assert(LLVMGetIntrinsicID(g->stacksave_fn_val)); + + return g->stacksave_fn_val; +} + +static LLVMValueRef get_stackrestore_fn_val(CodeGen *g) { + if (g->stackrestore_fn_val) + return g->stackrestore_fn_val; + + // declare void @llvm.stackrestore(i8* %ptr) + + LLVMTypeRef param_type = LLVMPointerType(LLVMInt8Type(), 0); + LLVMTypeRef fn_type = LLVMFunctionType(LLVMVoidType(), ¶m_type, 1, false); + g->stackrestore_fn_val = LLVMAddFunction(g->module, "llvm.stackrestore", fn_type); + assert(LLVMGetIntrinsicID(g->stackrestore_fn_val)); + + return g->stackrestore_fn_val; +} + +static LLVMValueRef get_write_register_fn_val(CodeGen *g) { + if (g->write_register_fn_val) + return g->write_register_fn_val; + + // declare void @llvm.write_register.i64(metadata, i64 @value) + // !0 = !{!"sp\00"} + + LLVMTypeRef param_types[] = { + LLVMMetadataTypeInContext(LLVMGetGlobalContext()), + LLVMIntType(g->pointer_size_bytes * 8), + }; + + LLVMTypeRef fn_type = LLVMFunctionType(LLVMVoidType(), param_types, 2, false); + Buf *name = buf_sprintf("llvm.write_register.i%d", g->pointer_size_bytes * 8); + g->write_register_fn_val = LLVMAddFunction(g->module, buf_ptr(name), fn_type); + assert(LLVMGetIntrinsicID(g->write_register_fn_val)); + + return g->write_register_fn_val; +} + static LLVMValueRef get_coro_destroy_fn_val(CodeGen *g) { if (g->coro_destroy_fn_val) return g->coro_destroy_fn_val; @@ -2901,6 +2948,38 @@ static size_t get_async_err_code_arg_index(CodeGen *g, FnTypeId *fn_type_id) { return 1 + get_async_allocator_arg_index(g, fn_type_id); } + +static LLVMValueRef get_new_stack_addr(CodeGen *g, LLVMValueRef new_stack) { + LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, new_stack, (unsigned)slice_ptr_index, ""); + LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, new_stack, (unsigned)slice_len_index, ""); + + LLVMValueRef ptr_value = gen_load_untyped(g, ptr_field_ptr, 0, false, ""); + LLVMValueRef len_value = gen_load_untyped(g, len_field_ptr, 0, false, ""); + + LLVMValueRef ptr_addr = LLVMBuildPtrToInt(g->builder, ptr_value, LLVMTypeOf(len_value), ""); + LLVMValueRef end_addr = LLVMBuildNUWAdd(g->builder, ptr_addr, len_value, ""); + LLVMValueRef align_amt = LLVMConstInt(LLVMTypeOf(end_addr), get_abi_alignment(g, g->builtin_types.entry_usize), false); + LLVMValueRef align_adj = LLVMBuildURem(g->builder, end_addr, align_amt, ""); + return LLVMBuildNUWSub(g->builder, end_addr, align_adj, ""); +} + +static void gen_set_stack_pointer(CodeGen *g, LLVMValueRef aligned_end_addr) { + LLVMValueRef write_register_fn_val = get_write_register_fn_val(g); + + if (g->sp_md_node == nullptr) { + Buf *sp_reg_name = buf_create_from_str(arch_stack_pointer_register_name(&g->zig_target.arch)); + LLVMValueRef str_node = LLVMMDString(buf_ptr(sp_reg_name), buf_len(sp_reg_name) + 1); + g->sp_md_node = LLVMMDNode(&str_node, 1); + } + + LLVMValueRef params[] = { + g->sp_md_node, + aligned_end_addr, + }; + + LLVMBuildCall(g->builder, write_register_fn_val, params, 2, ""); +} + static LLVMValueRef ir_render_call(CodeGen *g, IrExecutable *executable, IrInstructionCall *instruction) { LLVMValueRef fn_val; TypeTableEntry *fn_type; @@ -2967,8 +3046,23 @@ static LLVMValueRef ir_render_call(CodeGen *g, IrExecutable *executable, IrInstr } LLVMCallConv llvm_cc = get_llvm_cc(g, fn_type->data.fn.fn_type_id.cc); - LLVMValueRef result = ZigLLVMBuildCall(g->builder, fn_val, - gen_param_values, (unsigned)gen_param_index, llvm_cc, fn_inline, ""); + LLVMValueRef result; + + if (instruction->new_stack == nullptr) { + result = ZigLLVMBuildCall(g->builder, fn_val, + gen_param_values, (unsigned)gen_param_index, llvm_cc, fn_inline, ""); + } else { + LLVMValueRef stacksave_fn_val = get_stacksave_fn_val(g); + LLVMValueRef stackrestore_fn_val = get_stackrestore_fn_val(g); + + LLVMValueRef new_stack_addr = get_new_stack_addr(g, ir_llvm_value(g, instruction->new_stack)); + LLVMValueRef old_stack_ref = LLVMBuildCall(g->builder, stacksave_fn_val, nullptr, 0, ""); + gen_set_stack_pointer(g, new_stack_addr); + result = ZigLLVMBuildCall(g->builder, fn_val, + gen_param_values, (unsigned)gen_param_index, llvm_cc, fn_inline, ""); + LLVMBuildCall(g->builder, stackrestore_fn_val, &old_stack_ref, 1, ""); + } + for (size_t param_i = 0; param_i < fn_type_id->param_count; param_i += 1) { FnGenParamInfo *gen_info = &fn_type->data.fn.gen_param_info[param_i]; @@ -6171,6 +6265,7 @@ static void define_builtin_fns(CodeGen *g) { create_builtin_fn(g, BuiltinFnIdSqrt, "sqrt", 2); create_builtin_fn(g, BuiltinFnIdInlineCall, "inlineCall", SIZE_MAX); create_builtin_fn(g, BuiltinFnIdNoInlineCall, "noInlineCall", SIZE_MAX); + create_builtin_fn(g, BuiltinFnIdNewStackCall, "newStackCall", SIZE_MAX); create_builtin_fn(g, BuiltinFnIdTypeId, "typeId", 1); create_builtin_fn(g, BuiltinFnIdShlExact, "shlExact", 2); create_builtin_fn(g, BuiltinFnIdShrExact, "shrExact", 2); diff --git a/src/ir.cpp b/src/ir.cpp index c251f30320..7bc837d908 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -1102,7 +1102,8 @@ static IrInstruction *ir_build_union_field_ptr_from(IrBuilder *irb, IrInstructio static IrInstruction *ir_build_call(IrBuilder *irb, Scope *scope, AstNode *source_node, FnTableEntry *fn_entry, IrInstruction *fn_ref, size_t arg_count, IrInstruction **args, - bool is_comptime, FnInline fn_inline, bool is_async, IrInstruction *async_allocator) + bool is_comptime, FnInline fn_inline, bool is_async, IrInstruction *async_allocator, + IrInstruction *new_stack) { IrInstructionCall *call_instruction = ir_build_instruction(irb, scope, source_node); call_instruction->fn_entry = fn_entry; @@ -1113,6 +1114,7 @@ static IrInstruction *ir_build_call(IrBuilder *irb, Scope *scope, AstNode *sourc call_instruction->arg_count = arg_count; call_instruction->is_async = is_async; call_instruction->async_allocator = async_allocator; + call_instruction->new_stack = new_stack; if (fn_ref) ir_ref_instruction(fn_ref, irb->current_basic_block); @@ -1120,16 +1122,19 @@ static IrInstruction *ir_build_call(IrBuilder *irb, Scope *scope, AstNode *sourc ir_ref_instruction(args[i], irb->current_basic_block); if (async_allocator) ir_ref_instruction(async_allocator, irb->current_basic_block); + if (new_stack != nullptr) + ir_ref_instruction(new_stack, irb->current_basic_block); return &call_instruction->base; } static IrInstruction *ir_build_call_from(IrBuilder *irb, IrInstruction *old_instruction, FnTableEntry *fn_entry, IrInstruction *fn_ref, size_t arg_count, IrInstruction **args, - bool is_comptime, FnInline fn_inline, bool is_async, IrInstruction *async_allocator) + bool is_comptime, FnInline fn_inline, bool is_async, IrInstruction *async_allocator, + IrInstruction *new_stack) { IrInstruction *new_instruction = ir_build_call(irb, old_instruction->scope, - old_instruction->source_node, fn_entry, fn_ref, arg_count, args, is_comptime, fn_inline, is_async, async_allocator); + old_instruction->source_node, fn_entry, fn_ref, arg_count, args, is_comptime, fn_inline, is_async, async_allocator, new_stack); ir_link_new_instruction(new_instruction, old_instruction); return new_instruction; } @@ -4303,7 +4308,37 @@ static IrInstruction *ir_gen_builtin_fn_call(IrBuilder *irb, Scope *scope, AstNo } FnInline fn_inline = (builtin_fn->id == BuiltinFnIdInlineCall) ? FnInlineAlways : FnInlineNever; - IrInstruction *call = ir_build_call(irb, scope, node, nullptr, fn_ref, arg_count, args, false, fn_inline, false, nullptr); + IrInstruction *call = ir_build_call(irb, scope, node, nullptr, fn_ref, arg_count, args, false, fn_inline, false, nullptr, nullptr); + return ir_lval_wrap(irb, scope, call, lval); + } + case BuiltinFnIdNewStackCall: + { + if (node->data.fn_call_expr.params.length == 0) { + add_node_error(irb->codegen, node, buf_sprintf("expected at least 1 argument, found 0")); + return irb->codegen->invalid_instruction; + } + + AstNode *new_stack_node = node->data.fn_call_expr.params.at(0); + IrInstruction *new_stack = ir_gen_node(irb, new_stack_node, scope); + if (new_stack == irb->codegen->invalid_instruction) + return new_stack; + + AstNode *fn_ref_node = node->data.fn_call_expr.params.at(1); + IrInstruction *fn_ref = ir_gen_node(irb, fn_ref_node, scope); + if (fn_ref == irb->codegen->invalid_instruction) + return fn_ref; + + size_t arg_count = node->data.fn_call_expr.params.length - 2; + + IrInstruction **args = allocate(arg_count); + for (size_t i = 0; i < arg_count; i += 1) { + AstNode *arg_node = node->data.fn_call_expr.params.at(i + 2); + args[i] = ir_gen_node(irb, arg_node, scope); + if (args[i] == irb->codegen->invalid_instruction) + return args[i]; + } + + IrInstruction *call = ir_build_call(irb, scope, node, nullptr, fn_ref, arg_count, args, false, FnInlineAuto, false, nullptr, new_stack); return ir_lval_wrap(irb, scope, call, lval); } case BuiltinFnIdTypeId: @@ -4513,7 +4548,7 @@ static IrInstruction *ir_gen_fn_call(IrBuilder *irb, Scope *scope, AstNode *node } } - IrInstruction *fn_call = ir_build_call(irb, scope, node, nullptr, fn_ref, arg_count, args, false, FnInlineAuto, is_async, async_allocator); + IrInstruction *fn_call = ir_build_call(irb, scope, node, nullptr, fn_ref, arg_count, args, false, FnInlineAuto, is_async, async_allocator, nullptr); return ir_lval_wrap(irb, scope, fn_call, lval); } @@ -6825,7 +6860,7 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec IrInstruction **args = allocate(arg_count); args[0] = implicit_allocator_ptr; // self args[1] = mem_slice; // old_mem - ir_build_call(irb, scope, node, nullptr, free_fn, arg_count, args, false, FnInlineAuto, false, nullptr); + ir_build_call(irb, scope, node, nullptr, free_fn, arg_count, args, false, FnInlineAuto, false, nullptr, nullptr); IrBasicBlock *resume_block = ir_create_basic_block(irb, scope, "Resume"); ir_build_cond_br(irb, scope, node, resume_awaiter, resume_block, irb->exec->coro_suspend_block, const_bool_false); @@ -11992,7 +12027,7 @@ static IrInstruction *ir_analyze_async_call(IrAnalyze *ira, IrInstructionCall *c TypeTableEntry *async_return_type = get_error_union_type(ira->codegen, alloc_fn_error_set_type, promise_type); IrInstruction *result = ir_build_call(&ira->new_irb, call_instruction->base.scope, call_instruction->base.source_node, - fn_entry, fn_ref, arg_count, casted_args, false, FnInlineAuto, true, async_allocator_inst); + fn_entry, fn_ref, arg_count, casted_args, false, FnInlineAuto, true, async_allocator_inst, nullptr); result->value.type = async_return_type; return result; } @@ -12362,6 +12397,19 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal return ir_finish_anal(ira, return_type); } + IrInstruction *casted_new_stack = nullptr; + if (call_instruction->new_stack != nullptr) { + TypeTableEntry *u8_ptr = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, false); + TypeTableEntry *u8_slice = get_slice_type(ira->codegen, u8_ptr); + IrInstruction *new_stack = call_instruction->new_stack->other; + if (type_is_invalid(new_stack->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + casted_new_stack = ir_implicit_cast(ira, new_stack, u8_slice); + if (type_is_invalid(casted_new_stack->value.type)) + return ira->codegen->builtin_types.entry_invalid; + } + if (fn_type->data.fn.is_generic) { if (!fn_entry) { ir_add_error(ira, call_instruction->fn_ref, @@ -12588,7 +12636,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal assert(async_allocator_inst == nullptr); IrInstruction *new_call_instruction = ir_build_call_from(&ira->new_irb, &call_instruction->base, impl_fn, nullptr, impl_param_count, casted_args, false, fn_inline, - call_instruction->is_async, nullptr); + call_instruction->is_async, nullptr, casted_new_stack); ir_add_alloca(ira, new_call_instruction, return_type); @@ -12679,7 +12727,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal IrInstruction *new_call_instruction = ir_build_call_from(&ira->new_irb, &call_instruction->base, - fn_entry, fn_ref, call_param_count, casted_args, false, fn_inline, false, nullptr); + fn_entry, fn_ref, call_param_count, casted_args, false, fn_inline, false, nullptr, casted_new_stack); ir_add_alloca(ira, new_call_instruction, return_type); return ir_finish_anal(ira, return_type); diff --git a/src/target.cpp b/src/target.cpp index 5008b51a09..57970888fc 100644 --- a/src/target.cpp +++ b/src/target.cpp @@ -896,3 +896,65 @@ bool target_can_exec(const ZigTarget *host_target, const ZigTarget *guest_target return false; } + +const char *arch_stack_pointer_register_name(const ArchType *arch) { + switch (arch->arch) { + case ZigLLVM_UnknownArch: + zig_unreachable(); + case ZigLLVM_x86: + return "sp"; + case ZigLLVM_x86_64: + return "rsp"; + + case ZigLLVM_aarch64: + case ZigLLVM_arm: + case ZigLLVM_thumb: + case ZigLLVM_aarch64_be: + case ZigLLVM_amdgcn: + case ZigLLVM_amdil: + case ZigLLVM_amdil64: + case ZigLLVM_armeb: + case ZigLLVM_arc: + case ZigLLVM_avr: + case ZigLLVM_bpfeb: + case ZigLLVM_bpfel: + case ZigLLVM_hexagon: + case ZigLLVM_lanai: + case ZigLLVM_hsail: + case ZigLLVM_hsail64: + case ZigLLVM_kalimba: + case ZigLLVM_le32: + case ZigLLVM_le64: + case ZigLLVM_mips: + case ZigLLVM_mips64: + case ZigLLVM_mips64el: + case ZigLLVM_mipsel: + case ZigLLVM_msp430: + case ZigLLVM_nios2: + case ZigLLVM_nvptx: + case ZigLLVM_nvptx64: + case ZigLLVM_ppc64le: + case ZigLLVM_r600: + case ZigLLVM_renderscript32: + case ZigLLVM_renderscript64: + case ZigLLVM_riscv32: + case ZigLLVM_riscv64: + case ZigLLVM_shave: + case ZigLLVM_sparc: + case ZigLLVM_sparcel: + case ZigLLVM_sparcv9: + case ZigLLVM_spir: + case ZigLLVM_spir64: + case ZigLLVM_systemz: + case ZigLLVM_tce: + case ZigLLVM_tcele: + case ZigLLVM_thumbeb: + case ZigLLVM_wasm32: + case ZigLLVM_wasm64: + case ZigLLVM_xcore: + case ZigLLVM_ppc: + case ZigLLVM_ppc64: + zig_panic("TODO populate this table with stack pointer register name for this CPU architecture"); + } + zig_unreachable(); +} diff --git a/src/target.hpp b/src/target.hpp index 614b0627d5..5a118f6d8d 100644 --- a/src/target.hpp +++ b/src/target.hpp @@ -77,6 +77,8 @@ size_t target_arch_count(void); const ArchType *get_target_arch(size_t index); void get_arch_name(char *out_str, const ArchType *arch); +const char *arch_stack_pointer_register_name(const ArchType *arch); + size_t target_vendor_count(void); ZigLLVM_VendorType get_target_vendor(size_t index); diff --git a/test/behavior.zig b/test/behavior.zig index d700faaebc..fbec60f648 100644 --- a/test/behavior.zig +++ b/test/behavior.zig @@ -23,6 +23,7 @@ comptime { _ = @import("cases/eval.zig"); _ = @import("cases/field_parent_ptr.zig"); _ = @import("cases/fn.zig"); + _ = @import("cases/fn_in_struct_in_comptime.zig"); _ = @import("cases/for.zig"); _ = @import("cases/generics.zig"); _ = @import("cases/if.zig"); @@ -32,11 +33,11 @@ comptime { _ = @import("cases/math.zig"); _ = @import("cases/misc.zig"); _ = @import("cases/namespace_depends_on_compile_var/index.zig"); + _ = @import("cases/new_stack_call.zig"); _ = @import("cases/null.zig"); _ = @import("cases/pub_enum/index.zig"); _ = @import("cases/ref_var_in_if_after_if_2nd_switch_prong.zig"); _ = @import("cases/reflection.zig"); - _ = @import("cases/type_info.zig"); _ = @import("cases/sizeof_and_typeof.zig"); _ = @import("cases/slice.zig"); _ = @import("cases/struct.zig"); @@ -48,10 +49,10 @@ comptime { _ = @import("cases/syntax.zig"); _ = @import("cases/this.zig"); _ = @import("cases/try.zig"); + _ = @import("cases/type_info.zig"); _ = @import("cases/undefined.zig"); _ = @import("cases/union.zig"); _ = @import("cases/var_args.zig"); _ = @import("cases/void.zig"); _ = @import("cases/while.zig"); - _ = @import("cases/fn_in_struct_in_comptime.zig"); } diff --git a/test/cases/new_stack_call.zig b/test/cases/new_stack_call.zig new file mode 100644 index 0000000000..ea9f0c914f --- /dev/null +++ b/test/cases/new_stack_call.zig @@ -0,0 +1,26 @@ +const std = @import("std"); +const assert = std.debug.assert; + +var new_stack_bytes: [1024]u8 = undefined; + +test "calling a function with a new stack" { + const arg = 1234; + + const a = @newStackCall(new_stack_bytes[0..512], targetFunction, arg); + const b = @newStackCall(new_stack_bytes[512..], targetFunction, arg); + _ = targetFunction(arg); + + assert(arg == 1234); + assert(a < b); +} + +fn targetFunction(x: i32) usize { + assert(x == 1234); + + var local_variable: i32 = 42; + const ptr = &local_variable; + *ptr += 1; + + assert(local_variable == 43); + return @ptrToInt(ptr); +} From 911cbf57cd10159176950285feb9ee14fb88a803 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 12 May 2018 19:03:39 -0400 Subject: [PATCH 08/75] recursive render top level decl --- std/zig/render.zig | 42 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/std/zig/render.zig b/std/zig/render.zig index cced30cd60..c7a08a11fd 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -21,32 +21,28 @@ const RenderState = union(enum) { const indent_delta = 4; pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) !void { + var it = tree.root_node.decls.iterator(0); + while (it.next()) |decl| { + try renderTopLevelDecl(allocator, stream, tree, *decl); + if (it.peek()) |next_decl| { + const n = if (nodeLineOffset(tree, *decl, *next_decl) >= 2) u8(2) else u8(1); + try stream.writeByteNTimes('\n', n); + } + } + try stream.write("\n"); +} + +fn nodeLineOffset(tree: &ast.Tree, a: &ast.Node, b: &ast.Node) usize { + const a_last_token = tree.tokens.at(a.lastToken()); + const loc = tree.tokenLocation(a_last_token.end, b.firstToken()); + return loc.line; +} + +fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, decl_ptr: &ast.Node) !void { var stack = std.ArrayList(RenderState).init(allocator); defer stack.deinit(); - { - try stack.append(RenderState { .Text = "\n"}); - - var i = tree.root_node.decls.len; - while (i != 0) { - i -= 1; - const decl = *tree.root_node.decls.at(i); - try stack.append(RenderState {.TopLevelDecl = decl}); - if (i != 0) { - try stack.append(RenderState { - .Text = blk: { - const prev_node = *tree.root_node.decls.at(i - 1); - const prev_node_last_token = tree.tokens.at(prev_node.lastToken()); - const loc = tree.tokenLocation(prev_node_last_token.end, decl.firstToken()); - if (loc.line >= 2) { - break :blk "\n\n"; - } - break :blk "\n"; - }, - }); - } - } - } + try stack.append(RenderState {.TopLevelDecl = decl_ptr}); var indent: usize = 0; while (stack.popOrNull()) |state| { From 7cdc9d98c7134be5edd18eb6f94dd8cfc55bb764 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 12 May 2018 23:06:54 -0400 Subject: [PATCH 09/75] refactor std.zig.render to be recursive See #1006 --- std/zig/render.zig | 2377 ++++++++++++++++++++++---------------------- 1 file changed, 1167 insertions(+), 1210 deletions(-) diff --git a/std/zig/render.zig b/std/zig/render.zig index c7a08a11fd..13ef4607f4 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -1,29 +1,23 @@ const std = @import("../index.zig"); +const builtin = @import("builtin"); const assert = std.debug.assert; const mem = std.mem; const ast = std.zig.ast; const Token = std.zig.Token; -const RenderState = union(enum) { - TopLevelDecl: &ast.Node, - ParamDecl: &ast.Node, - Text: []const u8, - Expression: &ast.Node, - VarDecl: &ast.Node.VarDecl, - Statement: &ast.Node, - PrintIndent, - Indent: usize, - MaybeSemiColon: &ast.Node, - Token: ast.TokenIndex, - NonBreakToken: ast.TokenIndex, -}; - const indent_delta = 4; -pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) !void { +pub const Error = error { + /// Ran out of memory allocating call stack frames to complete rendering. + OutOfMemory, +}; + +pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(stream).Child.Error || Error)!void { + comptime assert(@typeId(@typeOf(stream)) == builtin.TypeId.Pointer); + var it = tree.root_node.decls.iterator(0); while (it.next()) |decl| { - try renderTopLevelDecl(allocator, stream, tree, *decl); + try renderTopLevelDecl(allocator, stream, tree, 0, *decl); if (it.peek()) |next_decl| { const n = if (nodeLineOffset(tree, *decl, *next_decl) >= 2) u8(2) else u8(1); try stream.writeByteNTimes('\n', n); @@ -38,1202 +32,1165 @@ fn nodeLineOffset(tree: &ast.Tree, a: &ast.Node, b: &ast.Node) usize { return loc.line; } -fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, decl_ptr: &ast.Node) !void { - var stack = std.ArrayList(RenderState).init(allocator); - defer stack.deinit(); - - try stack.append(RenderState {.TopLevelDecl = decl_ptr}); - - var indent: usize = 0; - while (stack.popOrNull()) |state| { - switch (state) { - RenderState.TopLevelDecl => |decl| { - switch (decl.id) { - ast.Node.Id.FnProto => { - const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl); - try renderComments(tree, stream, fn_proto, indent); - - if (fn_proto.body_node) |body_node| { - stack.append(RenderState { .Expression = body_node}) catch unreachable; - try stack.append(RenderState { .Text = " "}); - } else { - stack.append(RenderState { .Text = ";" }) catch unreachable; - } - - try stack.append(RenderState { .Expression = decl }); - }, - ast.Node.Id.Use => { - const use_decl = @fieldParentPtr(ast.Node.Use, "base", decl); - if (use_decl.visib_token) |visib_token| { - try stream.print("{} ", tree.tokenSlice(visib_token)); - } - try stream.print("use "); - try stack.append(RenderState { .Text = ";" }); - try stack.append(RenderState { .Expression = use_decl.expr }); - }, - ast.Node.Id.VarDecl => { - const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", decl); - try renderComments(tree, stream, var_decl, indent); - try stack.append(RenderState { .VarDecl = var_decl}); - }, - ast.Node.Id.TestDecl => { - const test_decl = @fieldParentPtr(ast.Node.TestDecl, "base", decl); - try renderComments(tree, stream, test_decl, indent); - try stream.print("test "); - try stack.append(RenderState { .Expression = test_decl.body_node }); - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = test_decl.name }); - }, - ast.Node.Id.StructField => { - const field = @fieldParentPtr(ast.Node.StructField, "base", decl); - try renderComments(tree, stream, field, indent); - if (field.visib_token) |visib_token| { - try stream.print("{} ", tree.tokenSlice(visib_token)); - } - try stream.print("{}: ", tree.tokenSlice(field.name_token)); - try stack.append(RenderState { .Token = field.lastToken() + 1 }); - try stack.append(RenderState { .Expression = field.type_expr}); - }, - ast.Node.Id.UnionTag => { - const tag = @fieldParentPtr(ast.Node.UnionTag, "base", decl); - try renderComments(tree, stream, tag, indent); - try stream.print("{}", tree.tokenSlice(tag.name_token)); - - try stack.append(RenderState { .Text = "," }); - - if (tag.value_expr) |value_expr| { - try stack.append(RenderState { .Expression = value_expr }); - try stack.append(RenderState { .Text = " = " }); - } - - if (tag.type_expr) |type_expr| { - try stream.print(": "); - try stack.append(RenderState { .Expression = type_expr}); - } - }, - ast.Node.Id.EnumTag => { - const tag = @fieldParentPtr(ast.Node.EnumTag, "base", decl); - try renderComments(tree, stream, tag, indent); - try stream.print("{}", tree.tokenSlice(tag.name_token)); - - try stack.append(RenderState { .Text = "," }); - if (tag.value) |value| { - try stream.print(" = "); - try stack.append(RenderState { .Expression = value}); - } - }, - ast.Node.Id.ErrorTag => { - const tag = @fieldParentPtr(ast.Node.ErrorTag, "base", decl); - try renderComments(tree, stream, tag, indent); - try stream.print("{}", tree.tokenSlice(tag.name_token)); - }, - ast.Node.Id.Comptime => { - try stack.append(RenderState { .MaybeSemiColon = decl }); - try stack.append(RenderState { .Expression = decl }); - }, - ast.Node.Id.LineComment => { - const line_comment_node = @fieldParentPtr(ast.Node.LineComment, "base", decl); - try stream.write(tree.tokenSlice(line_comment_node.token)); - }, - else => unreachable, - } - }, - - RenderState.VarDecl => |var_decl| { - try stack.append(RenderState { .Token = var_decl.semicolon_token }); - if (var_decl.init_node) |init_node| { - try stack.append(RenderState { .Expression = init_node }); - const text = if (init_node.id == ast.Node.Id.MultilineStringLiteral) " =" else " = "; - try stack.append(RenderState { .Text = text }); - } - if (var_decl.align_node) |align_node| { - try stack.append(RenderState { .Text = ")" }); - try stack.append(RenderState { .Expression = align_node }); - try stack.append(RenderState { .Text = " align(" }); - } - if (var_decl.type_node) |type_node| { - try stack.append(RenderState { .Expression = type_node }); - try stack.append(RenderState { .Text = ": " }); - } - try stack.append(RenderState { .Text = tree.tokenSlice(var_decl.name_token) }); - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Text = tree.tokenSlice(var_decl.mut_token) }); - - if (var_decl.comptime_token) |comptime_token| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Text = tree.tokenSlice(comptime_token) }); - } - - if (var_decl.extern_export_token) |extern_export_token| { - if (var_decl.lib_name != null) { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = ??var_decl.lib_name }); - } - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Text = tree.tokenSlice(extern_export_token) }); - } - - if (var_decl.visib_token) |visib_token| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Text = tree.tokenSlice(visib_token) }); - } - }, - - RenderState.ParamDecl => |base| { - const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base); - if (param_decl.comptime_token) |comptime_token| { - try stream.print("{} ", tree.tokenSlice(comptime_token)); - } - if (param_decl.noalias_token) |noalias_token| { - try stream.print("{} ", tree.tokenSlice(noalias_token)); - } - if (param_decl.name_token) |name_token| { - try stream.print("{}: ", tree.tokenSlice(name_token)); - } - if (param_decl.var_args_token) |var_args_token| { - try stream.print("{}", tree.tokenSlice(var_args_token)); - } else { - try stack.append(RenderState { .Expression = param_decl.type_node}); - } - }, - RenderState.Text => |bytes| { - try stream.write(bytes); - }, - RenderState.Expression => |base| switch (base.id) { - ast.Node.Id.Identifier => { - const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base); - try stream.print("{}", tree.tokenSlice(identifier.token)); - }, - ast.Node.Id.Block => { - const block = @fieldParentPtr(ast.Node.Block, "base", base); - if (block.label) |label| { - try stream.print("{}: ", tree.tokenSlice(label)); - } - - if (block.statements.len == 0) { - try stream.write("{}"); - } else { - try stream.write("{"); - try stack.append(RenderState { .Text = "}"}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent}); - try stack.append(RenderState { .Text = "\n"}); - var i = block.statements.len; - while (i != 0) { - i -= 1; - const statement_node = *block.statements.at(i); - try stack.append(RenderState { .Statement = statement_node}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent + indent_delta}); - try stack.append(RenderState { - .Text = blk: { - if (i != 0) { - const prev_node = *block.statements.at(i - 1); - const prev_node_last_token_end = tree.tokens.at(prev_node.lastToken()).end; - const loc = tree.tokenLocation(prev_node_last_token_end, statement_node.firstToken()); - if (loc.line >= 2) { - break :blk "\n\n"; - } - } - break :blk "\n"; - }, - }); - } - } - }, - ast.Node.Id.Defer => { - const defer_node = @fieldParentPtr(ast.Node.Defer, "base", base); - try stream.print("{} ", tree.tokenSlice(defer_node.defer_token)); - try stack.append(RenderState { .Expression = defer_node.expr }); - }, - ast.Node.Id.Comptime => { - const comptime_node = @fieldParentPtr(ast.Node.Comptime, "base", base); - try stream.print("{} ", tree.tokenSlice(comptime_node.comptime_token)); - try stack.append(RenderState { .Expression = comptime_node.expr }); - }, - ast.Node.Id.AsyncAttribute => { - const async_attr = @fieldParentPtr(ast.Node.AsyncAttribute, "base", base); - try stream.print("{}", tree.tokenSlice(async_attr.async_token)); - - if (async_attr.allocator_type) |allocator_type| { - try stack.append(RenderState { .Text = ">" }); - try stack.append(RenderState { .Expression = allocator_type }); - try stack.append(RenderState { .Text = "<" }); - } - }, - ast.Node.Id.Suspend => { - const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base); - if (suspend_node.label) |label| { - try stream.print("{}: ", tree.tokenSlice(label)); - } - try stream.print("{}", tree.tokenSlice(suspend_node.suspend_token)); - - if (suspend_node.body) |body| { - try stack.append(RenderState { .Expression = body }); - try stack.append(RenderState { .Text = " " }); - } - - if (suspend_node.payload) |payload| { - try stack.append(RenderState { .Expression = payload }); - try stack.append(RenderState { .Text = " " }); - } - }, - ast.Node.Id.InfixOp => { - const prefix_op_node = @fieldParentPtr(ast.Node.InfixOp, "base", base); - try stack.append(RenderState { .Expression = prefix_op_node.rhs }); - - if (prefix_op_node.op == ast.Node.InfixOp.Op.Catch) { - if (prefix_op_node.op.Catch) |payload| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = payload }); - } - try stack.append(RenderState { .Text = " catch " }); - } else { - const text = switch (prefix_op_node.op) { - ast.Node.InfixOp.Op.Add => " + ", - ast.Node.InfixOp.Op.AddWrap => " +% ", - ast.Node.InfixOp.Op.ArrayCat => " ++ ", - ast.Node.InfixOp.Op.ArrayMult => " ** ", - ast.Node.InfixOp.Op.Assign => " = ", - ast.Node.InfixOp.Op.AssignBitAnd => " &= ", - ast.Node.InfixOp.Op.AssignBitOr => " |= ", - ast.Node.InfixOp.Op.AssignBitShiftLeft => " <<= ", - ast.Node.InfixOp.Op.AssignBitShiftRight => " >>= ", - ast.Node.InfixOp.Op.AssignBitXor => " ^= ", - ast.Node.InfixOp.Op.AssignDiv => " /= ", - ast.Node.InfixOp.Op.AssignMinus => " -= ", - ast.Node.InfixOp.Op.AssignMinusWrap => " -%= ", - ast.Node.InfixOp.Op.AssignMod => " %= ", - ast.Node.InfixOp.Op.AssignPlus => " += ", - ast.Node.InfixOp.Op.AssignPlusWrap => " +%= ", - ast.Node.InfixOp.Op.AssignTimes => " *= ", - ast.Node.InfixOp.Op.AssignTimesWarp => " *%= ", - ast.Node.InfixOp.Op.BangEqual => " != ", - ast.Node.InfixOp.Op.BitAnd => " & ", - ast.Node.InfixOp.Op.BitOr => " | ", - ast.Node.InfixOp.Op.BitShiftLeft => " << ", - ast.Node.InfixOp.Op.BitShiftRight => " >> ", - ast.Node.InfixOp.Op.BitXor => " ^ ", - ast.Node.InfixOp.Op.BoolAnd => " and ", - ast.Node.InfixOp.Op.BoolOr => " or ", - ast.Node.InfixOp.Op.Div => " / ", - ast.Node.InfixOp.Op.EqualEqual => " == ", - ast.Node.InfixOp.Op.ErrorUnion => "!", - ast.Node.InfixOp.Op.GreaterOrEqual => " >= ", - ast.Node.InfixOp.Op.GreaterThan => " > ", - ast.Node.InfixOp.Op.LessOrEqual => " <= ", - ast.Node.InfixOp.Op.LessThan => " < ", - ast.Node.InfixOp.Op.MergeErrorSets => " || ", - ast.Node.InfixOp.Op.Mod => " % ", - ast.Node.InfixOp.Op.Mult => " * ", - ast.Node.InfixOp.Op.MultWrap => " *% ", - ast.Node.InfixOp.Op.Period => ".", - ast.Node.InfixOp.Op.Sub => " - ", - ast.Node.InfixOp.Op.SubWrap => " -% ", - ast.Node.InfixOp.Op.UnwrapMaybe => " ?? ", - ast.Node.InfixOp.Op.Range => " ... ", - ast.Node.InfixOp.Op.Catch => unreachable, - }; - - try stack.append(RenderState { .Text = text }); - } - try stack.append(RenderState { .Expression = prefix_op_node.lhs }); - }, - ast.Node.Id.PrefixOp => { - const prefix_op_node = @fieldParentPtr(ast.Node.PrefixOp, "base", base); - try stack.append(RenderState { .Expression = prefix_op_node.rhs }); - switch (prefix_op_node.op) { - ast.Node.PrefixOp.Op.AddrOf => |addr_of_info| { - try stream.write("&"); - if (addr_of_info.volatile_token != null) { - try stack.append(RenderState { .Text = "volatile "}); - } - if (addr_of_info.const_token != null) { - try stack.append(RenderState { .Text = "const "}); - } - if (addr_of_info.align_expr) |align_expr| { - try stream.print("align("); - try stack.append(RenderState { .Text = ") "}); - try stack.append(RenderState { .Expression = align_expr}); - } - }, - ast.Node.PrefixOp.Op.SliceType => |addr_of_info| { - try stream.write("[]"); - if (addr_of_info.volatile_token != null) { - try stack.append(RenderState { .Text = "volatile "}); - } - if (addr_of_info.const_token != null) { - try stack.append(RenderState { .Text = "const "}); - } - if (addr_of_info.align_expr) |align_expr| { - try stream.print("align("); - try stack.append(RenderState { .Text = ") "}); - try stack.append(RenderState { .Expression = align_expr}); - } - }, - ast.Node.PrefixOp.Op.ArrayType => |array_index| { - try stack.append(RenderState { .Text = "]"}); - try stack.append(RenderState { .Expression = array_index}); - try stack.append(RenderState { .Text = "["}); - }, - ast.Node.PrefixOp.Op.BitNot => try stream.write("~"), - ast.Node.PrefixOp.Op.BoolNot => try stream.write("!"), - ast.Node.PrefixOp.Op.Deref => try stream.write("*"), - ast.Node.PrefixOp.Op.Negation => try stream.write("-"), - ast.Node.PrefixOp.Op.NegationWrap => try stream.write("-%"), - ast.Node.PrefixOp.Op.Try => try stream.write("try "), - ast.Node.PrefixOp.Op.UnwrapMaybe => try stream.write("??"), - ast.Node.PrefixOp.Op.MaybeType => try stream.write("?"), - ast.Node.PrefixOp.Op.Await => try stream.write("await "), - ast.Node.PrefixOp.Op.Cancel => try stream.write("cancel "), - ast.Node.PrefixOp.Op.Resume => try stream.write("resume "), - } - }, - ast.Node.Id.SuffixOp => { - const suffix_op = @fieldParentPtr(ast.Node.SuffixOp, "base", base); - - switch (suffix_op.op) { - @TagType(ast.Node.SuffixOp.Op).Call => |*call_info| { - try stack.append(RenderState { .Text = ")"}); - var i = call_info.params.len; - while (i != 0) { - i -= 1; - const param_node = *call_info.params.at(i); - try stack.append(RenderState { .Expression = param_node}); - if (i != 0) { - try stack.append(RenderState { .Text = ", " }); - } - } - try stack.append(RenderState { .Text = "("}); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - - if (call_info.async_attr) |async_attr| { - try stack.append(RenderState { .Text = " "}); - try stack.append(RenderState { .Expression = &async_attr.base }); - } - }, - ast.Node.SuffixOp.Op.ArrayAccess => |index_expr| { - try stack.append(RenderState { .Text = "]"}); - try stack.append(RenderState { .Expression = index_expr}); - try stack.append(RenderState { .Text = "["}); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - }, - @TagType(ast.Node.SuffixOp.Op).Slice => |range| { - try stack.append(RenderState { .Text = "]"}); - if (range.end) |end| { - try stack.append(RenderState { .Expression = end}); - } - try stack.append(RenderState { .Text = ".."}); - try stack.append(RenderState { .Expression = range.start}); - try stack.append(RenderState { .Text = "["}); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - }, - ast.Node.SuffixOp.Op.StructInitializer => |*field_inits| { - if (field_inits.len == 0) { - try stack.append(RenderState { .Text = "{}" }); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - continue; - } - if (field_inits.len == 1) { - const field_init = *field_inits.at(0); - - try stack.append(RenderState { .Text = " }" }); - try stack.append(RenderState { .Expression = field_init }); - try stack.append(RenderState { .Text = "{ " }); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - continue; - } - try stack.append(RenderState { .Text = "}"}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent }); - try stack.append(RenderState { .Text = "\n" }); - var i = field_inits.len; - while (i != 0) { - i -= 1; - const field_init = *field_inits.at(i); - if (field_init.id != ast.Node.Id.LineComment) { - try stack.append(RenderState { .Text = "," }); - } - try stack.append(RenderState { .Expression = field_init }); - try stack.append(RenderState.PrintIndent); - if (i != 0) { - try stack.append(RenderState { .Text = blk: { - const prev_node = *field_inits.at(i - 1); - const prev_node_last_token_end = tree.tokens.at(prev_node.lastToken()).end; - const loc = tree.tokenLocation(prev_node_last_token_end, field_init.firstToken()); - if (loc.line >= 2) { - break :blk "\n\n"; - } - break :blk "\n"; - }}); - } - } - try stack.append(RenderState { .Indent = indent + indent_delta }); - try stack.append(RenderState { .Text = "{\n"}); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - }, - ast.Node.SuffixOp.Op.ArrayInitializer => |*exprs| { - if (exprs.len == 0) { - try stack.append(RenderState { .Text = "{}" }); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - continue; - } - if (exprs.len == 1) { - const expr = *exprs.at(0); - - try stack.append(RenderState { .Text = "}" }); - try stack.append(RenderState { .Expression = expr }); - try stack.append(RenderState { .Text = "{" }); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - continue; - } - - try stack.append(RenderState { .Text = "}"}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent }); - var i = exprs.len; - while (i != 0) { - i -= 1; - const expr = *exprs.at(i); - try stack.append(RenderState { .Text = ",\n" }); - try stack.append(RenderState { .Expression = expr }); - try stack.append(RenderState.PrintIndent); - } - try stack.append(RenderState { .Indent = indent + indent_delta }); - try stack.append(RenderState { .Text = "{\n"}); - try stack.append(RenderState { .Expression = suffix_op.lhs }); - }, - } - }, - ast.Node.Id.ControlFlowExpression => { - const flow_expr = @fieldParentPtr(ast.Node.ControlFlowExpression, "base", base); - - if (flow_expr.rhs) |rhs| { - try stack.append(RenderState { .Expression = rhs }); - try stack.append(RenderState { .Text = " " }); - } - - switch (flow_expr.kind) { - ast.Node.ControlFlowExpression.Kind.Break => |maybe_label| { - try stream.print("break"); - if (maybe_label) |label| { - try stream.print(" :"); - try stack.append(RenderState { .Expression = label }); - } - }, - ast.Node.ControlFlowExpression.Kind.Continue => |maybe_label| { - try stream.print("continue"); - if (maybe_label) |label| { - try stream.print(" :"); - try stack.append(RenderState { .Expression = label }); - } - }, - ast.Node.ControlFlowExpression.Kind.Return => { - try stream.print("return"); - }, - - } - }, - ast.Node.Id.Payload => { - const payload = @fieldParentPtr(ast.Node.Payload, "base", base); - try stack.append(RenderState { .Text = "|"}); - try stack.append(RenderState { .Expression = payload.error_symbol }); - try stack.append(RenderState { .Text = "|"}); - }, - ast.Node.Id.PointerPayload => { - const payload = @fieldParentPtr(ast.Node.PointerPayload, "base", base); - try stack.append(RenderState { .Text = "|"}); - try stack.append(RenderState { .Expression = payload.value_symbol }); - - if (payload.ptr_token) |ptr_token| { - try stack.append(RenderState { .Text = tree.tokenSlice(ptr_token) }); - } - - try stack.append(RenderState { .Text = "|"}); - }, - ast.Node.Id.PointerIndexPayload => { - const payload = @fieldParentPtr(ast.Node.PointerIndexPayload, "base", base); - try stack.append(RenderState { .Text = "|"}); - - if (payload.index_symbol) |index_symbol| { - try stack.append(RenderState { .Expression = index_symbol }); - try stack.append(RenderState { .Text = ", "}); - } - - try stack.append(RenderState { .Expression = payload.value_symbol }); - - if (payload.ptr_token) |ptr_token| { - try stack.append(RenderState { .Text = tree.tokenSlice(ptr_token) }); - } - - try stack.append(RenderState { .Text = "|"}); - }, - ast.Node.Id.GroupedExpression => { - const grouped_expr = @fieldParentPtr(ast.Node.GroupedExpression, "base", base); - try stack.append(RenderState { .Text = ")"}); - try stack.append(RenderState { .Expression = grouped_expr.expr }); - try stack.append(RenderState { .Text = "("}); - }, - ast.Node.Id.FieldInitializer => { - const field_init = @fieldParentPtr(ast.Node.FieldInitializer, "base", base); - try stream.print(".{} = ", tree.tokenSlice(field_init.name_token)); - try stack.append(RenderState { .Expression = field_init.expr }); - }, - ast.Node.Id.IntegerLiteral => { - const integer_literal = @fieldParentPtr(ast.Node.IntegerLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(integer_literal.token)); - }, - ast.Node.Id.FloatLiteral => { - const float_literal = @fieldParentPtr(ast.Node.FloatLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(float_literal.token)); - }, - ast.Node.Id.StringLiteral => { - const string_literal = @fieldParentPtr(ast.Node.StringLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(string_literal.token)); - }, - ast.Node.Id.CharLiteral => { - const char_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(char_literal.token)); - }, - ast.Node.Id.BoolLiteral => { - const bool_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(bool_literal.token)); - }, - ast.Node.Id.NullLiteral => { - const null_literal = @fieldParentPtr(ast.Node.NullLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(null_literal.token)); - }, - ast.Node.Id.ThisLiteral => { - const this_literal = @fieldParentPtr(ast.Node.ThisLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(this_literal.token)); - }, - ast.Node.Id.Unreachable => { - const unreachable_node = @fieldParentPtr(ast.Node.Unreachable, "base", base); - try stream.print("{}", tree.tokenSlice(unreachable_node.token)); - }, - ast.Node.Id.ErrorType => { - const error_type = @fieldParentPtr(ast.Node.ErrorType, "base", base); - try stream.print("{}", tree.tokenSlice(error_type.token)); - }, - ast.Node.Id.VarType => { - const var_type = @fieldParentPtr(ast.Node.VarType, "base", base); - try stream.print("{}", tree.tokenSlice(var_type.token)); - }, - ast.Node.Id.ContainerDecl => { - const container_decl = @fieldParentPtr(ast.Node.ContainerDecl, "base", base); - - switch (container_decl.layout) { - ast.Node.ContainerDecl.Layout.Packed => try stream.print("packed "), - ast.Node.ContainerDecl.Layout.Extern => try stream.print("extern "), - ast.Node.ContainerDecl.Layout.Auto => { }, - } - - switch (container_decl.kind) { - ast.Node.ContainerDecl.Kind.Struct => try stream.print("struct"), - ast.Node.ContainerDecl.Kind.Enum => try stream.print("enum"), - ast.Node.ContainerDecl.Kind.Union => try stream.print("union"), - } - - if (container_decl.fields_and_decls.len == 0) { - try stack.append(RenderState { .Text = "{}"}); - } else { - try stack.append(RenderState { .Text = "}"}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent }); - try stack.append(RenderState { .Text = "\n"}); - - var i = container_decl.fields_and_decls.len; - while (i != 0) { - i -= 1; - const node = *container_decl.fields_and_decls.at(i); - try stack.append(RenderState { .TopLevelDecl = node}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { - .Text = blk: { - if (i != 0) { - const prev_node = *container_decl.fields_and_decls.at(i - 1); - const prev_node_last_token_end = tree.tokens.at(prev_node.lastToken()).end; - const loc = tree.tokenLocation(prev_node_last_token_end, node.firstToken()); - if (loc.line >= 2) { - break :blk "\n\n"; - } - } - break :blk "\n"; - }, - }); - } - try stack.append(RenderState { .Indent = indent + indent_delta}); - try stack.append(RenderState { .Text = "{"}); - } - - switch (container_decl.init_arg_expr) { - ast.Node.ContainerDecl.InitArg.None => try stack.append(RenderState { .Text = " "}), - ast.Node.ContainerDecl.InitArg.Enum => |enum_tag_type| { - if (enum_tag_type) |expr| { - try stack.append(RenderState { .Text = ")) "}); - try stack.append(RenderState { .Expression = expr}); - try stack.append(RenderState { .Text = "(enum("}); - } else { - try stack.append(RenderState { .Text = "(enum) "}); - } - }, - ast.Node.ContainerDecl.InitArg.Type => |type_expr| { - try stack.append(RenderState { .Text = ") "}); - try stack.append(RenderState { .Expression = type_expr}); - try stack.append(RenderState { .Text = "("}); - }, - } - }, - ast.Node.Id.ErrorSetDecl => { - const err_set_decl = @fieldParentPtr(ast.Node.ErrorSetDecl, "base", base); - - if (err_set_decl.decls.len == 0) { - try stream.write("error{}"); - continue; - } - - if (err_set_decl.decls.len == 1) blk: { - const node = *err_set_decl.decls.at(0); - - // if there are any doc comments or same line comments - // don't try to put it all on one line - if (node.cast(ast.Node.ErrorTag)) |tag| { - if (tag.doc_comments != null) break :blk; - } else { - break :blk; - } - - - try stream.write("error{"); - try stack.append(RenderState { .Text = "}" }); - try stack.append(RenderState { .TopLevelDecl = node }); - continue; - } - - try stream.write("error{"); - - try stack.append(RenderState { .Text = "}"}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent }); - try stack.append(RenderState { .Text = "\n"}); - - var i = err_set_decl.decls.len; - while (i != 0) { - i -= 1; - const node = *err_set_decl.decls.at(i); - if (node.id != ast.Node.Id.LineComment) { - try stack.append(RenderState { .Text = "," }); - } - try stack.append(RenderState { .TopLevelDecl = node }); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { - .Text = blk: { - if (i != 0) { - const prev_node = *err_set_decl.decls.at(i - 1); - const prev_node_last_token_end = tree.tokens.at(prev_node.lastToken()).end; - const loc = tree.tokenLocation(prev_node_last_token_end, node.firstToken()); - if (loc.line >= 2) { - break :blk "\n\n"; - } - } - break :blk "\n"; - }, - }); - } - try stack.append(RenderState { .Indent = indent + indent_delta}); - }, - ast.Node.Id.MultilineStringLiteral => { - const multiline_str_literal = @fieldParentPtr(ast.Node.MultilineStringLiteral, "base", base); - try stream.print("\n"); - - var i : usize = 0; - while (i < multiline_str_literal.lines.len) : (i += 1) { - const t = *multiline_str_literal.lines.at(i); - try stream.writeByteNTimes(' ', indent + indent_delta); - try stream.print("{}", tree.tokenSlice(t)); - } - try stream.writeByteNTimes(' ', indent); - }, - ast.Node.Id.UndefinedLiteral => { - const undefined_literal = @fieldParentPtr(ast.Node.UndefinedLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(undefined_literal.token)); - }, - ast.Node.Id.BuiltinCall => { - const builtin_call = @fieldParentPtr(ast.Node.BuiltinCall, "base", base); - try stream.print("{}(", tree.tokenSlice(builtin_call.builtin_token)); - try stack.append(RenderState { .Text = ")"}); - var i = builtin_call.params.len; - while (i != 0) { - i -= 1; - const param_node = *builtin_call.params.at(i); - try stack.append(RenderState { .Expression = param_node}); - if (i != 0) { - try stack.append(RenderState { .Text = ", " }); - } - } - }, - ast.Node.Id.FnProto => { - const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", base); - - switch (fn_proto.return_type) { - ast.Node.FnProto.ReturnType.Explicit => |node| { - try stack.append(RenderState { .Expression = node}); - }, - ast.Node.FnProto.ReturnType.InferErrorSet => |node| { - try stack.append(RenderState { .Expression = node}); - try stack.append(RenderState { .Text = "!"}); - }, - } - - if (fn_proto.align_expr) |align_expr| { - try stack.append(RenderState { .Text = ") " }); - try stack.append(RenderState { .Expression = align_expr}); - try stack.append(RenderState { .Text = "align(" }); - } - - try stack.append(RenderState { .Text = ") " }); - var i = fn_proto.params.len; - while (i != 0) { - i -= 1; - const param_decl_node = *fn_proto.params.at(i); - try stack.append(RenderState { .ParamDecl = param_decl_node}); - if (i != 0) { - try stack.append(RenderState { .Text = ", " }); - } - } - - try stack.append(RenderState { .Text = "(" }); - if (fn_proto.name_token) |name_token| { - try stack.append(RenderState { .Text = tree.tokenSlice(name_token) }); - try stack.append(RenderState { .Text = " " }); - } - - try stack.append(RenderState { .Text = "fn" }); - - if (fn_proto.async_attr) |async_attr| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = &async_attr.base }); - } - - if (fn_proto.cc_token) |cc_token| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Text = tree.tokenSlice(cc_token) }); - } - - if (fn_proto.lib_name) |lib_name| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = lib_name }); - } - if (fn_proto.extern_export_inline_token) |extern_export_inline_token| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Text = tree.tokenSlice(extern_export_inline_token) }); - } - - if (fn_proto.visib_token) |visib_token_index| { - const visib_token = tree.tokens.at(visib_token_index); - assert(visib_token.id == Token.Id.Keyword_pub or visib_token.id == Token.Id.Keyword_export); - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Text = tree.tokenSlice(visib_token_index) }); - } - }, - ast.Node.Id.PromiseType => { - const promise_type = @fieldParentPtr(ast.Node.PromiseType, "base", base); - try stream.write(tree.tokenSlice(promise_type.promise_token)); - if (promise_type.result) |result| { - try stream.write(tree.tokenSlice(result.arrow_token)); - try stack.append(RenderState { .Expression = result.return_type}); - } - }, - ast.Node.Id.LineComment => { - const line_comment_node = @fieldParentPtr(ast.Node.LineComment, "base", base); - try stream.write(tree.tokenSlice(line_comment_node.token)); - }, - ast.Node.Id.DocComment => unreachable, // doc comments are attached to nodes - ast.Node.Id.Switch => { - const switch_node = @fieldParentPtr(ast.Node.Switch, "base", base); - - try stream.print("{} (", tree.tokenSlice(switch_node.switch_token)); - - if (switch_node.cases.len == 0) { - try stack.append(RenderState { .Text = ") {}"}); - try stack.append(RenderState { .Expression = switch_node.expr }); - continue; - } - - try stack.append(RenderState { .Text = "}"}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent }); - try stack.append(RenderState { .Text = "\n"}); - - var i = switch_node.cases.len; - while (i != 0) { - i -= 1; - const node = *switch_node.cases.at(i); - try stack.append(RenderState { .Expression = node}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { - .Text = blk: { - if (i != 0) { - const prev_node = *switch_node.cases.at(i - 1); - const prev_node_last_token_end = tree.tokens.at(prev_node.lastToken()).end; - const loc = tree.tokenLocation(prev_node_last_token_end, node.firstToken()); - if (loc.line >= 2) { - break :blk "\n\n"; - } - } - break :blk "\n"; - }, - }); - } - try stack.append(RenderState { .Indent = indent + indent_delta}); - try stack.append(RenderState { .Text = ") {"}); - try stack.append(RenderState { .Expression = switch_node.expr }); - }, - ast.Node.Id.SwitchCase => { - const switch_case = @fieldParentPtr(ast.Node.SwitchCase, "base", base); - - try stack.append(RenderState { .Token = switch_case.lastToken() + 1 }); - try stack.append(RenderState { .Expression = switch_case.expr }); - if (switch_case.payload) |payload| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = payload }); - } - try stack.append(RenderState { .Text = " => "}); - - var i = switch_case.items.len; - while (i != 0) { - i -= 1; - try stack.append(RenderState { .Expression = *switch_case.items.at(i) }); - - if (i != 0) { - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Text = ",\n" }); - } - } - }, - ast.Node.Id.SwitchElse => { - const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base); - try stream.print("{}", tree.tokenSlice(switch_else.token)); - }, - ast.Node.Id.Else => { - const else_node = @fieldParentPtr(ast.Node.Else, "base", base); - try stream.print("{}", tree.tokenSlice(else_node.else_token)); - - switch (else_node.body.id) { - ast.Node.Id.Block, ast.Node.Id.If, - ast.Node.Id.For, ast.Node.Id.While, - ast.Node.Id.Switch => { - try stream.print(" "); - try stack.append(RenderState { .Expression = else_node.body }); - }, - else => { - try stack.append(RenderState { .Indent = indent }); - try stack.append(RenderState { .Expression = else_node.body }); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent + indent_delta }); - try stack.append(RenderState { .Text = "\n" }); - } - } - - if (else_node.payload) |payload| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = payload }); - } - }, - ast.Node.Id.While => { - const while_node = @fieldParentPtr(ast.Node.While, "base", base); - if (while_node.label) |label| { - try stream.print("{}: ", tree.tokenSlice(label)); - } - - if (while_node.inline_token) |inline_token| { - try stream.print("{} ", tree.tokenSlice(inline_token)); - } - - try stream.print("{} ", tree.tokenSlice(while_node.while_token)); - - if (while_node.@"else") |@"else"| { - try stack.append(RenderState { .Expression = &@"else".base }); - - if (while_node.body.id == ast.Node.Id.Block) { - try stack.append(RenderState { .Text = " " }); - } else { - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Text = "\n" }); - } - } - - if (while_node.body.id == ast.Node.Id.Block) { - try stack.append(RenderState { .Expression = while_node.body }); - try stack.append(RenderState { .Text = " " }); - } else { - try stack.append(RenderState { .Indent = indent }); - try stack.append(RenderState { .Expression = while_node.body }); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent + indent_delta }); - try stack.append(RenderState { .Text = "\n" }); - } - - if (while_node.continue_expr) |continue_expr| { - try stack.append(RenderState { .Text = ")" }); - try stack.append(RenderState { .Expression = continue_expr }); - try stack.append(RenderState { .Text = ": (" }); - try stack.append(RenderState { .Text = " " }); - } - - if (while_node.payload) |payload| { - try stack.append(RenderState { .Expression = payload }); - try stack.append(RenderState { .Text = " " }); - } - - try stack.append(RenderState { .Text = ")" }); - try stack.append(RenderState { .Expression = while_node.condition }); - try stack.append(RenderState { .Text = "(" }); - }, - ast.Node.Id.For => { - const for_node = @fieldParentPtr(ast.Node.For, "base", base); - if (for_node.label) |label| { - try stream.print("{}: ", tree.tokenSlice(label)); - } - - if (for_node.inline_token) |inline_token| { - try stream.print("{} ", tree.tokenSlice(inline_token)); - } - - try stream.print("{} ", tree.tokenSlice(for_node.for_token)); - - if (for_node.@"else") |@"else"| { - try stack.append(RenderState { .Expression = &@"else".base }); - - if (for_node.body.id == ast.Node.Id.Block) { - try stack.append(RenderState { .Text = " " }); - } else { - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Text = "\n" }); - } - } - - if (for_node.body.id == ast.Node.Id.Block) { - try stack.append(RenderState { .Expression = for_node.body }); - try stack.append(RenderState { .Text = " " }); - } else { - try stack.append(RenderState { .Indent = indent }); - try stack.append(RenderState { .Expression = for_node.body }); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent + indent_delta }); - try stack.append(RenderState { .Text = "\n" }); - } - - if (for_node.payload) |payload| { - try stack.append(RenderState { .Expression = payload }); - try stack.append(RenderState { .Text = " " }); - } - - try stack.append(RenderState { .Text = ")" }); - try stack.append(RenderState { .Expression = for_node.array_expr }); - try stack.append(RenderState { .Text = "(" }); - }, - ast.Node.Id.If => { - const if_node = @fieldParentPtr(ast.Node.If, "base", base); - try stream.print("{} ", tree.tokenSlice(if_node.if_token)); - - switch (if_node.body.id) { - ast.Node.Id.Block, ast.Node.Id.If, - ast.Node.Id.For, ast.Node.Id.While, - ast.Node.Id.Switch => { - if (if_node.@"else") |@"else"| { - try stack.append(RenderState { .Expression = &@"else".base }); - - if (if_node.body.id == ast.Node.Id.Block) { - try stack.append(RenderState { .Text = " " }); - } else { - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Text = "\n" }); - } - } - }, - else => { - if (if_node.@"else") |@"else"| { - try stack.append(RenderState { .Expression = @"else".body }); - - if (@"else".payload) |payload| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = payload }); - } - - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Text = tree.tokenSlice(@"else".else_token) }); - try stack.append(RenderState { .Text = " " }); - } - } - } - - try stack.append(RenderState { .Expression = if_node.body }); - - if (if_node.payload) |payload| { - try stack.append(RenderState { .Text = " " }); - try stack.append(RenderState { .Expression = payload }); - } - - try stack.append(RenderState { .NonBreakToken = if_node.condition.lastToken() + 1 }); - try stack.append(RenderState { .Expression = if_node.condition }); - try stack.append(RenderState { .Text = "(" }); - }, - ast.Node.Id.Asm => { - const asm_node = @fieldParentPtr(ast.Node.Asm, "base", base); - try stream.print("{} ", tree.tokenSlice(asm_node.asm_token)); - - if (asm_node.volatile_token) |volatile_token| { - try stream.print("{} ", tree.tokenSlice(volatile_token)); - } - - try stack.append(RenderState { .Indent = indent }); - try stack.append(RenderState { .Text = ")" }); - { - var i = asm_node.clobbers.len; - while (i != 0) { - i -= 1; - try stack.append(RenderState { .Expression = *asm_node.clobbers.at(i) }); - - if (i != 0) { - try stack.append(RenderState { .Text = ", " }); - } - } - } - try stack.append(RenderState { .Text = ": " }); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent + indent_delta }); - try stack.append(RenderState { .Text = "\n" }); - { - var i = asm_node.inputs.len; - while (i != 0) { - i -= 1; - const node = *asm_node.inputs.at(i); - try stack.append(RenderState { .Expression = &node.base}); - - if (i != 0) { - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { - .Text = blk: { - const prev_node = *asm_node.inputs.at(i - 1); - const prev_node_last_token_end = tree.tokens.at(prev_node.lastToken()).end; - const loc = tree.tokenLocation(prev_node_last_token_end, node.firstToken()); - if (loc.line >= 2) { - break :blk "\n\n"; - } - break :blk "\n"; - }, - }); - try stack.append(RenderState { .Text = "," }); - } - } - } - try stack.append(RenderState { .Indent = indent + indent_delta + 2}); - try stack.append(RenderState { .Text = ": "}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent + indent_delta}); - try stack.append(RenderState { .Text = "\n" }); - { - var i = asm_node.outputs.len; - while (i != 0) { - i -= 1; - const node = *asm_node.outputs.at(i); - try stack.append(RenderState { .Expression = &node.base}); - - if (i != 0) { - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { - .Text = blk: { - const prev_node = *asm_node.outputs.at(i - 1); - const prev_node_last_token_end = tree.tokens.at(prev_node.lastToken()).end; - const loc = tree.tokenLocation(prev_node_last_token_end, node.firstToken()); - if (loc.line >= 2) { - break :blk "\n\n"; - } - break :blk "\n"; - }, - }); - try stack.append(RenderState { .Text = "," }); - } - } - } - try stack.append(RenderState { .Indent = indent + indent_delta + 2}); - try stack.append(RenderState { .Text = ": "}); - try stack.append(RenderState.PrintIndent); - try stack.append(RenderState { .Indent = indent + indent_delta}); - try stack.append(RenderState { .Text = "\n" }); - try stack.append(RenderState { .Expression = asm_node.template }); - try stack.append(RenderState { .Text = "(" }); - }, - ast.Node.Id.AsmInput => { - const asm_input = @fieldParentPtr(ast.Node.AsmInput, "base", base); - - try stack.append(RenderState { .Text = ")"}); - try stack.append(RenderState { .Expression = asm_input.expr}); - try stack.append(RenderState { .Text = " ("}); - try stack.append(RenderState { .Expression = asm_input.constraint }); - try stack.append(RenderState { .Text = "] "}); - try stack.append(RenderState { .Expression = asm_input.symbolic_name }); - try stack.append(RenderState { .Text = "["}); - }, - ast.Node.Id.AsmOutput => { - const asm_output = @fieldParentPtr(ast.Node.AsmOutput, "base", base); - - try stack.append(RenderState { .Text = ")"}); - switch (asm_output.kind) { - ast.Node.AsmOutput.Kind.Variable => |variable_name| { - try stack.append(RenderState { .Expression = &variable_name.base}); - }, - ast.Node.AsmOutput.Kind.Return => |return_type| { - try stack.append(RenderState { .Expression = return_type}); - try stack.append(RenderState { .Text = "-> "}); - }, - } - try stack.append(RenderState { .Text = " ("}); - try stack.append(RenderState { .Expression = asm_output.constraint }); - try stack.append(RenderState { .Text = "] "}); - try stack.append(RenderState { .Expression = asm_output.symbolic_name }); - try stack.append(RenderState { .Text = "["}); - }, - - ast.Node.Id.StructField, - ast.Node.Id.UnionTag, - ast.Node.Id.EnumTag, - ast.Node.Id.ErrorTag, - ast.Node.Id.Root, - ast.Node.Id.VarDecl, - ast.Node.Id.Use, - ast.Node.Id.TestDecl, - ast.Node.Id.ParamDecl => unreachable, - }, - RenderState.Statement => |base| { - switch (base.id) { - ast.Node.Id.VarDecl => { - const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base); - try stack.append(RenderState { .VarDecl = var_decl}); - }, - else => { - try stack.append(RenderState { .MaybeSemiColon = base }); - try stack.append(RenderState { .Expression = base }); - }, - } - }, - RenderState.Indent => |new_indent| indent = new_indent, - RenderState.PrintIndent => try stream.writeByteNTimes(' ', indent), - RenderState.Token => |token_index| try renderToken(tree, stream, token_index, indent, true), - RenderState.NonBreakToken => |token_index| try renderToken(tree, stream, token_index, indent, false), - RenderState.MaybeSemiColon => |base| { - if (base.requireSemiColon()) { - const semicolon_index = base.lastToken() + 1; - assert(tree.tokens.at(semicolon_index).id == Token.Id.Semicolon); - try renderToken(tree, stream, semicolon_index, indent, true); - } - }, - } +fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, decl: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { + switch (decl.id) { + ast.Node.Id.FnProto => { + const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl); + + try renderComments(tree, stream, fn_proto, indent); + try renderExpression(allocator, stream, tree, indent, decl); + + if (fn_proto.body_node) |body_node| { + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, body_node); + } else { + try stream.write(";"); + } + }, + ast.Node.Id.Use => { + const use_decl = @fieldParentPtr(ast.Node.Use, "base", decl); + + if (use_decl.visib_token) |visib_token| { + try stream.print("{} ", tree.tokenSlice(visib_token)); + } + try stream.write("use "); + try renderExpression(allocator, stream, tree, indent, use_decl.expr); + try stream.write(";"); + }, + ast.Node.Id.VarDecl => { + const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", decl); + + try renderComments(tree, stream, var_decl, indent); + try renderVarDecl(allocator, stream, tree, indent, var_decl); + }, + ast.Node.Id.TestDecl => { + const test_decl = @fieldParentPtr(ast.Node.TestDecl, "base", decl); + + try renderComments(tree, stream, test_decl, indent); + try stream.write("test "); + try renderExpression(allocator, stream, tree, indent, test_decl.name); + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, test_decl.body_node); + }, + ast.Node.Id.StructField => { + const field = @fieldParentPtr(ast.Node.StructField, "base", decl); + + try renderComments(tree, stream, field, indent); + if (field.visib_token) |visib_token| { + try stream.print("{} ", tree.tokenSlice(visib_token)); + } + try stream.print("{}: ", tree.tokenSlice(field.name_token)); + try renderExpression(allocator, stream, tree, indent, field.type_expr); + try renderToken(tree, stream, field.lastToken() + 1, indent, true); + }, + ast.Node.Id.UnionTag => { + const tag = @fieldParentPtr(ast.Node.UnionTag, "base", decl); + + try renderComments(tree, stream, tag, indent); + try stream.print("{}", tree.tokenSlice(tag.name_token)); + + if (tag.type_expr) |type_expr| { + try stream.print(": "); + try renderExpression(allocator, stream, tree, indent, type_expr); + } + + if (tag.value_expr) |value_expr| { + try stream.print(" = "); + try renderExpression(allocator, stream, tree, indent, value_expr); + } + + try stream.write(","); + }, + ast.Node.Id.EnumTag => { + const tag = @fieldParentPtr(ast.Node.EnumTag, "base", decl); + + try renderComments(tree, stream, tag, indent); + try stream.print("{}", tree.tokenSlice(tag.name_token)); + + if (tag.value) |value| { + try stream.print(" = "); + try renderExpression(allocator, stream, tree, indent, value); + } + + try stream.write(","); + }, + ast.Node.Id.ErrorTag => { + const tag = @fieldParentPtr(ast.Node.ErrorTag, "base", decl); + + try renderComments(tree, stream, tag, indent); + try stream.print("{}", tree.tokenSlice(tag.name_token)); + }, + ast.Node.Id.Comptime => { + try renderExpression(allocator, stream, tree, indent, decl); + try maybeRenderSemicolon(stream, tree, indent, decl); + }, + ast.Node.Id.LineComment => { + const line_comment_node = @fieldParentPtr(ast.Node.LineComment, "base", decl); + + try stream.write(tree.tokenSlice(line_comment_node.token)); + }, + else => unreachable, } } -fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, line_break: bool) !void { +fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { + switch (base.id) { + ast.Node.Id.Identifier => { + const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base); + try stream.print("{}", tree.tokenSlice(identifier.token)); + }, + ast.Node.Id.Block => { + const block = @fieldParentPtr(ast.Node.Block, "base", base); + if (block.label) |label| { + try stream.print("{}: ", tree.tokenSlice(label)); + } + + if (block.statements.len == 0) { + try stream.write("{}"); + } else { + try stream.write("{\n"); + const block_indent = indent + indent_delta; + + var it = block.statements.iterator(0); + while (it.next()) |statement| { + try stream.writeByteNTimes(' ', block_indent); + try renderStatement(allocator, stream, tree, block_indent, *statement); + + if (it.peek()) |next_statement| { + const n = if (nodeLineOffset(tree, *statement, *next_statement) >= 2) u8(2) else u8(1); + try stream.writeByteNTimes('\n', n); + } + } + + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + try stream.write("}"); + } + }, + ast.Node.Id.Defer => { + const defer_node = @fieldParentPtr(ast.Node.Defer, "base", base); + try stream.print("{} ", tree.tokenSlice(defer_node.defer_token)); + try renderExpression(allocator, stream, tree, indent, defer_node.expr); + }, + ast.Node.Id.Comptime => { + const comptime_node = @fieldParentPtr(ast.Node.Comptime, "base", base); + try stream.print("{} ", tree.tokenSlice(comptime_node.comptime_token)); + try renderExpression(allocator, stream, tree, indent, comptime_node.expr); + }, + ast.Node.Id.AsyncAttribute => { + const async_attr = @fieldParentPtr(ast.Node.AsyncAttribute, "base", base); + try stream.print("{}", tree.tokenSlice(async_attr.async_token)); + + if (async_attr.allocator_type) |allocator_type| { + try stream.write("<"); + try renderExpression(allocator, stream, tree, indent, allocator_type); + try stream.write(">"); + } + }, + ast.Node.Id.Suspend => { + const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base); + if (suspend_node.label) |label| { + try stream.print("{}: ", tree.tokenSlice(label)); + } + try stream.print("{}", tree.tokenSlice(suspend_node.suspend_token)); + + if (suspend_node.payload) |payload| { + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, payload); + } + + if (suspend_node.body) |body| { + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, body); + } + + }, + + ast.Node.Id.InfixOp => { + const infix_op_node = @fieldParentPtr(ast.Node.InfixOp, "base", base); + + try renderExpression(allocator, stream, tree, indent, infix_op_node.lhs); + + const text = switch (infix_op_node.op) { + ast.Node.InfixOp.Op.Add => " + ", + ast.Node.InfixOp.Op.AddWrap => " +% ", + ast.Node.InfixOp.Op.ArrayCat => " ++ ", + ast.Node.InfixOp.Op.ArrayMult => " ** ", + ast.Node.InfixOp.Op.Assign => " = ", + ast.Node.InfixOp.Op.AssignBitAnd => " &= ", + ast.Node.InfixOp.Op.AssignBitOr => " |= ", + ast.Node.InfixOp.Op.AssignBitShiftLeft => " <<= ", + ast.Node.InfixOp.Op.AssignBitShiftRight => " >>= ", + ast.Node.InfixOp.Op.AssignBitXor => " ^= ", + ast.Node.InfixOp.Op.AssignDiv => " /= ", + ast.Node.InfixOp.Op.AssignMinus => " -= ", + ast.Node.InfixOp.Op.AssignMinusWrap => " -%= ", + ast.Node.InfixOp.Op.AssignMod => " %= ", + ast.Node.InfixOp.Op.AssignPlus => " += ", + ast.Node.InfixOp.Op.AssignPlusWrap => " +%= ", + ast.Node.InfixOp.Op.AssignTimes => " *= ", + ast.Node.InfixOp.Op.AssignTimesWarp => " *%= ", + ast.Node.InfixOp.Op.BangEqual => " != ", + ast.Node.InfixOp.Op.BitAnd => " & ", + ast.Node.InfixOp.Op.BitOr => " | ", + ast.Node.InfixOp.Op.BitShiftLeft => " << ", + ast.Node.InfixOp.Op.BitShiftRight => " >> ", + ast.Node.InfixOp.Op.BitXor => " ^ ", + ast.Node.InfixOp.Op.BoolAnd => " and ", + ast.Node.InfixOp.Op.BoolOr => " or ", + ast.Node.InfixOp.Op.Div => " / ", + ast.Node.InfixOp.Op.EqualEqual => " == ", + ast.Node.InfixOp.Op.ErrorUnion => "!", + ast.Node.InfixOp.Op.GreaterOrEqual => " >= ", + ast.Node.InfixOp.Op.GreaterThan => " > ", + ast.Node.InfixOp.Op.LessOrEqual => " <= ", + ast.Node.InfixOp.Op.LessThan => " < ", + ast.Node.InfixOp.Op.MergeErrorSets => " || ", + ast.Node.InfixOp.Op.Mod => " % ", + ast.Node.InfixOp.Op.Mult => " * ", + ast.Node.InfixOp.Op.MultWrap => " *% ", + ast.Node.InfixOp.Op.Period => ".", + ast.Node.InfixOp.Op.Sub => " - ", + ast.Node.InfixOp.Op.SubWrap => " -% ", + ast.Node.InfixOp.Op.UnwrapMaybe => " ?? ", + ast.Node.InfixOp.Op.Range => " ... ", + ast.Node.InfixOp.Op.Catch => |maybe_payload| blk: { + try stream.write(" catch "); + if (maybe_payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload); + try stream.write(" "); + } + break :blk ""; + }, + }; + + try stream.write(text); + try renderExpression(allocator, stream, tree, indent, infix_op_node.rhs); + }, + + ast.Node.Id.PrefixOp => { + const prefix_op_node = @fieldParentPtr(ast.Node.PrefixOp, "base", base); + + switch (prefix_op_node.op) { + ast.Node.PrefixOp.Op.AddrOf => |addr_of_info| { + try stream.write("&"); + if (addr_of_info.align_expr) |align_expr| { + try stream.write("align("); + try renderExpression(allocator, stream, tree, indent, align_expr); + try stream.write(") "); + } + if (addr_of_info.const_token != null) { + try stream.write("const "); + } + if (addr_of_info.volatile_token != null) { + try stream.write("volatile "); + } + }, + ast.Node.PrefixOp.Op.SliceType => |addr_of_info| { + try stream.write("[]"); + if (addr_of_info.align_expr) |align_expr| { + try stream.print("align("); + try renderExpression(allocator, stream, tree, indent, align_expr); + try stream.print(") "); + } + if (addr_of_info.const_token != null) { + try stream.print("const "); + } + if (addr_of_info.volatile_token != null) { + try stream.print("volatile "); + } + }, + ast.Node.PrefixOp.Op.ArrayType => |array_index| { + try stream.print("["); + try renderExpression(allocator, stream, tree, indent, array_index); + try stream.print("]"); + }, + ast.Node.PrefixOp.Op.BitNot => try stream.write("~"), + ast.Node.PrefixOp.Op.BoolNot => try stream.write("!"), + ast.Node.PrefixOp.Op.Deref => try stream.write("*"), + ast.Node.PrefixOp.Op.Negation => try stream.write("-"), + ast.Node.PrefixOp.Op.NegationWrap => try stream.write("-%"), + ast.Node.PrefixOp.Op.Try => try stream.write("try "), + ast.Node.PrefixOp.Op.UnwrapMaybe => try stream.write("??"), + ast.Node.PrefixOp.Op.MaybeType => try stream.write("?"), + ast.Node.PrefixOp.Op.Await => try stream.write("await "), + ast.Node.PrefixOp.Op.Cancel => try stream.write("cancel "), + ast.Node.PrefixOp.Op.Resume => try stream.write("resume "), + } + + try renderExpression(allocator, stream, tree, indent, prefix_op_node.rhs); + }, + + ast.Node.Id.SuffixOp => { + const suffix_op = @fieldParentPtr(ast.Node.SuffixOp, "base", base); + + switch (suffix_op.op) { + @TagType(ast.Node.SuffixOp.Op).Call => |*call_info| { + if (call_info.async_attr) |async_attr| { + try renderExpression(allocator, stream, tree, indent, &async_attr.base); + try stream.write(" "); + } + + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try stream.write("("); + + var it = call_info.params.iterator(0); + while (it.next()) |param_node| { + try renderExpression(allocator, stream, tree, indent, *param_node); + if (it.peek() != null) { + try stream.write(", "); + } + } + + try stream.write(")"); + }, + + ast.Node.SuffixOp.Op.ArrayAccess => |index_expr| { + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try stream.write("["); + try renderExpression(allocator, stream, tree, indent, index_expr); + try stream.write("]"); + }, + + @TagType(ast.Node.SuffixOp.Op).Slice => |range| { + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try stream.write("["); + try renderExpression(allocator, stream, tree, indent, range.start); + try stream.write(".."); + if (range.end) |end| { + try renderExpression(allocator, stream, tree, indent, end); + } + try stream.write("]"); + }, + + ast.Node.SuffixOp.Op.StructInitializer => |*field_inits| { + if (field_inits.len == 0) { + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try stream.write("{}"); + return; + } + + if (field_inits.len == 1) { + const field_init = *field_inits.at(0); + + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try stream.write("{ "); + try renderExpression(allocator, stream, tree, indent, field_init); + try stream.write(" }"); + return; + } + + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try stream.write("{\n"); + + const new_indent = indent + indent_delta; + + var it = field_inits.iterator(0); + while (it.next()) |field_init| { + try stream.writeByteNTimes(' ', new_indent); + try renderExpression(allocator, stream, tree, new_indent, *field_init); + if ((*field_init).id != ast.Node.Id.LineComment) { + try stream.write(","); + } + if (it.peek()) |next_field_init| { + const n = if (nodeLineOffset(tree, *field_init, *next_field_init) >= 2) u8(2) else u8(1); + try stream.writeByteNTimes('\n', n); + } + } + + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + try stream.write("}"); + }, + + ast.Node.SuffixOp.Op.ArrayInitializer => |*exprs| { + + if (exprs.len == 0) { + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try stream.write("{}"); + return; + } + if (exprs.len == 1) { + const expr = *exprs.at(0); + + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try stream.write("{"); + try renderExpression(allocator, stream, tree, indent, expr); + try stream.write("}"); + return; + } + + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + + const new_indent = indent + indent_delta; + try stream.write("{\n"); + + var it = exprs.iterator(0); + while (it.next()) |expr| { + try stream.writeByteNTimes(' ', new_indent); + try renderExpression(allocator, stream, tree, new_indent, *expr); + try stream.write(","); + + if (it.peek()) |next_expr| { + const n = if (nodeLineOffset(tree, *expr, *next_expr) >= 2) u8(2) else u8(1); + try stream.writeByteNTimes('\n', n); + } + } + + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + try stream.write("}"); + }, + } + }, + + ast.Node.Id.ControlFlowExpression => { + const flow_expr = @fieldParentPtr(ast.Node.ControlFlowExpression, "base", base); + + switch (flow_expr.kind) { + ast.Node.ControlFlowExpression.Kind.Break => |maybe_label| { + try stream.print("break"); + if (maybe_label) |label| { + try stream.print(" :"); + try renderExpression(allocator, stream, tree, indent, label); + } + }, + ast.Node.ControlFlowExpression.Kind.Continue => |maybe_label| { + try stream.print("continue"); + if (maybe_label) |label| { + try stream.print(" :"); + try renderExpression(allocator, stream, tree, indent, label); + } + }, + ast.Node.ControlFlowExpression.Kind.Return => { + try stream.print("return"); + }, + + } + + if (flow_expr.rhs) |rhs| { + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, rhs); + } + }, + + ast.Node.Id.Payload => { + const payload = @fieldParentPtr(ast.Node.Payload, "base", base); + + try stream.write("|"); + try renderExpression(allocator, stream, tree, indent, payload.error_symbol); + try stream.write("|"); + }, + + ast.Node.Id.PointerPayload => { + const payload = @fieldParentPtr(ast.Node.PointerPayload, "base", base); + + try stream.write("|"); + if (payload.ptr_token) |ptr_token| { + try stream.write(tree.tokenSlice(ptr_token)); + } + try renderExpression(allocator, stream, tree, indent, payload.value_symbol); + try stream.write("|"); + }, + + ast.Node.Id.PointerIndexPayload => { + const payload = @fieldParentPtr(ast.Node.PointerIndexPayload, "base", base); + + try stream.write("|"); + if (payload.ptr_token) |ptr_token| { + try stream.write(tree.tokenSlice(ptr_token)); + } + try renderExpression(allocator, stream, tree, indent, payload.value_symbol); + + if (payload.index_symbol) |index_symbol| { + try stream.write(", "); + try renderExpression(allocator, stream, tree, indent, index_symbol); + } + + try stream.write("|"); + }, + + ast.Node.Id.GroupedExpression => { + const grouped_expr = @fieldParentPtr(ast.Node.GroupedExpression, "base", base); + + try stream.write("("); + try renderExpression(allocator, stream, tree, indent, grouped_expr.expr); + try stream.write(")"); + }, + + ast.Node.Id.FieldInitializer => { + const field_init = @fieldParentPtr(ast.Node.FieldInitializer, "base", base); + + try stream.print(".{} = ", tree.tokenSlice(field_init.name_token)); + try renderExpression(allocator, stream, tree, indent, field_init.expr); + }, + + ast.Node.Id.IntegerLiteral => { + const integer_literal = @fieldParentPtr(ast.Node.IntegerLiteral, "base", base); + try stream.print("{}", tree.tokenSlice(integer_literal.token)); + }, + ast.Node.Id.FloatLiteral => { + const float_literal = @fieldParentPtr(ast.Node.FloatLiteral, "base", base); + try stream.print("{}", tree.tokenSlice(float_literal.token)); + }, + ast.Node.Id.StringLiteral => { + const string_literal = @fieldParentPtr(ast.Node.StringLiteral, "base", base); + try stream.print("{}", tree.tokenSlice(string_literal.token)); + }, + ast.Node.Id.CharLiteral => { + const char_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); + try stream.print("{}", tree.tokenSlice(char_literal.token)); + }, + ast.Node.Id.BoolLiteral => { + const bool_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); + try stream.print("{}", tree.tokenSlice(bool_literal.token)); + }, + ast.Node.Id.NullLiteral => { + const null_literal = @fieldParentPtr(ast.Node.NullLiteral, "base", base); + try stream.print("{}", tree.tokenSlice(null_literal.token)); + }, + ast.Node.Id.ThisLiteral => { + const this_literal = @fieldParentPtr(ast.Node.ThisLiteral, "base", base); + try stream.print("{}", tree.tokenSlice(this_literal.token)); + }, + ast.Node.Id.Unreachable => { + const unreachable_node = @fieldParentPtr(ast.Node.Unreachable, "base", base); + try stream.print("{}", tree.tokenSlice(unreachable_node.token)); + }, + ast.Node.Id.ErrorType => { + const error_type = @fieldParentPtr(ast.Node.ErrorType, "base", base); + try stream.print("{}", tree.tokenSlice(error_type.token)); + }, + ast.Node.Id.VarType => { + const var_type = @fieldParentPtr(ast.Node.VarType, "base", base); + try stream.print("{}", tree.tokenSlice(var_type.token)); + }, + ast.Node.Id.ContainerDecl => { + const container_decl = @fieldParentPtr(ast.Node.ContainerDecl, "base", base); + + switch (container_decl.layout) { + ast.Node.ContainerDecl.Layout.Packed => try stream.print("packed "), + ast.Node.ContainerDecl.Layout.Extern => try stream.print("extern "), + ast.Node.ContainerDecl.Layout.Auto => { }, + } + + switch (container_decl.kind) { + ast.Node.ContainerDecl.Kind.Struct => try stream.print("struct"), + ast.Node.ContainerDecl.Kind.Enum => try stream.print("enum"), + ast.Node.ContainerDecl.Kind.Union => try stream.print("union"), + } + + switch (container_decl.init_arg_expr) { + ast.Node.ContainerDecl.InitArg.None => try stream.write(" "), + ast.Node.ContainerDecl.InitArg.Enum => |enum_tag_type| { + if (enum_tag_type) |expr| { + try stream.write("(enum("); + try renderExpression(allocator, stream, tree, indent, expr); + try stream.write(")) "); + } else { + try stream.write("(enum) "); + } + }, + ast.Node.ContainerDecl.InitArg.Type => |type_expr| { + try stream.write("("); + try renderExpression(allocator, stream, tree, indent, type_expr); + try stream.write(") "); + }, + } + + if (container_decl.fields_and_decls.len == 0) { + try stream.write("{}"); + } else { + try stream.write("{\n"); + const new_indent = indent + indent_delta; + + var it = container_decl.fields_and_decls.iterator(0); + while (it.next()) |decl| { + try stream.writeByteNTimes(' ', new_indent); + try renderTopLevelDecl(allocator, stream, tree, new_indent, *decl); + + if (it.peek()) |next_decl| { + const n = if (nodeLineOffset(tree, *decl, *next_decl) >= 2) u8(2) else u8(1); + try stream.writeByteNTimes('\n', n); + } + } + + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + try stream.write("}"); + } + }, + + ast.Node.Id.ErrorSetDecl => { + const err_set_decl = @fieldParentPtr(ast.Node.ErrorSetDecl, "base", base); + + if (err_set_decl.decls.len == 0) { + try stream.write("error{}"); + return; + } + + if (err_set_decl.decls.len == 1) blk: { + const node = *err_set_decl.decls.at(0); + + // if there are any doc comments or same line comments + // don't try to put it all on one line + if (node.cast(ast.Node.ErrorTag)) |tag| { + if (tag.doc_comments != null) break :blk; + } else { + break :blk; + } + + + try stream.write("error{"); + try renderTopLevelDecl(allocator, stream, tree, indent, node); + try stream.write("}"); + return; + } + + try stream.write("error{\n"); + const new_indent = indent + indent_delta; + + var it = err_set_decl.decls.iterator(0); + while (it.next()) |node| { + try stream.writeByteNTimes(' ', new_indent); + try renderTopLevelDecl(allocator, stream, tree, new_indent, *node); + if ((*node).id != ast.Node.Id.LineComment) { + try stream.write(","); + } + if (it.peek()) |next_node| { + const n = if (nodeLineOffset(tree, *node, *next_node) >= 2) u8(2) else u8(1); + try stream.writeByteNTimes('\n', n); + } + } + + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + try stream.write("}"); + }, + + ast.Node.Id.MultilineStringLiteral => { + const multiline_str_literal = @fieldParentPtr(ast.Node.MultilineStringLiteral, "base", base); + try stream.print("\n"); + + var i : usize = 0; + while (i < multiline_str_literal.lines.len) : (i += 1) { + const t = *multiline_str_literal.lines.at(i); + try stream.writeByteNTimes(' ', indent + indent_delta); + try stream.print("{}", tree.tokenSlice(t)); + } + try stream.writeByteNTimes(' ', indent); + }, + ast.Node.Id.UndefinedLiteral => { + const undefined_literal = @fieldParentPtr(ast.Node.UndefinedLiteral, "base", base); + try stream.print("{}", tree.tokenSlice(undefined_literal.token)); + }, + + ast.Node.Id.BuiltinCall => { + const builtin_call = @fieldParentPtr(ast.Node.BuiltinCall, "base", base); + try stream.print("{}(", tree.tokenSlice(builtin_call.builtin_token)); + + var it = builtin_call.params.iterator(0); + while (it.next()) |param_node| { + try renderExpression(allocator, stream, tree, indent, *param_node); + if (it.peek() != null) { + try stream.write(", "); + } + } + try stream.write(")"); + }, + + ast.Node.Id.FnProto => { + const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", base); + + if (fn_proto.visib_token) |visib_token_index| { + const visib_token = tree.tokens.at(visib_token_index); + assert(visib_token.id == Token.Id.Keyword_pub or visib_token.id == Token.Id.Keyword_export); + try stream.print("{} ", tree.tokenSlice(visib_token_index)); + } + + if (fn_proto.extern_export_inline_token) |extern_export_inline_token| { + try stream.print("{} ", tree.tokenSlice(extern_export_inline_token)); + } + + if (fn_proto.lib_name) |lib_name| { + try renderExpression(allocator, stream, tree, indent, lib_name); + try stream.write(" "); + } + + if (fn_proto.cc_token) |cc_token| { + try stream.print("{} ", tree.tokenSlice(cc_token)); + } + + if (fn_proto.async_attr) |async_attr| { + try renderExpression(allocator, stream, tree, indent, &async_attr.base); + try stream.write(" "); + } + + try stream.write("fn"); + + if (fn_proto.name_token) |name_token| { + try stream.print(" {}", tree.tokenSlice(name_token)); + } + + try stream.write("("); + + var it = fn_proto.params.iterator(0); + while (it.next()) |param_decl_node| { + try renderParamDecl(allocator, stream, tree, indent, *param_decl_node); + + if (it.peek() != null) { + try stream.write(", "); + } + } + + try stream.write(") "); + + if (fn_proto.align_expr) |align_expr| { + try stream.write("align("); + try renderExpression(allocator, stream, tree, indent, align_expr); + try stream.write(") "); + } + + switch (fn_proto.return_type) { + ast.Node.FnProto.ReturnType.Explicit => |node| { + try renderExpression(allocator, stream, tree, indent, node); + }, + ast.Node.FnProto.ReturnType.InferErrorSet => |node| { + try stream.write("!"); + try renderExpression(allocator, stream, tree, indent, node); + }, + } + + }, + + ast.Node.Id.PromiseType => { + const promise_type = @fieldParentPtr(ast.Node.PromiseType, "base", base); + try stream.write(tree.tokenSlice(promise_type.promise_token)); + if (promise_type.result) |result| { + try stream.write(tree.tokenSlice(result.arrow_token)); + try renderExpression(allocator, stream, tree, indent, result.return_type); + } + }, + + ast.Node.Id.LineComment => { + const line_comment_node = @fieldParentPtr(ast.Node.LineComment, "base", base); + try stream.write(tree.tokenSlice(line_comment_node.token)); + }, + + ast.Node.Id.DocComment => unreachable, // doc comments are attached to nodes + + ast.Node.Id.Switch => { + const switch_node = @fieldParentPtr(ast.Node.Switch, "base", base); + + try stream.print("{} (", tree.tokenSlice(switch_node.switch_token)); + if (switch_node.cases.len == 0) { + try renderExpression(allocator, stream, tree, indent, switch_node.expr); + try stream.write(") {}"); + return; + } + + try renderExpression(allocator, stream, tree, indent, switch_node.expr); + try stream.write(") {\n"); + + const new_indent = indent + indent_delta; + + var it = switch_node.cases.iterator(0); + while (it.next()) |node| { + try stream.writeByteNTimes(' ', new_indent); + try renderExpression(allocator, stream, tree, new_indent, *node); + + if (it.peek()) |next_node| { + const n = if (nodeLineOffset(tree, *node, *next_node) >= 2) u8(2) else u8(1); + try stream.writeByteNTimes('\n', n); + } + } + + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + try stream.write("}"); + }, + + ast.Node.Id.SwitchCase => { + const switch_case = @fieldParentPtr(ast.Node.SwitchCase, "base", base); + + var it = switch_case.items.iterator(0); + while (it.next()) |node| { + try renderExpression(allocator, stream, tree, indent, *node); + + if (it.peek() != null) { + try stream.write(",\n"); + try stream.writeByteNTimes(' ', indent); + } + } + + try stream.write(" => "); + + if (switch_case.payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload); + try stream.write(" "); + } + + try renderExpression(allocator, stream, tree, indent, switch_case.expr); + try renderToken(tree, stream, switch_case.lastToken() + 1, indent, true); + }, + ast.Node.Id.SwitchElse => { + const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base); + try stream.print("{}", tree.tokenSlice(switch_else.token)); + }, + ast.Node.Id.Else => { + const else_node = @fieldParentPtr(ast.Node.Else, "base", base); + try stream.print("{}", tree.tokenSlice(else_node.else_token)); + + const block_body = switch (else_node.body.id) { + ast.Node.Id.Block, ast.Node.Id.If, + ast.Node.Id.For, ast.Node.Id.While, + ast.Node.Id.Switch => true, + else => false, + }; + + if (block_body) { + try stream.write(" "); + } + + if (else_node.payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload); + try stream.write(" "); + } + + if (block_body) { + try renderExpression(allocator, stream, tree, indent, else_node.body); + } else { + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent + indent_delta); + try renderExpression(allocator, stream, tree, indent, else_node.body); + } + }, + + ast.Node.Id.While => { + const while_node = @fieldParentPtr(ast.Node.While, "base", base); + + if (while_node.label) |label| { + try stream.print("{}: ", tree.tokenSlice(label)); + } + + if (while_node.inline_token) |inline_token| { + try stream.print("{} ", tree.tokenSlice(inline_token)); + } + + try stream.print("{} (", tree.tokenSlice(while_node.while_token)); + try renderExpression(allocator, stream, tree, indent, while_node.condition); + try stream.write(")"); + + if (while_node.payload) |payload| { + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, payload); + } + + if (while_node.continue_expr) |continue_expr| { + try stream.write(" : ("); + try renderExpression(allocator, stream, tree, indent, continue_expr); + try stream.write(")"); + } + + if (while_node.body.id == ast.Node.Id.Block) { + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, while_node.body); + } else { + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent + indent_delta); + try renderExpression(allocator, stream, tree, indent, while_node.body); + } + + if (while_node.@"else") |@"else"| { + if (while_node.body.id == ast.Node.Id.Block) { + try stream.write(" "); + } else { + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + } + + try renderExpression(allocator, stream, tree, indent, &@"else".base); + } + }, + + ast.Node.Id.For => { + const for_node = @fieldParentPtr(ast.Node.For, "base", base); + if (for_node.label) |label| { + try stream.print("{}: ", tree.tokenSlice(label)); + } + + if (for_node.inline_token) |inline_token| { + try stream.print("{} ", tree.tokenSlice(inline_token)); + } + + try stream.print("{} (", tree.tokenSlice(for_node.for_token)); + try renderExpression(allocator, stream, tree, indent, for_node.array_expr); + try stream.write(")"); + + if (for_node.payload) |payload| { + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, payload); + } + + if (for_node.body.id == ast.Node.Id.Block) { + try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, for_node.body); + } else { + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent + indent_delta); + try renderExpression(allocator, stream, tree, indent, for_node.body); + } + + if (for_node.@"else") |@"else"| { + if (for_node.body.id == ast.Node.Id.Block) { + try stream.write(" "); + } else { + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + } + + try renderExpression(allocator, stream, tree, indent, &@"else".base); + } + }, + + ast.Node.Id.If => { + const if_node = @fieldParentPtr(ast.Node.If, "base", base); + try stream.print("{} (", tree.tokenSlice(if_node.if_token)); + + try renderExpression(allocator, stream, tree, indent, if_node.condition); + try renderToken(tree, stream, if_node.condition.lastToken() + 1, indent, false); + + if (if_node.payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload); + try stream.write(" "); + } + + try renderExpression(allocator, stream, tree, indent, if_node.body); + + switch (if_node.body.id) { + ast.Node.Id.Block, ast.Node.Id.If, ast.Node.Id.For, ast.Node.Id.While, ast.Node.Id.Switch => { + if (if_node.@"else") |@"else"| { + if (if_node.body.id == ast.Node.Id.Block) { + try stream.write(" "); + } else { + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + } + + try renderExpression(allocator, stream, tree, indent, &@"else".base); + } + }, + else => { + if (if_node.@"else") |@"else"| { + try stream.print(" {} ", tree.tokenSlice(@"else".else_token)); + + if (@"else".payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload); + try stream.write(" "); + } + + try renderExpression(allocator, stream, tree, indent, @"else".body); + } + } + } + }, + + ast.Node.Id.Asm => { + const asm_node = @fieldParentPtr(ast.Node.Asm, "base", base); + try stream.print("{} ", tree.tokenSlice(asm_node.asm_token)); + + if (asm_node.volatile_token) |volatile_token| { + try stream.print("{} ", tree.tokenSlice(volatile_token)); + } + + try stream.print("("); + try renderExpression(allocator, stream, tree, indent, asm_node.template); + try stream.print("\n"); + const indent_once = indent + indent_delta; + try stream.writeByteNTimes(' ', indent_once); + try stream.print(": "); + const indent_extra = indent_once + 2; + + { + var it = asm_node.outputs.iterator(0); + while (it.next()) |asm_output| { + const node = &(*asm_output).base; + try renderExpression(allocator, stream, tree, indent_extra, node); + + if (it.peek()) |next_asm_output| { + const next_node = &(*next_asm_output).base; + const n = if (nodeLineOffset(tree, node, next_node) >= 2) u8(2) else u8(1); + try stream.writeByte(','); + try stream.writeByteNTimes('\n', n); + try stream.writeByteNTimes(' ', indent_extra); + } + } + } + + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent_once); + try stream.write(": "); + + { + var it = asm_node.inputs.iterator(0); + while (it.next()) |asm_input| { + const node = &(*asm_input).base; + try renderExpression(allocator, stream, tree, indent_extra, node); + + if (it.peek()) |next_asm_input| { + const next_node = &(*next_asm_input).base; + const n = if (nodeLineOffset(tree, node, next_node) >= 2) u8(2) else u8(1); + try stream.writeByte(','); + try stream.writeByteNTimes('\n', n); + try stream.writeByteNTimes(' ', indent_extra); + } + } + } + + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent_once); + try stream.write(": "); + + { + var it = asm_node.clobbers.iterator(0); + while (it.next()) |node| { + try renderExpression(allocator, stream, tree, indent_once, *node); + + if (it.peek() != null) { + try stream.write(", "); + } + } + } + + try stream.write(")"); + }, + + ast.Node.Id.AsmInput => { + const asm_input = @fieldParentPtr(ast.Node.AsmInput, "base", base); + + try stream.write("["); + try renderExpression(allocator, stream, tree, indent, asm_input.symbolic_name); + try stream.write("] "); + try renderExpression(allocator, stream, tree, indent, asm_input.constraint); + try stream.write(" ("); + try renderExpression(allocator, stream, tree, indent, asm_input.expr); + try stream.write(")"); + }, + + ast.Node.Id.AsmOutput => { + const asm_output = @fieldParentPtr(ast.Node.AsmOutput, "base", base); + + try stream.write("["); + try renderExpression(allocator, stream, tree, indent, asm_output.symbolic_name); + try stream.write("] "); + try renderExpression(allocator, stream, tree, indent, asm_output.constraint); + try stream.write(" ("); + + switch (asm_output.kind) { + ast.Node.AsmOutput.Kind.Variable => |variable_name| { + try renderExpression(allocator, stream, tree, indent, &variable_name.base); + }, + ast.Node.AsmOutput.Kind.Return => |return_type| { + try stream.write("-> "); + try renderExpression(allocator, stream, tree, indent, return_type); + }, + } + + try stream.write(")"); + }, + + ast.Node.Id.StructField, + ast.Node.Id.UnionTag, + ast.Node.Id.EnumTag, + ast.Node.Id.ErrorTag, + ast.Node.Id.Root, + ast.Node.Id.VarDecl, + ast.Node.Id.Use, + ast.Node.Id.TestDecl, + ast.Node.Id.ParamDecl => unreachable, + } +} + +fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, var_decl: &ast.Node.VarDecl) (@typeOf(stream).Child.Error || Error)!void { + if (var_decl.visib_token) |visib_token| { + try stream.print("{} ", tree.tokenSlice(visib_token)); + } + + if (var_decl.extern_export_token) |extern_export_token| { + try stream.print("{} ", tree.tokenSlice(extern_export_token)); + + if (var_decl.lib_name) |lib_name| { + try renderExpression(allocator, stream, tree, indent, lib_name); + try stream.write(" "); + } + } + + if (var_decl.comptime_token) |comptime_token| { + try stream.print("{} ", tree.tokenSlice(comptime_token)); + } + + try stream.print("{} {}", tree.tokenSlice(var_decl.mut_token), tree.tokenSlice(var_decl.name_token)); + + if (var_decl.type_node) |type_node| { + try stream.write(": "); + try renderExpression(allocator, stream, tree, indent, type_node); + } + + if (var_decl.align_node) |align_node| { + try stream.write(" align("); + try renderExpression(allocator, stream, tree, indent, align_node); + try stream.write(")"); + } + + if (var_decl.init_node) |init_node| { + const text = if (init_node.id == ast.Node.Id.MultilineStringLiteral) " =" else " = "; + try stream.write(text); + try renderExpression(allocator, stream, tree, indent, init_node); + } + + try renderToken(tree, stream, var_decl.semicolon_token, indent, true); +} + +fn maybeRenderSemicolon(stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { + if (base.requireSemiColon()) { + const semicolon_index = base.lastToken() + 1; + assert(tree.tokens.at(semicolon_index).id == Token.Id.Semicolon); + try renderToken(tree, stream, semicolon_index, indent, true); + } +} + +fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { + const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base); + if (param_decl.comptime_token) |comptime_token| { + try stream.print("{} ", tree.tokenSlice(comptime_token)); + } + if (param_decl.noalias_token) |noalias_token| { + try stream.print("{} ", tree.tokenSlice(noalias_token)); + } + if (param_decl.name_token) |name_token| { + try stream.print("{}: ", tree.tokenSlice(name_token)); + } + if (param_decl.var_args_token) |var_args_token| { + try stream.print("{}", tree.tokenSlice(var_args_token)); + } else { + try renderExpression(allocator, stream, tree, indent, param_decl.type_node); + } +} + +fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { + switch (base.id) { + ast.Node.Id.VarDecl => { + const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base); + try renderVarDecl(allocator, stream, tree, indent, var_decl); + }, + else => { + try renderExpression(allocator, stream, tree, indent, base); + try maybeRenderSemicolon(stream, tree, indent, base); + }, + } +} + +fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, line_break: bool) (@typeOf(stream).Child.Error || Error)!void { const token = tree.tokens.at(token_index); try stream.write(tree.tokenSlicePtr(token)); @@ -1255,7 +1212,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } } -fn renderComments(tree: &ast.Tree, stream: var, node: var, indent: usize) !void { +fn renderComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@typeOf(stream).Child.Error || Error)!void { const comment = node.doc_comments ?? return; var it = comment.lines.iterator(0); while (it.next()) |line_token_index| { From 548ddd1f0c35033cd7e0d1940975bc7185bf7346 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 12 May 2018 23:57:15 -0400 Subject: [PATCH 10/75] fix AST dumping code in self hosted compiler --- src/ir.cpp | 6 +++++- std/zig/ast.zig | 54 ++++++++++++++++++++++++++++++++--------------- std/zig/parse.zig | 35 +----------------------------- 3 files changed, 43 insertions(+), 52 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index 7bc837d908..31d22ca82a 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -18083,7 +18083,11 @@ static TypeTableEntry *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira if (type_is_invalid(end_value->value.type)) return ira->codegen->builtin_types.entry_invalid; - assert(start_value->value.type->id == TypeTableEntryIdEnum); + if (start_value->value.type->id != TypeTableEntryIdEnum) { + ir_add_error(ira, range->start, buf_sprintf("not an enum type")); + return ira->codegen->builtin_types.entry_invalid; + } + BigInt start_index; bigint_init_bigint(&start_index, &start_value->value.data.x_enum_tag); diff --git a/std/zig/ast.zig b/std/zig/ast.zig index a92555731d..a452ed8906 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -67,6 +67,11 @@ pub const Tree = struct { pub fn tokenLocation(self: &Tree, start_index: usize, token_index: TokenIndex) Location { return self.tokenLocationPtr(start_index, self.tokens.at(token_index)); } + + pub fn dump(self: &Tree) void { + self.root_node.base.dump(0); + } + }; pub const Error = union(enum) { @@ -415,6 +420,20 @@ pub const Node = struct { } } + pub fn dump(self: &Node, indent: usize) void { + { + var i: usize = 0; + while (i < indent) : (i += 1) { + std.debug.warn(" "); + } + } + std.debug.warn("{}\n", @tagName(self.id)); + + var child_i: usize = 0; + while (self.iterate(child_i)) |child| : (child_i += 1) { + child.dump(indent + 2); + } + } pub const Root = struct { base: Node, @@ -426,7 +445,7 @@ pub const Node = struct { pub fn iterate(self: &Root, index: usize) ?&Node { if (index < self.decls.len) { - return self.decls.items[self.decls.len - index - 1]; + return *self.decls.at(index); } return null; } @@ -790,8 +809,16 @@ pub const Node = struct { pub fn iterate(self: &FnProto, index: usize) ?&Node { var i = index; - if (self.body_node) |body_node| { - if (i < 1) return body_node; + if (self.lib_name) |lib_name| { + if (i < 1) return lib_name; + i -= 1; + } + + if (i < self.params.len) return *self.params.at(self.params.len - i - 1); + i -= self.params.len; + + if (self.align_expr) |align_expr| { + if (i < 1) return align_expr; i -= 1; } @@ -807,18 +834,11 @@ pub const Node = struct { }, } - if (self.align_expr) |align_expr| { - if (i < 1) return align_expr; + if (self.body_node) |body_node| { + if (i < 1) return body_node; i -= 1; } - if (i < self.params.len) return self.params.items[self.params.len - i - 1]; - i -= self.params.len; - - if (self.lib_name) |lib_name| { - if (i < 1) return lib_name; - i -= 1; - } return null; } @@ -914,7 +934,7 @@ pub const Node = struct { pub fn iterate(self: &Block, index: usize) ?&Node { var i = index; - if (i < self.statements.len) return self.statements.items[i]; + if (i < self.statements.len) return *self.statements.at(i); i -= self.statements.len; return null; @@ -1596,7 +1616,7 @@ pub const Node = struct { i -= 1; switch (self.op) { - Op.Call => |call_info| { + @TagType(Op).Call => |*call_info| { if (i < call_info.params.len) return *call_info.params.at(i); i -= call_info.params.len; }, @@ -1604,7 +1624,7 @@ pub const Node = struct { if (i < 1) return index_expr; i -= 1; }, - Op.Slice => |range| { + @TagType(Op).Slice => |range| { if (i < 1) return range.start; i -= 1; @@ -1613,11 +1633,11 @@ pub const Node = struct { i -= 1; } }, - Op.ArrayInitializer => |exprs| { + Op.ArrayInitializer => |*exprs| { if (i < exprs.len) return *exprs.at(i); i -= exprs.len; }, - Op.StructInitializer => |fields| { + Op.StructInitializer => |*fields| { if (i < fields.len) return *fields.at(i); i -= fields.len; }, diff --git a/std/zig/parse.zig b/std/zig/parse.zig index c96893fd96..f88fdfab62 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -7,9 +7,8 @@ const Token = std.zig.Token; const TokenIndex = ast.TokenIndex; const Error = ast.Error; -/// Returns an AST tree, allocated with the parser's allocator. /// Result should be freed with tree.deinit() when there are -/// no more references to any AST nodes of the tree. +/// no more references to any of the tokens or nodes. pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { var tree_arena = std.heap.ArenaAllocator.init(allocator); errdefer tree_arena.deinit(); @@ -3466,38 +3465,6 @@ fn putBackToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) void { } } -const RenderAstFrame = struct { - node: &ast.Node, - indent: usize, -}; - -pub fn renderAst(allocator: &mem.Allocator, tree: &const ast.Tree, stream: var) !void { - var stack = std.ArrayList(State).init(allocator); - defer stack.deinit(); - - try stack.append(RenderAstFrame { - .node = &root_node.base, - .indent = 0, - }); - - while (stack.popOrNull()) |frame| { - { - var i: usize = 0; - while (i < frame.indent) : (i += 1) { - try stream.print(" "); - } - } - try stream.print("{}\n", @tagName(frame.node.id)); - var child_i: usize = 0; - while (frame.node.iterate(child_i)) |child| : (child_i += 1) { - try stack.append(RenderAstFrame { - .node = child, - .indent = frame.indent + 2, - }); - } - } -} - test "std.zig.parser" { _ = @import("parser_test.zig"); } From 4c3aa09f2a88f0608c14f5717de21aaa3d56c89e Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 10 May 2018 18:57:57 -0400 Subject: [PATCH 11/75] self hosted compiler: remove unused flag --- src-self-hosted/main.zig | 2 -- 1 file changed, 2 deletions(-) diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index 8dc1d8ce3b..22f49e80d9 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -637,14 +637,12 @@ const usage_fmt = \\ \\Options: \\ --help Print this help and exit - \\ --keep-backups Retain backup entries for every file \\ \\ ; const args_fmt_spec = []Flag { Flag.Bool("--help"), - Flag.Bool("--keep-backups"), }; fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void { From 05ecb49bac30041459ae08764edd2aced23d10eb Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 13 May 2018 01:07:55 -0400 Subject: [PATCH 12/75] README: https links --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1f23e133f8..552b784a50 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -![ZIG](http://ziglang.org/zig-logo.svg) +![ZIG](https://ziglang.org/zig-logo.svg) A programming language designed for robustness, optimality, and clarity. -[ziglang.org](http://ziglang.org) +[ziglang.org](https://ziglang.org) ## Feature Highlights From abcd418451051fe8c3b5c283d1701d101337dde8 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 13 May 2018 14:20:01 -0400 Subject: [PATCH 13/75] std.zig.parse cleanup --- std/zig/parse.zig | 784 ++++++++++++++++++---------------------- std/zig/parser_test.zig | 8 + 2 files changed, 368 insertions(+), 424 deletions(-) diff --git a/std/zig/parse.zig b/std/zig/parse.zig index f88fdfab62..3d6429ba71 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -17,15 +17,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { defer stack.deinit(); const arena = &tree_arena.allocator; - const root_node = try createNode(arena, ast.Node.Root, - ast.Node.Root { - .base = undefined, - .decls = ast.Node.Root.DeclList.init(arena), - .doc_comments = null, - // initialized when we get the eof token - .eof_token = undefined, - } - ); + const root_node = try arena.construct(ast.Node.Root { + .base = ast.Node { .id = ast.Node.Id.Root }, + .decls = ast.Node.Root.DeclList.init(arena), + .doc_comments = null, + // initialized when we get the eof token + .eof_token = undefined, + }); var tree = ast.Tree { .source = source, @@ -113,15 +111,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_comptime => { - const block = try createNode(arena, ast.Node.Block, - ast.Node.Block { - .base = undefined, - .label = null, - .lbrace = undefined, - .statements = ast.Node.Block.StatementList.init(arena), - .rbrace = undefined, - } - ); + const block = try arena.construct(ast.Node.Block { + .base = ast.Node {.id = ast.Node.Id.Block }, + .label = null, + .lbrace = undefined, + .statements = ast.Node.Block.StatementList.init(arena), + .rbrace = undefined, + }); const node = try arena.construct(ast.Node.Comptime { .base = ast.Node { .id = ast.Node.Id.Comptime, @@ -312,14 +308,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_async => { - const async_node = try createNode(arena, ast.Node.AsyncAttribute, - ast.Node.AsyncAttribute { - .base = undefined, - .async_token = token_index, - .allocator_type = null, - .rangle_bracket = null, - } - ); + const async_node = try arena.construct(ast.Node.AsyncAttribute { + .base = ast.Node {.id = ast.Node.Id.AsyncAttribute }, + .async_token = token_index, + .allocator_type = null, + .rangle_bracket = null, + }); fn_proto.async_attr = async_node; try stack.append(State { @@ -396,27 +390,26 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; - const node = try createToCtxNode(arena, ctx.opt_ctx, ast.Node.ContainerDecl, - ast.Node.ContainerDecl { - .base = undefined, - .ltoken = ctx.ltoken, - .layout = ctx.layout, - .kind = switch (token_ptr.id) { - Token.Id.Keyword_struct => ast.Node.ContainerDecl.Kind.Struct, - Token.Id.Keyword_union => ast.Node.ContainerDecl.Kind.Union, - Token.Id.Keyword_enum => ast.Node.ContainerDecl.Kind.Enum, - else => { - *(try tree.errors.addOne()) = Error { - .ExpectedAggregateKw = Error.ExpectedAggregateKw { .token = token_index }, - }; - return tree; - }, + const node = try arena.construct(ast.Node.ContainerDecl { + .base = ast.Node {.id = ast.Node.Id.ContainerDecl }, + .ltoken = ctx.ltoken, + .layout = ctx.layout, + .kind = switch (token_ptr.id) { + Token.Id.Keyword_struct => ast.Node.ContainerDecl.Kind.Struct, + Token.Id.Keyword_union => ast.Node.ContainerDecl.Kind.Union, + Token.Id.Keyword_enum => ast.Node.ContainerDecl.Kind.Enum, + else => { + *(try tree.errors.addOne()) = Error { + .ExpectedAggregateKw = Error.ExpectedAggregateKw { .token = token_index }, + }; + return tree; }, - .init_arg_expr = ast.Node.ContainerDecl.InitArg.None, - .fields_and_decls = ast.Node.ContainerDecl.DeclList.init(arena), - .rbrace_token = undefined, - } - ); + }, + .init_arg_expr = ast.Node.ContainerDecl.InitArg.None, + .fields_and_decls = ast.Node.ContainerDecl.DeclList.init(arena), + .rbrace_token = undefined, + }); + ctx.opt_ctx.store(&node.base); stack.append(State { .ContainerDecl = node }) catch unreachable; try stack.append(State { .ExpectToken = Token.Id.LBrace }); @@ -844,15 +837,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.LBrace => { - const block = try createToCtxNode(arena, ctx.opt_ctx, ast.Node.Block, - ast.Node.Block { - .base = undefined, - .label = ctx.label, - .lbrace = token_index, - .statements = ast.Node.Block.StatementList.init(arena), - .rbrace = undefined, - } - ); + const block = try arena.construct(ast.Node.Block { + .base = ast.Node {.id = ast.Node.Id.Block}, + .label = ctx.label, + .lbrace = token_index, + .statements = ast.Node.Block.StatementList.init(arena), + .rbrace = undefined, + }); + ctx.opt_ctx.store(&block.base); stack.append(State { .Block = block }) catch unreachable; continue; }, @@ -957,19 +949,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, State.While => |ctx| { - const node = try createToCtxNode(arena, ctx.opt_ctx, ast.Node.While, - ast.Node.While { - .base = undefined, - .label = ctx.label, - .inline_token = ctx.inline_token, - .while_token = ctx.loop_token, - .condition = undefined, - .payload = null, - .continue_expr = null, - .body = undefined, - .@"else" = null, - } - ); + const node = try arena.construct(ast.Node.While { + .base = ast.Node {.id = ast.Node.Id.While }, + .label = ctx.label, + .inline_token = ctx.inline_token, + .while_token = ctx.loop_token, + .condition = undefined, + .payload = null, + .continue_expr = null, + .body = undefined, + .@"else" = null, + }); + ctx.opt_ctx.store(&node.base); stack.append(State { .Else = &node.@"else" }) catch unreachable; try stack.append(State { .Expression = OptionalCtx { .Required = &node.body } }); try stack.append(State { .WhileContinueExpr = &node.continue_expr }); @@ -987,18 +978,17 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, State.For => |ctx| { - const node = try createToCtxNode(arena, ctx.opt_ctx, ast.Node.For, - ast.Node.For { - .base = undefined, - .label = ctx.label, - .inline_token = ctx.inline_token, - .for_token = ctx.loop_token, - .array_expr = undefined, - .payload = null, - .body = undefined, - .@"else" = null, - } - ); + const node = try arena.construct(ast.Node.For { + .base = ast.Node {.id = ast.Node.Id.For }, + .label = ctx.label, + .inline_token = ctx.inline_token, + .for_token = ctx.loop_token, + .array_expr = undefined, + .payload = null, + .body = undefined, + .@"else" = null, + }); + ctx.opt_ctx.store(&node.base); stack.append(State { .Else = &node.@"else" }) catch unreachable; try stack.append(State { .Expression = OptionalCtx { .Required = &node.body } }); try stack.append(State { .PointerIndexPayload = OptionalCtx { .Optional = &node.payload } }); @@ -1009,14 +999,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.Else => |dest| { if (eatToken(&tok_it, &tree, Token.Id.Keyword_else)) |else_token| { - const node = try createNode(arena, ast.Node.Else, - ast.Node.Else { - .base = undefined, - .else_token = else_token, - .payload = null, - .body = undefined, - } - ); + const node = try arena.construct(ast.Node.Else { + .base = ast.Node {.id = ast.Node.Id.Else }, + .else_token = else_token, + .payload = null, + .body = undefined, + }); *dest = node; stack.append(State { .Expression = OptionalCtx { .Required = &node.body } }) catch unreachable; @@ -1170,14 +1158,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try createNode(arena, ast.Node.AsmOutput, - ast.Node.AsmOutput { - .base = undefined, - .symbolic_name = undefined, - .constraint = undefined, - .kind = undefined, - } - ); + const node = try arena.construct(ast.Node.AsmOutput { + .base = ast.Node {.id = ast.Node.Id.AsmOutput }, + .symbolic_name = undefined, + .constraint = undefined, + .kind = undefined, + }); try items.push(node); stack.append(State { .AsmOutputItems = items }) catch unreachable; @@ -1223,14 +1209,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try createNode(arena, ast.Node.AsmInput, - ast.Node.AsmInput { - .base = undefined, - .symbolic_name = undefined, - .constraint = undefined, - .expr = undefined, - } - ); + const node = try arena.construct(ast.Node.AsmInput { + .base = ast.Node {.id = ast.Node.Id.AsmInput }, + .symbolic_name = undefined, + .constraint = undefined, + .expr = undefined, + }); try items.push(node); stack.append(State { .AsmInputItems = items }) catch unreachable; @@ -1668,14 +1652,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try createToCtxNode(arena, opt_ctx, ast.Node.Payload, - ast.Node.Payload { - .base = undefined, - .lpipe = token_index, - .error_symbol = undefined, - .rpipe = undefined - } - ); + const node = try arena.construct(ast.Node.Payload { + .base = ast.Node {.id = ast.Node.Id.Payload }, + .lpipe = token_index, + .error_symbol = undefined, + .rpipe = undefined + }); + opt_ctx.store(&node.base); stack.append(State { .ExpectTokenSave = ExpectTokenSave { @@ -1705,15 +1688,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try createToCtxNode(arena, opt_ctx, ast.Node.PointerPayload, - ast.Node.PointerPayload { - .base = undefined, - .lpipe = token_index, - .ptr_token = null, - .value_symbol = undefined, - .rpipe = undefined - } - ); + const node = try arena.construct(ast.Node.PointerPayload { + .base = ast.Node {.id = ast.Node.Id.PointerPayload }, + .lpipe = token_index, + .ptr_token = null, + .value_symbol = undefined, + .rpipe = undefined + }); + opt_ctx.store(&node.base); try stack.append(State { .ExpectTokenSave = ExpectTokenSave { @@ -1749,16 +1731,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try createToCtxNode(arena, opt_ctx, ast.Node.PointerIndexPayload, - ast.Node.PointerIndexPayload { - .base = undefined, - .lpipe = token_index, - .ptr_token = null, - .value_symbol = undefined, - .index_symbol = null, - .rpipe = undefined - } - ); + const node = try arena.construct(ast.Node.PointerIndexPayload { + .base = ast.Node {.id = ast.Node.Id.PointerIndexPayload }, + .lpipe = token_index, + .ptr_token = null, + .value_symbol = undefined, + .index_symbol = null, + .rpipe = undefined + }); + opt_ctx.store(&node.base); stack.append(State { .ExpectTokenSave = ExpectTokenSave { @@ -1785,14 +1766,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Keyword_return, Token.Id.Keyword_break, Token.Id.Keyword_continue => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.ControlFlowExpression, - ast.Node.ControlFlowExpression { - .base = undefined, - .ltoken = token_index, - .kind = undefined, - .rhs = null, - } - ); + const node = try arena.construct(ast.Node.ControlFlowExpression { + .base = ast.Node {.id = ast.Node.Id.ControlFlowExpression }, + .ltoken = token_index, + .kind = undefined, + .rhs = null, + }); + opt_ctx.store(&node.base); stack.append(State { .Expression = OptionalCtx { .Optional = &node.rhs } }) catch unreachable; @@ -1815,19 +1795,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_try, Token.Id.Keyword_cancel, Token.Id.Keyword_resume => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.PrefixOp, - ast.Node.PrefixOp { - .base = undefined, - .op_token = token_index, - .op = switch (token_ptr.id) { - Token.Id.Keyword_try => ast.Node.PrefixOp.Op { .Try = void{} }, - Token.Id.Keyword_cancel => ast.Node.PrefixOp.Op { .Cancel = void{} }, - Token.Id.Keyword_resume => ast.Node.PrefixOp.Op { .Resume = void{} }, - else => unreachable, - }, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.PrefixOp { + .base = ast.Node {.id = ast.Node.Id.PrefixOp }, + .op_token = token_index, + .op = switch (token_ptr.id) { + Token.Id.Keyword_try => ast.Node.PrefixOp.Op { .Try = void{} }, + Token.Id.Keyword_cancel => ast.Node.PrefixOp.Op { .Cancel = void{} }, + Token.Id.Keyword_resume => ast.Node.PrefixOp.Op { .Resume = void{} }, + else => unreachable, + }, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .Expression = OptionalCtx { .Required = &node.rhs } }) catch unreachable; continue; @@ -1850,15 +1829,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Ellipsis3)) |ellipsis3| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = ellipsis3, - .op = ast.Node.InfixOp.Op.Range, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = ellipsis3, + .op = ast.Node.InfixOp.Op.Range, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .Expression = OptionalCtx { .Required = &node.rhs } }) catch unreachable; continue; } @@ -1876,15 +1854,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToAssignment(token_ptr.id)) |ass_id| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = token_index, - .op = ass_id, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = token_index, + .op = ass_id, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .AssignmentExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .Expression = OptionalCtx { .Required = &node.rhs } }); continue; @@ -1907,15 +1884,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToUnwrapExpr(token_ptr.id)) |unwrap_id| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = token_index, - .op = unwrap_id, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = token_index, + .op = unwrap_id, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .UnwrapExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .Expression = OptionalCtx { .Required = &node.rhs } }); @@ -1940,15 +1916,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Keyword_or)) |or_token| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = or_token, - .op = ast.Node.InfixOp.Op.BoolOr, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = or_token, + .op = ast.Node.InfixOp.Op.BoolOr, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .BoolOrExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .BoolAndExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -1965,15 +1940,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Keyword_and)) |and_token| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = and_token, - .op = ast.Node.InfixOp.Op.BoolAnd, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = and_token, + .op = ast.Node.InfixOp.Op.BoolAnd, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .BoolAndExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .ComparisonExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -1993,15 +1967,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToComparison(token_ptr.id)) |comp_id| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = token_index, - .op = comp_id, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = token_index, + .op = comp_id, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .ComparisonExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .BinaryOrExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2021,15 +1994,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Pipe)) |pipe| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = pipe, - .op = ast.Node.InfixOp.Op.BitOr, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = pipe, + .op = ast.Node.InfixOp.Op.BitOr, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .BinaryOrExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .BinaryXorExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2046,15 +2018,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Caret)) |caret| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = caret, - .op = ast.Node.InfixOp.Op.BitXor, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = caret, + .op = ast.Node.InfixOp.Op.BitXor, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .BinaryXorExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .BinaryAndExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2071,15 +2042,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Ampersand)) |ampersand| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = ampersand, - .op = ast.Node.InfixOp.Op.BitAnd, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = ampersand, + .op = ast.Node.InfixOp.Op.BitAnd, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .BinaryAndExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .BitShiftExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2099,15 +2069,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToBitShift(token_ptr.id)) |bitshift_id| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = token_index, - .op = bitshift_id, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = token_index, + .op = bitshift_id, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .BitShiftExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .AdditionExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2130,15 +2099,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToAddition(token_ptr.id)) |add_id| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = token_index, - .op = add_id, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = token_index, + .op = add_id, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .AdditionExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .MultiplyExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2161,15 +2129,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToMultiply(token_ptr.id)) |mult_id| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = token_index, - .op = mult_id, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = token_index, + .op = mult_id, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .MultiplyExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .CurlySuffixExpressionBegin = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2211,16 +2178,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try createToCtxNode(arena, opt_ctx, ast.Node.SuffixOp, - ast.Node.SuffixOp { - .base = undefined, - .lhs = lhs, - .op = ast.Node.SuffixOp.Op { - .ArrayInitializer = ast.Node.SuffixOp.Op.InitList.init(arena), - }, - .rtoken = undefined, - } - ); + const node = try arena.construct(ast.Node.SuffixOp { + .base = ast.Node {.id = ast.Node.Id.SuffixOp }, + .lhs = lhs, + .op = ast.Node.SuffixOp.Op { + .ArrayInitializer = ast.Node.SuffixOp.Op.InitList.init(arena), + }, + .rtoken = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .IfToken = Token.Id.LBrace }); try stack.append(State { @@ -2243,15 +2209,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Bang)) |bang| { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = bang, - .op = ast.Node.InfixOp.Op.ErrorUnion, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = bang, + .op = ast.Node.InfixOp.Op.ErrorUnion, + .rhs = undefined, + }); + opt_ctx.store(&node.base); stack.append(State { .TypeExprEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .PrefixOpExpression = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2263,25 +2228,22 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToPrefixOp(token_ptr.id)) |prefix_id| { - var node = try createToCtxNode(arena, opt_ctx, ast.Node.PrefixOp, - ast.Node.PrefixOp { - .base = undefined, - .op_token = token_index, - .op = prefix_id, - .rhs = undefined, - } - ); + var node = try arena.construct(ast.Node.PrefixOp { + .base = ast.Node {.id = ast.Node.Id.PrefixOp }, + .op_token = token_index, + .op = prefix_id, + .rhs = undefined, + }); + opt_ctx.store(&node.base); // Treat '**' token as two derefs if (token_ptr.id == Token.Id.AsteriskAsterisk) { - const child = try createNode(arena, ast.Node.PrefixOp, - ast.Node.PrefixOp { - .base = undefined, - .op_token = token_index, - .op = prefix_id, - .rhs = undefined, - } - ); + const child = try arena.construct(ast.Node.PrefixOp { + .base = ast.Node {.id = ast.Node.Id.PrefixOp}, + .op_token = token_index, + .op = prefix_id, + .rhs = undefined, + }); node.rhs = &child.base; node = child; } @@ -2300,14 +2262,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { State.SuffixOpExpressionBegin => |opt_ctx| { if (eatToken(&tok_it, &tree, Token.Id.Keyword_async)) |async_token| { - const async_node = try createNode(arena, ast.Node.AsyncAttribute, - ast.Node.AsyncAttribute { - .base = undefined, - .async_token = async_token, - .allocator_type = null, - .rangle_bracket = null, - } - ); + const async_node = try arena.construct(ast.Node.AsyncAttribute { + .base = ast.Node {.id = ast.Node.Id.AsyncAttribute}, + .async_token = async_token, + .allocator_type = null, + .rangle_bracket = null, + }); stack.append(State { .AsyncEnd = AsyncEndCtx { .ctx = opt_ctx, @@ -2333,19 +2293,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.LParen => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.SuffixOp, - ast.Node.SuffixOp { - .base = undefined, - .lhs = lhs, - .op = ast.Node.SuffixOp.Op { - .Call = ast.Node.SuffixOp.Op.Call { - .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena), - .async_attr = null, - } - }, - .rtoken = undefined, - } - ); + const node = try arena.construct(ast.Node.SuffixOp { + .base = ast.Node {.id = ast.Node.Id.SuffixOp }, + .lhs = lhs, + .op = ast.Node.SuffixOp.Op { + .Call = ast.Node.SuffixOp.Op.Call { + .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena), + .async_attr = null, + } + }, + .rtoken = undefined, + }); + opt_ctx.store(&node.base); + stack.append(State { .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .ExprListItemOrEnd = ExprListCtx { @@ -2357,31 +2317,31 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.LBracket => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.SuffixOp, - ast.Node.SuffixOp { - .base = undefined, - .lhs = lhs, - .op = ast.Node.SuffixOp.Op { - .ArrayAccess = undefined, - }, - .rtoken = undefined - } - ); + const node = try arena.construct(ast.Node.SuffixOp { + .base = ast.Node {.id = ast.Node.Id.SuffixOp }, + .lhs = lhs, + .op = ast.Node.SuffixOp.Op { + .ArrayAccess = undefined, + }, + .rtoken = undefined + }); + opt_ctx.store(&node.base); + stack.append(State { .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .SliceOrArrayAccess = node }); try stack.append(State { .Expression = OptionalCtx { .Required = &node.op.ArrayAccess }}); continue; }, Token.Id.Period => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.InfixOp, - ast.Node.InfixOp { - .base = undefined, - .lhs = lhs, - .op_token = token_index, - .op = ast.Node.InfixOp.Op.Period, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.InfixOp { + .base = ast.Node {.id = ast.Node.Id.InfixOp }, + .lhs = lhs, + .op_token = token_index, + .op = ast.Node.InfixOp.Op.Period, + .rhs = undefined, + }); + opt_ctx.store(&node.base); + stack.append(State { .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State { .Identifier = OptionalCtx { .Required = &node.rhs } }); continue; @@ -2461,14 +2421,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.LParen => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.GroupedExpression, - ast.Node.GroupedExpression { - .base = undefined, - .lparen = token.index, - .expr = undefined, - .rparen = undefined, - } - ); + const node = try arena.construct(ast.Node.GroupedExpression { + .base = ast.Node {.id = ast.Node.Id.GroupedExpression }, + .lparen = token.index, + .expr = undefined, + .rparen = undefined, + }); + opt_ctx.store(&node.base); + stack.append(State { .ExpectTokenSave = ExpectTokenSave { .id = Token.Id.RParen, @@ -2479,14 +2439,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Builtin => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.BuiltinCall, - ast.Node.BuiltinCall { - .base = undefined, - .builtin_token = token.index, - .params = ast.Node.BuiltinCall.ParamList.init(arena), - .rparen_token = undefined, - } - ); + const node = try arena.construct(ast.Node.BuiltinCall { + .base = ast.Node {.id = ast.Node.Id.BuiltinCall }, + .builtin_token = token.index, + .params = ast.Node.BuiltinCall.ParamList.init(arena), + .rparen_token = undefined, + }); + opt_ctx.store(&node.base); + stack.append(State { .ExprListItemOrEnd = ExprListCtx { .list = &node.params, @@ -2498,14 +2458,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.LBracket => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.PrefixOp, - ast.Node.PrefixOp { - .base = undefined, - .op_token = token.index, - .op = undefined, - .rhs = undefined, - } - ); + const node = try arena.construct(ast.Node.PrefixOp { + .base = ast.Node {.id = ast.Node.Id.PrefixOp }, + .op_token = token.index, + .op = undefined, + .rhs = undefined, + }); + opt_ctx.store(&node.base); + stack.append(State { .SliceOrArrayType = node }) catch unreachable; continue; }, @@ -2611,18 +2571,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_asm => { - const node = try createToCtxNode(arena, opt_ctx, ast.Node.Asm, - ast.Node.Asm { - .base = undefined, - .asm_token = token.index, - .volatile_token = null, - .template = undefined, - .outputs = ast.Node.Asm.OutputList.init(arena), - .inputs = ast.Node.Asm.InputList.init(arena), - .clobbers = ast.Node.Asm.ClobberList.init(arena), - .rparen = undefined, - } - ); + const node = try arena.construct(ast.Node.Asm { + .base = ast.Node {.id = ast.Node.Id.Asm }, + .asm_token = token.index, + .volatile_token = null, + .template = undefined, + .outputs = ast.Node.Asm.OutputList.init(arena), + .inputs = ast.Node.Asm.InputList.init(arena), + .clobbers = ast.Node.Asm.ClobberList.init(arena), + .rparen = undefined, + }); + opt_ctx.store(&node.base); + stack.append(State { .ExpectTokenSave = ExpectTokenSave { .id = Token.Id.RParen, @@ -3155,31 +3115,29 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con token_ptr: &const Token, token_index: TokenIndex) !bool { switch (token_ptr.id) { Token.Id.Keyword_suspend => { - const node = try createToCtxNode(arena, ctx, ast.Node.Suspend, - ast.Node.Suspend { - .base = undefined, - .label = null, - .suspend_token = token_index, - .payload = null, - .body = null, - } - ); + const node = try arena.construct(ast.Node.Suspend { + .base = ast.Node {.id = ast.Node.Id.Suspend }, + .label = null, + .suspend_token = token_index, + .payload = null, + .body = null, + }); + ctx.store(&node.base); stack.append(State { .SuspendBody = node }) catch unreachable; try stack.append(State { .Payload = OptionalCtx { .Optional = &node.payload } }); return true; }, Token.Id.Keyword_if => { - const node = try createToCtxNode(arena, ctx, ast.Node.If, - ast.Node.If { - .base = undefined, - .if_token = token_index, - .condition = undefined, - .payload = null, - .body = undefined, - .@"else" = null, - } - ); + const node = try arena.construct(ast.Node.If { + .base = ast.Node {.id = ast.Node.Id.If }, + .if_token = token_index, + .condition = undefined, + .payload = null, + .body = undefined, + .@"else" = null, + }); + ctx.store(&node.base); stack.append(State { .Else = &node.@"else" }) catch unreachable; try stack.append(State { .Expression = OptionalCtx { .Required = &node.body } }); @@ -3236,14 +3194,14 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con return true; }, Token.Id.Keyword_comptime => { - const node = try createToCtxNode(arena, ctx, ast.Node.Comptime, - ast.Node.Comptime { - .base = undefined, - .comptime_token = token_index, - .expr = undefined, - .doc_comments = null, - } - ); + const node = try arena.construct(ast.Node.Comptime { + .base = ast.Node {.id = ast.Node.Id.Comptime }, + .comptime_token = token_index, + .expr = undefined, + .doc_comments = null, + }); + ctx.store(&node.base); + try stack.append(State { .Expression = OptionalCtx { .Required = &node.expr } }); return true; }, @@ -3390,33 +3348,11 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op { }; } -fn createNode(arena: &mem.Allocator, comptime T: type, init_to: &const T) !&T { - const node = try arena.create(T); - *node = *init_to; - node.base = blk: { - const id = ast.Node.typeToId(T); - break :blk ast.Node { - .id = id, - }; - }; - - return node; -} - -fn createToCtxNode(arena: &mem.Allocator, opt_ctx: &const OptionalCtx, comptime T: type, init_to: &const T) !&T { - const node = try createNode(arena, T, init_to); - opt_ctx.store(&node.base); - - return node; -} - fn createLiteral(arena: &mem.Allocator, comptime T: type, token_index: TokenIndex) !&T { - return createNode(arena, T, - T { - .base = undefined, - .token = token_index, - } - ); + return arena.construct(T { + .base = ast.Node {.id = ast.Node.typeToId(T)}, + .token = token_index, + }); } fn createToCtxLiteral(arena: &mem.Allocator, opt_ctx: &const OptionalCtx, comptime T: type, token_index: TokenIndex) !&T { diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 29b231a4db..0f0ea5fdf1 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,11 @@ +//test "zig fmt: same-line doc comment on variable declaration" { +// try testCanonical( +// \\pub const MAP_ANONYMOUS = 0x1000; /// allocated from memory, swap space +// \\pub const MAP_FILE = 0x0000; /// map from file (default) +// \\ +// ); +//} + test "zig fmt: same-line comment after a statement" { try testCanonical( \\test "" { From 04bca58a3a3a85eeaa36ab4c2cc0881347e123b0 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 15 May 2018 00:33:34 -0400 Subject: [PATCH 14/75] zig fmt: preserve same line doc comments on var decls --- std/zig/parse.zig | 66 ++++++++++++++++++++++++++++------------- std/zig/parser_test.zig | 20 ++++++++----- 2 files changed, 58 insertions(+), 28 deletions(-) diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 3d6429ba71..f2376f0df3 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -640,12 +640,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { switch (token_ptr.id) { Token.Id.Equal => { var_decl.eq_token = token_index; - stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Semicolon, - .ptr = &var_decl.semicolon_token, - }, - }) catch unreachable; + stack.append(State { .VarDeclSemiColon = var_decl }) catch unreachable; try stack.append(State { .Expression = OptionalCtx { .RequiredNull = &var_decl.init_node } }); continue; }, @@ -662,6 +657,30 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, + State.VarDeclSemiColon => |var_decl| { + const semicolon_token = nextToken(&tok_it, &tree); + + if (semicolon_token.ptr.id != Token.Id.Semicolon) { + *(try tree.errors.addOne()) = Error { + .ExpectedToken = Error.ExpectedToken { + .token = semicolon_token.index, + .expected_id = Token.Id.Semicolon, + }, + }; + return tree; + } + + var_decl.semicolon_token = semicolon_token.index; + + if (eatToken(&tok_it, &tree, Token.Id.DocComment)) |doc_comment_token| { + const loc = tree.tokenLocation(semicolon_token.ptr.end, doc_comment_token); + if (loc.line == 0) { + try pushDocComment(arena, doc_comment_token, &var_decl.doc_comments); + } else { + putBackToken(&tok_it, &tree); + } + } + }, State.FnDef => |fn_proto| { const token = nextToken(&tok_it, &tree); @@ -2938,6 +2957,7 @@ const State = union(enum) { VarDecl: VarDeclCtx, VarDeclAlign: &ast.Node.VarDecl, VarDeclEq: &ast.Node.VarDecl, + VarDeclSemiColon: &ast.Node.VarDecl, FnDef: &ast.Node.FnProto, FnProto: &ast.Node.FnProto, @@ -3042,25 +3062,29 @@ const State = union(enum) { OptionalTokenSave: OptionalTokenSave, }; +fn pushDocComment(arena: &mem.Allocator, line_comment: TokenIndex, result: &?&ast.Node.DocComment) !void { + const node = blk: { + if (*result) |comment_node| { + break :blk comment_node; + } else { + const comment_node = try arena.construct(ast.Node.DocComment { + .base = ast.Node { + .id = ast.Node.Id.DocComment, + }, + .lines = ast.Node.DocComment.LineList.init(arena), + }); + *result = comment_node; + break :blk comment_node; + } + }; + try node.lines.push(line_comment); +} + fn eatDocComments(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) !?&ast.Node.DocComment { var result: ?&ast.Node.DocComment = null; while (true) { if (eatToken(tok_it, tree, Token.Id.DocComment)) |line_comment| { - const node = blk: { - if (result) |comment_node| { - break :blk comment_node; - } else { - const comment_node = try arena.construct(ast.Node.DocComment { - .base = ast.Node { - .id = ast.Node.Id.DocComment, - }, - .lines = ast.Node.DocComment.LineList.init(arena), - }); - result = comment_node; - break :blk comment_node; - } - }; - try node.lines.push(line_comment); + try pushDocComment(arena, line_comment, &result); continue; } break; diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 0f0ea5fdf1..f95ecfaee3 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,10 +1,16 @@ -//test "zig fmt: same-line doc comment on variable declaration" { -// try testCanonical( -// \\pub const MAP_ANONYMOUS = 0x1000; /// allocated from memory, swap space -// \\pub const MAP_FILE = 0x0000; /// map from file (default) -// \\ -// ); -//} +test "zig fmt: same-line doc comment on variable declaration" { + try testTransform( + \\pub const MAP_ANONYMOUS = 0x1000; /// allocated from memory, swap space + \\pub const MAP_FILE = 0x0000; /// map from file (default) + \\ + , + \\/// allocated from memory, swap space + \\pub const MAP_ANONYMOUS = 0x1000; + \\/// map from file (default) + \\pub const MAP_FILE = 0x0000; + \\ + ); +} test "zig fmt: same-line comment after a statement" { try testCanonical( From 74b10c08d1bd0b64aa8175dff6dec178c7c3bbee Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 15 May 2018 14:11:41 -0400 Subject: [PATCH 15/75] fix @typeInfo not setting a field to comptime --- src/ir.cpp | 1 + test/cases/type_info.zig | 305 ++++++++++++++++++++++----------------- 2 files changed, 171 insertions(+), 135 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index 31d22ca82a..cade660651 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -16549,6 +16549,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t { size_t byte_offset = LLVMOffsetOfElement(ira->codegen->target_data_ref, type_entry->type_ref, struct_field->gen_index); inner_fields[1].data.x_maybe = create_const_vals(1); + inner_fields[1].data.x_maybe->special = ConstValSpecialStatic; inner_fields[1].data.x_maybe->type = ira->codegen->builtin_types.entry_usize; bigint_init_unsigned(&inner_fields[1].data.x_maybe->data.x_bigint, byte_offset); } diff --git a/test/cases/type_info.zig b/test/cases/type_info.zig index f10703e3ee..7bf1e68180 100644 --- a/test/cases/type_info.zig +++ b/test/cases/type_info.zig @@ -4,167 +4,199 @@ const TypeInfo = @import("builtin").TypeInfo; const TypeId = @import("builtin").TypeId; test "type info: tag type, void info" { - comptime { - assert(@TagType(TypeInfo) == TypeId); - const void_info = @typeInfo(void); - assert(TypeId(void_info) == TypeId.Void); - assert(void_info.Void == {}); - } + testBasic(); + comptime testBasic(); +} + +fn testBasic() void { + assert(@TagType(TypeInfo) == TypeId); + const void_info = @typeInfo(void); + assert(TypeId(void_info) == TypeId.Void); + assert(void_info.Void == {}); } test "type info: integer, floating point type info" { - comptime { - const u8_info = @typeInfo(u8); - assert(TypeId(u8_info) == TypeId.Int); - assert(!u8_info.Int.is_signed); - assert(u8_info.Int.bits == 8); + testIntFloat(); + comptime testIntFloat(); +} - const f64_info = @typeInfo(f64); - assert(TypeId(f64_info) == TypeId.Float); - assert(f64_info.Float.bits == 64); - } +fn testIntFloat() void { + const u8_info = @typeInfo(u8); + assert(TypeId(u8_info) == TypeId.Int); + assert(!u8_info.Int.is_signed); + assert(u8_info.Int.bits == 8); + + const f64_info = @typeInfo(f64); + assert(TypeId(f64_info) == TypeId.Float); + assert(f64_info.Float.bits == 64); } test "type info: pointer type info" { - comptime { - const u32_ptr_info = @typeInfo(&u32); - assert(TypeId(u32_ptr_info) == TypeId.Pointer); - assert(u32_ptr_info.Pointer.is_const == false); - assert(u32_ptr_info.Pointer.is_volatile == false); - assert(u32_ptr_info.Pointer.alignment == 4); - assert(u32_ptr_info.Pointer.child == u32); - } + testPointer(); + comptime testPointer(); +} + +fn testPointer() void { + const u32_ptr_info = @typeInfo(&u32); + assert(TypeId(u32_ptr_info) == TypeId.Pointer); + assert(u32_ptr_info.Pointer.is_const == false); + assert(u32_ptr_info.Pointer.is_volatile == false); + assert(u32_ptr_info.Pointer.alignment == 4); + assert(u32_ptr_info.Pointer.child == u32); } test "type info: slice type info" { - comptime { - const u32_slice_info = @typeInfo([]u32); - assert(TypeId(u32_slice_info) == TypeId.Slice); - assert(u32_slice_info.Slice.is_const == false); - assert(u32_slice_info.Slice.is_volatile == false); - assert(u32_slice_info.Slice.alignment == 4); - assert(u32_slice_info.Slice.child == u32); - } + testSlice(); + comptime testSlice(); +} + +fn testSlice() void { + const u32_slice_info = @typeInfo([]u32); + assert(TypeId(u32_slice_info) == TypeId.Slice); + assert(u32_slice_info.Slice.is_const == false); + assert(u32_slice_info.Slice.is_volatile == false); + assert(u32_slice_info.Slice.alignment == 4); + assert(u32_slice_info.Slice.child == u32); } test "type info: array type info" { - comptime { - const arr_info = @typeInfo([42]bool); - assert(TypeId(arr_info) == TypeId.Array); - assert(arr_info.Array.len == 42); - assert(arr_info.Array.child == bool); - } + testArray(); + comptime testArray(); +} + +fn testArray() void { + const arr_info = @typeInfo([42]bool); + assert(TypeId(arr_info) == TypeId.Array); + assert(arr_info.Array.len == 42); + assert(arr_info.Array.child == bool); } test "type info: nullable type info" { - comptime { - const null_info = @typeInfo(?void); - assert(TypeId(null_info) == TypeId.Nullable); - assert(null_info.Nullable.child == void); - } + testNullable(); + comptime testNullable(); +} + +fn testNullable() void { + const null_info = @typeInfo(?void); + assert(TypeId(null_info) == TypeId.Nullable); + assert(null_info.Nullable.child == void); } test "type info: promise info" { - comptime { - const null_promise_info = @typeInfo(promise); - assert(TypeId(null_promise_info) == TypeId.Promise); - assert(null_promise_info.Promise.child == @typeOf(undefined)); + testPromise(); + comptime testPromise(); +} - const promise_info = @typeInfo(promise->usize); - assert(TypeId(promise_info) == TypeId.Promise); - assert(promise_info.Promise.child == usize); - } +fn testPromise() void { + const null_promise_info = @typeInfo(promise); + assert(TypeId(null_promise_info) == TypeId.Promise); + assert(null_promise_info.Promise.child == @typeOf(undefined)); + const promise_info = @typeInfo(promise->usize); + assert(TypeId(promise_info) == TypeId.Promise); + assert(promise_info.Promise.child == usize); } test "type info: error set, error union info" { - comptime { - const TestErrorSet = error { - First, - Second, - Third, - }; + testErrorSet(); + comptime testErrorSet(); +} - const error_set_info = @typeInfo(TestErrorSet); - assert(TypeId(error_set_info) == TypeId.ErrorSet); - assert(error_set_info.ErrorSet.errors.len == 3); - assert(mem.eql(u8, error_set_info.ErrorSet.errors[0].name, "First")); - assert(error_set_info.ErrorSet.errors[2].value == usize(TestErrorSet.Third)); +fn testErrorSet() void { + const TestErrorSet = error { + First, + Second, + Third, + }; - const error_union_info = @typeInfo(TestErrorSet!usize); - assert(TypeId(error_union_info) == TypeId.ErrorUnion); - assert(error_union_info.ErrorUnion.error_set == TestErrorSet); - assert(error_union_info.ErrorUnion.payload == usize); - } + const error_set_info = @typeInfo(TestErrorSet); + assert(TypeId(error_set_info) == TypeId.ErrorSet); + assert(error_set_info.ErrorSet.errors.len == 3); + assert(mem.eql(u8, error_set_info.ErrorSet.errors[0].name, "First")); + assert(error_set_info.ErrorSet.errors[2].value == usize(TestErrorSet.Third)); + + const error_union_info = @typeInfo(TestErrorSet!usize); + assert(TypeId(error_union_info) == TypeId.ErrorUnion); + assert(error_union_info.ErrorUnion.error_set == TestErrorSet); + assert(error_union_info.ErrorUnion.payload == usize); } test "type info: enum info" { - comptime { - const Os = @import("builtin").Os; + testEnum(); + comptime testEnum(); +} - const os_info = @typeInfo(Os); - assert(TypeId(os_info) == TypeId.Enum); - assert(os_info.Enum.layout == TypeInfo.ContainerLayout.Auto); - assert(os_info.Enum.fields.len == 32); - assert(mem.eql(u8, os_info.Enum.fields[1].name, "ananas")); - assert(os_info.Enum.fields[10].value == 10); - assert(os_info.Enum.tag_type == u5); - assert(os_info.Enum.defs.len == 0); - } +fn testEnum() void { + const Os = @import("builtin").Os; + + const os_info = @typeInfo(Os); + assert(TypeId(os_info) == TypeId.Enum); + assert(os_info.Enum.layout == TypeInfo.ContainerLayout.Auto); + assert(os_info.Enum.fields.len == 32); + assert(mem.eql(u8, os_info.Enum.fields[1].name, "ananas")); + assert(os_info.Enum.fields[10].value == 10); + assert(os_info.Enum.tag_type == u5); + assert(os_info.Enum.defs.len == 0); } test "type info: union info" { - comptime { - const typeinfo_info = @typeInfo(TypeInfo); - assert(TypeId(typeinfo_info) == TypeId.Union); - assert(typeinfo_info.Union.layout == TypeInfo.ContainerLayout.Auto); - assert(typeinfo_info.Union.tag_type == TypeId); - assert(typeinfo_info.Union.fields.len == 26); - assert(typeinfo_info.Union.fields[4].enum_field != null); - assert((??typeinfo_info.Union.fields[4].enum_field).value == 4); - assert(typeinfo_info.Union.fields[4].field_type == @typeOf(@typeInfo(u8).Int)); - assert(typeinfo_info.Union.defs.len == 21); + testUnion(); + comptime testUnion(); +} - const TestNoTagUnion = union { - Foo: void, - Bar: u32, - }; +fn testUnion() void { + const typeinfo_info = @typeInfo(TypeInfo); + assert(TypeId(typeinfo_info) == TypeId.Union); + assert(typeinfo_info.Union.layout == TypeInfo.ContainerLayout.Auto); + assert(typeinfo_info.Union.tag_type == TypeId); + assert(typeinfo_info.Union.fields.len == 26); + assert(typeinfo_info.Union.fields[4].enum_field != null); + assert((??typeinfo_info.Union.fields[4].enum_field).value == 4); + assert(typeinfo_info.Union.fields[4].field_type == @typeOf(@typeInfo(u8).Int)); + assert(typeinfo_info.Union.defs.len == 21); - const notag_union_info = @typeInfo(TestNoTagUnion); - assert(TypeId(notag_union_info) == TypeId.Union); - assert(notag_union_info.Union.tag_type == @typeOf(undefined)); - assert(notag_union_info.Union.layout == TypeInfo.ContainerLayout.Auto); - assert(notag_union_info.Union.fields.len == 2); - assert(notag_union_info.Union.fields[0].enum_field == null); - assert(notag_union_info.Union.fields[1].field_type == u32); + const TestNoTagUnion = union { + Foo: void, + Bar: u32, + }; - const TestExternUnion = extern union { - foo: &c_void, - }; + const notag_union_info = @typeInfo(TestNoTagUnion); + assert(TypeId(notag_union_info) == TypeId.Union); + assert(notag_union_info.Union.tag_type == @typeOf(undefined)); + assert(notag_union_info.Union.layout == TypeInfo.ContainerLayout.Auto); + assert(notag_union_info.Union.fields.len == 2); + assert(notag_union_info.Union.fields[0].enum_field == null); + assert(notag_union_info.Union.fields[1].field_type == u32); - const extern_union_info = @typeInfo(TestExternUnion); - assert(extern_union_info.Union.layout == TypeInfo.ContainerLayout.Extern); - assert(extern_union_info.Union.tag_type == @typeOf(undefined)); - assert(extern_union_info.Union.fields[0].enum_field == null); - assert(extern_union_info.Union.fields[0].field_type == &c_void); - } + const TestExternUnion = extern union { + foo: &c_void, + }; + + const extern_union_info = @typeInfo(TestExternUnion); + assert(extern_union_info.Union.layout == TypeInfo.ContainerLayout.Extern); + assert(extern_union_info.Union.tag_type == @typeOf(undefined)); + assert(extern_union_info.Union.fields[0].enum_field == null); + assert(extern_union_info.Union.fields[0].field_type == &c_void); } test "type info: struct info" { - comptime { - const struct_info = @typeInfo(TestStruct); - assert(TypeId(struct_info) == TypeId.Struct); - assert(struct_info.Struct.layout == TypeInfo.ContainerLayout.Packed); - assert(struct_info.Struct.fields.len == 3); - assert(struct_info.Struct.fields[1].offset == null); - assert(struct_info.Struct.fields[2].field_type == &TestStruct); - assert(struct_info.Struct.defs.len == 2); - assert(struct_info.Struct.defs[0].is_pub); - assert(!struct_info.Struct.defs[0].data.Fn.is_extern); - assert(struct_info.Struct.defs[0].data.Fn.lib_name == null); - assert(struct_info.Struct.defs[0].data.Fn.return_type == void); - assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn(&const TestStruct)void); - } + testStruct(); + comptime testStruct(); +} + +fn testStruct() void { + const struct_info = @typeInfo(TestStruct); + assert(TypeId(struct_info) == TypeId.Struct); + assert(struct_info.Struct.layout == TypeInfo.ContainerLayout.Packed); + assert(struct_info.Struct.fields.len == 3); + assert(struct_info.Struct.fields[1].offset == null); + assert(struct_info.Struct.fields[2].field_type == &TestStruct); + assert(struct_info.Struct.defs.len == 2); + assert(struct_info.Struct.defs[0].is_pub); + assert(!struct_info.Struct.defs[0].data.Fn.is_extern); + assert(struct_info.Struct.defs[0].data.Fn.lib_name == null); + assert(struct_info.Struct.defs[0].data.Fn.return_type == void); + assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn(&const TestStruct)void); } const TestStruct = packed struct { @@ -178,21 +210,24 @@ const TestStruct = packed struct { }; test "type info: function type info" { - comptime { - const fn_info = @typeInfo(@typeOf(foo)); - assert(TypeId(fn_info) == TypeId.Fn); - assert(fn_info.Fn.calling_convention == TypeInfo.CallingConvention.Unspecified); - assert(fn_info.Fn.is_generic); - assert(fn_info.Fn.args.len == 2); - assert(fn_info.Fn.is_var_args); - assert(fn_info.Fn.return_type == @typeOf(undefined)); - assert(fn_info.Fn.async_allocator_type == @typeOf(undefined)); + testFunction(); + comptime testFunction(); +} - const test_instance: TestStruct = undefined; - const bound_fn_info = @typeInfo(@typeOf(test_instance.foo)); - assert(TypeId(bound_fn_info) == TypeId.BoundFn); - assert(bound_fn_info.BoundFn.args[0].arg_type == &const TestStruct); - } +fn testFunction() void { + const fn_info = @typeInfo(@typeOf(foo)); + assert(TypeId(fn_info) == TypeId.Fn); + assert(fn_info.Fn.calling_convention == TypeInfo.CallingConvention.Unspecified); + assert(fn_info.Fn.is_generic); + assert(fn_info.Fn.args.len == 2); + assert(fn_info.Fn.is_var_args); + assert(fn_info.Fn.return_type == @typeOf(undefined)); + assert(fn_info.Fn.async_allocator_type == @typeOf(undefined)); + + const test_instance: TestStruct = undefined; + const bound_fn_info = @typeInfo(@typeOf(test_instance.foo)); + assert(TypeId(bound_fn_info) == TypeId.BoundFn); + assert(bound_fn_info.BoundFn.args[0].arg_type == &const TestStruct); } fn foo(comptime a: usize, b: bool, args: ...) usize { From 3625df25d6fe0b11e4c1c33454b621ec8a8c10ba Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 15 May 2018 16:21:47 -0400 Subject: [PATCH 16/75] build: add flag to LLD to fix gcc 8 build (#1013) * build: add flag to LLD to fix gcc 8 build * build: add -Wno-unknown-warning-option to work around older gcc --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0aad51c7bc..bda576347e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -196,7 +196,7 @@ else() if(MSVC) set(ZIG_LLD_COMPILE_FLAGS "-std=c++11 -D_CRT_SECURE_NO_WARNINGS /w") else() - set(ZIG_LLD_COMPILE_FLAGS "-std=c++11 -fno-exceptions -fno-rtti -Wno-comment") + set(ZIG_LLD_COMPILE_FLAGS "-std=c++11 -fno-exceptions -fno-rtti -Wno-comment -Wno-class-memaccess -Wno-unknown-warning-option") endif() set_target_properties(embedded_lld_lib PROPERTIES COMPILE_FLAGS ${ZIG_LLD_COMPILE_FLAGS} From 492a214d4c4f4feb15620dfd05230de0086825e5 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 15 May 2018 22:11:03 -0400 Subject: [PATCH 17/75] std.fmt.format: support {B} for human readable bytes --- std/fmt/index.zig | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 43e758038f..e26b2f6c8b 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -27,6 +27,8 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), Character, Buf, BufWidth, + Bytes, + BytesWidth, }; comptime var start_index = 0; @@ -95,6 +97,10 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), '.' => { state = State.Float; }, + 'B' => { + width = 0; + state = State.Bytes; + }, else => @compileError("Unknown format character: " ++ []u8{c}), }, State.Buf => switch (c) { @@ -206,6 +212,30 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), }, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, + State.Bytes => switch (c) { + '}' => { + try formatBytes(args[next_arg], 0, context, Errors, output); + next_arg += 1; + state = State.Start; + start_index = i + 1; + }, + '0' ... '9' => { + width_start = i; + state = State.BytesWidth; + }, + else => @compileError("Unexpected character in format string: " ++ []u8{c}), + }, + State.BytesWidth => switch (c) { + '}' => { + width = comptime (parseUnsigned(usize, fmt[width_start..i], 10) catch unreachable); + try formatBytes(args[next_arg], width, context, Errors, output); + next_arg += 1; + state = State.Start; + start_index = i + 1; + }, + '0' ... '9' => {}, + else => @compileError("Unexpected character in format string: " ++ []u8{c}), + }, } } comptime { @@ -520,6 +550,25 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com } } +pub fn formatBytes(value: var, width: ?usize, + context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void +{ + if (value == 0) { + return output(context, "0B"); + } + + const mags = " KMGTPEZY"; + const magnitude = math.min(math.log2(value) / 10, mags.len - 1); + const new_value = f64(value) / math.pow(f64, 1024, f64(magnitude)); + const suffix = mags[magnitude]; + + try formatFloatDecimal(new_value, width, context, Errors, output); + + if (suffix != ' ') { + try output(context, (&suffix)[0..1]); + } + return output(context, "B"); +} pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void @@ -767,6 +816,12 @@ test "fmt.format" { const result = try bufPrint(buf1[0..], "u3: {}\n", value); assert(mem.eql(u8, result, "u3: 5\n")); } + { + var buf1: [32]u8 = undefined; + const value: usize = 63 * 1024 * 1024; + const result = try bufPrint(buf1[0..], "file size: {B}\n", value); + assert(mem.eql(u8, result, "file size: 63MB\n")); + } { // Dummy field because of https://github.com/zig-lang/zig/issues/557. const Struct = struct { From ee5f9ffad02b3cf263c13ca58c4d2e4526e29a84 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 16 May 2018 00:27:18 -0400 Subject: [PATCH 18/75] zig fmt: add comma on last switch prong --- std/zig/parse.zig | 2 +- std/zig/parser_test.zig | 31 +++++++++++++++++++++++++++++++ std/zig/render.zig | 15 ++++++++++++++- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/std/zig/parse.zig b/std/zig/parse.zig index f2376f0df3..4f1e3dcefe 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -1406,7 +1406,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.SwitchCaseCommaOrEnd => |list_state| { - switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.RParen)) { + switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.RBrace)) { ExpectCommaOrEndResult.end_token => |maybe_end| if (maybe_end) |end| { *list_state.ptr = end; continue; diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index f95ecfaee3..129e62e6dd 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,34 @@ +test "zig fmt: add comma on last switch prong" { + try testTransform( + \\test "aoeu" { + \\switch (self.init_arg_expr) { + \\ InitArg.Type => |t| { }, + \\ InitArg.None, + \\ InitArg.Enum => { } + \\} + \\ switch (self.init_arg_expr) { + \\ InitArg.Type => |t| { }, + \\ InitArg.None, + \\ InitArg.Enum => { }//line comment + \\ } + \\} + , + \\test "aoeu" { + \\ switch (self.init_arg_expr) { + \\ InitArg.Type => |t| {}, + \\ InitArg.None, + \\ InitArg.Enum => {}, + \\ } + \\ switch (self.init_arg_expr) { + \\ InitArg.Type => |t| {}, + \\ InitArg.None, + \\ InitArg.Enum => {}, //line comment + \\ } + \\} + \\ + ); +} + test "zig fmt: same-line doc comment on variable declaration" { try testTransform( \\pub const MAP_ANONYMOUS = 0x1000; /// allocated from memory, swap space diff --git a/std/zig/render.zig b/std/zig/render.zig index 13ef4607f4..5084c1d096 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -831,7 +831,20 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } try renderExpression(allocator, stream, tree, indent, switch_case.expr); - try renderToken(tree, stream, switch_case.lastToken() + 1, indent, true); + { + // Handle missing comma after last switch case + var index = switch_case.lastToken() + 1; + switch (tree.tokens.at(index).id) { + Token.Id.RBrace => { + try stream.write(","); + }, + Token.Id.LineComment => { + try stream.write(", "); + try renderToken(tree, stream, index, indent, true); + }, + else => try renderToken(tree, stream, index, indent, true), + } + } }, ast.Node.Id.SwitchElse => { const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base); From 288fc3a8d361972daeded19d207b410128d70d67 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 16 May 2018 00:43:28 -0400 Subject: [PATCH 19/75] convert more std lib files to postfix pointer deref --- std/crypto/test.zig | 3 +- std/fmt/errol/index.zig | 54 +- std/os/darwin.zig | 274 +++-- std/zig/ast.zig | 71 +- std/zig/parse.zig | 2083 +++++++++++++++++---------------------- std/zig/render.zig | 88 +- 6 files changed, 1203 insertions(+), 1370 deletions(-) diff --git a/std/crypto/test.zig b/std/crypto/test.zig index e41c6a7a2d..3fa24272e5 100644 --- a/std/crypto/test.zig +++ b/std/crypto/test.zig @@ -14,9 +14,8 @@ pub fn assertEqualHash(comptime Hasher: var, comptime expected: []const u8, inpu pub fn assertEqual(comptime expected: []const u8, input: []const u8) void { var expected_bytes: [expected.len / 2]u8 = undefined; for (expected_bytes) |*r, i| { - *r = fmt.parseInt(u8, expected[2*i .. 2*i+2], 16) catch unreachable; + r.* = fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable; } debug.assert(mem.eql(u8, expected_bytes, input)); } - diff --git a/std/fmt/errol/index.zig b/std/fmt/errol/index.zig index 00c69cd294..f4ec251b77 100644 --- a/std/fmt/errol/index.zig +++ b/std/fmt/errol/index.zig @@ -86,7 +86,7 @@ pub fn errol3(value: f64, buffer: []u8) FloatDecimal { const data = enum3_data[i]; const digits = buffer[1..data.str.len + 1]; mem.copy(u8, digits, data.str); - return FloatDecimal { + return FloatDecimal{ .digits = digits, .exp = data.exp, }; @@ -105,7 +105,6 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal { return errolFixed(val, buffer); } - // normalize the midpoint const e = math.frexp(val).exponent; @@ -137,11 +136,11 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal { } // compute boundaries - var high = HP { + var high = HP{ .val = mid.val, .off = mid.off + (fpnext(val) - val) * lten * ten / 2.0, }; - var low = HP { + var low = HP{ .val = mid.val, .off = mid.off + (fpprev(val) - val) * lten * ten / 2.0, }; @@ -171,15 +170,12 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal { var buf_index: usize = 1; while (true) { var hdig = u8(math.floor(high.val)); - if ((high.val == f64(hdig)) and (high.off < 0)) - hdig -= 1; + if ((high.val == f64(hdig)) and (high.off < 0)) hdig -= 1; var ldig = u8(math.floor(low.val)); - if ((low.val == f64(ldig)) and (low.off < 0)) - ldig -= 1; + if ((low.val == f64(ldig)) and (low.off < 0)) ldig -= 1; - if (ldig != hdig) - break; + if (ldig != hdig) break; buffer[buf_index] = hdig + '0'; buf_index += 1; @@ -191,13 +187,12 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal { const tmp = (high.val + low.val) / 2.0; var mdig = u8(math.floor(tmp + 0.5)); - if ((f64(mdig) - tmp) == 0.5 and (mdig & 0x1) != 0) - mdig -= 1; + if ((f64(mdig) - tmp) == 0.5 and (mdig & 0x1) != 0) mdig -= 1; buffer[buf_index] = mdig + '0'; buf_index += 1; - return FloatDecimal { + return FloatDecimal{ .digits = buffer[1..buf_index], .exp = exp, }; @@ -235,7 +230,7 @@ fn hpProd(in: &const HP, val: f64) HP { const p = in.val * val; const e = ((hi * hi2 - p) + lo * hi2 + hi * lo2) + lo * lo2; - return HP { + return HP{ .val = p, .off = in.off * val + e, }; @@ -246,8 +241,8 @@ fn hpProd(in: &const HP, val: f64) HP { /// @hi: The high bits. /// @lo: The low bits. fn split(val: f64, hi: &f64, lo: &f64) void { - *hi = gethi(val); - *lo = val - *hi; + hi.* = gethi(val); + lo.* = val - hi.*; } fn gethi(in: f64) f64 { @@ -301,7 +296,6 @@ fn hpMul10(hp: &HP) void { hpNormalize(hp); } - /// Integer conversion algorithm, guaranteed correct, optimal, and best. /// @val: The val. /// @buf: The output buffer. @@ -343,8 +337,7 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { } const m64 = @truncate(u64, @divTrunc(mid, x)); - if (lf != hf) - mi += 19; + if (lf != hf) mi += 19; var buf_index = u64toa(m64, buffer) - 1; @@ -354,7 +347,7 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { buf_index += 1; } - return FloatDecimal { + return FloatDecimal{ .digits = buffer[0..buf_index], .exp = i32(buf_index) + mi, }; @@ -396,25 +389,24 @@ fn errolFixed(val: f64, buffer: []u8) FloatDecimal { buffer[j] = u8(mdig + '0'); j += 1; - if(hdig != ldig or j > 50) - break; + if (hdig != ldig or j > 50) break; } if (mid > 0.5) { - buffer[j-1] += 1; - } else if ((mid == 0.5) and (buffer[j-1] & 0x1) != 0) { - buffer[j-1] += 1; + buffer[j - 1] += 1; + } else if ((mid == 0.5) and (buffer[j - 1] & 0x1) != 0) { + buffer[j - 1] += 1; } } else { - while (buffer[j-1] == '0') { - buffer[j-1] = 0; + while (buffer[j - 1] == '0') { + buffer[j - 1] = 0; j -= 1; } } buffer[j] = 0; - return FloatDecimal { + return FloatDecimal{ .digits = buffer[0..j], .exp = exp, }; @@ -587,7 +579,7 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buffer[buf_index] = c_digits_lut[d8 + 1]; buf_index += 1; } else { - const a = u32(value / kTen16); // 1 to 1844 + const a = u32(value / kTen16); // 1 to 1844 value %= kTen16; if (a < 10) { @@ -686,7 +678,6 @@ fn fpeint(from: f64) u128 { return u128(1) << @truncate(u7, (bits >> 52) -% 1023); } - /// Given two different integers with the same length in terms of the number /// of decimal digits, index the digits from the right-most position starting /// from zero, find the first index where the digits in the two integers @@ -713,7 +704,6 @@ fn mismatch10(a: u64, b: u64) i32 { a_copy /= 10; b_copy /= 10; - if (a_copy == b_copy) - return i; + if (a_copy == b_copy) return i; } } diff --git a/std/os/darwin.zig b/std/os/darwin.zig index 0a62b03ab2..45359e757d 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -10,33 +10,56 @@ pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; -pub const PROT_NONE = 0x00; /// [MC2] no permissions -pub const PROT_READ = 0x01; /// [MC2] pages can be read -pub const PROT_WRITE = 0x02; /// [MC2] pages can be written -pub const PROT_EXEC = 0x04; /// [MC2] pages can be executed +/// [MC2] no permissions +pub const PROT_NONE = 0x00; +/// [MC2] pages can be read +pub const PROT_READ = 0x01; +/// [MC2] pages can be written +pub const PROT_WRITE = 0x02; +/// [MC2] pages can be executed +pub const PROT_EXEC = 0x04; -pub const MAP_ANONYMOUS = 0x1000; /// allocated from memory, swap space -pub const MAP_FILE = 0x0000; /// map from file (default) -pub const MAP_FIXED = 0x0010; /// interpret addr exactly -pub const MAP_HASSEMAPHORE = 0x0200; /// region may contain semaphores -pub const MAP_PRIVATE = 0x0002; /// changes are private -pub const MAP_SHARED = 0x0001; /// share changes -pub const MAP_NOCACHE = 0x0400; /// don't cache pages for this mapping -pub const MAP_NORESERVE = 0x0040; /// don't reserve needed swap area +/// allocated from memory, swap space +pub const MAP_ANONYMOUS = 0x1000; +/// map from file (default) +pub const MAP_FILE = 0x0000; +/// interpret addr exactly +pub const MAP_FIXED = 0x0010; +/// region may contain semaphores +pub const MAP_HASSEMAPHORE = 0x0200; +/// changes are private +pub const MAP_PRIVATE = 0x0002; +/// share changes +pub const MAP_SHARED = 0x0001; +/// don't cache pages for this mapping +pub const MAP_NOCACHE = 0x0400; +/// don't reserve needed swap area +pub const MAP_NORESERVE = 0x0040; pub const MAP_FAILED = @maxValue(usize); -pub const WNOHANG = 0x00000001; /// [XSI] no hang in wait/no child to reap -pub const WUNTRACED = 0x00000002; /// [XSI] notify on stop, untraced child +/// [XSI] no hang in wait/no child to reap +pub const WNOHANG = 0x00000001; +/// [XSI] notify on stop, untraced child +pub const WUNTRACED = 0x00000002; -pub const SA_ONSTACK = 0x0001; /// take signal on signal stack -pub const SA_RESTART = 0x0002; /// restart system on signal return -pub const SA_RESETHAND = 0x0004; /// reset to SIG_DFL when taking signal -pub const SA_NOCLDSTOP = 0x0008; /// do not generate SIGCHLD on child stop -pub const SA_NODEFER = 0x0010; /// don't mask the signal we're delivering -pub const SA_NOCLDWAIT = 0x0020; /// don't keep zombies around -pub const SA_SIGINFO = 0x0040; /// signal handler with SA_SIGINFO args -pub const SA_USERTRAMP = 0x0100; /// do not bounce off kernel's sigtramp -pub const SA_64REGSET = 0x0200; /// signal handler with SA_SIGINFO args with 64bit regs information +/// take signal on signal stack +pub const SA_ONSTACK = 0x0001; +/// restart system on signal return +pub const SA_RESTART = 0x0002; +/// reset to SIG_DFL when taking signal +pub const SA_RESETHAND = 0x0004; +/// do not generate SIGCHLD on child stop +pub const SA_NOCLDSTOP = 0x0008; +/// don't mask the signal we're delivering +pub const SA_NODEFER = 0x0010; +/// don't keep zombies around +pub const SA_NOCLDWAIT = 0x0020; +/// signal handler with SA_SIGINFO args +pub const SA_SIGINFO = 0x0040; +/// do not bounce off kernel's sigtramp +pub const SA_USERTRAMP = 0x0100; +/// signal handler with SA_SIGINFO args with 64bit regs information +pub const SA_64REGSET = 0x0200; pub const O_LARGEFILE = 0x0000; pub const O_PATH = 0x0000; @@ -46,20 +69,34 @@ pub const X_OK = 1; pub const W_OK = 2; pub const R_OK = 4; -pub const O_RDONLY = 0x0000; /// open for reading only -pub const O_WRONLY = 0x0001; /// open for writing only -pub const O_RDWR = 0x0002; /// open for reading and writing -pub const O_NONBLOCK = 0x0004; /// do not block on open or for data to become available -pub const O_APPEND = 0x0008; /// append on each write -pub const O_CREAT = 0x0200; /// create file if it does not exist -pub const O_TRUNC = 0x0400; /// truncate size to 0 -pub const O_EXCL = 0x0800; /// error if O_CREAT and the file exists -pub const O_SHLOCK = 0x0010; /// atomically obtain a shared lock -pub const O_EXLOCK = 0x0020; /// atomically obtain an exclusive lock -pub const O_NOFOLLOW = 0x0100; /// do not follow symlinks -pub const O_SYMLINK = 0x200000; /// allow open of symlinks -pub const O_EVTONLY = 0x8000; /// descriptor requested for event notifications only -pub const O_CLOEXEC = 0x1000000; /// mark as close-on-exec +/// open for reading only +pub const O_RDONLY = 0x0000; +/// open for writing only +pub const O_WRONLY = 0x0001; +/// open for reading and writing +pub const O_RDWR = 0x0002; +/// do not block on open or for data to become available +pub const O_NONBLOCK = 0x0004; +/// append on each write +pub const O_APPEND = 0x0008; +/// create file if it does not exist +pub const O_CREAT = 0x0200; +/// truncate size to 0 +pub const O_TRUNC = 0x0400; +/// error if O_CREAT and the file exists +pub const O_EXCL = 0x0800; +/// atomically obtain a shared lock +pub const O_SHLOCK = 0x0010; +/// atomically obtain an exclusive lock +pub const O_EXLOCK = 0x0020; +/// do not follow symlinks +pub const O_NOFOLLOW = 0x0100; +/// allow open of symlinks +pub const O_SYMLINK = 0x200000; +/// descriptor requested for event notifications only +pub const O_EVTONLY = 0x8000; +/// mark as close-on-exec +pub const O_CLOEXEC = 0x1000000; pub const O_ACCMODE = 3; pub const O_ALERT = 536870912; @@ -87,52 +124,102 @@ pub const DT_LNK = 10; pub const DT_SOCK = 12; pub const DT_WHT = 14; -pub const SIG_BLOCK = 1; /// block specified signal set -pub const SIG_UNBLOCK = 2; /// unblock specified signal set -pub const SIG_SETMASK = 3; /// set specified signal set +/// block specified signal set +pub const SIG_BLOCK = 1; +/// unblock specified signal set +pub const SIG_UNBLOCK = 2; +/// set specified signal set +pub const SIG_SETMASK = 3; -pub const SIGHUP = 1; /// hangup -pub const SIGINT = 2; /// interrupt -pub const SIGQUIT = 3; /// quit -pub const SIGILL = 4; /// illegal instruction (not reset when caught) -pub const SIGTRAP = 5; /// trace trap (not reset when caught) -pub const SIGABRT = 6; /// abort() -pub const SIGPOLL = 7; /// pollable event ([XSR] generated, not supported) -pub const SIGIOT = SIGABRT; /// compatibility -pub const SIGEMT = 7; /// EMT instruction -pub const SIGFPE = 8; /// floating point exception -pub const SIGKILL = 9; /// kill (cannot be caught or ignored) -pub const SIGBUS = 10; /// bus error -pub const SIGSEGV = 11; /// segmentation violation -pub const SIGSYS = 12; /// bad argument to system call -pub const SIGPIPE = 13; /// write on a pipe with no one to read it -pub const SIGALRM = 14; /// alarm clock -pub const SIGTERM = 15; /// software termination signal from kill -pub const SIGURG = 16; /// urgent condition on IO channel -pub const SIGSTOP = 17; /// sendable stop signal not from tty -pub const SIGTSTP = 18; /// stop signal from tty -pub const SIGCONT = 19; /// continue a stopped process -pub const SIGCHLD = 20; /// to parent on child stop or exit -pub const SIGTTIN = 21; /// to readers pgrp upon background tty read -pub const SIGTTOU = 22; /// like TTIN for output if (tp->t_local<OSTOP) -pub const SIGIO = 23; /// input/output possible signal -pub const SIGXCPU = 24; /// exceeded CPU time limit -pub const SIGXFSZ = 25; /// exceeded file size limit -pub const SIGVTALRM = 26; /// virtual time alarm -pub const SIGPROF = 27; /// profiling time alarm -pub const SIGWINCH = 28; /// window size changes -pub const SIGINFO = 29; /// information request -pub const SIGUSR1 = 30; /// user defined signal 1 -pub const SIGUSR2 = 31; /// user defined signal 2 +/// hangup +pub const SIGHUP = 1; +/// interrupt +pub const SIGINT = 2; +/// quit +pub const SIGQUIT = 3; +/// illegal instruction (not reset when caught) +pub const SIGILL = 4; +/// trace trap (not reset when caught) +pub const SIGTRAP = 5; +/// abort() +pub const SIGABRT = 6; +/// pollable event ([XSR] generated, not supported) +pub const SIGPOLL = 7; +/// compatibility +pub const SIGIOT = SIGABRT; +/// EMT instruction +pub const SIGEMT = 7; +/// floating point exception +pub const SIGFPE = 8; +/// kill (cannot be caught or ignored) +pub const SIGKILL = 9; +/// bus error +pub const SIGBUS = 10; +/// segmentation violation +pub const SIGSEGV = 11; +/// bad argument to system call +pub const SIGSYS = 12; +/// write on a pipe with no one to read it +pub const SIGPIPE = 13; +/// alarm clock +pub const SIGALRM = 14; +/// software termination signal from kill +pub const SIGTERM = 15; +/// urgent condition on IO channel +pub const SIGURG = 16; +/// sendable stop signal not from tty +pub const SIGSTOP = 17; +/// stop signal from tty +pub const SIGTSTP = 18; +/// continue a stopped process +pub const SIGCONT = 19; +/// to parent on child stop or exit +pub const SIGCHLD = 20; +/// to readers pgrp upon background tty read +pub const SIGTTIN = 21; +/// like TTIN for output if (tp->t_local<OSTOP) +pub const SIGTTOU = 22; +/// input/output possible signal +pub const SIGIO = 23; +/// exceeded CPU time limit +pub const SIGXCPU = 24; +/// exceeded file size limit +pub const SIGXFSZ = 25; +/// virtual time alarm +pub const SIGVTALRM = 26; +/// profiling time alarm +pub const SIGPROF = 27; +/// window size changes +pub const SIGWINCH = 28; +/// information request +pub const SIGINFO = 29; +/// user defined signal 1 +pub const SIGUSR1 = 30; +/// user defined signal 2 +pub const SIGUSR2 = 31; -fn wstatus(x: i32) i32 { return x & 0o177; } +fn wstatus(x: i32) i32 { + return x & 0o177; +} const wstopped = 0o177; -pub fn WEXITSTATUS(x: i32) i32 { return x >> 8; } -pub fn WTERMSIG(x: i32) i32 { return wstatus(x); } -pub fn WSTOPSIG(x: i32) i32 { return x >> 8; } -pub fn WIFEXITED(x: i32) bool { return wstatus(x) == 0; } -pub fn WIFSTOPPED(x: i32) bool { return wstatus(x) == wstopped and WSTOPSIG(x) != 0x13; } -pub fn WIFSIGNALED(x: i32) bool { return wstatus(x) != wstopped and wstatus(x) != 0; } +pub fn WEXITSTATUS(x: i32) i32 { + return x >> 8; +} +pub fn WTERMSIG(x: i32) i32 { + return wstatus(x); +} +pub fn WSTOPSIG(x: i32) i32 { + return x >> 8; +} +pub fn WIFEXITED(x: i32) bool { + return wstatus(x) == 0; +} +pub fn WIFSTOPPED(x: i32) bool { + return wstatus(x) == wstopped and WSTOPSIG(x) != 0x13; +} +pub fn WIFSIGNALED(x: i32) bool { + return wstatus(x) != wstopped and wstatus(x) != 0; +} /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { @@ -184,11 +271,8 @@ pub fn write(fd: i32, buf: &const u8, nbyte: usize) usize { return errnoWrap(c.write(fd, @ptrCast(&const c_void, buf), nbyte)); } -pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, - offset: isize) usize -{ - const ptr_result = c.mmap(@ptrCast(&c_void, address), length, - @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset); +pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { + const ptr_result = c.mmap(@ptrCast(&c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset); const isize_result = @bitCast(isize, @ptrToInt(ptr_result)); return errnoWrap(isize_result); } @@ -202,7 +286,7 @@ pub fn unlink(path: &const u8) usize { } pub fn getcwd(buf: &u8, size: usize) usize { - return if (c.getcwd(buf, size) == null) @bitCast(usize, -isize(*c._errno())) else 0; + return if (c.getcwd(buf, size) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } pub fn waitpid(pid: i32, status: &i32, options: u32) usize { @@ -223,7 +307,6 @@ pub fn pipe(fds: &[2]i32) usize { return errnoWrap(c.pipe(@ptrCast(&c_int, fds))); } - pub fn getdirentries64(fd: i32, buf_ptr: &u8, buf_len: usize, basep: &i64) usize { return errnoWrap(@bitCast(isize, c.__getdirentries64(fd, buf_ptr, buf_len, basep))); } @@ -269,7 +352,7 @@ pub fn nanosleep(req: &const timespec, rem: ?×pec) usize { } pub fn realpath(noalias filename: &const u8, noalias resolved_name: &u8) usize { - return if (c.realpath(filename, resolved_name) == null) @bitCast(usize, -isize(*c._errno())) else 0; + return if (c.realpath(filename, resolved_name) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } pub fn setreuid(ruid: u32, euid: u32) usize { @@ -287,8 +370,8 @@ pub fn sigprocmask(flags: u32, noalias set: &const sigset_t, noalias oldset: ?&s pub fn sigaction(sig: u5, noalias act: &const Sigaction, noalias oact: ?&Sigaction) usize { assert(sig != SIGKILL); assert(sig != SIGSTOP); - var cact = c.Sigaction { - .handler = @ptrCast(extern fn(c_int)void, act.handler), + var cact = c.Sigaction{ + .handler = @ptrCast(extern fn(c_int) void, act.handler), .sa_flags = @bitCast(c_int, act.flags), .sa_mask = act.mask, }; @@ -298,8 +381,8 @@ pub fn sigaction(sig: u5, noalias act: &const Sigaction, noalias oact: ?&Sigacti return result; } if (oact) |old| { - *old = Sigaction { - .handler = @ptrCast(extern fn(i32)void, coact.handler), + old.* = Sigaction{ + .handler = @ptrCast(extern fn(i32) void, coact.handler), .flags = @bitCast(u32, coact.sa_flags), .mask = coact.sa_mask, }; @@ -319,23 +402,22 @@ pub const sockaddr = c.sockaddr; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = struct { - handler: extern fn(i32)void, + handler: extern fn(i32) void, mask: sigset_t, flags: u32, }; pub fn sigaddset(set: &sigset_t, signo: u5) void { - *set |= u32(1) << (signo - 1); + set.* |= u32(1) << (signo - 1); } /// Takes the return value from a syscall and formats it back in the way /// that the kernel represents it to libc. Errno was a mistake, let's make /// it go away forever. fn errnoWrap(value: isize) usize { - return @bitCast(usize, if (value == -1) -isize(*c._errno()) else value); + return @bitCast(usize, if (value == -1) -isize(c._errno().*) else value); } - pub const timezone = c.timezone; pub const timeval = c.timeval; pub const mach_timebase_info_data = c.mach_timebase_info_data; diff --git a/std/zig/ast.zig b/std/zig/ast.zig index 596b57bdb6..86135fe100 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -40,7 +40,7 @@ pub const Tree = struct { }; pub fn tokenLocationPtr(self: &Tree, start_index: usize, token: &const Token) Location { - var loc = Location { + var loc = Location{ .line = 0, .column = 0, .line_start = start_index, @@ -71,7 +71,6 @@ pub const Tree = struct { pub fn dump(self: &Tree) void { self.root_node.base.dump(0); } - }; pub const Error = union(enum) { @@ -95,7 +94,7 @@ pub const Error = union(enum) { ExpectedCommaOrEnd: ExpectedCommaOrEnd, pub fn render(self: &Error, tokens: &Tree.TokenList, stream: var) !void { - switch (*self) { + switch (self.*) { // TODO https://github.com/zig-lang/zig/issues/683 @TagType(Error).InvalidToken => |*x| return x.render(tokens, stream), @TagType(Error).ExpectedVarDeclOrFn => |*x| return x.render(tokens, stream), @@ -119,7 +118,7 @@ pub const Error = union(enum) { } pub fn loc(self: &Error) TokenIndex { - switch (*self) { + switch (self.*) { // TODO https://github.com/zig-lang/zig/issues/683 @TagType(Error).InvalidToken => |x| return x.token, @TagType(Error).ExpectedVarDeclOrFn => |x| return x.token, @@ -144,15 +143,12 @@ pub const Error = union(enum) { pub const InvalidToken = SingleTokenError("Invalid token {}"); pub const ExpectedVarDeclOrFn = SingleTokenError("Expected variable declaration or function, found {}"); - pub const ExpectedAggregateKw = SingleTokenError("Expected " ++ - @tagName(Token.Id.Keyword_struct) ++ ", " ++ @tagName(Token.Id.Keyword_union) ++ ", or " ++ - @tagName(Token.Id.Keyword_enum) ++ ", found {}"); + pub const ExpectedAggregateKw = SingleTokenError("Expected " ++ @tagName(Token.Id.Keyword_struct) ++ ", " ++ @tagName(Token.Id.Keyword_union) ++ ", or " ++ @tagName(Token.Id.Keyword_enum) ++ ", found {}"); pub const ExpectedEqOrSemi = SingleTokenError("Expected '=' or ';', found {}"); pub const ExpectedSemiOrLBrace = SingleTokenError("Expected ';' or '{{', found {}"); pub const ExpectedLabelable = SingleTokenError("Expected 'while', 'for', 'inline', 'suspend', or '{{', found {}"); pub const ExpectedInlinable = SingleTokenError("Expected 'while' or 'for', found {}"); - pub const ExpectedAsmOutputReturnOrType = SingleTokenError("Expected '->' or " ++ - @tagName(Token.Id.Identifier) ++ ", found {}"); + pub const ExpectedAsmOutputReturnOrType = SingleTokenError("Expected '->' or " ++ @tagName(Token.Id.Identifier) ++ ", found {}"); pub const ExpectedSliceOrRBracket = SingleTokenError("Expected ']' or '..', found {}"); pub const ExpectedPrimaryExpr = SingleTokenError("Expected primary expression, found {}"); @@ -165,8 +161,7 @@ pub const Error = union(enum) { node: &Node, pub fn render(self: &ExpectedCall, tokens: &Tree.TokenList, stream: var) !void { - return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ ", found {}", - @tagName(self.node.id)); + return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ ", found {}", @tagName(self.node.id)); } }; @@ -174,8 +169,7 @@ pub const Error = union(enum) { node: &Node, pub fn render(self: &ExpectedCallOrFnProto, tokens: &Tree.TokenList, stream: var) !void { - return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ " or " ++ - @tagName(Node.Id.FnProto) ++ ", found {}", @tagName(self.node.id)); + return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ " or " ++ @tagName(Node.Id.FnProto) ++ ", found {}", @tagName(self.node.id)); } }; @@ -445,17 +439,17 @@ pub const Node = struct { pub fn iterate(self: &Root, index: usize) ?&Node { if (index < self.decls.len) { - return *self.decls.at(index); + return self.decls.at(index).*; } return null; } pub fn firstToken(self: &Root) TokenIndex { - return if (self.decls.len == 0) self.eof_token else (*self.decls.at(0)).firstToken(); + return if (self.decls.len == 0) self.eof_token else (self.decls.at(0).*).firstToken(); } pub fn lastToken(self: &Root) TokenIndex { - return if (self.decls.len == 0) self.eof_token else (*self.decls.at(self.decls.len - 1)).lastToken(); + return if (self.decls.len == 0) self.eof_token else (self.decls.at(self.decls.len - 1).*).lastToken(); } }; @@ -545,7 +539,7 @@ pub const Node = struct { pub fn iterate(self: &ErrorSetDecl, index: usize) ?&Node { var i = index; - if (i < self.decls.len) return *self.decls.at(i); + if (i < self.decls.len) return self.decls.at(i).*; i -= self.decls.len; return null; @@ -598,10 +592,10 @@ pub const Node = struct { i -= 1; }, InitArg.None, - InitArg.Enum => { } + InitArg.Enum => {}, } - if (i < self.fields_and_decls.len) return *self.fields_and_decls.at(i); + if (i < self.fields_and_decls.len) return self.fields_and_decls.at(i).*; i -= self.fields_and_decls.len; return null; @@ -814,7 +808,7 @@ pub const Node = struct { i -= 1; } - if (i < self.params.len) return *self.params.at(self.params.len - i - 1); + if (i < self.params.len) return self.params.at(self.params.len - i - 1).*; i -= self.params.len; if (self.align_expr) |align_expr| { @@ -839,7 +833,6 @@ pub const Node = struct { i -= 1; } - return null; } @@ -934,7 +927,7 @@ pub const Node = struct { pub fn iterate(self: &Block, index: usize) ?&Node { var i = index; - if (i < self.statements.len) return *self.statements.at(i); + if (i < self.statements.len) return self.statements.at(i).*; i -= self.statements.len; return null; @@ -1119,6 +1112,7 @@ pub const Node = struct { base: Node, switch_token: TokenIndex, expr: &Node, + /// these can be SwitchCase nodes or LineComment nodes cases: CaseList, rbrace: TokenIndex, @@ -1131,7 +1125,7 @@ pub const Node = struct { if (i < 1) return self.expr; i -= 1; - if (i < self.cases.len) return *self.cases.at(i); + if (i < self.cases.len) return self.cases.at(i).*; i -= self.cases.len; return null; @@ -1157,7 +1151,7 @@ pub const Node = struct { pub fn iterate(self: &SwitchCase, index: usize) ?&Node { var i = index; - if (i < self.items.len) return *self.items.at(i); + if (i < self.items.len) return self.items.at(i).*; i -= self.items.len; if (self.payload) |payload| { @@ -1172,7 +1166,7 @@ pub const Node = struct { } pub fn firstToken(self: &SwitchCase) TokenIndex { - return (*self.items.at(0)).firstToken(); + return (self.items.at(0).*).firstToken(); } pub fn lastToken(self: &SwitchCase) TokenIndex { @@ -1616,7 +1610,7 @@ pub const Node = struct { switch (self.op) { @TagType(Op).Call => |*call_info| { - if (i < call_info.params.len) return *call_info.params.at(i); + if (i < call_info.params.len) return call_info.params.at(i).*; i -= call_info.params.len; }, Op.ArrayAccess => |index_expr| { @@ -1633,11 +1627,11 @@ pub const Node = struct { } }, Op.ArrayInitializer => |*exprs| { - if (i < exprs.len) return *exprs.at(i); + if (i < exprs.len) return exprs.at(i).*; i -= exprs.len; }, Op.StructInitializer => |*fields| { - if (i < fields.len) return *fields.at(i); + if (i < fields.len) return fields.at(i).*; i -= fields.len; }, } @@ -1830,7 +1824,7 @@ pub const Node = struct { pub fn iterate(self: &BuiltinCall, index: usize) ?&Node { var i = index; - if (i < self.params.len) return *self.params.at(i); + if (i < self.params.len) return self.params.at(i).*; i -= self.params.len; return null; @@ -1873,11 +1867,11 @@ pub const Node = struct { } pub fn firstToken(self: &MultilineStringLiteral) TokenIndex { - return *self.lines.at(0); + return self.lines.at(0).*; } pub fn lastToken(self: &MultilineStringLiteral) TokenIndex { - return *self.lines.at(self.lines.len - 1); + return self.lines.at(self.lines.len - 1).*; } }; @@ -1974,7 +1968,7 @@ pub const Node = struct { const Kind = union(enum) { Variable: &Identifier, - Return: &Node + Return: &Node, }; pub fn iterate(self: &AsmOutput, index: usize) ?&Node { @@ -1994,7 +1988,7 @@ pub const Node = struct { Kind.Return => |return_type| { if (i < 1) return return_type; i -= 1; - } + }, } return null; @@ -2059,13 +2053,13 @@ pub const Node = struct { pub fn iterate(self: &Asm, index: usize) ?&Node { var i = index; - if (i < self.outputs.len) return &(*self.outputs.at(index)).base; + if (i < self.outputs.len) return &(self.outputs.at(index).*).base; i -= self.outputs.len; - if (i < self.inputs.len) return &(*self.inputs.at(index)).base; + if (i < self.inputs.len) return &(self.inputs.at(index).*).base; i -= self.inputs.len; - if (i < self.clobbers.len) return *self.clobbers.at(index); + if (i < self.clobbers.len) return self.clobbers.at(index).*; i -= self.clobbers.len; return null; @@ -2159,11 +2153,11 @@ pub const Node = struct { } pub fn firstToken(self: &DocComment) TokenIndex { - return *self.lines.at(0); + return self.lines.at(0).*; } pub fn lastToken(self: &DocComment) TokenIndex { - return *self.lines.at(self.lines.len - 1); + return self.lines.at(self.lines.len - 1).*; } }; @@ -2192,4 +2186,3 @@ pub const Node = struct { } }; }; - diff --git a/std/zig/parse.zig b/std/zig/parse.zig index f2376f0df3..04aeeccaeb 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -17,15 +17,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { defer stack.deinit(); const arena = &tree_arena.allocator; - const root_node = try arena.construct(ast.Node.Root { - .base = ast.Node { .id = ast.Node.Id.Root }, + const root_node = try arena.construct(ast.Node.Root{ + .base = ast.Node{ .id = ast.Node.Id.Root }, .decls = ast.Node.Root.DeclList.init(arena), .doc_comments = null, // initialized when we get the eof token .eof_token = undefined, }); - var tree = ast.Tree { + var tree = ast.Tree{ .source = source, .root_node = root_node, .arena_allocator = tree_arena, @@ -36,9 +36,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { var tokenizer = Tokenizer.init(tree.source); while (true) { const token_ptr = try tree.tokens.addOne(); - *token_ptr = tokenizer.next(); - if (token_ptr.id == Token.Id.Eof) - break; + token_ptr.* = tokenizer.next(); + if (token_ptr.id == Token.Id.Eof) break; } var tok_it = tree.tokens.iterator(0); @@ -63,33 +62,27 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_test => { stack.append(State.TopLevel) catch unreachable; - const block = try arena.construct(ast.Node.Block { - .base = ast.Node { - .id = ast.Node.Id.Block, - }, + const block = try arena.construct(ast.Node.Block{ + .base = ast.Node{ .id = ast.Node.Id.Block }, .label = null, .lbrace = undefined, .statements = ast.Node.Block.StatementList.init(arena), .rbrace = undefined, }); - const test_node = try arena.construct(ast.Node.TestDecl { - .base = ast.Node { - .id = ast.Node.Id.TestDecl, - }, + const test_node = try arena.construct(ast.Node.TestDecl{ + .base = ast.Node{ .id = ast.Node.Id.TestDecl }, .doc_comments = comments, .test_token = token_index, .name = undefined, .body_node = &block.base, }); try root_node.decls.push(&test_node.base); - try stack.append(State { .Block = block }); - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.LBrace, - .ptr = &block.rbrace, - } - }); - try stack.append(State { .StringLiteral = OptionalCtx { .Required = &test_node.name } }); + try stack.append(State{ .Block = block }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &block.rbrace, + } }); + try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &test_node.name } }); continue; }, Token.Id.Eof => { @@ -99,29 +92,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, Token.Id.Keyword_pub => { stack.append(State.TopLevel) catch unreachable; - try stack.append(State { - .TopLevelExtern = TopLevelDeclCtx { - .decls = &root_node.decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } - }); + try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ + .decls = &root_node.decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + } }); continue; }, Token.Id.Keyword_comptime => { - const block = try arena.construct(ast.Node.Block { - .base = ast.Node {.id = ast.Node.Id.Block }, + const block = try arena.construct(ast.Node.Block{ + .base = ast.Node{ .id = ast.Node.Id.Block }, .label = null, .lbrace = undefined, .statements = ast.Node.Block.StatementList.init(arena), .rbrace = undefined, }); - const node = try arena.construct(ast.Node.Comptime { - .base = ast.Node { - .id = ast.Node.Id.Comptime, - }, + const node = try arena.construct(ast.Node.Comptime{ + .base = ast.Node{ .id = ast.Node.Id.Comptime }, .comptime_token = token_index, .expr = &block.base, .doc_comments = comments, @@ -129,27 +118,23 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try root_node.decls.push(&node.base); stack.append(State.TopLevel) catch unreachable; - try stack.append(State { .Block = block }); - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.LBrace, - .ptr = &block.rbrace, - } - }); + try stack.append(State{ .Block = block }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &block.rbrace, + } }); continue; }, else => { putBackToken(&tok_it, &tree); stack.append(State.TopLevel) catch unreachable; - try stack.append(State { - .TopLevelExtern = TopLevelDeclCtx { - .decls = &root_node.decls, - .visib_token = null, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } - }); + try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ + .decls = &root_node.decls, + .visib_token = null, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + } }); continue; }, } @@ -159,41 +144,38 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_export, Token.Id.Keyword_inline => { - stack.append(State { - .TopLevelDecl = TopLevelDeclCtx { - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = AnnotatedToken { - .index = token_index, - .ptr = token_ptr, - }, - .lib_name = null, - .comments = ctx.comments, + Token.Id.Keyword_export, + Token.Id.Keyword_inline => { + stack.append(State{ .TopLevelDecl = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = AnnotatedToken{ + .index = token_index, + .ptr = token_ptr, }, - }) catch unreachable; + .lib_name = null, + .comments = ctx.comments, + } }) catch unreachable; continue; }, Token.Id.Keyword_extern => { - stack.append(State { - .TopLevelLibname = TopLevelDeclCtx { - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = AnnotatedToken { - .index = token_index, - .ptr = token_ptr, - }, - .lib_name = null, - .comments = ctx.comments, + stack.append(State{ .TopLevelLibname = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = AnnotatedToken{ + .index = token_index, + .ptr = token_ptr, }, - }) catch unreachable; + .lib_name = null, + .comments = ctx.comments, + } }) catch unreachable; continue; }, else => { putBackToken(&tok_it, &tree); - stack.append(State { .TopLevelDecl = ctx }) catch unreachable; + stack.append(State{ .TopLevelDecl = ctx }) catch unreachable; continue; - } + }, } }, State.TopLevelLibname => |ctx| { @@ -207,15 +189,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }; }; - stack.append(State { - .TopLevelDecl = TopLevelDeclCtx { - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = ctx.extern_export_inline_token, - .lib_name = lib_name, - .comments = ctx.comments, - }, - }) catch unreachable; + stack.append(State{ .TopLevelDecl = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = ctx.extern_export_inline_token, + .lib_name = lib_name, + .comments = ctx.comments, + } }) catch unreachable; continue; }, State.TopLevelDecl => |ctx| { @@ -225,14 +205,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { switch (token_ptr.id) { Token.Id.Keyword_use => { if (ctx.extern_export_inline_token) |annotated_token| { - *(try tree.errors.addOne()) = Error { - .InvalidToken = Error.InvalidToken { .token = annotated_token.index }, - }; + ((try tree.errors.addOne())).* = Error{ .InvalidToken = Error.InvalidToken{ .token = annotated_token.index } }; return tree; } - const node = try arena.construct(ast.Node.Use { - .base = ast.Node {.id = ast.Node.Id.Use }, + const node = try arena.construct(ast.Node.Use{ + .base = ast.Node{ .id = ast.Node.Id.Use }, .visib_token = ctx.visib_token, .expr = undefined, .semicolon_token = undefined, @@ -240,44 +218,39 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try ctx.decls.push(&node.base); - stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Semicolon, - .ptr = &node.semicolon_token, - } - }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = &node.expr } }); + stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Semicolon, + .ptr = &node.semicolon_token, + } }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); continue; }, - Token.Id.Keyword_var, Token.Id.Keyword_const => { + Token.Id.Keyword_var, + Token.Id.Keyword_const => { if (ctx.extern_export_inline_token) |annotated_token| { if (annotated_token.ptr.id == Token.Id.Keyword_inline) { - *(try tree.errors.addOne()) = Error { - .InvalidToken = Error.InvalidToken { .token = annotated_token.index }, - }; + ((try tree.errors.addOne())).* = Error{ .InvalidToken = Error.InvalidToken{ .token = annotated_token.index } }; return tree; } } - try stack.append(State { - .VarDecl = VarDeclCtx { - .comments = ctx.comments, - .visib_token = ctx.visib_token, - .lib_name = ctx.lib_name, - .comptime_token = null, - .extern_export_token = if (ctx.extern_export_inline_token) |at| at.index else null, - .mut_token = token_index, - .list = ctx.decls - } - }); + try stack.append(State{ .VarDecl = VarDeclCtx{ + .comments = ctx.comments, + .visib_token = ctx.visib_token, + .lib_name = ctx.lib_name, + .comptime_token = null, + .extern_export_token = if (ctx.extern_export_inline_token) |at| at.index else null, + .mut_token = token_index, + .list = ctx.decls, + } }); continue; }, - Token.Id.Keyword_fn, Token.Id.Keyword_nakedcc, - Token.Id.Keyword_stdcallcc, Token.Id.Keyword_async => { - const fn_proto = try arena.construct(ast.Node.FnProto { - .base = ast.Node { - .id = ast.Node.Id.FnProto, - }, + Token.Id.Keyword_fn, + Token.Id.Keyword_nakedcc, + Token.Id.Keyword_stdcallcc, + Token.Id.Keyword_async => { + const fn_proto = try arena.construct(ast.Node.FnProto{ + .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = ctx.comments, .visib_token = ctx.visib_token, .name_token = null, @@ -293,36 +266,33 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .align_expr = null, }); try ctx.decls.push(&fn_proto.base); - stack.append(State { .FnDef = fn_proto }) catch unreachable; - try stack.append(State { .FnProto = fn_proto }); + stack.append(State{ .FnDef = fn_proto }) catch unreachable; + try stack.append(State{ .FnProto = fn_proto }); switch (token_ptr.id) { - Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => { + Token.Id.Keyword_nakedcc, + Token.Id.Keyword_stdcallcc => { fn_proto.cc_token = token_index; - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token, - } - }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + } }); continue; }, Token.Id.Keyword_async => { - const async_node = try arena.construct(ast.Node.AsyncAttribute { - .base = ast.Node {.id = ast.Node.Id.AsyncAttribute }, + const async_node = try arena.construct(ast.Node.AsyncAttribute{ + .base = ast.Node{ .id = ast.Node.Id.AsyncAttribute }, .async_token = token_index, .allocator_type = null, .rangle_bracket = null, }); fn_proto.async_attr = async_node; - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token, - } - }); - try stack.append(State { .AsyncAllocator = async_node }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + } }); + try stack.append(State{ .AsyncAllocator = async_node }); continue; }, Token.Id.Keyword_fn => { @@ -333,9 +303,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, else => { - *(try tree.errors.addOne()) = Error { - .ExpectedVarDeclOrFn = Error.ExpectedVarDeclOrFn { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedVarDeclOrFn = Error.ExpectedVarDeclOrFn{ .token = token_index } }; return tree; }, } @@ -343,34 +311,30 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { State.TopLevelExternOrField => |ctx| { if (eatToken(&tok_it, &tree, Token.Id.Identifier)) |identifier| { std.debug.assert(ctx.container_decl.kind == ast.Node.ContainerDecl.Kind.Struct); - const node = try arena.construct(ast.Node.StructField { - .base = ast.Node { - .id = ast.Node.Id.StructField, - }, + const node = try arena.construct(ast.Node.StructField{ + .base = ast.Node{ .id = ast.Node.Id.StructField }, .doc_comments = ctx.comments, .visib_token = ctx.visib_token, .name_token = identifier, .type_expr = undefined, }); const node_ptr = try ctx.container_decl.fields_and_decls.addOne(); - *node_ptr = &node.base; + node_ptr.* = &node.base; - stack.append(State { .FieldListCommaOrEnd = ctx.container_decl }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = &node.type_expr } }); - try stack.append(State { .ExpectToken = Token.Id.Colon }); + stack.append(State{ .FieldListCommaOrEnd = ctx.container_decl }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.type_expr } }); + try stack.append(State{ .ExpectToken = Token.Id.Colon }); continue; } stack.append(State{ .ContainerDecl = ctx.container_decl }) catch unreachable; - try stack.append(State { - .TopLevelExtern = TopLevelDeclCtx { - .decls = &ctx.container_decl.fields_and_decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = null, - .lib_name = null, - .comments = ctx.comments, - } - }); + try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ + .decls = &ctx.container_decl.fields_and_decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = null, + .lib_name = null, + .comments = ctx.comments, + } }); continue; }, @@ -382,7 +346,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { putBackToken(&tok_it, &tree); continue; } - stack.append(State { .Expression = ctx }) catch unreachable; + stack.append(State{ .Expression = ctx }) catch unreachable; continue; }, @@ -390,8 +354,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; - const node = try arena.construct(ast.Node.ContainerDecl { - .base = ast.Node {.id = ast.Node.Id.ContainerDecl }, + const node = try arena.construct(ast.Node.ContainerDecl{ + .base = ast.Node{ .id = ast.Node.Id.ContainerDecl }, .ltoken = ctx.ltoken, .layout = ctx.layout, .kind = switch (token_ptr.id) { @@ -399,9 +363,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_union => ast.Node.ContainerDecl.Kind.Union, Token.Id.Keyword_enum => ast.Node.ContainerDecl.Kind.Enum, else => { - *(try tree.errors.addOne()) = Error { - .ExpectedAggregateKw = Error.ExpectedAggregateKw { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedAggregateKw = Error.ExpectedAggregateKw{ .token = token_index } }; return tree; }, }, @@ -411,9 +373,9 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); ctx.opt_ctx.store(&node.base); - stack.append(State { .ContainerDecl = node }) catch unreachable; - try stack.append(State { .ExpectToken = Token.Id.LBrace }); - try stack.append(State { .ContainerInitArgStart = node }); + stack.append(State{ .ContainerDecl = node }) catch unreachable; + try stack.append(State{ .ExpectToken = Token.Id.LBrace }); + try stack.append(State{ .ContainerInitArgStart = node }); continue; }, @@ -422,8 +384,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - stack.append(State { .ExpectToken = Token.Id.RParen }) catch unreachable; - try stack.append(State { .ContainerInitArg = container_decl }); + stack.append(State{ .ExpectToken = Token.Id.RParen }) catch unreachable; + try stack.append(State{ .ContainerInitArg = container_decl }); continue; }, @@ -433,23 +395,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const init_arg_token_ptr = init_arg_token.ptr; switch (init_arg_token_ptr.id) { Token.Id.Keyword_enum => { - container_decl.init_arg_expr = ast.Node.ContainerDecl.InitArg {.Enum = null}; + container_decl.init_arg_expr = ast.Node.ContainerDecl.InitArg{ .Enum = null }; const lparen_tok = nextToken(&tok_it, &tree); const lparen_tok_index = lparen_tok.index; const lparen_tok_ptr = lparen_tok.ptr; if (lparen_tok_ptr.id == Token.Id.LParen) { - try stack.append(State { .ExpectToken = Token.Id.RParen } ); - try stack.append(State { .Expression = OptionalCtx { - .RequiredNull = &container_decl.init_arg_expr.Enum, - } }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .RequiredNull = &container_decl.init_arg_expr.Enum } }); } else { putBackToken(&tok_it, &tree); } }, else => { putBackToken(&tok_it, &tree); - container_decl.init_arg_expr = ast.Node.ContainerDecl.InitArg { .Type = undefined }; - stack.append(State { .Expression = OptionalCtx { .Required = &container_decl.init_arg_expr.Type } }) catch unreachable; + container_decl.init_arg_expr = ast.Node.ContainerDecl.InitArg{ .Type = undefined }; + stack.append(State{ .Expression = OptionalCtx{ .Required = &container_decl.init_arg_expr.Type } }) catch unreachable; }, } continue; @@ -468,26 +428,24 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Identifier => { switch (container_decl.kind) { ast.Node.ContainerDecl.Kind.Struct => { - const node = try arena.construct(ast.Node.StructField { - .base = ast.Node { - .id = ast.Node.Id.StructField, - }, + const node = try arena.construct(ast.Node.StructField{ + .base = ast.Node{ .id = ast.Node.Id.StructField }, .doc_comments = comments, .visib_token = null, .name_token = token_index, .type_expr = undefined, }); const node_ptr = try container_decl.fields_and_decls.addOne(); - *node_ptr = &node.base; + node_ptr.* = &node.base; - try stack.append(State { .FieldListCommaOrEnd = container_decl }); - try stack.append(State { .TypeExprBegin = OptionalCtx { .Required = &node.type_expr } }); - try stack.append(State { .ExpectToken = Token.Id.Colon }); + try stack.append(State{ .FieldListCommaOrEnd = container_decl }); + try stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.type_expr } }); + try stack.append(State{ .ExpectToken = Token.Id.Colon }); continue; }, ast.Node.ContainerDecl.Kind.Union => { - const node = try arena.construct(ast.Node.UnionTag { - .base = ast.Node {.id = ast.Node.Id.UnionTag }, + const node = try arena.construct(ast.Node.UnionTag{ + .base = ast.Node{ .id = ast.Node.Id.UnionTag }, .name_token = token_index, .type_expr = null, .value_expr = null, @@ -495,24 +453,24 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try container_decl.fields_and_decls.push(&node.base); - stack.append(State { .FieldListCommaOrEnd = container_decl }) catch unreachable; - try stack.append(State { .FieldInitValue = OptionalCtx { .RequiredNull = &node.value_expr } }); - try stack.append(State { .TypeExprBegin = OptionalCtx { .RequiredNull = &node.type_expr } }); - try stack.append(State { .IfToken = Token.Id.Colon }); + stack.append(State{ .FieldListCommaOrEnd = container_decl }) catch unreachable; + try stack.append(State{ .FieldInitValue = OptionalCtx{ .RequiredNull = &node.value_expr } }); + try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &node.type_expr } }); + try stack.append(State{ .IfToken = Token.Id.Colon }); continue; }, ast.Node.ContainerDecl.Kind.Enum => { - const node = try arena.construct(ast.Node.EnumTag { - .base = ast.Node { .id = ast.Node.Id.EnumTag }, + const node = try arena.construct(ast.Node.EnumTag{ + .base = ast.Node{ .id = ast.Node.Id.EnumTag }, .name_token = token_index, .value = null, .doc_comments = comments, }); try container_decl.fields_and_decls.push(&node.base); - stack.append(State { .FieldListCommaOrEnd = container_decl }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .RequiredNull = &node.value } }); - try stack.append(State { .IfToken = Token.Id.Equal }); + stack.append(State{ .FieldListCommaOrEnd = container_decl }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .RequiredNull = &node.value } }); + try stack.append(State{ .IfToken = Token.Id.Equal }); continue; }, } @@ -520,48 +478,40 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_pub => { switch (container_decl.kind) { ast.Node.ContainerDecl.Kind.Struct => { - try stack.append(State { - .TopLevelExternOrField = TopLevelExternOrFieldCtx { - .visib_token = token_index, - .container_decl = container_decl, - .comments = comments, - } - }); + try stack.append(State{ .TopLevelExternOrField = TopLevelExternOrFieldCtx{ + .visib_token = token_index, + .container_decl = container_decl, + .comments = comments, + } }); continue; }, else => { stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State { - .TopLevelExtern = TopLevelDeclCtx { - .decls = &container_decl.fields_and_decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } - }); + try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + } }); continue; - } + }, } }, Token.Id.Keyword_export => { stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State { - .TopLevelExtern = TopLevelDeclCtx { - .decls = &container_decl.fields_and_decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } - }); + try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + } }); continue; }, Token.Id.RBrace => { if (comments != null) { - *(try tree.errors.addOne()) = Error { - .UnattachedDocComment = Error.UnattachedDocComment { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .UnattachedDocComment = Error.UnattachedDocComment{ .token = token_index } }; return tree; } container_decl.rbrace_token = token_index; @@ -570,26 +520,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { else => { putBackToken(&tok_it, &tree); stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State { - .TopLevelExtern = TopLevelDeclCtx { - .decls = &container_decl.fields_and_decls, - .visib_token = null, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } - }); + try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = null, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + } }); continue; - } + }, } }, - State.VarDecl => |ctx| { - const var_decl = try arena.construct(ast.Node.VarDecl { - .base = ast.Node { - .id = ast.Node.Id.VarDecl, - }, + const var_decl = try arena.construct(ast.Node.VarDecl{ + .base = ast.Node{ .id = ast.Node.Id.VarDecl }, .doc_comments = ctx.comments, .visib_token = ctx.visib_token, .mut_token = ctx.mut_token, @@ -606,27 +551,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try ctx.list.push(&var_decl.base); - try stack.append(State { .VarDeclAlign = var_decl }); - try stack.append(State { .TypeExprBegin = OptionalCtx { .RequiredNull = &var_decl.type_node} }); - try stack.append(State { .IfToken = Token.Id.Colon }); - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Identifier, - .ptr = &var_decl.name_token, - } - }); + try stack.append(State{ .VarDeclAlign = var_decl }); + try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &var_decl.type_node } }); + try stack.append(State{ .IfToken = Token.Id.Colon }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Identifier, + .ptr = &var_decl.name_token, + } }); continue; }, State.VarDeclAlign => |var_decl| { - try stack.append(State { .VarDeclEq = var_decl }); + try stack.append(State{ .VarDeclEq = var_decl }); const next_token = nextToken(&tok_it, &tree); const next_token_index = next_token.index; const next_token_ptr = next_token.ptr; if (next_token_ptr.id == Token.Id.Keyword_align) { - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .Expression = OptionalCtx { .RequiredNull = &var_decl.align_node} }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .RequiredNull = &var_decl.align_node } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); continue; } @@ -640,8 +583,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { switch (token_ptr.id) { Token.Id.Equal => { var_decl.eq_token = token_index; - stack.append(State { .VarDeclSemiColon = var_decl }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .RequiredNull = &var_decl.init_node } }); + stack.append(State{ .VarDeclSemiColon = var_decl }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .RequiredNull = &var_decl.init_node } }); continue; }, Token.Id.Semicolon => { @@ -649,11 +592,9 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - *(try tree.errors.addOne()) = Error { - .ExpectedEqOrSemi = Error.ExpectedEqOrSemi { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedEqOrSemi = Error.ExpectedEqOrSemi{ .token = token_index } }; return tree; - } + }, } }, @@ -661,12 +602,10 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const semicolon_token = nextToken(&tok_it, &tree); if (semicolon_token.ptr.id != Token.Id.Semicolon) { - *(try tree.errors.addOne()) = Error { - .ExpectedToken = Error.ExpectedToken { - .token = semicolon_token.index, - .expected_id = Token.Id.Semicolon, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ + .token = semicolon_token.index, + .expected_id = Token.Id.Semicolon, + } }; return tree; } @@ -686,32 +625,30 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; - switch(token_ptr.id) { + switch (token_ptr.id) { Token.Id.LBrace => { - const block = try arena.construct(ast.Node.Block { - .base = ast.Node { .id = ast.Node.Id.Block }, + const block = try arena.construct(ast.Node.Block{ + .base = ast.Node{ .id = ast.Node.Id.Block }, .label = null, .lbrace = token_index, .statements = ast.Node.Block.StatementList.init(arena), .rbrace = undefined, }); fn_proto.body_node = &block.base; - stack.append(State { .Block = block }) catch unreachable; + stack.append(State{ .Block = block }) catch unreachable; continue; }, Token.Id.Semicolon => continue, else => { - *(try tree.errors.addOne()) = Error { - .ExpectedSemiOrLBrace = Error.ExpectedSemiOrLBrace { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedSemiOrLBrace = Error.ExpectedSemiOrLBrace{ .token = token_index } }; return tree; }, } }, State.FnProto => |fn_proto| { - stack.append(State { .FnProtoAlign = fn_proto }) catch unreachable; - try stack.append(State { .ParamDecl = fn_proto }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + stack.append(State{ .FnProtoAlign = fn_proto }) catch unreachable; + try stack.append(State{ .ParamDecl = fn_proto }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); if (eatToken(&tok_it, &tree, Token.Id.Identifier)) |name_token| { fn_proto.name_token = name_token; @@ -719,12 +656,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, State.FnProtoAlign => |fn_proto| { - stack.append(State { .FnProtoReturnType = fn_proto }) catch unreachable; + stack.append(State{ .FnProtoReturnType = fn_proto }) catch unreachable; if (eatToken(&tok_it, &tree, Token.Id.Keyword_align)) |align_token| { - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .Expression = OptionalCtx { .RequiredNull = &fn_proto.align_expr } }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .RequiredNull = &fn_proto.align_expr } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); } continue; }, @@ -734,42 +671,37 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Bang => { - fn_proto.return_type = ast.Node.FnProto.ReturnType { .InferErrorSet = undefined }; - stack.append(State { - .TypeExprBegin = OptionalCtx { .Required = &fn_proto.return_type.InferErrorSet }, - }) catch unreachable; + fn_proto.return_type = ast.Node.FnProto.ReturnType{ .InferErrorSet = undefined }; + stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &fn_proto.return_type.InferErrorSet } }) catch unreachable; continue; }, else => { // TODO: this is a special case. Remove this when #760 is fixed if (token_ptr.id == Token.Id.Keyword_error) { if ((??tok_it.peek()).id == Token.Id.LBrace) { - const error_type_node = try arena.construct(ast.Node.ErrorType { - .base = ast.Node { .id = ast.Node.Id.ErrorType }, + const error_type_node = try arena.construct(ast.Node.ErrorType{ + .base = ast.Node{ .id = ast.Node.Id.ErrorType }, .token = token_index, }); - fn_proto.return_type = ast.Node.FnProto.ReturnType { - .Explicit = &error_type_node.base, - }; + fn_proto.return_type = ast.Node.FnProto.ReturnType{ .Explicit = &error_type_node.base }; continue; } } putBackToken(&tok_it, &tree); - fn_proto.return_type = ast.Node.FnProto.ReturnType { .Explicit = undefined }; - stack.append(State { .TypeExprBegin = OptionalCtx { .Required = &fn_proto.return_type.Explicit }, }) catch unreachable; + fn_proto.return_type = ast.Node.FnProto.ReturnType{ .Explicit = undefined }; + stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &fn_proto.return_type.Explicit } }) catch unreachable; continue; }, } }, - State.ParamDecl => |fn_proto| { if (eatToken(&tok_it, &tree, Token.Id.RParen)) |_| { continue; } - const param_decl = try arena.construct(ast.Node.ParamDecl { - .base = ast.Node {.id = ast.Node.Id.ParamDecl }, + const param_decl = try arena.construct(ast.Node.ParamDecl{ + .base = ast.Node{ .id = ast.Node.Id.ParamDecl }, .comptime_token = null, .noalias_token = null, .name_token = null, @@ -778,14 +710,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try fn_proto.params.push(¶m_decl.base); - stack.append(State { - .ParamDeclEnd = ParamDeclEndCtx { - .param_decl = param_decl, - .fn_proto = fn_proto, - } - }) catch unreachable; - try stack.append(State { .ParamDeclName = param_decl }); - try stack.append(State { .ParamDeclAliasOrComptime = param_decl }); + stack.append(State{ .ParamDeclEnd = ParamDeclEndCtx{ + .param_decl = param_decl, + .fn_proto = fn_proto, + } }) catch unreachable; + try stack.append(State{ .ParamDeclName = param_decl }); + try stack.append(State{ .ParamDeclAliasOrComptime = param_decl }); continue; }, State.ParamDeclAliasOrComptime => |param_decl| { @@ -811,21 +741,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { State.ParamDeclEnd => |ctx| { if (eatToken(&tok_it, &tree, Token.Id.Ellipsis3)) |ellipsis3| { ctx.param_decl.var_args_token = ellipsis3; - stack.append(State { .ExpectToken = Token.Id.RParen }) catch unreachable; + stack.append(State{ .ExpectToken = Token.Id.RParen }) catch unreachable; continue; } - try stack.append(State { .ParamDeclComma = ctx.fn_proto }); - try stack.append(State { - .TypeExprBegin = OptionalCtx { .Required = &ctx.param_decl.type_node } - }); + try stack.append(State{ .ParamDeclComma = ctx.fn_proto }); + try stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &ctx.param_decl.type_node } }); continue; }, State.ParamDeclComma => |fn_proto| { switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.RParen)) { ExpectCommaOrEndResult.end_token => |t| { if (t == null) { - stack.append(State { .ParamDecl = fn_proto }) catch unreachable; + stack.append(State{ .ParamDecl = fn_proto }) catch unreachable; } continue; }, @@ -838,12 +766,10 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { State.MaybeLabeledExpression => |ctx| { if (eatToken(&tok_it, &tree, Token.Id.Colon)) |_| { - stack.append(State { - .LabeledExpression = LabelCtx { - .label = ctx.label, - .opt_ctx = ctx.opt_ctx, - } - }) catch unreachable; + stack.append(State{ .LabeledExpression = LabelCtx{ + .label = ctx.label, + .opt_ctx = ctx.opt_ctx, + } }) catch unreachable; continue; } @@ -856,69 +782,59 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.LBrace => { - const block = try arena.construct(ast.Node.Block { - .base = ast.Node {.id = ast.Node.Id.Block}, + const block = try arena.construct(ast.Node.Block{ + .base = ast.Node{ .id = ast.Node.Id.Block }, .label = ctx.label, .lbrace = token_index, .statements = ast.Node.Block.StatementList.init(arena), .rbrace = undefined, }); ctx.opt_ctx.store(&block.base); - stack.append(State { .Block = block }) catch unreachable; + stack.append(State{ .Block = block }) catch unreachable; continue; }, Token.Id.Keyword_while => { - stack.append(State { - .While = LoopCtx { - .label = ctx.label, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } - }) catch unreachable; + stack.append(State{ .While = LoopCtx{ + .label = ctx.label, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + } }) catch unreachable; continue; }, Token.Id.Keyword_for => { - stack.append(State { - .For = LoopCtx { - .label = ctx.label, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } - }) catch unreachable; + stack.append(State{ .For = LoopCtx{ + .label = ctx.label, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + } }) catch unreachable; continue; }, Token.Id.Keyword_suspend => { - const node = try arena.construct(ast.Node.Suspend { - .base = ast.Node { - .id = ast.Node.Id.Suspend, - }, + const node = try arena.construct(ast.Node.Suspend{ + .base = ast.Node{ .id = ast.Node.Id.Suspend }, .label = ctx.label, .suspend_token = token_index, .payload = null, .body = null, }); ctx.opt_ctx.store(&node.base); - stack.append(State { .SuspendBody = node }) catch unreachable; - try stack.append(State { .Payload = OptionalCtx { .Optional = &node.payload } }); + stack.append(State{ .SuspendBody = node }) catch unreachable; + try stack.append(State{ .Payload = OptionalCtx{ .Optional = &node.payload } }); continue; }, Token.Id.Keyword_inline => { - stack.append(State { - .Inline = InlineCtx { - .label = ctx.label, - .inline_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } - }) catch unreachable; + stack.append(State{ .Inline = InlineCtx{ + .label = ctx.label, + .inline_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + } }) catch unreachable; continue; }, else => { if (ctx.opt_ctx != OptionalCtx.Optional) { - *(try tree.errors.addOne()) = Error { - .ExpectedLabelable = Error.ExpectedLabelable { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedLabelable = Error.ExpectedLabelable{ .token = token_index } }; return tree; } @@ -933,32 +849,26 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Keyword_while => { - stack.append(State { - .While = LoopCtx { - .inline_token = ctx.inline_token, - .label = ctx.label, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } - }) catch unreachable; + stack.append(State{ .While = LoopCtx{ + .inline_token = ctx.inline_token, + .label = ctx.label, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + } }) catch unreachable; continue; }, Token.Id.Keyword_for => { - stack.append(State { - .For = LoopCtx { - .inline_token = ctx.inline_token, - .label = ctx.label, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } - }) catch unreachable; + stack.append(State{ .For = LoopCtx{ + .inline_token = ctx.inline_token, + .label = ctx.label, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + } }) catch unreachable; continue; }, else => { if (ctx.opt_ctx != OptionalCtx.Optional) { - *(try tree.errors.addOne()) = Error { - .ExpectedInlinable = Error.ExpectedInlinable { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedInlinable = Error.ExpectedInlinable{ .token = token_index } }; return tree; } @@ -968,8 +878,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, State.While => |ctx| { - const node = try arena.construct(ast.Node.While { - .base = ast.Node {.id = ast.Node.Id.While }, + const node = try arena.construct(ast.Node.While{ + .base = ast.Node{ .id = ast.Node.Id.While }, .label = ctx.label, .inline_token = ctx.inline_token, .while_token = ctx.loop_token, @@ -980,25 +890,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .@"else" = null, }); ctx.opt_ctx.store(&node.base); - stack.append(State { .Else = &node.@"else" }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = &node.body } }); - try stack.append(State { .WhileContinueExpr = &node.continue_expr }); - try stack.append(State { .IfToken = Token.Id.Colon }); - try stack.append(State { .PointerPayload = OptionalCtx { .Optional = &node.payload } }); - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .Expression = OptionalCtx { .Required = &node.condition } }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + stack.append(State{ .Else = &node.@"else" }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.body } }); + try stack.append(State{ .WhileContinueExpr = &node.continue_expr }); + try stack.append(State{ .IfToken = Token.Id.Colon }); + try stack.append(State{ .PointerPayload = OptionalCtx{ .Optional = &node.payload } }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.condition } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); continue; }, State.WhileContinueExpr => |dest| { - stack.append(State { .ExpectToken = Token.Id.RParen }) catch unreachable; - try stack.append(State { .AssignmentExpressionBegin = OptionalCtx { .RequiredNull = dest } }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + stack.append(State{ .ExpectToken = Token.Id.RParen }) catch unreachable; + try stack.append(State{ .AssignmentExpressionBegin = OptionalCtx{ .RequiredNull = dest } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); continue; }, State.For => |ctx| { - const node = try arena.construct(ast.Node.For { - .base = ast.Node {.id = ast.Node.Id.For }, + const node = try arena.construct(ast.Node.For{ + .base = ast.Node{ .id = ast.Node.Id.For }, .label = ctx.label, .inline_token = ctx.inline_token, .for_token = ctx.loop_token, @@ -1008,33 +918,32 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .@"else" = null, }); ctx.opt_ctx.store(&node.base); - stack.append(State { .Else = &node.@"else" }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = &node.body } }); - try stack.append(State { .PointerIndexPayload = OptionalCtx { .Optional = &node.payload } }); - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .Expression = OptionalCtx { .Required = &node.array_expr } }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + stack.append(State{ .Else = &node.@"else" }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.body } }); + try stack.append(State{ .PointerIndexPayload = OptionalCtx{ .Optional = &node.payload } }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.array_expr } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); continue; }, State.Else => |dest| { if (eatToken(&tok_it, &tree, Token.Id.Keyword_else)) |else_token| { - const node = try arena.construct(ast.Node.Else { - .base = ast.Node {.id = ast.Node.Id.Else }, + const node = try arena.construct(ast.Node.Else{ + .base = ast.Node{ .id = ast.Node.Id.Else }, .else_token = else_token, .payload = null, .body = undefined, }); - *dest = node; + dest.* = node; - stack.append(State { .Expression = OptionalCtx { .Required = &node.body } }) catch unreachable; - try stack.append(State { .Payload = OptionalCtx { .Optional = &node.payload } }); + stack.append(State{ .Expression = OptionalCtx{ .Required = &node.body } }) catch unreachable; + try stack.append(State{ .Payload = OptionalCtx{ .Optional = &node.payload } }); continue; } else { continue; } }, - State.Block => |block| { const token = nextToken(&tok_it, &tree); const token_index = token.index; @@ -1046,7 +955,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, else => { putBackToken(&tok_it, &tree); - stack.append(State { .Block = block }) catch unreachable; + stack.append(State{ .Block = block }) catch unreachable; var any_comments = false; while (try eatLineComment(arena, &tok_it, &tree)) |line_comment| { @@ -1055,7 +964,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } if (any_comments) continue; - try stack.append(State { .Statement = block }); + try stack.append(State{ .Statement = block }); continue; }, } @@ -1066,33 +975,29 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Keyword_comptime => { - stack.append(State { - .ComptimeStatement = ComptimeStatementCtx { - .comptime_token = token_index, - .block = block, - } - }) catch unreachable; + stack.append(State{ .ComptimeStatement = ComptimeStatementCtx{ + .comptime_token = token_index, + .block = block, + } }) catch unreachable; continue; }, - Token.Id.Keyword_var, Token.Id.Keyword_const => { - stack.append(State { - .VarDecl = VarDeclCtx { - .comments = null, - .visib_token = null, - .comptime_token = null, - .extern_export_token = null, - .lib_name = null, - .mut_token = token_index, - .list = &block.statements, - } - }) catch unreachable; + Token.Id.Keyword_var, + Token.Id.Keyword_const => { + stack.append(State{ .VarDecl = VarDeclCtx{ + .comments = null, + .visib_token = null, + .comptime_token = null, + .extern_export_token = null, + .lib_name = null, + .mut_token = token_index, + .list = &block.statements, + } }) catch unreachable; continue; }, - Token.Id.Keyword_defer, Token.Id.Keyword_errdefer => { - const node = try arena.construct(ast.Node.Defer { - .base = ast.Node { - .id = ast.Node.Id.Defer, - }, + Token.Id.Keyword_defer, + Token.Id.Keyword_errdefer => { + const node = try arena.construct(ast.Node.Defer{ + .base = ast.Node{ .id = ast.Node.Id.Defer }, .defer_token = token_index, .kind = switch (token_ptr.id) { Token.Id.Keyword_defer => ast.Node.Defer.Kind.Unconditional, @@ -1102,15 +1007,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .expr = undefined, }); const node_ptr = try block.statements.addOne(); - *node_ptr = &node.base; + node_ptr.* = &node.base; - stack.append(State { .Semicolon = node_ptr }) catch unreachable; - try stack.append(State { .AssignmentExpressionBegin = OptionalCtx{ .Required = &node.expr } }); + stack.append(State{ .Semicolon = node_ptr }) catch unreachable; + try stack.append(State{ .AssignmentExpressionBegin = OptionalCtx{ .Required = &node.expr } }); continue; }, Token.Id.LBrace => { - const inner_block = try arena.construct(ast.Node.Block { - .base = ast.Node { .id = ast.Node.Id.Block }, + const inner_block = try arena.construct(ast.Node.Block{ + .base = ast.Node{ .id = ast.Node.Id.Block }, .label = null, .lbrace = token_index, .statements = ast.Node.Block.StatementList.init(arena), @@ -1118,16 +1023,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try block.statements.push(&inner_block.base); - stack.append(State { .Block = inner_block }) catch unreachable; + stack.append(State{ .Block = inner_block }) catch unreachable; continue; }, else => { putBackToken(&tok_it, &tree); const statement = try block.statements.addOne(); - try stack.append(State { .Semicolon = statement }); - try stack.append(State { .AssignmentExpressionBegin = OptionalCtx{ .Required = statement } }); + try stack.append(State{ .Semicolon = statement }); + try stack.append(State{ .AssignmentExpressionBegin = OptionalCtx{ .Required = statement } }); continue; - } + }, } }, State.ComptimeStatement => |ctx| { @@ -1135,34 +1040,33 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_var, Token.Id.Keyword_const => { - stack.append(State { - .VarDecl = VarDeclCtx { - .comments = null, - .visib_token = null, - .comptime_token = ctx.comptime_token, - .extern_export_token = null, - .lib_name = null, - .mut_token = token_index, - .list = &ctx.block.statements, - } - }) catch unreachable; + Token.Id.Keyword_var, + Token.Id.Keyword_const => { + stack.append(State{ .VarDecl = VarDeclCtx{ + .comments = null, + .visib_token = null, + .comptime_token = ctx.comptime_token, + .extern_export_token = null, + .lib_name = null, + .mut_token = token_index, + .list = &ctx.block.statements, + } }) catch unreachable; continue; }, else => { putBackToken(&tok_it, &tree); putBackToken(&tok_it, &tree); const statement = try ctx.block.statements.addOne(); - try stack.append(State { .Semicolon = statement }); - try stack.append(State { .Expression = OptionalCtx { .Required = statement } }); + try stack.append(State{ .Semicolon = statement }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = statement } }); continue; - } + }, } }, State.Semicolon => |node_ptr| { - const node = *node_ptr; + const node = node_ptr.*; if (node.requireSemiColon()) { - stack.append(State { .ExpectToken = Token.Id.Semicolon }) catch unreachable; + stack.append(State{ .ExpectToken = Token.Id.Semicolon }) catch unreachable; continue; } continue; @@ -1177,22 +1081,22 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try arena.construct(ast.Node.AsmOutput { - .base = ast.Node {.id = ast.Node.Id.AsmOutput }, + const node = try arena.construct(ast.Node.AsmOutput{ + .base = ast.Node{ .id = ast.Node.Id.AsmOutput }, .symbolic_name = undefined, .constraint = undefined, .kind = undefined, }); try items.push(node); - stack.append(State { .AsmOutputItems = items }) catch unreachable; - try stack.append(State { .IfToken = Token.Id.Comma }); - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .AsmOutputReturnOrType = node }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); - try stack.append(State { .StringLiteral = OptionalCtx { .Required = &node.constraint } }); - try stack.append(State { .ExpectToken = Token.Id.RBracket }); - try stack.append(State { .Identifier = OptionalCtx { .Required = &node.symbolic_name } }); + stack.append(State{ .AsmOutputItems = items }) catch unreachable; + try stack.append(State{ .IfToken = Token.Id.Comma }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .AsmOutputReturnOrType = node }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); + try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } }); + try stack.append(State{ .ExpectToken = Token.Id.RBracket }); + try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.symbolic_name } }); continue; }, State.AsmOutputReturnOrType => |node| { @@ -1201,20 +1105,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Identifier => { - node.kind = ast.Node.AsmOutput.Kind { .Variable = try createLiteral(arena, ast.Node.Identifier, token_index) }; + node.kind = ast.Node.AsmOutput.Kind{ .Variable = try createLiteral(arena, ast.Node.Identifier, token_index) }; continue; }, Token.Id.Arrow => { - node.kind = ast.Node.AsmOutput.Kind { .Return = undefined }; - try stack.append(State { .TypeExprBegin = OptionalCtx { .Required = &node.kind.Return } }); + node.kind = ast.Node.AsmOutput.Kind{ .Return = undefined }; + try stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.kind.Return } }); continue; }, else => { - *(try tree.errors.addOne()) = Error { - .ExpectedAsmOutputReturnOrType = Error.ExpectedAsmOutputReturnOrType { - .token = token_index, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedAsmOutputReturnOrType = Error.ExpectedAsmOutputReturnOrType{ .token = token_index } }; return tree; }, } @@ -1228,49 +1128,48 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try arena.construct(ast.Node.AsmInput { - .base = ast.Node {.id = ast.Node.Id.AsmInput }, + const node = try arena.construct(ast.Node.AsmInput{ + .base = ast.Node{ .id = ast.Node.Id.AsmInput }, .symbolic_name = undefined, .constraint = undefined, .expr = undefined, }); try items.push(node); - stack.append(State { .AsmInputItems = items }) catch unreachable; - try stack.append(State { .IfToken = Token.Id.Comma }); - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .Expression = OptionalCtx { .Required = &node.expr } }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); - try stack.append(State { .StringLiteral = OptionalCtx { .Required = &node.constraint } }); - try stack.append(State { .ExpectToken = Token.Id.RBracket }); - try stack.append(State { .Identifier = OptionalCtx { .Required = &node.symbolic_name } }); + stack.append(State{ .AsmInputItems = items }) catch unreachable; + try stack.append(State{ .IfToken = Token.Id.Comma }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); + try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } }); + try stack.append(State{ .ExpectToken = Token.Id.RBracket }); + try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.symbolic_name } }); continue; }, State.AsmClobberItems => |items| { - stack.append(State { .AsmClobberItems = items }) catch unreachable; - try stack.append(State { .IfToken = Token.Id.Comma }); - try stack.append(State { .StringLiteral = OptionalCtx { .Required = try items.addOne() } }); + stack.append(State{ .AsmClobberItems = items }) catch unreachable; + try stack.append(State{ .IfToken = Token.Id.Comma }); + try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = try items.addOne() } }); continue; }, - State.ExprListItemOrEnd => |list_state| { if (eatToken(&tok_it, &tree, list_state.end)) |token_index| { - *list_state.ptr = token_index; + (list_state.ptr).* = token_index; continue; } - stack.append(State { .ExprListCommaOrEnd = list_state }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = try list_state.list.addOne() } }); + stack.append(State{ .ExprListCommaOrEnd = list_state }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = try list_state.list.addOne() } }); continue; }, State.ExprListCommaOrEnd => |list_state| { switch (expectCommaOrEnd(&tok_it, &tree, list_state.end)) { ExpectCommaOrEndResult.end_token => |maybe_end| if (maybe_end) |end| { - *list_state.ptr = end; + (list_state.ptr).* = end; continue; } else { - stack.append(State { .ExprListItemOrEnd = list_state }) catch unreachable; + stack.append(State{ .ExprListItemOrEnd = list_state }) catch unreachable; continue; }, ExpectCommaOrEndResult.parse_error => |e| { @@ -1285,44 +1184,38 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } if (eatToken(&tok_it, &tree, Token.Id.RBrace)) |rbrace| { - *list_state.ptr = rbrace; + (list_state.ptr).* = rbrace; continue; } - const node = try arena.construct(ast.Node.FieldInitializer { - .base = ast.Node { - .id = ast.Node.Id.FieldInitializer, - }, + const node = try arena.construct(ast.Node.FieldInitializer{ + .base = ast.Node{ .id = ast.Node.Id.FieldInitializer }, .period_token = undefined, .name_token = undefined, .expr = undefined, }); try list_state.list.push(&node.base); - stack.append(State { .FieldInitListCommaOrEnd = list_state }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx{ .Required = &node.expr } }); - try stack.append(State { .ExpectToken = Token.Id.Equal }); - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Identifier, - .ptr = &node.name_token, - } - }); - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Period, - .ptr = &node.period_token, - } - }); + stack.append(State{ .FieldInitListCommaOrEnd = list_state }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); + try stack.append(State{ .ExpectToken = Token.Id.Equal }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Identifier, + .ptr = &node.name_token, + } }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Period, + .ptr = &node.period_token, + } }); continue; }, State.FieldInitListCommaOrEnd => |list_state| { switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.RBrace)) { ExpectCommaOrEndResult.end_token => |maybe_end| if (maybe_end) |end| { - *list_state.ptr = end; + (list_state.ptr).* = end; continue; } else { - stack.append(State { .FieldInitListItemOrEnd = list_state }) catch unreachable; + stack.append(State{ .FieldInitListItemOrEnd = list_state }) catch unreachable; continue; }, ExpectCommaOrEndResult.parse_error => |e| { @@ -1337,7 +1230,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { container_decl.rbrace_token = end; continue; } else { - try stack.append(State { .ContainerDecl = container_decl }); + try stack.append(State{ .ContainerDecl = container_decl }); continue; }, ExpectCommaOrEndResult.parse_error => |e| { @@ -1352,23 +1245,23 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } if (eatToken(&tok_it, &tree, Token.Id.RBrace)) |rbrace| { - *list_state.ptr = rbrace; + (list_state.ptr).* = rbrace; continue; } const node_ptr = try list_state.list.addOne(); - try stack.append(State { .ErrorTagListCommaOrEnd = list_state }); - try stack.append(State { .ErrorTag = node_ptr }); + try stack.append(State{ .ErrorTagListCommaOrEnd = list_state }); + try stack.append(State{ .ErrorTag = node_ptr }); continue; }, State.ErrorTagListCommaOrEnd => |list_state| { switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.RBrace)) { ExpectCommaOrEndResult.end_token => |maybe_end| if (maybe_end) |end| { - *list_state.ptr = end; + (list_state.ptr).* = end; continue; } else { - stack.append(State { .ErrorTagListItemOrEnd = list_state }) catch unreachable; + stack.append(State{ .ErrorTagListItemOrEnd = list_state }) catch unreachable; continue; }, ExpectCommaOrEndResult.parse_error => |e| { @@ -1383,24 +1276,22 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } if (eatToken(&tok_it, &tree, Token.Id.RBrace)) |rbrace| { - *list_state.ptr = rbrace; + (list_state.ptr).* = rbrace; continue; } const comments = try eatDocComments(arena, &tok_it, &tree); - const node = try arena.construct(ast.Node.SwitchCase { - .base = ast.Node { - .id = ast.Node.Id.SwitchCase, - }, + const node = try arena.construct(ast.Node.SwitchCase{ + .base = ast.Node{ .id = ast.Node.Id.SwitchCase }, .items = ast.Node.SwitchCase.ItemList.init(arena), .payload = null, .expr = undefined, }); try list_state.list.push(&node.base); - try stack.append(State { .SwitchCaseCommaOrEnd = list_state }); - try stack.append(State { .AssignmentExpressionBegin = OptionalCtx { .Required = &node.expr } }); - try stack.append(State { .PointerPayload = OptionalCtx { .Optional = &node.payload } }); - try stack.append(State { .SwitchCaseFirstItem = &node.items }); + try stack.append(State{ .SwitchCaseCommaOrEnd = list_state }); + try stack.append(State{ .AssignmentExpressionBegin = OptionalCtx{ .Required = &node.expr } }); + try stack.append(State{ .PointerPayload = OptionalCtx{ .Optional = &node.payload } }); + try stack.append(State{ .SwitchCaseFirstItem = &node.items }); continue; }, @@ -1408,10 +1299,10 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { State.SwitchCaseCommaOrEnd => |list_state| { switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.RParen)) { ExpectCommaOrEndResult.end_token => |maybe_end| if (maybe_end) |end| { - *list_state.ptr = end; + (list_state.ptr).* = end; continue; } else { - try stack.append(State { .SwitchCaseOrEnd = list_state }); + try stack.append(State{ .SwitchCaseOrEnd = list_state }); continue; }, ExpectCommaOrEndResult.parse_error => |e| { @@ -1426,29 +1317,29 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (token_ptr.id == Token.Id.Keyword_else) { - const else_node = try arena.construct(ast.Node.SwitchElse { - .base = ast.Node{ .id = ast.Node.Id.SwitchElse}, + const else_node = try arena.construct(ast.Node.SwitchElse{ + .base = ast.Node{ .id = ast.Node.Id.SwitchElse }, .token = token_index, }); try case_items.push(&else_node.base); - try stack.append(State { .ExpectToken = Token.Id.EqualAngleBracketRight }); + try stack.append(State{ .ExpectToken = Token.Id.EqualAngleBracketRight }); continue; } else { putBackToken(&tok_it, &tree); - try stack.append(State { .SwitchCaseItem = case_items }); + try stack.append(State{ .SwitchCaseItem = case_items }); continue; } }, State.SwitchCaseItem => |case_items| { - stack.append(State { .SwitchCaseItemCommaOrEnd = case_items }) catch unreachable; - try stack.append(State { .RangeExpressionBegin = OptionalCtx { .Required = try case_items.addOne() } }); + stack.append(State{ .SwitchCaseItemCommaOrEnd = case_items }) catch unreachable; + try stack.append(State{ .RangeExpressionBegin = OptionalCtx{ .Required = try case_items.addOne() } }); }, State.SwitchCaseItemCommaOrEnd => |case_items| { switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.EqualAngleBracketRight)) { ExpectCommaOrEndResult.end_token => |t| { if (t == null) { - stack.append(State { .SwitchCaseItem = case_items }) catch unreachable; + stack.append(State{ .SwitchCaseItem = case_items }) catch unreachable; } continue; }, @@ -1460,10 +1351,9 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, - State.SuspendBody => |suspend_node| { if (suspend_node.payload != null) { - try stack.append(State { .AssignmentExpressionBegin = OptionalCtx { .RequiredNull = &suspend_node.body } }); + try stack.append(State{ .AssignmentExpressionBegin = OptionalCtx{ .RequiredNull = &suspend_node.body } }); } continue; }, @@ -1473,13 +1363,11 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } async_node.rangle_bracket = TokenIndex(0); - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.AngleBracketRight, - .ptr = &??async_node.rangle_bracket, - } - }); - try stack.append(State { .TypeExprBegin = OptionalCtx { .RequiredNull = &async_node.allocator_type } }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.AngleBracketRight, + .ptr = &??async_node.rangle_bracket, + } }); + try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &async_node.allocator_type } }); continue; }, State.AsyncEnd => |ctx| { @@ -1498,27 +1386,20 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - *(try tree.errors.addOne()) = Error { - .ExpectedCall = Error.ExpectedCall { .node = node }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedCall = Error.ExpectedCall{ .node = node } }; return tree; }, else => { - *(try tree.errors.addOne()) = Error { - .ExpectedCallOrFnProto = Error.ExpectedCallOrFnProto { .node = node }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedCallOrFnProto = Error.ExpectedCallOrFnProto{ .node = node } }; return tree; - } + }, } }, - State.ExternType => |ctx| { if (eatToken(&tok_it, &tree, Token.Id.Keyword_fn)) |fn_token| { - const fn_proto = try arena.construct(ast.Node.FnProto { - .base = ast.Node { - .id = ast.Node.Id.FnProto, - }, + const fn_proto = try arena.construct(ast.Node.FnProto{ + .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = ctx.comments, .visib_token = null, .name_token = null, @@ -1534,17 +1415,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .align_expr = null, }); ctx.opt_ctx.store(&fn_proto.base); - stack.append(State { .FnProto = fn_proto }) catch unreachable; + stack.append(State{ .FnProto = fn_proto }) catch unreachable; continue; } - stack.append(State { - .ContainerKind = ContainerKindCtx { - .opt_ctx = ctx.opt_ctx, - .ltoken = ctx.extern_token, - .layout = ast.Node.ContainerDecl.Layout.Extern, - }, - }) catch unreachable; + stack.append(State{ .ContainerKind = ContainerKindCtx{ + .opt_ctx = ctx.opt_ctx, + .ltoken = ctx.extern_token, + .layout = ast.Node.ContainerDecl.Layout.Extern, + } }) catch unreachable; continue; }, State.SliceOrArrayAccess => |node| { @@ -1554,20 +1433,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { switch (token_ptr.id) { Token.Id.Ellipsis2 => { const start = node.op.ArrayAccess; - node.op = ast.Node.SuffixOp.Op { - .Slice = ast.Node.SuffixOp.Op.Slice { - .start = start, - .end = null, - } - }; + node.op = ast.Node.SuffixOp.Op{ .Slice = ast.Node.SuffixOp.Op.Slice{ + .start = start, + .end = null, + } }; - stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.RBracket, - .ptr = &node.rtoken, - } - }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Optional = &node.op.Slice.end } }); + stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RBracket, + .ptr = &node.rtoken, + } }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Optional = &node.op.Slice.end } }); continue; }, Token.Id.RBracket => { @@ -1575,33 +1450,29 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - *(try tree.errors.addOne()) = Error { - .ExpectedSliceOrRBracket = Error.ExpectedSliceOrRBracket { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedSliceOrRBracket = Error.ExpectedSliceOrRBracket{ .token = token_index } }; return tree; - } + }, } }, State.SliceOrArrayType => |node| { if (eatToken(&tok_it, &tree, Token.Id.RBracket)) |_| { - node.op = ast.Node.PrefixOp.Op { - .SliceType = ast.Node.PrefixOp.AddrOfInfo { - .align_expr = null, - .bit_offset_start_token = null, - .bit_offset_end_token = null, - .const_token = null, - .volatile_token = null, - } - }; - stack.append(State { .TypeExprBegin = OptionalCtx { .Required = &node.rhs } }) catch unreachable; - try stack.append(State { .AddrOfModifiers = &node.op.SliceType }); + node.op = ast.Node.PrefixOp.Op{ .SliceType = ast.Node.PrefixOp.AddrOfInfo{ + .align_expr = null, + .bit_offset_start_token = null, + .bit_offset_end_token = null, + .const_token = null, + .volatile_token = null, + } }; + stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable; + try stack.append(State{ .AddrOfModifiers = &node.op.SliceType }); continue; } - node.op = ast.Node.PrefixOp.Op { .ArrayType = undefined }; - stack.append(State { .TypeExprBegin = OptionalCtx { .Required = &node.rhs } }) catch unreachable; - try stack.append(State { .ExpectToken = Token.Id.RBracket }); - try stack.append(State { .Expression = OptionalCtx { .Required = &node.op.ArrayType } }); + node.op = ast.Node.PrefixOp.Op{ .ArrayType = undefined }; + stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable; + try stack.append(State{ .ExpectToken = Token.Id.RBracket }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.op.ArrayType } }); continue; }, State.AddrOfModifiers => |addr_of_info| { @@ -1612,22 +1483,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_align => { stack.append(state) catch unreachable; if (addr_of_info.align_expr != null) { - *(try tree.errors.addOne()) = Error { - .ExtraAlignQualifier = Error.ExtraAlignQualifier { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExtraAlignQualifier = Error.ExtraAlignQualifier{ .token = token_index } }; return tree; } - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .Expression = OptionalCtx { .RequiredNull = &addr_of_info.align_expr} }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .RequiredNull = &addr_of_info.align_expr } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); continue; }, Token.Id.Keyword_const => { stack.append(state) catch unreachable; if (addr_of_info.const_token != null) { - *(try tree.errors.addOne()) = Error { - .ExtraConstQualifier = Error.ExtraConstQualifier { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExtraConstQualifier = Error.ExtraConstQualifier{ .token = token_index } }; return tree; } addr_of_info.const_token = token_index; @@ -1636,9 +1503,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_volatile => { stack.append(state) catch unreachable; if (addr_of_info.volatile_token != null) { - *(try tree.errors.addOne()) = Error { - .ExtraVolatileQualifier = Error.ExtraVolatileQualifier { .token = token_index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExtraVolatileQualifier = Error.ExtraVolatileQualifier{ .token = token_index } }; return tree; } addr_of_info.volatile_token = token_index; @@ -1651,19 +1516,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, - State.Payload => |opt_ctx| { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - *(try tree.errors.addOne()) = Error { - .ExpectedToken = Error.ExpectedToken { - .token = token_index, - .expected_id = Token.Id.Pipe, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + } }; return tree; } @@ -1671,21 +1533,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try arena.construct(ast.Node.Payload { - .base = ast.Node {.id = ast.Node.Id.Payload }, + const node = try arena.construct(ast.Node.Payload{ + .base = ast.Node{ .id = ast.Node.Id.Payload }, .lpipe = token_index, .error_symbol = undefined, - .rpipe = undefined + .rpipe = undefined, }); opt_ctx.store(&node.base); - stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } - }) catch unreachable; - try stack.append(State { .Identifier = OptionalCtx { .Required = &node.error_symbol } }); + stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + } }) catch unreachable; + try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.error_symbol } }); continue; }, State.PointerPayload => |opt_ctx| { @@ -1694,12 +1554,10 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - *(try tree.errors.addOne()) = Error { - .ExpectedToken = Error.ExpectedToken { - .token = token_index, - .expected_id = Token.Id.Pipe, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + } }; return tree; } @@ -1707,28 +1565,24 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try arena.construct(ast.Node.PointerPayload { - .base = ast.Node {.id = ast.Node.Id.PointerPayload }, + const node = try arena.construct(ast.Node.PointerPayload{ + .base = ast.Node{ .id = ast.Node.Id.PointerPayload }, .lpipe = token_index, .ptr_token = null, .value_symbol = undefined, - .rpipe = undefined + .rpipe = undefined, }); opt_ctx.store(&node.base); - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } - }); - try stack.append(State { .Identifier = OptionalCtx { .Required = &node.value_symbol } }); - try stack.append(State { - .OptionalTokenSave = OptionalTokenSave { - .id = Token.Id.Asterisk, - .ptr = &node.ptr_token, - } - }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + } }); + try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } }); + try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Asterisk, + .ptr = &node.ptr_token, + } }); continue; }, State.PointerIndexPayload => |opt_ctx| { @@ -1737,12 +1591,10 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - *(try tree.errors.addOne()) = Error { - .ExpectedToken = Error.ExpectedToken { - .token = token_index, - .expected_id = Token.Id.Pipe, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + } }; return tree; } @@ -1750,61 +1602,58 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - const node = try arena.construct(ast.Node.PointerIndexPayload { - .base = ast.Node {.id = ast.Node.Id.PointerIndexPayload }, + const node = try arena.construct(ast.Node.PointerIndexPayload{ + .base = ast.Node{ .id = ast.Node.Id.PointerIndexPayload }, .lpipe = token_index, .ptr_token = null, .value_symbol = undefined, .index_symbol = null, - .rpipe = undefined + .rpipe = undefined, }); opt_ctx.store(&node.base); - stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } - }) catch unreachable; - try stack.append(State { .Identifier = OptionalCtx { .RequiredNull = &node.index_symbol } }); - try stack.append(State { .IfToken = Token.Id.Comma }); - try stack.append(State { .Identifier = OptionalCtx { .Required = &node.value_symbol } }); - try stack.append(State { - .OptionalTokenSave = OptionalTokenSave { - .id = Token.Id.Asterisk, - .ptr = &node.ptr_token, - } - }); + stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + } }) catch unreachable; + try stack.append(State{ .Identifier = OptionalCtx{ .RequiredNull = &node.index_symbol } }); + try stack.append(State{ .IfToken = Token.Id.Comma }); + try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } }); + try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Asterisk, + .ptr = &node.ptr_token, + } }); continue; }, - State.Expression => |opt_ctx| { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_return, Token.Id.Keyword_break, Token.Id.Keyword_continue => { - const node = try arena.construct(ast.Node.ControlFlowExpression { - .base = ast.Node {.id = ast.Node.Id.ControlFlowExpression }, + Token.Id.Keyword_return, + Token.Id.Keyword_break, + Token.Id.Keyword_continue => { + const node = try arena.construct(ast.Node.ControlFlowExpression{ + .base = ast.Node{ .id = ast.Node.Id.ControlFlowExpression }, .ltoken = token_index, .kind = undefined, .rhs = null, }); opt_ctx.store(&node.base); - stack.append(State { .Expression = OptionalCtx { .Optional = &node.rhs } }) catch unreachable; + stack.append(State{ .Expression = OptionalCtx{ .Optional = &node.rhs } }) catch unreachable; switch (token_ptr.id) { Token.Id.Keyword_break => { - node.kind = ast.Node.ControlFlowExpression.Kind { .Break = null }; - try stack.append(State { .Identifier = OptionalCtx { .RequiredNull = &node.kind.Break } }); - try stack.append(State { .IfToken = Token.Id.Colon }); + node.kind = ast.Node.ControlFlowExpression.Kind{ .Break = null }; + try stack.append(State{ .Identifier = OptionalCtx{ .RequiredNull = &node.kind.Break } }); + try stack.append(State{ .IfToken = Token.Id.Colon }); }, Token.Id.Keyword_continue => { - node.kind = ast.Node.ControlFlowExpression.Kind { .Continue = null }; - try stack.append(State { .Identifier = OptionalCtx { .RequiredNull = &node.kind.Continue } }); - try stack.append(State { .IfToken = Token.Id.Colon }); + node.kind = ast.Node.ControlFlowExpression.Kind{ .Continue = null }; + try stack.append(State{ .Identifier = OptionalCtx{ .RequiredNull = &node.kind.Continue } }); + try stack.append(State{ .IfToken = Token.Id.Colon }); }, Token.Id.Keyword_return => { node.kind = ast.Node.ControlFlowExpression.Kind.Return; @@ -1813,56 +1662,58 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } continue; }, - Token.Id.Keyword_try, Token.Id.Keyword_cancel, Token.Id.Keyword_resume => { - const node = try arena.construct(ast.Node.PrefixOp { - .base = ast.Node {.id = ast.Node.Id.PrefixOp }, + Token.Id.Keyword_try, + Token.Id.Keyword_cancel, + Token.Id.Keyword_resume => { + const node = try arena.construct(ast.Node.PrefixOp{ + .base = ast.Node{ .id = ast.Node.Id.PrefixOp }, .op_token = token_index, .op = switch (token_ptr.id) { - Token.Id.Keyword_try => ast.Node.PrefixOp.Op { .Try = void{} }, - Token.Id.Keyword_cancel => ast.Node.PrefixOp.Op { .Cancel = void{} }, - Token.Id.Keyword_resume => ast.Node.PrefixOp.Op { .Resume = void{} }, + Token.Id.Keyword_try => ast.Node.PrefixOp.Op{ .Try = void{} }, + Token.Id.Keyword_cancel => ast.Node.PrefixOp.Op{ .Cancel = void{} }, + Token.Id.Keyword_resume => ast.Node.PrefixOp.Op{ .Resume = void{} }, else => unreachable, }, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .Expression = OptionalCtx { .Required = &node.rhs } }) catch unreachable; + stack.append(State{ .Expression = OptionalCtx{ .Required = &node.rhs } }) catch unreachable; continue; }, else => { if (!try parseBlockExpr(&stack, arena, opt_ctx, token_ptr, token_index)) { putBackToken(&tok_it, &tree); - stack.append(State { .UnwrapExpressionBegin = opt_ctx }) catch unreachable; + stack.append(State{ .UnwrapExpressionBegin = opt_ctx }) catch unreachable; } continue; - } + }, } }, State.RangeExpressionBegin => |opt_ctx| { - stack.append(State { .RangeExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .Expression = opt_ctx }); + stack.append(State{ .RangeExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .Expression = opt_ctx }); continue; }, State.RangeExpressionEnd => |opt_ctx| { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Ellipsis3)) |ellipsis3| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = ellipsis3, .op = ast.Node.InfixOp.Op.Range, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .Expression = OptionalCtx { .Required = &node.rhs } }) catch unreachable; + stack.append(State{ .Expression = OptionalCtx{ .Required = &node.rhs } }) catch unreachable; continue; } }, State.AssignmentExpressionBegin => |opt_ctx| { - stack.append(State { .AssignmentExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .Expression = opt_ctx }); + stack.append(State{ .AssignmentExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .Expression = opt_ctx }); continue; }, @@ -1873,16 +1724,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToAssignment(token_ptr.id)) |ass_id| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = token_index, .op = ass_id, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .AssignmentExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .AssignmentExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.rhs } }); continue; } else { putBackToken(&tok_it, &tree); @@ -1891,8 +1742,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.UnwrapExpressionBegin => |opt_ctx| { - stack.append(State { .UnwrapExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .BoolOrExpressionBegin = opt_ctx }); + stack.append(State{ .UnwrapExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .BoolOrExpressionBegin = opt_ctx }); continue; }, @@ -1903,8 +1754,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToUnwrapExpr(token_ptr.id)) |unwrap_id| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = token_index, .op = unwrap_id, @@ -1912,11 +1763,11 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State { .UnwrapExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .UnwrapExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.rhs } }); if (node.op == ast.Node.InfixOp.Op.Catch) { - try stack.append(State { .Payload = OptionalCtx { .Optional = &node.op.Catch } }); + try stack.append(State{ .Payload = OptionalCtx{ .Optional = &node.op.Catch } }); } continue; } else { @@ -1926,8 +1777,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.BoolOrExpressionBegin => |opt_ctx| { - stack.append(State { .BoolOrExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .BoolAndExpressionBegin = opt_ctx }); + stack.append(State{ .BoolOrExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .BoolAndExpressionBegin = opt_ctx }); continue; }, @@ -1935,23 +1786,23 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Keyword_or)) |or_token| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = or_token, .op = ast.Node.InfixOp.Op.BoolOr, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .BoolOrExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .BoolAndExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .BoolOrExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .BoolAndExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } }, State.BoolAndExpressionBegin => |opt_ctx| { - stack.append(State { .BoolAndExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .ComparisonExpressionBegin = opt_ctx }); + stack.append(State{ .BoolAndExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .ComparisonExpressionBegin = opt_ctx }); continue; }, @@ -1959,23 +1810,23 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Keyword_and)) |and_token| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = and_token, .op = ast.Node.InfixOp.Op.BoolAnd, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .BoolAndExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .ComparisonExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .BoolAndExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .ComparisonExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } }, State.ComparisonExpressionBegin => |opt_ctx| { - stack.append(State { .ComparisonExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .BinaryOrExpressionBegin = opt_ctx }); + stack.append(State{ .ComparisonExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .BinaryOrExpressionBegin = opt_ctx }); continue; }, @@ -1986,16 +1837,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToComparison(token_ptr.id)) |comp_id| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = token_index, .op = comp_id, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .ComparisonExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .BinaryOrExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .ComparisonExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .BinaryOrExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } else { putBackToken(&tok_it, &tree); @@ -2004,8 +1855,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.BinaryOrExpressionBegin => |opt_ctx| { - stack.append(State { .BinaryOrExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .BinaryXorExpressionBegin = opt_ctx }); + stack.append(State{ .BinaryOrExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .BinaryXorExpressionBegin = opt_ctx }); continue; }, @@ -2013,23 +1864,23 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Pipe)) |pipe| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = pipe, .op = ast.Node.InfixOp.Op.BitOr, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .BinaryOrExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .BinaryXorExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .BinaryOrExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .BinaryXorExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } }, State.BinaryXorExpressionBegin => |opt_ctx| { - stack.append(State { .BinaryXorExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .BinaryAndExpressionBegin = opt_ctx }); + stack.append(State{ .BinaryXorExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .BinaryAndExpressionBegin = opt_ctx }); continue; }, @@ -2037,23 +1888,23 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Caret)) |caret| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = caret, .op = ast.Node.InfixOp.Op.BitXor, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .BinaryXorExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .BinaryAndExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .BinaryXorExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .BinaryAndExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } }, State.BinaryAndExpressionBegin => |opt_ctx| { - stack.append(State { .BinaryAndExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .BitShiftExpressionBegin = opt_ctx }); + stack.append(State{ .BinaryAndExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .BitShiftExpressionBegin = opt_ctx }); continue; }, @@ -2061,23 +1912,23 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Ampersand)) |ampersand| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = ampersand, .op = ast.Node.InfixOp.Op.BitAnd, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .BinaryAndExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .BitShiftExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .BinaryAndExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .BitShiftExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } }, State.BitShiftExpressionBegin => |opt_ctx| { - stack.append(State { .BitShiftExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .AdditionExpressionBegin = opt_ctx }); + stack.append(State{ .BitShiftExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .AdditionExpressionBegin = opt_ctx }); continue; }, @@ -2088,16 +1939,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToBitShift(token_ptr.id)) |bitshift_id| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = token_index, .op = bitshift_id, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .BitShiftExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .AdditionExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .BitShiftExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .AdditionExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } else { putBackToken(&tok_it, &tree); @@ -2106,8 +1957,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.AdditionExpressionBegin => |opt_ctx| { - stack.append(State { .AdditionExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .MultiplyExpressionBegin = opt_ctx }); + stack.append(State{ .AdditionExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .MultiplyExpressionBegin = opt_ctx }); continue; }, @@ -2118,16 +1969,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToAddition(token_ptr.id)) |add_id| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = token_index, .op = add_id, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .AdditionExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .MultiplyExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .AdditionExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .MultiplyExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } else { putBackToken(&tok_it, &tree); @@ -2136,8 +1987,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.MultiplyExpressionBegin => |opt_ctx| { - stack.append(State { .MultiplyExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .CurlySuffixExpressionBegin = opt_ctx }); + stack.append(State{ .MultiplyExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .CurlySuffixExpressionBegin = opt_ctx }); continue; }, @@ -2148,16 +1999,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToMultiply(token_ptr.id)) |mult_id| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = token_index, .op = mult_id, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .MultiplyExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .CurlySuffixExpressionBegin = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .MultiplyExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .CurlySuffixExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } else { putBackToken(&tok_it, &tree); @@ -2166,9 +2017,9 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.CurlySuffixExpressionBegin => |opt_ctx| { - stack.append(State { .CurlySuffixExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .IfToken = Token.Id.LBrace }); - try stack.append(State { .TypeExprBegin = opt_ctx }); + stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .IfToken = Token.Id.LBrace }); + try stack.append(State{ .TypeExprBegin = opt_ctx }); continue; }, @@ -2176,51 +2027,43 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if ((??tok_it.peek()).id == Token.Id.Period) { - const node = try arena.construct(ast.Node.SuffixOp { - .base = ast.Node { .id = ast.Node.Id.SuffixOp }, + const node = try arena.construct(ast.Node.SuffixOp{ + .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, .lhs = lhs, - .op = ast.Node.SuffixOp.Op { - .StructInitializer = ast.Node.SuffixOp.Op.InitList.init(arena), - }, + .op = ast.Node.SuffixOp.Op{ .StructInitializer = ast.Node.SuffixOp.Op.InitList.init(arena) }, .rtoken = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .IfToken = Token.Id.LBrace }); - try stack.append(State { - .FieldInitListItemOrEnd = ListSave(@typeOf(node.op.StructInitializer)) { - .list = &node.op.StructInitializer, - .ptr = &node.rtoken, - } - }); + stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .IfToken = Token.Id.LBrace }); + try stack.append(State{ .FieldInitListItemOrEnd = ListSave(@typeOf(node.op.StructInitializer)){ + .list = &node.op.StructInitializer, + .ptr = &node.rtoken, + } }); continue; } - const node = try arena.construct(ast.Node.SuffixOp { - .base = ast.Node {.id = ast.Node.Id.SuffixOp }, + const node = try arena.construct(ast.Node.SuffixOp{ + .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, .lhs = lhs, - .op = ast.Node.SuffixOp.Op { - .ArrayInitializer = ast.Node.SuffixOp.Op.InitList.init(arena), - }, + .op = ast.Node.SuffixOp.Op{ .ArrayInitializer = ast.Node.SuffixOp.Op.InitList.init(arena) }, .rtoken = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .IfToken = Token.Id.LBrace }); - try stack.append(State { - .ExprListItemOrEnd = ExprListCtx { - .list = &node.op.ArrayInitializer, - .end = Token.Id.RBrace, - .ptr = &node.rtoken, - } - }); + stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .IfToken = Token.Id.LBrace }); + try stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ + .list = &node.op.ArrayInitializer, + .end = Token.Id.RBrace, + .ptr = &node.rtoken, + } }); continue; }, State.TypeExprBegin => |opt_ctx| { - stack.append(State { .TypeExprEnd = opt_ctx }) catch unreachable; - try stack.append(State { .PrefixOpExpression = opt_ctx }); + stack.append(State{ .TypeExprEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .PrefixOpExpression = opt_ctx }); continue; }, @@ -2228,16 +2071,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lhs = opt_ctx.get() ?? continue; if (eatToken(&tok_it, &tree, Token.Id.Bang)) |bang| { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = bang, .op = ast.Node.InfixOp.Op.ErrorUnion, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .TypeExprEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .PrefixOpExpression = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .TypeExprEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .PrefixOpExpression = OptionalCtx{ .Required = &node.rhs } }); continue; } }, @@ -2247,8 +2090,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (tokenIdToPrefixOp(token_ptr.id)) |prefix_id| { - var node = try arena.construct(ast.Node.PrefixOp { - .base = ast.Node {.id = ast.Node.Id.PrefixOp }, + var node = try arena.construct(ast.Node.PrefixOp{ + .base = ast.Node{ .id = ast.Node.Id.PrefixOp }, .op_token = token_index, .op = prefix_id, .rhs = undefined, @@ -2257,8 +2100,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { // Treat '**' token as two derefs if (token_ptr.id == Token.Id.AsteriskAsterisk) { - const child = try arena.construct(ast.Node.PrefixOp { - .base = ast.Node {.id = ast.Node.Id.PrefixOp}, + const child = try arena.construct(ast.Node.PrefixOp{ + .base = ast.Node{ .id = ast.Node.Id.PrefixOp }, .op_token = token_index, .op = prefix_id, .rhs = undefined, @@ -2267,40 +2110,38 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { node = child; } - stack.append(State { .TypeExprBegin = OptionalCtx { .Required = &node.rhs } }) catch unreachable; + stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable; if (node.op == ast.Node.PrefixOp.Op.AddrOf) { - try stack.append(State { .AddrOfModifiers = &node.op.AddrOf }); + try stack.append(State{ .AddrOfModifiers = &node.op.AddrOf }); } continue; } else { putBackToken(&tok_it, &tree); - stack.append(State { .SuffixOpExpressionBegin = opt_ctx }) catch unreachable; + stack.append(State{ .SuffixOpExpressionBegin = opt_ctx }) catch unreachable; continue; } }, State.SuffixOpExpressionBegin => |opt_ctx| { if (eatToken(&tok_it, &tree, Token.Id.Keyword_async)) |async_token| { - const async_node = try arena.construct(ast.Node.AsyncAttribute { - .base = ast.Node {.id = ast.Node.Id.AsyncAttribute}, + const async_node = try arena.construct(ast.Node.AsyncAttribute{ + .base = ast.Node{ .id = ast.Node.Id.AsyncAttribute }, .async_token = async_token, .allocator_type = null, .rangle_bracket = null, }); - stack.append(State { - .AsyncEnd = AsyncEndCtx { - .ctx = opt_ctx, - .attribute = async_node, - } - }) catch unreachable; - try stack.append(State { .SuffixOpExpressionEnd = opt_ctx.toRequired() }); - try stack.append(State { .PrimaryExpression = opt_ctx.toRequired() }); - try stack.append(State { .AsyncAllocator = async_node }); + stack.append(State{ .AsyncEnd = AsyncEndCtx{ + .ctx = opt_ctx, + .attribute = async_node, + } }) catch unreachable; + try stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }); + try stack.append(State{ .PrimaryExpression = opt_ctx.toRequired() }); + try stack.append(State{ .AsyncAllocator = async_node }); continue; } - stack.append(State { .SuffixOpExpressionEnd = opt_ctx }) catch unreachable; - try stack.append(State { .PrimaryExpression = opt_ctx }); + stack.append(State{ .SuffixOpExpressionEnd = opt_ctx }) catch unreachable; + try stack.append(State{ .PrimaryExpression = opt_ctx }); continue; }, @@ -2312,48 +2153,42 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.LParen => { - const node = try arena.construct(ast.Node.SuffixOp { - .base = ast.Node {.id = ast.Node.Id.SuffixOp }, + const node = try arena.construct(ast.Node.SuffixOp{ + .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, .lhs = lhs, - .op = ast.Node.SuffixOp.Op { - .Call = ast.Node.SuffixOp.Op.Call { - .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena), - .async_attr = null, - } - }, + .op = ast.Node.SuffixOp.Op{ .Call = ast.Node.SuffixOp.Op.Call{ + .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena), + .async_attr = null, + } }, .rtoken = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { - .ExprListItemOrEnd = ExprListCtx { - .list = &node.op.Call.params, - .end = Token.Id.RParen, - .ptr = &node.rtoken, - } - }); + stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ + .list = &node.op.Call.params, + .end = Token.Id.RParen, + .ptr = &node.rtoken, + } }); continue; }, Token.Id.LBracket => { - const node = try arena.construct(ast.Node.SuffixOp { - .base = ast.Node {.id = ast.Node.Id.SuffixOp }, + const node = try arena.construct(ast.Node.SuffixOp{ + .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, .lhs = lhs, - .op = ast.Node.SuffixOp.Op { - .ArrayAccess = undefined, - }, - .rtoken = undefined + .op = ast.Node.SuffixOp.Op{ .ArrayAccess = undefined }, + .rtoken = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .SliceOrArrayAccess = node }); - try stack.append(State { .Expression = OptionalCtx { .Required = &node.op.ArrayAccess }}); + stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .SliceOrArrayAccess = node }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.op.ArrayAccess } }); continue; }, Token.Id.Period => { - const node = try arena.construct(ast.Node.InfixOp { - .base = ast.Node {.id = ast.Node.Id.InfixOp }, + const node = try arena.construct(ast.Node.InfixOp{ + .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, .op_token = token_index, .op = ast.Node.InfixOp.Op.Period, @@ -2361,8 +2196,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State { .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State { .Identifier = OptionalCtx { .Required = &node.rhs } }); + stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.rhs } }); continue; }, else => { @@ -2391,7 +2226,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.UndefinedLiteral, token.index); continue; }, - Token.Id.Keyword_true, Token.Id.Keyword_false => { + Token.Id.Keyword_true, + Token.Id.Keyword_false => { _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.BoolLiteral, token.index); continue; }, @@ -2412,10 +2248,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_promise => { - const node = try arena.construct(ast.Node.PromiseType { - .base = ast.Node { - .id = ast.Node.Id.PromiseType, - }, + const node = try arena.construct(ast.Node.PromiseType{ + .base = ast.Node{ .id = ast.Node.Id.PromiseType }, .promise_token = token.index, .result = null, }); @@ -2427,121 +2261,108 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { putBackToken(&tok_it, &tree); continue; } - node.result = ast.Node.PromiseType.Result { + node.result = ast.Node.PromiseType.Result{ .arrow_token = next_token_index, .return_type = undefined, }; const return_type_ptr = &((??node.result).return_type); - try stack.append(State { .Expression = OptionalCtx { .Required = return_type_ptr, } }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = return_type_ptr } }); continue; }, - Token.Id.StringLiteral, Token.Id.MultilineStringLiteralLine => { + Token.Id.StringLiteral, + Token.Id.MultilineStringLiteralLine => { opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) ?? unreachable); continue; }, Token.Id.LParen => { - const node = try arena.construct(ast.Node.GroupedExpression { - .base = ast.Node {.id = ast.Node.Id.GroupedExpression }, + const node = try arena.construct(ast.Node.GroupedExpression{ + .base = ast.Node{ .id = ast.Node.Id.GroupedExpression }, .lparen = token.index, .expr = undefined, .rparen = undefined, }); opt_ctx.store(&node.base); - stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.RParen, - .ptr = &node.rparen, - } - }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = &node.expr } }); + stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + } }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); continue; }, Token.Id.Builtin => { - const node = try arena.construct(ast.Node.BuiltinCall { - .base = ast.Node {.id = ast.Node.Id.BuiltinCall }, + const node = try arena.construct(ast.Node.BuiltinCall{ + .base = ast.Node{ .id = ast.Node.Id.BuiltinCall }, .builtin_token = token.index, .params = ast.Node.BuiltinCall.ParamList.init(arena), .rparen_token = undefined, }); opt_ctx.store(&node.base); - stack.append(State { - .ExprListItemOrEnd = ExprListCtx { - .list = &node.params, - .end = Token.Id.RParen, - .ptr = &node.rparen_token, - } - }) catch unreachable; - try stack.append(State { .ExpectToken = Token.Id.LParen, }); + stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ + .list = &node.params, + .end = Token.Id.RParen, + .ptr = &node.rparen_token, + } }) catch unreachable; + try stack.append(State{ .ExpectToken = Token.Id.LParen }); continue; }, Token.Id.LBracket => { - const node = try arena.construct(ast.Node.PrefixOp { - .base = ast.Node {.id = ast.Node.Id.PrefixOp }, + const node = try arena.construct(ast.Node.PrefixOp{ + .base = ast.Node{ .id = ast.Node.Id.PrefixOp }, .op_token = token.index, .op = undefined, .rhs = undefined, }); opt_ctx.store(&node.base); - stack.append(State { .SliceOrArrayType = node }) catch unreachable; + stack.append(State{ .SliceOrArrayType = node }) catch unreachable; continue; }, Token.Id.Keyword_error => { - stack.append(State { - .ErrorTypeOrSetDecl = ErrorTypeOrSetDeclCtx { - .error_token = token.index, - .opt_ctx = opt_ctx - } - }) catch unreachable; + stack.append(State{ .ErrorTypeOrSetDecl = ErrorTypeOrSetDeclCtx{ + .error_token = token.index, + .opt_ctx = opt_ctx, + } }) catch unreachable; continue; }, Token.Id.Keyword_packed => { - stack.append(State { - .ContainerKind = ContainerKindCtx { - .opt_ctx = opt_ctx, - .ltoken = token.index, - .layout = ast.Node.ContainerDecl.Layout.Packed, - }, - }) catch unreachable; + stack.append(State{ .ContainerKind = ContainerKindCtx{ + .opt_ctx = opt_ctx, + .ltoken = token.index, + .layout = ast.Node.ContainerDecl.Layout.Packed, + } }) catch unreachable; continue; }, Token.Id.Keyword_extern => { - stack.append(State { - .ExternType = ExternTypeCtx { - .opt_ctx = opt_ctx, - .extern_token = token.index, - .comments = null, - }, - }) catch unreachable; + stack.append(State{ .ExternType = ExternTypeCtx{ + .opt_ctx = opt_ctx, + .extern_token = token.index, + .comments = null, + } }) catch unreachable; continue; }, - Token.Id.Keyword_struct, Token.Id.Keyword_union, Token.Id.Keyword_enum => { + Token.Id.Keyword_struct, + Token.Id.Keyword_union, + Token.Id.Keyword_enum => { putBackToken(&tok_it, &tree); - stack.append(State { - .ContainerKind = ContainerKindCtx { - .opt_ctx = opt_ctx, - .ltoken = token.index, - .layout = ast.Node.ContainerDecl.Layout.Auto, - }, - }) catch unreachable; + stack.append(State{ .ContainerKind = ContainerKindCtx{ + .opt_ctx = opt_ctx, + .ltoken = token.index, + .layout = ast.Node.ContainerDecl.Layout.Auto, + } }) catch unreachable; continue; }, Token.Id.Identifier => { - stack.append(State { - .MaybeLabeledExpression = MaybeLabeledExpressionCtx { - .label = token.index, - .opt_ctx = opt_ctx - } - }) catch unreachable; + stack.append(State{ .MaybeLabeledExpression = MaybeLabeledExpressionCtx{ + .label = token.index, + .opt_ctx = opt_ctx, + } }) catch unreachable; continue; }, Token.Id.Keyword_fn => { - const fn_proto = try arena.construct(ast.Node.FnProto { - .base = ast.Node { - .id = ast.Node.Id.FnProto, - }, + const fn_proto = try arena.construct(ast.Node.FnProto{ + .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = null, .visib_token = null, .name_token = null, @@ -2557,14 +2378,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .align_expr = null, }); opt_ctx.store(&fn_proto.base); - stack.append(State { .FnProto = fn_proto }) catch unreachable; + stack.append(State{ .FnProto = fn_proto }) catch unreachable; continue; }, - Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => { - const fn_proto = try arena.construct(ast.Node.FnProto { - .base = ast.Node { - .id = ast.Node.Id.FnProto, - }, + Token.Id.Keyword_nakedcc, + Token.Id.Keyword_stdcallcc => { + const fn_proto = try arena.construct(ast.Node.FnProto{ + .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = null, .visib_token = null, .name_token = null, @@ -2580,18 +2400,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .align_expr = null, }); opt_ctx.store(&fn_proto.base); - stack.append(State { .FnProto = fn_proto }) catch unreachable; - try stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token - } - }); + stack.append(State{ .FnProto = fn_proto }) catch unreachable; + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + } }); continue; }, Token.Id.Keyword_asm => { - const node = try arena.construct(ast.Node.Asm { - .base = ast.Node {.id = ast.Node.Id.Asm }, + const node = try arena.construct(ast.Node.Asm{ + .base = ast.Node{ .id = ast.Node.Id.Asm }, .asm_token = token.index, .volatile_token = null, .template = undefined, @@ -2602,94 +2420,77 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State { - .ExpectTokenSave = ExpectTokenSave { - .id = Token.Id.RParen, - .ptr = &node.rparen, - } - }) catch unreachable; - try stack.append(State { .AsmClobberItems = &node.clobbers }); - try stack.append(State { .IfToken = Token.Id.Colon }); - try stack.append(State { .AsmInputItems = &node.inputs }); - try stack.append(State { .IfToken = Token.Id.Colon }); - try stack.append(State { .AsmOutputItems = &node.outputs }); - try stack.append(State { .IfToken = Token.Id.Colon }); - try stack.append(State { .StringLiteral = OptionalCtx { .Required = &node.template } }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); - try stack.append(State { - .OptionalTokenSave = OptionalTokenSave { - .id = Token.Id.Keyword_volatile, - .ptr = &node.volatile_token, - } - }); + stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + } }) catch unreachable; + try stack.append(State{ .AsmClobberItems = &node.clobbers }); + try stack.append(State{ .IfToken = Token.Id.Colon }); + try stack.append(State{ .AsmInputItems = &node.inputs }); + try stack.append(State{ .IfToken = Token.Id.Colon }); + try stack.append(State{ .AsmOutputItems = &node.outputs }); + try stack.append(State{ .IfToken = Token.Id.Colon }); + try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.template } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); + try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Keyword_volatile, + .ptr = &node.volatile_token, + } }); }, Token.Id.Keyword_inline => { - stack.append(State { - .Inline = InlineCtx { - .label = null, - .inline_token = token.index, - .opt_ctx = opt_ctx, - } - }) catch unreachable; + stack.append(State{ .Inline = InlineCtx{ + .label = null, + .inline_token = token.index, + .opt_ctx = opt_ctx, + } }) catch unreachable; continue; }, else => { if (!try parseBlockExpr(&stack, arena, opt_ctx, token.ptr, token.index)) { putBackToken(&tok_it, &tree); if (opt_ctx != OptionalCtx.Optional) { - *(try tree.errors.addOne()) = Error { - .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr { .token = token.index }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr{ .token = token.index } }; return tree; } } continue; - } + }, } }, - State.ErrorTypeOrSetDecl => |ctx| { if (eatToken(&tok_it, &tree, Token.Id.LBrace) == null) { _ = try createToCtxLiteral(arena, ctx.opt_ctx, ast.Node.ErrorType, ctx.error_token); continue; } - const node = try arena.construct(ast.Node.ErrorSetDecl { - .base = ast.Node { - .id = ast.Node.Id.ErrorSetDecl, - }, + const node = try arena.construct(ast.Node.ErrorSetDecl{ + .base = ast.Node{ .id = ast.Node.Id.ErrorSetDecl }, .error_token = ctx.error_token, .decls = ast.Node.ErrorSetDecl.DeclList.init(arena), .rbrace_token = undefined, }); ctx.opt_ctx.store(&node.base); - stack.append(State { - .ErrorTagListItemOrEnd = ListSave(@typeOf(node.decls)) { - .list = &node.decls, - .ptr = &node.rbrace_token, - } - }) catch unreachable; + stack.append(State{ .ErrorTagListItemOrEnd = ListSave(@typeOf(node.decls)){ + .list = &node.decls, + .ptr = &node.rbrace_token, + } }) catch unreachable; continue; }, State.StringLiteral => |opt_ctx| { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; - opt_ctx.store( - (try parseStringLiteral(arena, &tok_it, token_ptr, token_index, &tree)) ?? { - putBackToken(&tok_it, &tree); - if (opt_ctx != OptionalCtx.Optional) { - *(try tree.errors.addOne()) = Error { - .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr { .token = token_index }, - }; - return tree; - } - - continue; + opt_ctx.store((try parseStringLiteral(arena, &tok_it, token_ptr, token_index, &tree)) ?? { + putBackToken(&tok_it, &tree); + if (opt_ctx != OptionalCtx.Optional) { + ((try tree.errors.addOne())).* = Error{ .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr{ .token = token_index } }; + return tree; } - ); + + continue; + }); }, State.Identifier => |opt_ctx| { @@ -2702,12 +2503,10 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; - *(try tree.errors.addOne()) = Error { - .ExpectedToken = Error.ExpectedToken { - .token = token_index, - .expected_id = Token.Id.Identifier, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Identifier, + } }; return tree; } }, @@ -2718,23 +2517,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const ident_token_index = ident_token.index; const ident_token_ptr = ident_token.ptr; if (ident_token_ptr.id != Token.Id.Identifier) { - *(try tree.errors.addOne()) = Error { - .ExpectedToken = Error.ExpectedToken { - .token = ident_token_index, - .expected_id = Token.Id.Identifier, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ + .token = ident_token_index, + .expected_id = Token.Id.Identifier, + } }; return tree; } - const node = try arena.construct(ast.Node.ErrorTag { - .base = ast.Node { - .id = ast.Node.Id.ErrorTag, - }, + const node = try arena.construct(ast.Node.ErrorTag{ + .base = ast.Node{ .id = ast.Node.Id.ErrorTag }, .doc_comments = comments, .name_token = ident_token_index, }); - *node_ptr = &node.base; + node_ptr.* = &node.base; continue; }, @@ -2743,12 +2538,10 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (token_ptr.id != token_id) { - *(try tree.errors.addOne()) = Error { - .ExpectedToken = Error.ExpectedToken { - .token = token_index, - .expected_id = token_id, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = token_id, + } }; return tree; } continue; @@ -2758,15 +2551,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (token_ptr.id != expect_token_save.id) { - *(try tree.errors.addOne()) = Error { - .ExpectedToken = Error.ExpectedToken { - .token = token_index, - .expected_id = expect_token_save.id, - }, - }; + ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = expect_token_save.id, + } }; return tree; } - *expect_token_save.ptr = token_index; + (expect_token_save.ptr).* = token_index; continue; }, State.IfToken => |token_id| { @@ -2779,7 +2570,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.IfTokenSave => |if_token_save| { if (eatToken(&tok_it, &tree, if_token_save.id)) |token_index| { - *if_token_save.ptr = token_index; + (if_token_save.ptr).* = token_index; continue; } @@ -2788,7 +2579,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.OptionalTokenSave => |optional_token_save| { if (eatToken(&tok_it, &tree, optional_token_save.id)) |token_index| { - *optional_token_save.ptr = token_index; + (optional_token_save.ptr).* = token_index; continue; } @@ -2911,28 +2702,28 @@ const OptionalCtx = union(enum) { Required: &&ast.Node, pub fn store(self: &const OptionalCtx, value: &ast.Node) void { - switch (*self) { - OptionalCtx.Optional => |ptr| *ptr = value, - OptionalCtx.RequiredNull => |ptr| *ptr = value, - OptionalCtx.Required => |ptr| *ptr = value, + switch (self.*) { + OptionalCtx.Optional => |ptr| ptr.* = value, + OptionalCtx.RequiredNull => |ptr| ptr.* = value, + OptionalCtx.Required => |ptr| ptr.* = value, } } pub fn get(self: &const OptionalCtx) ?&ast.Node { - switch (*self) { - OptionalCtx.Optional => |ptr| return *ptr, - OptionalCtx.RequiredNull => |ptr| return ??*ptr, - OptionalCtx.Required => |ptr| return *ptr, + switch (self.*) { + OptionalCtx.Optional => |ptr| return ptr.*, + OptionalCtx.RequiredNull => |ptr| return ??ptr.*, + OptionalCtx.Required => |ptr| return ptr.*, } } pub fn toRequired(self: &const OptionalCtx) OptionalCtx { - switch (*self) { + switch (self.*) { OptionalCtx.Optional => |ptr| { - return OptionalCtx { .RequiredNull = ptr }; + return OptionalCtx{ .RequiredNull = ptr }; }, - OptionalCtx.RequiredNull => |ptr| return *self, - OptionalCtx.Required => |ptr| return *self, + OptionalCtx.RequiredNull => |ptr| return self.*, + OptionalCtx.Required => |ptr| return self.*, } } }; @@ -3054,7 +2845,6 @@ const State = union(enum) { Identifier: OptionalCtx, ErrorTag: &&ast.Node, - IfToken: @TagType(Token.Id), IfTokenSave: ExpectTokenSave, ExpectToken: @TagType(Token.Id), @@ -3064,16 +2854,14 @@ const State = union(enum) { fn pushDocComment(arena: &mem.Allocator, line_comment: TokenIndex, result: &?&ast.Node.DocComment) !void { const node = blk: { - if (*result) |comment_node| { + if (result.*) |comment_node| { break :blk comment_node; } else { - const comment_node = try arena.construct(ast.Node.DocComment { - .base = ast.Node { - .id = ast.Node.Id.DocComment, - }, + const comment_node = try arena.construct(ast.Node.DocComment{ + .base = ast.Node{ .id = ast.Node.Id.DocComment }, .lines = ast.Node.DocComment.LineList.init(arena), }); - *result = comment_node; + result.* = comment_node; break :blk comment_node; } }; @@ -3094,24 +2882,20 @@ fn eatDocComments(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, t fn eatLineComment(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) !?&ast.Node.LineComment { const token = eatToken(tok_it, tree, Token.Id.LineComment) ?? return null; - return try arena.construct(ast.Node.LineComment { - .base = ast.Node { - .id = ast.Node.Id.LineComment, - }, + return try arena.construct(ast.Node.LineComment{ + .base = ast.Node{ .id = ast.Node.Id.LineComment }, .token = token, }); } -fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, - token_ptr: &const Token, token_index: TokenIndex, tree: &ast.Tree) !?&ast.Node -{ +fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, token_ptr: &const Token, token_index: TokenIndex, tree: &ast.Tree) !?&ast.Node { switch (token_ptr.id) { Token.Id.StringLiteral => { return &(try createLiteral(arena, ast.Node.StringLiteral, token_index)).base; }, Token.Id.MultilineStringLiteralLine => { - const node = try arena.construct(ast.Node.MultilineStringLiteral { - .base = ast.Node { .id = ast.Node.Id.MultilineStringLiteral }, + const node = try arena.construct(ast.Node.MultilineStringLiteral{ + .base = ast.Node{ .id = ast.Node.Id.MultilineStringLiteral }, .lines = ast.Node.MultilineStringLiteral.LineList.init(arena), }); try node.lines.push(token_index); @@ -3135,12 +2919,11 @@ fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterato } } -fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &const OptionalCtx, - token_ptr: &const Token, token_index: TokenIndex) !bool { +fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &const OptionalCtx, token_ptr: &const Token, token_index: TokenIndex) !bool { switch (token_ptr.id) { Token.Id.Keyword_suspend => { - const node = try arena.construct(ast.Node.Suspend { - .base = ast.Node {.id = ast.Node.Id.Suspend }, + const node = try arena.construct(ast.Node.Suspend{ + .base = ast.Node{ .id = ast.Node.Id.Suspend }, .label = null, .suspend_token = token_index, .payload = null, @@ -3148,13 +2931,13 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con }); ctx.store(&node.base); - stack.append(State { .SuspendBody = node }) catch unreachable; - try stack.append(State { .Payload = OptionalCtx { .Optional = &node.payload } }); + stack.append(State{ .SuspendBody = node }) catch unreachable; + try stack.append(State{ .Payload = OptionalCtx{ .Optional = &node.payload } }); return true; }, Token.Id.Keyword_if => { - const node = try arena.construct(ast.Node.If { - .base = ast.Node {.id = ast.Node.Id.If }, + const node = try arena.construct(ast.Node.If{ + .base = ast.Node{ .id = ast.Node.Id.If }, .if_token = token_index, .condition = undefined, .payload = null, @@ -3163,41 +2946,35 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con }); ctx.store(&node.base); - stack.append(State { .Else = &node.@"else" }) catch unreachable; - try stack.append(State { .Expression = OptionalCtx { .Required = &node.body } }); - try stack.append(State { .PointerPayload = OptionalCtx { .Optional = &node.payload } }); - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .Expression = OptionalCtx { .Required = &node.condition } }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + stack.append(State{ .Else = &node.@"else" }) catch unreachable; + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.body } }); + try stack.append(State{ .PointerPayload = OptionalCtx{ .Optional = &node.payload } }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.condition } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); return true; }, Token.Id.Keyword_while => { - stack.append(State { - .While = LoopCtx { - .label = null, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = *ctx, - } - }) catch unreachable; + stack.append(State{ .While = LoopCtx{ + .label = null, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.*, + } }) catch unreachable; return true; }, Token.Id.Keyword_for => { - stack.append(State { - .For = LoopCtx { - .label = null, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = *ctx, - } - }) catch unreachable; + stack.append(State{ .For = LoopCtx{ + .label = null, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.*, + } }) catch unreachable; return true; }, Token.Id.Keyword_switch => { - const node = try arena.construct(ast.Node.Switch { - .base = ast.Node { - .id = ast.Node.Id.Switch, - }, + const node = try arena.construct(ast.Node.Switch{ + .base = ast.Node{ .id = ast.Node.Id.Switch }, .switch_token = token_index, .expr = undefined, .cases = ast.Node.Switch.CaseList.init(arena), @@ -3205,45 +2982,43 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con }); ctx.store(&node.base); - stack.append(State { - .SwitchCaseOrEnd = ListSave(@typeOf(node.cases)) { - .list = &node.cases, - .ptr = &node.rbrace, - }, - }) catch unreachable; - try stack.append(State { .ExpectToken = Token.Id.LBrace }); - try stack.append(State { .ExpectToken = Token.Id.RParen }); - try stack.append(State { .Expression = OptionalCtx { .Required = &node.expr } }); - try stack.append(State { .ExpectToken = Token.Id.LParen }); + stack.append(State{ .SwitchCaseOrEnd = ListSave(@typeOf(node.cases)){ + .list = &node.cases, + .ptr = &node.rbrace, + } }) catch unreachable; + try stack.append(State{ .ExpectToken = Token.Id.LBrace }); + try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); + try stack.append(State{ .ExpectToken = Token.Id.LParen }); return true; }, Token.Id.Keyword_comptime => { - const node = try arena.construct(ast.Node.Comptime { - .base = ast.Node {.id = ast.Node.Id.Comptime }, + const node = try arena.construct(ast.Node.Comptime{ + .base = ast.Node{ .id = ast.Node.Id.Comptime }, .comptime_token = token_index, .expr = undefined, .doc_comments = null, }); ctx.store(&node.base); - try stack.append(State { .Expression = OptionalCtx { .Required = &node.expr } }); + try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); return true; }, Token.Id.LBrace => { - const block = try arena.construct(ast.Node.Block { - .base = ast.Node {.id = ast.Node.Id.Block }, + const block = try arena.construct(ast.Node.Block{ + .base = ast.Node{ .id = ast.Node.Id.Block }, .label = null, .lbrace = token_index, .statements = ast.Node.Block.StatementList.init(arena), .rbrace = undefined, }); ctx.store(&block.base); - stack.append(State { .Block = block }) catch unreachable; + stack.append(State{ .Block = block }) catch unreachable; return true; }, else => { return false; - } + }, } } @@ -3257,20 +3032,16 @@ fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end: const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Comma => return ExpectCommaOrEndResult { .end_token = null}, + Token.Id.Comma => return ExpectCommaOrEndResult{ .end_token = null }, else => { if (end == token_ptr.id) { - return ExpectCommaOrEndResult { .end_token = token_index }; + return ExpectCommaOrEndResult{ .end_token = token_index }; } - return ExpectCommaOrEndResult { - .parse_error = Error { - .ExpectedCommaOrEnd = Error.ExpectedCommaOrEnd { - .token = token_index, - .end_id = end, - }, - }, - }; + return ExpectCommaOrEndResult{ .parse_error = Error{ .ExpectedCommaOrEnd = Error.ExpectedCommaOrEnd{ + .token = token_index, + .end_id = end, + } } }; }, } } @@ -3278,103 +3049,102 @@ fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end: fn tokenIdToAssignment(id: &const Token.Id) ?ast.Node.InfixOp.Op { // TODO: We have to cast all cases because of this: // error: expected type '?InfixOp', found '?@TagType(InfixOp)' - return switch (*id) { - Token.Id.AmpersandEqual => ast.Node.InfixOp.Op { .AssignBitAnd = {} }, - Token.Id.AngleBracketAngleBracketLeftEqual => ast.Node.InfixOp.Op { .AssignBitShiftLeft = {} }, - Token.Id.AngleBracketAngleBracketRightEqual => ast.Node.InfixOp.Op { .AssignBitShiftRight = {} }, - Token.Id.AsteriskEqual => ast.Node.InfixOp.Op { .AssignTimes = {} }, - Token.Id.AsteriskPercentEqual => ast.Node.InfixOp.Op { .AssignTimesWarp = {} }, - Token.Id.CaretEqual => ast.Node.InfixOp.Op { .AssignBitXor = {} }, - Token.Id.Equal => ast.Node.InfixOp.Op { .Assign = {} }, - Token.Id.MinusEqual => ast.Node.InfixOp.Op { .AssignMinus = {} }, - Token.Id.MinusPercentEqual => ast.Node.InfixOp.Op { .AssignMinusWrap = {} }, - Token.Id.PercentEqual => ast.Node.InfixOp.Op { .AssignMod = {} }, - Token.Id.PipeEqual => ast.Node.InfixOp.Op { .AssignBitOr = {} }, - Token.Id.PlusEqual => ast.Node.InfixOp.Op { .AssignPlus = {} }, - Token.Id.PlusPercentEqual => ast.Node.InfixOp.Op { .AssignPlusWrap = {} }, - Token.Id.SlashEqual => ast.Node.InfixOp.Op { .AssignDiv = {} }, + return switch (id.*) { + Token.Id.AmpersandEqual => ast.Node.InfixOp.Op{ .AssignBitAnd = {} }, + Token.Id.AngleBracketAngleBracketLeftEqual => ast.Node.InfixOp.Op{ .AssignBitShiftLeft = {} }, + Token.Id.AngleBracketAngleBracketRightEqual => ast.Node.InfixOp.Op{ .AssignBitShiftRight = {} }, + Token.Id.AsteriskEqual => ast.Node.InfixOp.Op{ .AssignTimes = {} }, + Token.Id.AsteriskPercentEqual => ast.Node.InfixOp.Op{ .AssignTimesWarp = {} }, + Token.Id.CaretEqual => ast.Node.InfixOp.Op{ .AssignBitXor = {} }, + Token.Id.Equal => ast.Node.InfixOp.Op{ .Assign = {} }, + Token.Id.MinusEqual => ast.Node.InfixOp.Op{ .AssignMinus = {} }, + Token.Id.MinusPercentEqual => ast.Node.InfixOp.Op{ .AssignMinusWrap = {} }, + Token.Id.PercentEqual => ast.Node.InfixOp.Op{ .AssignMod = {} }, + Token.Id.PipeEqual => ast.Node.InfixOp.Op{ .AssignBitOr = {} }, + Token.Id.PlusEqual => ast.Node.InfixOp.Op{ .AssignPlus = {} }, + Token.Id.PlusPercentEqual => ast.Node.InfixOp.Op{ .AssignPlusWrap = {} }, + Token.Id.SlashEqual => ast.Node.InfixOp.Op{ .AssignDiv = {} }, else => null, }; } fn tokenIdToUnwrapExpr(id: @TagType(Token.Id)) ?ast.Node.InfixOp.Op { return switch (id) { - Token.Id.Keyword_catch => ast.Node.InfixOp.Op { .Catch = null }, - Token.Id.QuestionMarkQuestionMark => ast.Node.InfixOp.Op { .UnwrapMaybe = void{} }, + Token.Id.Keyword_catch => ast.Node.InfixOp.Op{ .Catch = null }, + Token.Id.QuestionMarkQuestionMark => ast.Node.InfixOp.Op{ .UnwrapMaybe = void{} }, else => null, }; } fn tokenIdToComparison(id: @TagType(Token.Id)) ?ast.Node.InfixOp.Op { return switch (id) { - Token.Id.BangEqual => ast.Node.InfixOp.Op { .BangEqual = void{} }, - Token.Id.EqualEqual => ast.Node.InfixOp.Op { .EqualEqual = void{} }, - Token.Id.AngleBracketLeft => ast.Node.InfixOp.Op { .LessThan = void{} }, - Token.Id.AngleBracketLeftEqual => ast.Node.InfixOp.Op { .LessOrEqual = void{} }, - Token.Id.AngleBracketRight => ast.Node.InfixOp.Op { .GreaterThan = void{} }, - Token.Id.AngleBracketRightEqual => ast.Node.InfixOp.Op { .GreaterOrEqual = void{} }, + Token.Id.BangEqual => ast.Node.InfixOp.Op{ .BangEqual = void{} }, + Token.Id.EqualEqual => ast.Node.InfixOp.Op{ .EqualEqual = void{} }, + Token.Id.AngleBracketLeft => ast.Node.InfixOp.Op{ .LessThan = void{} }, + Token.Id.AngleBracketLeftEqual => ast.Node.InfixOp.Op{ .LessOrEqual = void{} }, + Token.Id.AngleBracketRight => ast.Node.InfixOp.Op{ .GreaterThan = void{} }, + Token.Id.AngleBracketRightEqual => ast.Node.InfixOp.Op{ .GreaterOrEqual = void{} }, else => null, }; } fn tokenIdToBitShift(id: @TagType(Token.Id)) ?ast.Node.InfixOp.Op { return switch (id) { - Token.Id.AngleBracketAngleBracketLeft => ast.Node.InfixOp.Op { .BitShiftLeft = void{} }, - Token.Id.AngleBracketAngleBracketRight => ast.Node.InfixOp.Op { .BitShiftRight = void{} }, + Token.Id.AngleBracketAngleBracketLeft => ast.Node.InfixOp.Op{ .BitShiftLeft = void{} }, + Token.Id.AngleBracketAngleBracketRight => ast.Node.InfixOp.Op{ .BitShiftRight = void{} }, else => null, }; } fn tokenIdToAddition(id: @TagType(Token.Id)) ?ast.Node.InfixOp.Op { return switch (id) { - Token.Id.Minus => ast.Node.InfixOp.Op { .Sub = void{} }, - Token.Id.MinusPercent => ast.Node.InfixOp.Op { .SubWrap = void{} }, - Token.Id.Plus => ast.Node.InfixOp.Op { .Add = void{} }, - Token.Id.PlusPercent => ast.Node.InfixOp.Op { .AddWrap = void{} }, - Token.Id.PlusPlus => ast.Node.InfixOp.Op { .ArrayCat = void{} }, + Token.Id.Minus => ast.Node.InfixOp.Op{ .Sub = void{} }, + Token.Id.MinusPercent => ast.Node.InfixOp.Op{ .SubWrap = void{} }, + Token.Id.Plus => ast.Node.InfixOp.Op{ .Add = void{} }, + Token.Id.PlusPercent => ast.Node.InfixOp.Op{ .AddWrap = void{} }, + Token.Id.PlusPlus => ast.Node.InfixOp.Op{ .ArrayCat = void{} }, else => null, }; } fn tokenIdToMultiply(id: @TagType(Token.Id)) ?ast.Node.InfixOp.Op { return switch (id) { - Token.Id.Slash => ast.Node.InfixOp.Op { .Div = void{} }, - Token.Id.Asterisk => ast.Node.InfixOp.Op { .Mult = void{} }, - Token.Id.AsteriskAsterisk => ast.Node.InfixOp.Op { .ArrayMult = void{} }, - Token.Id.AsteriskPercent => ast.Node.InfixOp.Op { .MultWrap = void{} }, - Token.Id.Percent => ast.Node.InfixOp.Op { .Mod = void{} }, - Token.Id.PipePipe => ast.Node.InfixOp.Op { .MergeErrorSets = void{} }, + Token.Id.Slash => ast.Node.InfixOp.Op{ .Div = void{} }, + Token.Id.Asterisk => ast.Node.InfixOp.Op{ .Mult = void{} }, + Token.Id.AsteriskAsterisk => ast.Node.InfixOp.Op{ .ArrayMult = void{} }, + Token.Id.AsteriskPercent => ast.Node.InfixOp.Op{ .MultWrap = void{} }, + Token.Id.Percent => ast.Node.InfixOp.Op{ .Mod = void{} }, + Token.Id.PipePipe => ast.Node.InfixOp.Op{ .MergeErrorSets = void{} }, else => null, }; } fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op { return switch (id) { - Token.Id.Bang => ast.Node.PrefixOp.Op { .BoolNot = void{} }, - Token.Id.Tilde => ast.Node.PrefixOp.Op { .BitNot = void{} }, - Token.Id.Minus => ast.Node.PrefixOp.Op { .Negation = void{} }, - Token.Id.MinusPercent => ast.Node.PrefixOp.Op { .NegationWrap = void{} }, - Token.Id.Asterisk, Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op { .Deref = void{} }, - Token.Id.Ampersand => ast.Node.PrefixOp.Op { - .AddrOf = ast.Node.PrefixOp.AddrOfInfo { - .align_expr = null, - .bit_offset_start_token = null, - .bit_offset_end_token = null, - .const_token = null, - .volatile_token = null, - }, - }, - Token.Id.QuestionMark => ast.Node.PrefixOp.Op { .MaybeType = void{} }, - Token.Id.QuestionMarkQuestionMark => ast.Node.PrefixOp.Op { .UnwrapMaybe = void{} }, - Token.Id.Keyword_await => ast.Node.PrefixOp.Op { .Await = void{} }, - Token.Id.Keyword_try => ast.Node.PrefixOp.Op { .Try = void{ } }, + Token.Id.Bang => ast.Node.PrefixOp.Op{ .BoolNot = void{} }, + Token.Id.Tilde => ast.Node.PrefixOp.Op{ .BitNot = void{} }, + Token.Id.Minus => ast.Node.PrefixOp.Op{ .Negation = void{} }, + Token.Id.MinusPercent => ast.Node.PrefixOp.Op{ .NegationWrap = void{} }, + Token.Id.Asterisk, + Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .Deref = void{} }, + Token.Id.Ampersand => ast.Node.PrefixOp.Op{ .AddrOf = ast.Node.PrefixOp.AddrOfInfo{ + .align_expr = null, + .bit_offset_start_token = null, + .bit_offset_end_token = null, + .const_token = null, + .volatile_token = null, + } }, + Token.Id.QuestionMark => ast.Node.PrefixOp.Op{ .MaybeType = void{} }, + Token.Id.QuestionMarkQuestionMark => ast.Node.PrefixOp.Op{ .UnwrapMaybe = void{} }, + Token.Id.Keyword_await => ast.Node.PrefixOp.Op{ .Await = void{} }, + Token.Id.Keyword_try => ast.Node.PrefixOp.Op{ .Try = void{} }, else => null, }; } fn createLiteral(arena: &mem.Allocator, comptime T: type, token_index: TokenIndex) !&T { - return arena.construct(T { - .base = ast.Node {.id = ast.Node.typeToId(T)}, + return arena.construct(T{ + .base = ast.Node{ .id = ast.Node.typeToId(T) }, .token = token_index, }); } @@ -3389,15 +3159,14 @@ fn createToCtxLiteral(arena: &mem.Allocator, opt_ctx: &const OptionalCtx, compti fn eatToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, id: @TagType(Token.Id)) ?TokenIndex { const token = nextToken(tok_it, tree); - if (token.ptr.id == id) - return token.index; + if (token.ptr.id == id) return token.index; putBackToken(tok_it, tree); return null; } fn nextToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) AnnotatedToken { - const result = AnnotatedToken { + const result = AnnotatedToken{ .index = tok_it.index, .ptr = ??tok_it.next(), }; diff --git a/std/zig/render.zig b/std/zig/render.zig index 24a6566b56..52bc074d5d 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -7,7 +7,7 @@ const Token = std.zig.Token; const indent_delta = 4; -pub const Error = error { +pub const Error = error{ /// Ran out of memory allocating call stack frames to complete rendering. OutOfMemory, }; @@ -17,9 +17,9 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf( var it = tree.root_node.decls.iterator(0); while (it.next()) |decl| { - try renderTopLevelDecl(allocator, stream, tree, 0, *decl); + try renderTopLevelDecl(allocator, stream, tree, 0, decl.*); if (it.peek()) |next_decl| { - const n = if (nodeLineOffset(tree, *decl, *next_decl) >= 2) u8(2) else u8(1); + const n = if (nodeLineOffset(tree, decl.*, next_decl.*) >= 2) u8(2) else u8(1); try stream.writeByteNTimes('\n', n); } } @@ -154,10 +154,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = block.statements.iterator(0); while (it.next()) |statement| { try stream.writeByteNTimes(' ', block_indent); - try renderStatement(allocator, stream, tree, block_indent, *statement); + try renderStatement(allocator, stream, tree, block_indent, statement.*); if (it.peek()) |next_statement| { - const n = if (nodeLineOffset(tree, *statement, *next_statement) >= 2) u8(2) else u8(1); + const n = if (nodeLineOffset(tree, statement.*, next_statement.*) >= 2) u8(2) else u8(1); try stream.writeByteNTimes('\n', n); } } @@ -203,7 +203,6 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.write(" "); try renderExpression(allocator, stream, tree, indent, body); } - }, ast.Node.Id.InfixOp => { @@ -335,7 +334,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = call_info.params.iterator(0); while (it.next()) |param_node| { - try renderExpression(allocator, stream, tree, indent, *param_node); + try renderExpression(allocator, stream, tree, indent, param_node.*); if (it.peek() != null) { try stream.write(", "); } @@ -351,7 +350,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.write("]"); }, - ast.Node.SuffixOp.Op.SuffixOp { + ast.Node.SuffixOp.Op.SuffixOp => { try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); try stream.write(".*"); }, @@ -375,7 +374,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } if (field_inits.len == 1) { - const field_init = *field_inits.at(0); + const field_init = field_inits.at(0).*; try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); try stream.write("{ "); @@ -392,12 +391,12 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = field_inits.iterator(0); while (it.next()) |field_init| { try stream.writeByteNTimes(' ', new_indent); - try renderExpression(allocator, stream, tree, new_indent, *field_init); - if ((*field_init).id != ast.Node.Id.LineComment) { + try renderExpression(allocator, stream, tree, new_indent, field_init.*); + if ((field_init.*).id != ast.Node.Id.LineComment) { try stream.write(","); } if (it.peek()) |next_field_init| { - const n = if (nodeLineOffset(tree, *field_init, *next_field_init) >= 2) u8(2) else u8(1); + const n = if (nodeLineOffset(tree, field_init.*, next_field_init.*) >= 2) u8(2) else u8(1); try stream.writeByteNTimes('\n', n); } } @@ -408,14 +407,13 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind }, ast.Node.SuffixOp.Op.ArrayInitializer => |*exprs| { - if (exprs.len == 0) { try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); try stream.write("{}"); return; } if (exprs.len == 1) { - const expr = *exprs.at(0); + const expr = exprs.at(0).*; try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); try stream.write("{"); @@ -432,11 +430,11 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = exprs.iterator(0); while (it.next()) |expr| { try stream.writeByteNTimes(' ', new_indent); - try renderExpression(allocator, stream, tree, new_indent, *expr); + try renderExpression(allocator, stream, tree, new_indent, expr.*); try stream.write(","); if (it.peek()) |next_expr| { - const n = if (nodeLineOffset(tree, *expr, *next_expr) >= 2) u8(2) else u8(1); + const n = if (nodeLineOffset(tree, expr.*, next_expr.*) >= 2) u8(2) else u8(1); try stream.writeByteNTimes('\n', n); } } @@ -469,7 +467,6 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.ControlFlowExpression.Kind.Return => { try stream.print("return"); }, - } if (flow_expr.rhs) |rhs| { @@ -575,7 +572,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind switch (container_decl.layout) { ast.Node.ContainerDecl.Layout.Packed => try stream.print("packed "), ast.Node.ContainerDecl.Layout.Extern => try stream.print("extern "), - ast.Node.ContainerDecl.Layout.Auto => { }, + ast.Node.ContainerDecl.Layout.Auto => {}, } switch (container_decl.kind) { @@ -611,10 +608,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = container_decl.fields_and_decls.iterator(0); while (it.next()) |decl| { try stream.writeByteNTimes(' ', new_indent); - try renderTopLevelDecl(allocator, stream, tree, new_indent, *decl); + try renderTopLevelDecl(allocator, stream, tree, new_indent, decl.*); if (it.peek()) |next_decl| { - const n = if (nodeLineOffset(tree, *decl, *next_decl) >= 2) u8(2) else u8(1); + const n = if (nodeLineOffset(tree, decl.*, next_decl.*) >= 2) u8(2) else u8(1); try stream.writeByteNTimes('\n', n); } } @@ -634,7 +631,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } if (err_set_decl.decls.len == 1) blk: { - const node = *err_set_decl.decls.at(0); + const node = err_set_decl.decls.at(0).*; // if there are any doc comments or same line comments // don't try to put it all on one line @@ -644,7 +641,6 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind break :blk; } - try stream.write("error{"); try renderTopLevelDecl(allocator, stream, tree, indent, node); try stream.write("}"); @@ -657,12 +653,12 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = err_set_decl.decls.iterator(0); while (it.next()) |node| { try stream.writeByteNTimes(' ', new_indent); - try renderTopLevelDecl(allocator, stream, tree, new_indent, *node); - if ((*node).id != ast.Node.Id.LineComment) { + try renderTopLevelDecl(allocator, stream, tree, new_indent, node.*); + if ((node.*).id != ast.Node.Id.LineComment) { try stream.write(","); } if (it.peek()) |next_node| { - const n = if (nodeLineOffset(tree, *node, *next_node) >= 2) u8(2) else u8(1); + const n = if (nodeLineOffset(tree, node.*, next_node.*) >= 2) u8(2) else u8(1); try stream.writeByteNTimes('\n', n); } } @@ -676,9 +672,9 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const multiline_str_literal = @fieldParentPtr(ast.Node.MultilineStringLiteral, "base", base); try stream.print("\n"); - var i : usize = 0; + var i: usize = 0; while (i < multiline_str_literal.lines.len) : (i += 1) { - const t = *multiline_str_literal.lines.at(i); + const t = multiline_str_literal.lines.at(i).*; try stream.writeByteNTimes(' ', indent + indent_delta); try stream.print("{}", tree.tokenSlice(t)); } @@ -695,7 +691,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = builtin_call.params.iterator(0); while (it.next()) |param_node| { - try renderExpression(allocator, stream, tree, indent, *param_node); + try renderExpression(allocator, stream, tree, indent, param_node.*); if (it.peek() != null) { try stream.write(", "); } @@ -740,7 +736,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = fn_proto.params.iterator(0); while (it.next()) |param_decl_node| { - try renderParamDecl(allocator, stream, tree, indent, *param_decl_node); + try renderParamDecl(allocator, stream, tree, indent, param_decl_node.*); if (it.peek() != null) { try stream.write(", "); @@ -764,7 +760,6 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExpression(allocator, stream, tree, indent, node); }, } - }, ast.Node.Id.PromiseType => { @@ -801,10 +796,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = switch_node.cases.iterator(0); while (it.next()) |node| { try stream.writeByteNTimes(' ', new_indent); - try renderExpression(allocator, stream, tree, new_indent, *node); + try renderExpression(allocator, stream, tree, new_indent, node.*); if (it.peek()) |next_node| { - const n = if (nodeLineOffset(tree, *node, *next_node) >= 2) u8(2) else u8(1); + const n = if (nodeLineOffset(tree, node.*, next_node.*) >= 2) u8(2) else u8(1); try stream.writeByteNTimes('\n', n); } } @@ -819,7 +814,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = switch_case.items.iterator(0); while (it.next()) |node| { - try renderExpression(allocator, stream, tree, indent, *node); + try renderExpression(allocator, stream, tree, indent, node.*); if (it.peek() != null) { try stream.write(",\n"); @@ -846,8 +841,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.print("{}", tree.tokenSlice(else_node.else_token)); const block_body = switch (else_node.body.id) { - ast.Node.Id.Block, ast.Node.Id.If, - ast.Node.Id.For, ast.Node.Id.While, + ast.Node.Id.Block, + ast.Node.Id.If, + ast.Node.Id.For, + ast.Node.Id.While, ast.Node.Id.Switch => true, else => false, }; @@ -972,7 +969,11 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExpression(allocator, stream, tree, indent, if_node.body); switch (if_node.body.id) { - ast.Node.Id.Block, ast.Node.Id.If, ast.Node.Id.For, ast.Node.Id.While, ast.Node.Id.Switch => { + ast.Node.Id.Block, + ast.Node.Id.If, + ast.Node.Id.For, + ast.Node.Id.While, + ast.Node.Id.Switch => { if (if_node.@"else") |@"else"| { if (if_node.body.id == ast.Node.Id.Block) { try stream.write(" "); @@ -995,7 +996,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExpression(allocator, stream, tree, indent, @"else".body); } - } + }, } }, @@ -1018,11 +1019,11 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind { var it = asm_node.outputs.iterator(0); while (it.next()) |asm_output| { - const node = &(*asm_output).base; + const node = &(asm_output.*).base; try renderExpression(allocator, stream, tree, indent_extra, node); if (it.peek()) |next_asm_output| { - const next_node = &(*next_asm_output).base; + const next_node = &(next_asm_output.*).base; const n = if (nodeLineOffset(tree, node, next_node) >= 2) u8(2) else u8(1); try stream.writeByte(','); try stream.writeByteNTimes('\n', n); @@ -1038,11 +1039,11 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind { var it = asm_node.inputs.iterator(0); while (it.next()) |asm_input| { - const node = &(*asm_input).base; + const node = &(asm_input.*).base; try renderExpression(allocator, stream, tree, indent_extra, node); if (it.peek()) |next_asm_input| { - const next_node = &(*next_asm_input).base; + const next_node = &(next_asm_input.*).base; const n = if (nodeLineOffset(tree, node, next_node) >= 2) u8(2) else u8(1); try stream.writeByte(','); try stream.writeByteNTimes('\n', n); @@ -1058,7 +1059,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind { var it = asm_node.clobbers.iterator(0); while (it.next()) |node| { - try renderExpression(allocator, stream, tree, indent_once, *node); + try renderExpression(allocator, stream, tree, indent_once, node.*); if (it.peek() != null) { try stream.write(", "); @@ -1220,8 +1221,7 @@ fn renderComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@type const comment = node.doc_comments ?? return; var it = comment.lines.iterator(0); while (it.next()) |line_token_index| { - try stream.print("{}\n", tree.tokenSlice(*line_token_index)); + try stream.print("{}\n", tree.tokenSlice(line_token_index.*)); try stream.writeByteNTimes(' ', indent); } } - From 4a3d689550286fbf7859321991c8f7b7e6d87207 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 16 May 2018 18:22:39 -0400 Subject: [PATCH 20/75] std.fmt: use SI prefixes for printing bytes closes #1015 --- std/fmt/index.zig | 87 +++++++++++++++++++++++++++++++---------------- 1 file changed, 58 insertions(+), 29 deletions(-) diff --git a/std/fmt/index.zig b/std/fmt/index.zig index e26b2f6c8b..9170acbe89 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -28,6 +28,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), Buf, BufWidth, Bytes, + BytesBase, BytesWidth, }; @@ -99,6 +100,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), }, 'B' => { width = 0; + radix = 1000; state = State.Bytes; }, else => @compileError("Unknown format character: " ++ []u8{c}), @@ -214,7 +216,24 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), }, State.Bytes => switch (c) { '}' => { - try formatBytes(args[next_arg], 0, context, Errors, output); + try formatBytes(args[next_arg], 0, radix, context, Errors, output); + next_arg += 1; + state = State.Start; + start_index = i + 1; + }, + 'i' => { + radix = 1024; + state = State.BytesBase; + }, + '0' ... '9' => { + width_start = i; + state = State.BytesWidth; + }, + else => @compileError("Unexpected character in format string: " ++ []u8{c}), + }, + State.BytesBase => switch (c) { + '}' => { + try formatBytes(args[next_arg], 0, radix, context, Errors, output); next_arg += 1; state = State.Start; start_index = i + 1; @@ -228,7 +247,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), State.BytesWidth => switch (c) { '}' => { width = comptime (parseUnsigned(usize, fmt[width_start..i], 10) catch unreachable); - try formatBytes(args[next_arg], width, context, Errors, output); + try formatBytes(args[next_arg], width, radix, context, Errors, output); next_arg += 1; state = State.Start; start_index = i + 1; @@ -550,7 +569,7 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com } } -pub fn formatBytes(value: var, width: ?usize, +pub fn formatBytes(value: var, width: ?usize, comptime radix: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { if (value == 0) { @@ -558,16 +577,26 @@ pub fn formatBytes(value: var, width: ?usize, } const mags = " KMGTPEZY"; - const magnitude = math.min(math.log2(value) / 10, mags.len - 1); - const new_value = f64(value) / math.pow(f64, 1024, f64(magnitude)); + const magnitude = switch (radix) { + 1000 => math.min(math.log2(value) / comptime math.log2(1000), mags.len - 1), + 1024 => math.min(math.log2(value) / 10, mags.len - 1), + else => unreachable, + }; + const new_value = f64(value) / math.pow(f64, f64(radix), f64(magnitude)); const suffix = mags[magnitude]; try formatFloatDecimal(new_value, width, context, Errors, output); - if (suffix != ' ') { - try output(context, (&suffix)[0..1]); + if (suffix == ' ') { + return output(context, "B"); } - return output(context, "B"); + + const buf = switch (radix) { + 1000 => []u8 { suffix, 'B' }, + 1024 => []u8 { suffix, 'i', 'B' }, + else => unreachable, + }; + return output(context, buf); } pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, @@ -787,41 +816,27 @@ test "parse unsigned comptime" { test "fmt.format" { { - var buf1: [32]u8 = undefined; const value: ?i32 = 1234; - const result = try bufPrint(buf1[0..], "nullable: {}\n", value); - assert(mem.eql(u8, result, "nullable: 1234\n")); + try testFmt("nullable: 1234\n", "nullable: {}\n", value); } { - var buf1: [32]u8 = undefined; const value: ?i32 = null; - const result = try bufPrint(buf1[0..], "nullable: {}\n", value); - assert(mem.eql(u8, result, "nullable: null\n")); + try testFmt("nullable: null\n", "nullable: {}\n", value); } { - var buf1: [32]u8 = undefined; const value: error!i32 = 1234; - const result = try bufPrint(buf1[0..], "error union: {}\n", value); - assert(mem.eql(u8, result, "error union: 1234\n")); + try testFmt("error union: 1234\n", "error union: {}\n", value); } { - var buf1: [32]u8 = undefined; const value: error!i32 = error.InvalidChar; - const result = try bufPrint(buf1[0..], "error union: {}\n", value); - assert(mem.eql(u8, result, "error union: error.InvalidChar\n")); + try testFmt("error union: error.InvalidChar\n", "error union: {}\n", value); } { - var buf1: [32]u8 = undefined; const value: u3 = 0b101; - const result = try bufPrint(buf1[0..], "u3: {}\n", value); - assert(mem.eql(u8, result, "u3: 5\n")); - } - { - var buf1: [32]u8 = undefined; - const value: usize = 63 * 1024 * 1024; - const result = try bufPrint(buf1[0..], "file size: {B}\n", value); - assert(mem.eql(u8, result, "file size: 63MB\n")); + try testFmt("u3: 5\n", "u3: {}\n", value); } + try testFmt("file size: 63MiB\n", "file size: {Bi}\n", usize(63 * 1024 * 1024)); + try testFmt("file size: 66.06MB\n", "file size: {B2}\n", usize(63 * 1024 * 1024)); { // Dummy field because of https://github.com/zig-lang/zig/issues/557. const Struct = struct { @@ -1041,6 +1056,20 @@ test "fmt.format" { } } +fn testFmt(expected: []const u8, comptime template: []const u8, args: ...) !void { + var buf: [100]u8 = undefined; + const result = try bufPrint(buf[0..], template, args); + if (mem.eql(u8, result, expected)) + return; + + std.debug.warn("\n====== expected this output: =========\n"); + std.debug.warn("{}", expected); + std.debug.warn("\n======== instead found this: =========\n"); + std.debug.warn("{}", result); + std.debug.warn("\n======================================\n"); + return error.TestFailed; +} + pub fn trim(buf: []const u8) []const u8 { var start: usize = 0; while (start < buf.len and isWhiteSpace(buf[start])) : (start += 1) { } From 967bad43a053bf7d9d54dd352fcd8416c767785e Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 16 May 2018 20:18:38 -0400 Subject: [PATCH 21/75] OpenBSD has the same C integer sizes as Linux Thanks Jan S for this information closes #1016 --- src/target.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/target.cpp b/src/target.cpp index 57970888fc..c53ed74d14 100644 --- a/src/target.cpp +++ b/src/target.cpp @@ -702,6 +702,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) { case OsLinux: case OsMacOSX: case OsZen: + case OsOpenBSD: switch (id) { case CIntTypeShort: case CIntTypeUShort: @@ -742,7 +743,6 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) { case OsKFreeBSD: case OsLv2: case OsNetBSD: - case OsOpenBSD: case OsSolaris: case OsHaiku: case OsMinix: From 9ea0e4ca6803cd10cfbffbdf80033a90f0e544d5 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 17 May 2018 00:15:52 -0400 Subject: [PATCH 22/75] zig fmt: same line comments after tokens in expression --- std/zig/parser_test.zig | 43 +++++++++++++++++++++++++++++++++++++++++ std/zig/render.zig | 41 +++++++++++++++++++++++---------------- 2 files changed, 67 insertions(+), 17 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 129e62e6dd..ea26f823b5 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,46 @@ +test "zig fmt: same line comments in expression" { + try testCanonical( + \\test "aoeu" { + \\ const x = ( // a + \\ 0 // b + \\ ); // c + \\} + \\ + ); +} + +//test "zig fmt: line comment between if block and else keyword" { +// try testTransform( +// test "aoeu" { +// // cexp(finite|nan +- i inf|nan) = nan + i nan +// if ((hx & 0x7fffffff) != 0x7f800000) { +// return Complex(f32).new(y - y, y - y); +// } +// // cexp(-inf +- i inf|nan) = 0 + i0 +// else if (hx & 0x80000000 != 0) { +// return Complex(f32).new(0, 0); +// } +// // cexp(+inf +- i inf|nan) = inf + i nan +// else { +// return Complex(f32).new(x, y - y); +// } +// } +// , +// test "aoeu" { +// // cexp(finite|nan +- i inf|nan) = nan + i nan +// if ((hx & 0x7fffffff) != 0x7f800000) { +// return Complex(f32).new(y - y, y - y); +// } // cexp(-inf +- i inf|nan) = 0 + i0 +// else if (hx & 0x80000000 != 0) { +// return Complex(f32).new(0, 0); +// } // cexp(+inf +- i inf|nan) = inf + i nan +// else { +// return Complex(f32).new(x, y - y); +// } +// } +// ); +//} + test "zig fmt: add comma on last switch prong" { try testTransform( \\test "aoeu" { diff --git a/std/zig/render.zig b/std/zig/render.zig index 5084c1d096..9ce8ba0cbf 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -81,7 +81,7 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i } try stream.print("{}: ", tree.tokenSlice(field.name_token)); try renderExpression(allocator, stream, tree, indent, field.type_expr); - try renderToken(tree, stream, field.lastToken() + 1, indent, true); + try renderToken(tree, stream, field.lastToken() + 1, indent, true, true); }, ast.Node.Id.UnionTag => { const tag = @fieldParentPtr(ast.Node.UnionTag, "base", decl); @@ -513,9 +513,9 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.GroupedExpression => { const grouped_expr = @fieldParentPtr(ast.Node.GroupedExpression, "base", base); - try stream.write("("); + try renderToken(tree, stream, grouped_expr.lparen, indent, false, false); try renderExpression(allocator, stream, tree, indent, grouped_expr.expr); - try stream.write(")"); + try renderToken(tree, stream, grouped_expr.rparen, indent, false, false); }, ast.Node.Id.FieldInitializer => { @@ -527,7 +527,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.IntegerLiteral => { const integer_literal = @fieldParentPtr(ast.Node.IntegerLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(integer_literal.token)); + try renderToken(tree, stream, integer_literal.token, indent, false, false); }, ast.Node.Id.FloatLiteral => { const float_literal = @fieldParentPtr(ast.Node.FloatLiteral, "base", base); @@ -535,7 +535,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind }, ast.Node.Id.StringLiteral => { const string_literal = @fieldParentPtr(ast.Node.StringLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(string_literal.token)); + try renderToken(tree, stream, string_literal.token, indent, false, false); }, ast.Node.Id.CharLiteral => { const char_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); @@ -840,9 +840,9 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind }, Token.Id.LineComment => { try stream.write(", "); - try renderToken(tree, stream, index, indent, true); + try renderToken(tree, stream, index, indent, true, true); }, - else => try renderToken(tree, stream, index, indent, true), + else => try renderToken(tree, stream, index, indent, true, true), } } }, @@ -971,7 +971,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.print("{} (", tree.tokenSlice(if_node.if_token)); try renderExpression(allocator, stream, tree, indent, if_node.condition); - try renderToken(tree, stream, if_node.condition.lastToken() + 1, indent, false); + try renderToken(tree, stream, if_node.condition.lastToken() + 1, indent, false, true); if (if_node.payload) |payload| { try renderExpression(allocator, stream, tree, indent, payload); @@ -1126,11 +1126,11 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, var_decl: &ast.Node.VarDecl) (@typeOf(stream).Child.Error || Error)!void { if (var_decl.visib_token) |visib_token| { - try stream.print("{} ", tree.tokenSlice(visib_token)); + try renderToken(tree, stream, visib_token, indent, false, true); } if (var_decl.extern_export_token) |extern_export_token| { - try stream.print("{} ", tree.tokenSlice(extern_export_token)); + try renderToken(tree, stream, extern_export_token, indent, false, true); if (var_decl.lib_name) |lib_name| { try renderExpression(allocator, stream, tree, indent, lib_name); @@ -1139,10 +1139,11 @@ fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent } if (var_decl.comptime_token) |comptime_token| { - try stream.print("{} ", tree.tokenSlice(comptime_token)); + try renderToken(tree, stream, comptime_token, indent, false, true); } - try stream.print("{} {}", tree.tokenSlice(var_decl.mut_token), tree.tokenSlice(var_decl.name_token)); + try renderToken(tree, stream, var_decl.mut_token, indent, false, true); + try renderToken(tree, stream, var_decl.name_token, indent, false, false); if (var_decl.type_node) |type_node| { try stream.write(": "); @@ -1161,14 +1162,14 @@ fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent try renderExpression(allocator, stream, tree, indent, init_node); } - try renderToken(tree, stream, var_decl.semicolon_token, indent, true); + try renderToken(tree, stream, var_decl.semicolon_token, indent, true, false); } fn maybeRenderSemicolon(stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { if (base.requireSemiColon()) { const semicolon_index = base.lastToken() + 1; assert(tree.tokens.at(semicolon_index).id == Token.Id.Semicolon); - try renderToken(tree, stream, semicolon_index, indent, true); + try renderToken(tree, stream, semicolon_index, indent, true, true); } } @@ -1203,7 +1204,7 @@ fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, inde } } -fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, line_break: bool) (@typeOf(stream).Child.Error || Error)!void { +fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, line_break: bool, space: bool) (@typeOf(stream).Child.Error || Error)!void { const token = tree.tokens.at(token_index); try stream.write(tree.tokenSlicePtr(token)); @@ -1214,13 +1215,19 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent try stream.print(" {}", tree.tokenSlicePtr(next_token)); if (!line_break) { try stream.write("\n"); - try stream.writeByteNTimes(' ', indent + indent_delta); + + const after_comment_token = tree.tokens.at(token_index + 2); + const next_line_indent = switch (after_comment_token.id) { + Token.Id.RParen, Token.Id.RBrace, Token.Id.RBracket => indent, + else => indent + indent_delta, + }; + try stream.writeByteNTimes(' ', next_line_indent); return; } } } - if (!line_break) { + if (!line_break and space) { try stream.writeByte(' '); } } From 37c6afa5b4c25e008206d8a036e02b7fd7189459 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 17 May 2018 00:31:47 -0400 Subject: [PATCH 23/75] zig fmt: line comment between if block and else keyword --- std/zig/parse.zig | 1 + std/zig/parser_test.zig | 67 +++++++++++++++++++++-------------------- std/zig/render.zig | 9 ++++++ 3 files changed, 45 insertions(+), 32 deletions(-) diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 4f1e3dcefe..094d368c23 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -1017,6 +1017,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, State.Else => |dest| { + while (try eatLineComment(arena, &tok_it, &tree)) |_| { } if (eatToken(&tok_it, &tree, Token.Id.Keyword_else)) |else_token| { const node = try arena.construct(ast.Node.Else { .base = ast.Node {.id = ast.Node.Id.Else }, diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index ea26f823b5..38e61fe8fe 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,38 @@ +test "zig fmt: line comment between if block and else keyword" { + try testTransform( + \\test "aoeu" { + \\ // cexp(finite|nan +- i inf|nan) = nan + i nan + \\ if ((hx & 0x7fffffff) != 0x7f800000) { + \\ return Complex(f32).new(y - y, y - y); + \\ } + \\ // cexp(-inf +- i inf|nan) = 0 + i0 + \\ else if (hx & 0x80000000 != 0) { + \\ return Complex(f32).new(0, 0); + \\ } + \\ // cexp(+inf +- i inf|nan) = inf + i nan + \\ // another comment + \\ else { + \\ return Complex(f32).new(x, y - y); + \\ } + \\} + , + \\test "aoeu" { + \\ // cexp(finite|nan +- i inf|nan) = nan + i nan + \\ if ((hx & 0x7fffffff) != 0x7f800000) { + \\ return Complex(f32).new(y - y, y - y); + \\ } // cexp(-inf +- i inf|nan) = 0 + i0 + \\ else if (hx & 0x80000000 != 0) { + \\ return Complex(f32).new(0, 0); + \\ } // cexp(+inf +- i inf|nan) = inf + i nan + \\ // another comment + \\ else { + \\ return Complex(f32).new(x, y - y); + \\ } + \\} + \\ + ); +} + test "zig fmt: same line comments in expression" { try testCanonical( \\test "aoeu" { @@ -9,38 +44,6 @@ test "zig fmt: same line comments in expression" { ); } -//test "zig fmt: line comment between if block and else keyword" { -// try testTransform( -// test "aoeu" { -// // cexp(finite|nan +- i inf|nan) = nan + i nan -// if ((hx & 0x7fffffff) != 0x7f800000) { -// return Complex(f32).new(y - y, y - y); -// } -// // cexp(-inf +- i inf|nan) = 0 + i0 -// else if (hx & 0x80000000 != 0) { -// return Complex(f32).new(0, 0); -// } -// // cexp(+inf +- i inf|nan) = inf + i nan -// else { -// return Complex(f32).new(x, y - y); -// } -// } -// , -// test "aoeu" { -// // cexp(finite|nan +- i inf|nan) = nan + i nan -// if ((hx & 0x7fffffff) != 0x7f800000) { -// return Complex(f32).new(y - y, y - y); -// } // cexp(-inf +- i inf|nan) = 0 + i0 -// else if (hx & 0x80000000 != 0) { -// return Complex(f32).new(0, 0); -// } // cexp(+inf +- i inf|nan) = inf + i nan -// else { -// return Complex(f32).new(x, y - y); -// } -// } -// ); -//} - test "zig fmt: add comma on last switch prong" { try testTransform( \\test "aoeu" { diff --git a/std/zig/render.zig b/std/zig/render.zig index 9ce8ba0cbf..980addc77a 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -852,6 +852,15 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind }, ast.Node.Id.Else => { const else_node = @fieldParentPtr(ast.Node.Else, "base", base); + + var prev_tok_index = else_node.else_token - 1; + while (tree.tokens.at(prev_tok_index).id == Token.Id.LineComment) : (prev_tok_index -= 1) { } + prev_tok_index += 1; + while (prev_tok_index < else_node.else_token) : (prev_tok_index += 1) { + try stream.print("{}\n", tree.tokenSlice(prev_tok_index)); + try stream.writeByteNTimes(' ', indent); + } + try stream.print("{}", tree.tokenSlice(else_node.else_token)); const block_body = switch (else_node.body.id) { From b48d354600406d39b29fe7327b09a62d2584a83f Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 17 May 2018 00:44:55 -0400 Subject: [PATCH 24/75] zig fmt: fix comment after if before another if --- std/segmented_list.zig | 18 ++++++++++++------ std/zig/parse.zig | 9 ++++++++- std/zig/parser_test.zig | 15 +++++++++++++++ 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/std/segmented_list.zig b/std/segmented_list.zig index a89d332556..977a725033 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -298,21 +298,27 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type return &it.list.dynamic_segments[it.shelf_index][it.box_index]; } + + pub fn set(it: &Iterator, index: usize) void { + if (index < prealloc_item_count) { + it.index = index; + return; + } + it.shelf_index = shelfIndex(index); + it.box_index = boxIndex(index, it.shelf_index); + it.shelf_size = shelfSize(it.shelf_index); + } }; pub fn iterator(self: &Self, start_index: usize) Iterator { var it = Iterator { .list = self, - .index = start_index, + .index = undefined, .shelf_index = undefined, .box_index = undefined, .shelf_size = undefined, }; - if (start_index >= prealloc_item_count) { - it.shelf_index = shelfIndex(start_index); - it.box_index = boxIndex(start_index, it.shelf_index); - it.shelf_size = shelfSize(it.shelf_index); - } + it.set(start_index); return it; } }; diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 094d368c23..970c49c4b2 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -1017,7 +1017,11 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, State.Else => |dest| { - while (try eatLineComment(arena, &tok_it, &tree)) |_| { } + const old_index = tok_it.index; + var need_index_restore = false; + while (try eatLineComment(arena, &tok_it, &tree)) |_| { + need_index_restore = true; + } if (eatToken(&tok_it, &tree, Token.Id.Keyword_else)) |else_token| { const node = try arena.construct(ast.Node.Else { .base = ast.Node {.id = ast.Node.Id.Else }, @@ -1031,6 +1035,9 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State { .Payload = OptionalCtx { .Optional = &node.payload } }); continue; } else { + if (need_index_restore) { + tok_it.set(old_index); + } continue; } }, diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 38e61fe8fe..094c4d51f7 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,18 @@ +test "zig fmt: comment after if before another if" { + try testCanonical( + \\test "aoeu" { + \\ if (x) { + \\ foo(); + \\ } + \\ // comment + \\ if (x) { + \\ bar(); + \\ } + \\} + \\ + ); +} + test "zig fmt: line comment between if block and else keyword" { try testTransform( \\test "aoeu" { From 942d384831196acf24868c32ef84409b05441960 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 17 May 2018 00:52:36 -0400 Subject: [PATCH 25/75] fix std.SegmentedList.Iterator.set --- std/segmented_list.zig | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/std/segmented_list.zig b/std/segmented_list.zig index 977a725033..b324c6c4bd 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -300,10 +300,8 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } pub fn set(it: &Iterator, index: usize) void { - if (index < prealloc_item_count) { - it.index = index; - return; - } + it.index = index; + if (index < prealloc_item_count) return; it.shelf_index = shelfIndex(index); it.box_index = boxIndex(index, it.shelf_index); it.shelf_size = shelfSize(it.shelf_index); From b73307befb49dd3b131d99ecf1c7f3fb54578ec8 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 17 May 2018 00:56:14 -0400 Subject: [PATCH 26/75] more std lib to postfix deref with zig fmt --- std/math/complex/exp.zig | 28 +++++++++++----------------- std/math/complex/ldexp.zig | 17 +++++++---------- 2 files changed, 18 insertions(+), 27 deletions(-) diff --git a/std/math/complex/exp.zig b/std/math/complex/exp.zig index 03f7f9e41b..8fe069a43d 100644 --- a/std/math/complex/exp.zig +++ b/std/math/complex/exp.zig @@ -19,8 +19,8 @@ pub fn exp(z: var) Complex(@typeOf(z.re)) { fn exp32(z: &const Complex(f32)) Complex(f32) { @setFloatMode(this, @import("builtin").FloatMode.Strict); - const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955 - const cexp_overflow = 0x43400074; // (max_exp - min_denom_exp) * ln2 + const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955 + const cexp_overflow = 0x43400074; // (max_exp - min_denom_exp) * ln2 const x = z.re; const y = z.im; @@ -41,12 +41,10 @@ fn exp32(z: &const Complex(f32)) Complex(f32) { // cexp(finite|nan +- i inf|nan) = nan + i nan if ((hx & 0x7fffffff) != 0x7f800000) { return Complex(f32).new(y - y, y - y); - } - // cexp(-inf +- i inf|nan) = 0 + i0 + } // cexp(-inf +- i inf|nan) = 0 + i0 else if (hx & 0x80000000 != 0) { return Complex(f32).new(0, 0); - } - // cexp(+inf +- i inf|nan) = inf + i nan + } // cexp(+inf +- i inf|nan) = inf + i nan else { return Complex(f32).new(x, y - y); } @@ -55,8 +53,7 @@ fn exp32(z: &const Complex(f32)) Complex(f32) { // 88.7 <= x <= 192 so must scale if (hx >= exp_overflow and hx <= cexp_overflow) { return ldexp_cexp(z, 0); - } - // - x < exp_overflow => exp(x) won't overflow (common) + } // - x < exp_overflow => exp(x) won't overflow (common) // - x > cexp_overflow, so exp(x) * s overflows for s > 0 // - x = +-inf // - x = nan @@ -67,8 +64,8 @@ fn exp32(z: &const Complex(f32)) Complex(f32) { } fn exp64(z: &const Complex(f64)) Complex(f64) { - const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710 - const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2 + const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710 + const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2 const x = z.re; const y = z.im; @@ -95,12 +92,10 @@ fn exp64(z: &const Complex(f64)) Complex(f64) { // cexp(finite|nan +- i inf|nan) = nan + i nan if (lx != 0 or (hx & 0x7fffffff) != 0x7ff00000) { return Complex(f64).new(y - y, y - y); - } - // cexp(-inf +- i inf|nan) = 0 + i0 + } // cexp(-inf +- i inf|nan) = 0 + i0 else if (hx & 0x80000000 != 0) { return Complex(f64).new(0, 0); - } - // cexp(+inf +- i inf|nan) = inf + i nan + } // cexp(+inf +- i inf|nan) = inf + i nan else { return Complex(f64).new(x, y - y); } @@ -109,9 +104,8 @@ fn exp64(z: &const Complex(f64)) Complex(f64) { // 709.7 <= x <= 1454.3 so must scale if (hx >= exp_overflow and hx <= cexp_overflow) { const r = ldexp_cexp(z, 0); - return *r; - } - // - x < exp_overflow => exp(x) won't overflow (common) + return r.*; + } // - x < exp_overflow => exp(x) won't overflow (common) // - x > cexp_overflow, so exp(x) * s overflows for s > 0 // - x = +-inf // - x = nan diff --git a/std/math/complex/ldexp.zig b/std/math/complex/ldexp.zig index 4fb5a6815f..7ebefff40c 100644 --- a/std/math/complex/ldexp.zig +++ b/std/math/complex/ldexp.zig @@ -15,12 +15,12 @@ pub fn ldexp_cexp(z: var, expt: i32) Complex(@typeOf(z.re)) { } fn frexp_exp32(x: f32, expt: &i32) f32 { - const k = 235; // reduction constant - const kln2 = 162.88958740; // k * ln2 + const k = 235; // reduction constant + const kln2 = 162.88958740; // k * ln2 const exp_x = math.exp(x - kln2); const hx = @bitCast(u32, exp_x); - *expt = i32(hx >> 23) - (0x7f + 127) + k; + expt.* = i32(hx >> 23) - (0x7f + 127) + k; return @bitCast(f32, (hx & 0x7fffff) | ((0x7f + 127) << 23)); } @@ -35,15 +35,12 @@ fn ldexp_cexp32(z: &const Complex(f32), expt: i32) Complex(f32) { const half_expt2 = exptf - half_expt1; const scale2 = @bitCast(f32, (0x7f + half_expt2) << 23); - return Complex(f32).new( - math.cos(z.im) * exp_x * scale1 * scale2, - math.sin(z.im) * exp_x * scale1 * scale2, - ); + return Complex(f32).new(math.cos(z.im) * exp_x * scale1 * scale2, math.sin(z.im) * exp_x * scale1 * scale2); } fn frexp_exp64(x: f64, expt: &i32) f64 { - const k = 1799; // reduction constant - const kln2 = 1246.97177782734161156; // k * ln2 + const k = 1799; // reduction constant + const kln2 = 1246.97177782734161156; // k * ln2 const exp_x = math.exp(x - kln2); @@ -51,7 +48,7 @@ fn frexp_exp64(x: f64, expt: &i32) f64 { const hx = u32(fx >> 32); const lx = @truncate(u32, fx); - *expt = i32(hx >> 20) - (0x3ff + 1023) + k; + expt.* = i32(hx >> 20) - (0x3ff + 1023) + k; const high_word = (hx & 0xfffff) | ((0x3ff + 1023) << 20); return @bitCast(f64, (u64(high_word) << 32) | lx); From c38b165db4a16ba6a5c6d13537177db656fc4033 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 17 May 2018 23:21:44 -0400 Subject: [PATCH 27/75] all tests passing with postfix deref syntax --- build.zig | 59 ++++--- doc/langref.html.in | 60 +++---- src-self-hosted/arg.zig | 74 +++++---- src-self-hosted/module.zig | 18 +-- src-self-hosted/target.zig | 7 +- std/zig/ast.zig | 1 + std/zig/parse.zig | 2 +- std/zig/render.zig | 3 +- test/compare_output.zig | 4 +- test/compile_errors.zig | 30 ++-- test/standalone/brace_expansion/main.zig | 43 ++--- test/tests.zig | 190 +++++++++++------------ test/translate_c.zig | 100 ++++++------ 13 files changed, 302 insertions(+), 289 deletions(-) diff --git a/build.zig b/build.zig index b72641a2ef..a4e3dbcdfa 100644 --- a/build.zig +++ b/build.zig @@ -16,7 +16,7 @@ pub fn build(b: &Builder) !void { var docgen_exe = b.addExecutable("docgen", "doc/docgen.zig"); const rel_zig_exe = try os.path.relative(b.allocator, b.build_root, b.zig_exe); - var docgen_cmd = b.addCommand(null, b.env_map, [][]const u8 { + var docgen_cmd = b.addCommand(null, b.env_map, [][]const u8{ docgen_exe.getOutputPath(), rel_zig_exe, "doc/langref.html.in", @@ -30,7 +30,10 @@ pub fn build(b: &Builder) !void { const test_step = b.step("test", "Run all the tests"); // find the stage0 build artifacts because we're going to re-use config.h and zig_cpp library - const build_info = try b.exec([][]const u8{b.zig_exe, "BUILD_INFO"}); + const build_info = try b.exec([][]const u8{ + b.zig_exe, + "BUILD_INFO", + }); var index: usize = 0; const cmake_binary_dir = nextValue(&index, build_info); const cxx_compiler = nextValue(&index, build_info); @@ -67,7 +70,10 @@ pub fn build(b: &Builder) !void { dependOnLib(exe, llvm); if (exe.target.getOs() == builtin.Os.linux) { - const libstdcxx_path_padded = try b.exec([][]const u8{cxx_compiler, "-print-file-name=libstdc++.a"}); + const libstdcxx_path_padded = try b.exec([][]const u8{ + cxx_compiler, + "-print-file-name=libstdc++.a", + }); const libstdcxx_path = ??mem.split(libstdcxx_path_padded, "\r\n").next(); if (mem.eql(u8, libstdcxx_path, "libstdc++.a")) { warn( @@ -111,17 +117,11 @@ pub fn build(b: &Builder) !void { test_step.dependOn(docs_step); - test_step.dependOn(tests.addPkgTests(b, test_filter, - "test/behavior.zig", "behavior", "Run the behavior tests", - with_lldb)); + test_step.dependOn(tests.addPkgTests(b, test_filter, "test/behavior.zig", "behavior", "Run the behavior tests", with_lldb)); - test_step.dependOn(tests.addPkgTests(b, test_filter, - "std/index.zig", "std", "Run the standard library tests", - with_lldb)); + test_step.dependOn(tests.addPkgTests(b, test_filter, "std/index.zig", "std", "Run the standard library tests", with_lldb)); - test_step.dependOn(tests.addPkgTests(b, test_filter, - "std/special/compiler_rt/index.zig", "compiler-rt", "Run the compiler_rt tests", - with_lldb)); + test_step.dependOn(tests.addPkgTests(b, test_filter, "std/special/compiler_rt/index.zig", "compiler-rt", "Run the compiler_rt tests", with_lldb)); test_step.dependOn(tests.addCompareOutputTests(b, test_filter)); test_step.dependOn(tests.addBuildExampleTests(b, test_filter)); @@ -149,8 +149,7 @@ fn dependOnLib(lib_exe_obj: &std.build.LibExeObjStep, dep: &const LibraryDep) vo fn addCppLib(b: &Builder, lib_exe_obj: &std.build.LibExeObjStep, cmake_binary_dir: []const u8, lib_name: []const u8) void { const lib_prefix = if (lib_exe_obj.target.isWindows()) "" else "lib"; - lib_exe_obj.addObjectFile(os.path.join(b.allocator, cmake_binary_dir, "zig_cpp", - b.fmt("{}{}{}", lib_prefix, lib_name, lib_exe_obj.target.libFileExt())) catch unreachable); + lib_exe_obj.addObjectFile(os.path.join(b.allocator, cmake_binary_dir, "zig_cpp", b.fmt("{}{}{}", lib_prefix, lib_name, lib_exe_obj.target.libFileExt())) catch unreachable); } const LibraryDep = struct { @@ -161,11 +160,21 @@ const LibraryDep = struct { }; fn findLLVM(b: &Builder, llvm_config_exe: []const u8) !LibraryDep { - const libs_output = try b.exec([][]const u8{llvm_config_exe, "--libs", "--system-libs"}); - const includes_output = try b.exec([][]const u8{llvm_config_exe, "--includedir"}); - const libdir_output = try b.exec([][]const u8{llvm_config_exe, "--libdir"}); + const libs_output = try b.exec([][]const u8{ + llvm_config_exe, + "--libs", + "--system-libs", + }); + const includes_output = try b.exec([][]const u8{ + llvm_config_exe, + "--includedir", + }); + const libdir_output = try b.exec([][]const u8{ + llvm_config_exe, + "--libdir", + }); - var result = LibraryDep { + var result = LibraryDep{ .libs = ArrayList([]const u8).init(b.allocator), .system_libs = ArrayList([]const u8).init(b.allocator), .includes = ArrayList([]const u8).init(b.allocator), @@ -227,17 +236,17 @@ pub fn installCHeaders(b: &Builder, c_header_files: []const u8) void { } fn nextValue(index: &usize, build_info: []const u8) []const u8 { - const start = *index; - while (true) : (*index += 1) { - switch (build_info[*index]) { + const start = index.*; + while (true) : (index.* += 1) { + switch (build_info[index.*]) { '\n' => { - const result = build_info[start..*index]; - *index += 1; + const result = build_info[start..index.*]; + index.* += 1; return result; }, '\r' => { - const result = build_info[start..*index]; - *index += 2; + const result = build_info[start..index.*]; + index.* += 2; return result; }, else => continue, diff --git a/doc/langref.html.in b/doc/langref.html.in index cdfe7d9228..d047c7d9f2 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -1232,7 +1232,7 @@ mem.eql(u8, pattern, "ababab") -

*a
+
a.*
  • {#link|Pointers#}
  • @@ -1244,7 +1244,7 @@ mem.eql(u8, pattern, "ababab")
    const x: u32 = 1234;
     const ptr = &x;
    -*x == 1234
    +x.* == 1234
    @@ -1258,7 +1258,7 @@ const ptr = &x;
    const x: u32 = 1234;
     const ptr = &x;
    -*x == 1234
    +x.* == 1234
    @@ -1267,8 +1267,8 @@ const ptr = &x; {#header_open|Precedence#}
    x() x[] x.y
     a!b
    -!x -x -%x ~x *x &x ?x ??x
    -x{}
    +!x -x -%x ~x &x ?x ??x
    +x{} x.*
     ! * / % ** *%
     + - ++ +% -%
     << >>
    @@ -1316,7 +1316,7 @@ var some_integers: [100]i32 = undefined;
     
     test "modify an array" {
         for (some_integers) |*item, i| {
    -        *item = i32(i);
    +        item.* = i32(i);
         }
         assert(some_integers[10] == 10);
         assert(some_integers[99] == 99);
    @@ -1357,7 +1357,7 @@ comptime {
     var fancy_array = init: {
         var initial_value: [10]Point = undefined;
         for (initial_value) |*pt, i| {
    -        *pt = Point {
    +        pt.* = Point {
                 .x = i32(i),
                 .y = i32(i) * 2,
             };
    @@ -1400,7 +1400,7 @@ test "address of syntax" {
         const x_ptr = &x;
     
         // Deference a pointer:
    -    assert(*x_ptr == 1234);
    +    assert(x_ptr.* == 1234);
     
         // When you get the address of a const variable, you get a const pointer.
         assert(@typeOf(x_ptr) == &const i32);
    @@ -1409,8 +1409,8 @@ test "address of syntax" {
         var y: i32 = 5678;
         const y_ptr = &y;
         assert(@typeOf(y_ptr) == &i32);
    -    *y_ptr += 1;
    -    assert(*y_ptr == 5679);
    +    y_ptr.* += 1;
    +    assert(y_ptr.* == 5679);
     }
     
     test "pointer array access" {
    @@ -1448,9 +1448,9 @@ comptime {
         // @ptrCast.
         var x: i32 = 1;
         const ptr = &x;
    -    *ptr += 1;
    +    ptr.* += 1;
         x += 1;
    -    assert(*ptr == 3);
    +    assert(ptr.* == 3);
     }
     
     test "@ptrToInt and @intToPtr" {
    @@ -1492,7 +1492,7 @@ test "nullable pointers" {
         var x: i32 = 1;
         ptr = &x;
     
    -    assert(*??ptr == 1);
    +    assert((??ptr).* == 1);
     
         // Nullable pointers are the same size as normal pointers, because pointer
         // value 0 is used as the null value.
    @@ -1505,7 +1505,7 @@ test "pointer casting" {
         // conversions are not possible.
         const bytes align(@alignOf(u32)) = []u8{0x12, 0x12, 0x12, 0x12};
         const u32_ptr = @ptrCast(&const u32, &bytes[0]);
    -    assert(*u32_ptr == 0x12121212);
    +    assert(u32_ptr.* == 0x12121212);
     
         // Even this example is contrived - there are better ways to do the above than
         // pointer casting. For example, using a slice narrowing cast:
    @@ -1610,7 +1610,7 @@ fn foo(bytes: []u8) u32 {
           u8 can alias any memory.
           

    As an example, this code produces undefined behavior:

    -
    *@ptrCast(&u32, f32(12.34))
    +
    @ptrCast(&u32, f32(12.34)).*

    Instead, use {#link|@bitCast#}:

    @bitCast(u32, f32(12.34))

    As an added benefit, the @bitcast version works at compile-time.

    @@ -2040,7 +2040,7 @@ const Variant = union(enum) { Bool: bool, fn truthy(self: &const Variant) bool { - return switch (*self) { + return switch (self.*) { Variant.Int => |x_int| x_int != 0, Variant.Bool => |x_bool| x_bool, }; @@ -2151,7 +2151,7 @@ test "switch enum" { // A reference to the matched value can be obtained using `*` syntax. Item.C => |*item| blk: { - (*item).x += 1; + item.*.x += 1; break :blk 6; }, @@ -2374,7 +2374,7 @@ test "for reference" { // Iterate over the slice by reference by // specifying that the capture value is a pointer. for (items) |*value| { - *value += 1; + value.* += 1; } assert(items[0] == 4); @@ -2483,7 +2483,7 @@ test "if nullable" { // Access the value by reference using a pointer capture. var c: ?u32 = 3; if (c) |*value| { - *value = 2; + value.* = 2; } if (c) |value| { @@ -2524,7 +2524,7 @@ test "if error union" { // Access the value by reference using a pointer capture. var c: error!u32 = 3; if (c) |*value| { - *value = 9; + value.* = 9; } else |err| { unreachable; } @@ -3872,7 +3872,7 @@ pub fn main() void { {#header_open|@addWithOverflow#}
    @addWithOverflow(comptime T: type, a: T, b: T, result: &T) -> bool

    - Performs *result = a + b. If overflow or underflow occurs, + Performs result.* = a + b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.

    @@ -4073,9 +4073,9 @@ comptime {

    {#code_begin|syntax#} fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_value: T) ?T { - const old_value = *ptr; + const old_value = ptr.*; if (old_value == expected_value) { - *ptr = new_value; + ptr.* = new_value; return null; } else { return old_value; @@ -4100,9 +4100,9 @@ fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_v

    {#code_begin|syntax#} fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_value: T) ?T { - const old_value = *ptr; + const old_value = ptr.*; if (old_value == expected_value and usuallyTrueButSometimesFalse()) { - *ptr = new_value; + ptr.* = new_value; return null; } else { return old_value; @@ -4447,7 +4447,7 @@ mem.copy(u8, dest[0...byte_count], source[0...byte_count]);
    This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:

    -
    for (dest[0...byte_count]) |*b| *b = c;
    +
    for (dest[0...byte_count]) |*b| b.* = c;

    The optimizer is intelligent enough to turn the above snippet into a memset.

    @@ -4480,7 +4480,7 @@ mem.set(u8, dest, c);
    {#header_open|@mulWithOverflow#}
    @mulWithOverflow(comptime T: type, a: T, b: T, result: &T) -> bool

    - Performs *result = a * b. If overflow or underflow occurs, + Performs result.* = a * b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.

    @@ -4514,7 +4514,7 @@ fn targetFunction(x: i32) usize { var local_variable: i32 = 42; const ptr = &local_variable; - *ptr += 1; + ptr.* += 1; assert(local_variable == 43); return @ptrToInt(ptr); @@ -4746,7 +4746,7 @@ pub const FloatMode = enum { {#header_open|@shlWithOverflow#}
    @shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: &T) -> bool

    - Performs *result = a << b. If overflow or underflow occurs, + Performs result.* = a << b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.

    @@ -4790,7 +4790,7 @@ pub const FloatMode = enum { {#header_open|@subWithOverflow#}
    @subWithOverflow(comptime T: type, a: T, b: T, result: &T) -> bool

    - Performs *result = a - b. If overflow or underflow occurs, + Performs result.* = a - b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.

    diff --git a/src-self-hosted/arg.zig b/src-self-hosted/arg.zig index 707f208287..fa2166e3a5 100644 --- a/src-self-hosted/arg.zig +++ b/src-self-hosted/arg.zig @@ -30,24 +30,22 @@ fn argInAllowedSet(maybe_set: ?[]const []const u8, arg: []const u8) bool { } // Modifies the current argument index during iteration -fn readFlagArguments(allocator: &Allocator, args: []const []const u8, required: usize, - allowed_set: ?[]const []const u8, index: &usize) !FlagArg { - +fn readFlagArguments(allocator: &Allocator, args: []const []const u8, required: usize, allowed_set: ?[]const []const u8, index: &usize) !FlagArg { switch (required) { - 0 => return FlagArg { .None = undefined }, // TODO: Required to force non-tag but value? + 0 => return FlagArg{ .None = undefined }, // TODO: Required to force non-tag but value? 1 => { - if (*index + 1 >= args.len) { + if (index.* + 1 >= args.len) { return error.MissingFlagArguments; } - *index += 1; - const arg = args[*index]; + index.* += 1; + const arg = args[index.*]; if (!argInAllowedSet(allowed_set, arg)) { return error.ArgumentNotInAllowedSet; } - return FlagArg { .Single = arg }; + return FlagArg{ .Single = arg }; }, else => |needed| { var extra = ArrayList([]const u8).init(allocator); @@ -55,12 +53,12 @@ fn readFlagArguments(allocator: &Allocator, args: []const []const u8, required: var j: usize = 0; while (j < needed) : (j += 1) { - if (*index + 1 >= args.len) { + if (index.* + 1 >= args.len) { return error.MissingFlagArguments; } - *index += 1; - const arg = args[*index]; + index.* += 1; + const arg = args[index.*]; if (!argInAllowedSet(allowed_set, arg)) { return error.ArgumentNotInAllowedSet; @@ -69,7 +67,7 @@ fn readFlagArguments(allocator: &Allocator, args: []const []const u8, required: try extra.append(arg); } - return FlagArg { .Many = extra }; + return FlagArg{ .Many = extra }; }, } } @@ -82,7 +80,7 @@ pub const Args = struct { positionals: ArrayList([]const u8), pub fn parse(allocator: &Allocator, comptime spec: []const Flag, args: []const []const u8) !Args { - var parsed = Args { + var parsed = Args{ .flags = HashMapFlags.init(allocator), .positionals = ArrayList([]const u8).init(allocator), }; @@ -116,11 +114,7 @@ pub const Args = struct { }; if (flag.mergable) { - var prev = - if (parsed.flags.get(flag_name_trimmed)) |entry| - entry.value.Many - else - ArrayList([]const u8).init(allocator); + var prev = if (parsed.flags.get(flag_name_trimmed)) |entry| entry.value.Many else ArrayList([]const u8).init(allocator); // MergeN creation disallows 0 length flag entry (doesn't make sense) switch (flag_args) { @@ -129,7 +123,7 @@ pub const Args = struct { FlagArg.Many => |inner| try prev.appendSlice(inner.toSliceConst()), } - _ = try parsed.flags.put(flag_name_trimmed, FlagArg { .Many = prev }); + _ = try parsed.flags.put(flag_name_trimmed, FlagArg{ .Many = prev }); } else { _ = try parsed.flags.put(flag_name_trimmed, flag_args); } @@ -163,7 +157,9 @@ pub const Args = struct { pub fn single(self: &Args, name: []const u8) ?[]const u8 { if (self.flags.get(name)) |entry| { switch (entry.value) { - FlagArg.Single => |inner| { return inner; }, + FlagArg.Single => |inner| { + return inner; + }, else => @panic("attempted to retrieve flag with wrong type"), } } else { @@ -175,7 +171,9 @@ pub const Args = struct { pub fn many(self: &Args, name: []const u8) ?[]const []const u8 { if (self.flags.get(name)) |entry| { switch (entry.value) { - FlagArg.Many => |inner| { return inner.toSliceConst(); }, + FlagArg.Many => |inner| { + return inner.toSliceConst(); + }, else => @panic("attempted to retrieve flag with wrong type"), } } else { @@ -207,7 +205,7 @@ pub const Flag = struct { } pub fn ArgN(comptime name: []const u8, comptime n: usize) Flag { - return Flag { + return Flag{ .name = name, .required = n, .mergable = false, @@ -220,7 +218,7 @@ pub const Flag = struct { @compileError("n must be greater than 0"); } - return Flag { + return Flag{ .name = name, .required = n, .mergable = true, @@ -229,7 +227,7 @@ pub const Flag = struct { } pub fn Option(comptime name: []const u8, comptime set: []const []const u8) Flag { - return Flag { + return Flag{ .name = name, .required = 1, .mergable = false, @@ -239,26 +237,36 @@ pub const Flag = struct { }; test "parse arguments" { - const spec1 = comptime []const Flag { + const spec1 = comptime []const Flag{ Flag.Bool("--help"), Flag.Bool("--init"), Flag.Arg1("--build-file"), - Flag.Option("--color", []const []const u8 { "on", "off", "auto" }), + Flag.Option("--color", []const []const u8{ + "on", + "off", + "auto", + }), Flag.ArgN("--pkg-begin", 2), Flag.ArgMergeN("--object", 1), Flag.ArgN("--library", 1), }; - const cliargs = []const []const u8 { + const cliargs = []const []const u8{ "build", "--help", "pos1", - "--build-file", "build.zig", - "--object", "obj1", - "--object", "obj2", - "--library", "lib1", - "--library", "lib2", - "--color", "on", + "--build-file", + "build.zig", + "--object", + "obj1", + "--object", + "obj2", + "--library", + "lib1", + "--library", + "lib2", + "--color", + "on", "pos2", }; diff --git a/src-self-hosted/module.zig b/src-self-hosted/module.zig index ccbd683bdc..375e2e840b 100644 --- a/src-self-hosted/module.zig +++ b/src-self-hosted/module.zig @@ -96,6 +96,7 @@ pub const Module = struct { pub const LinkLib = struct { name: []const u8, path: ?[]const u8, + /// the list of symbols we depend on from this lib symbols: ArrayList([]u8), provided_explicitly: bool, @@ -130,9 +131,7 @@ pub const Module = struct { } }; - pub fn create(allocator: &mem.Allocator, name: []const u8, root_src_path: ?[]const u8, target: &const Target, - kind: Kind, build_mode: builtin.Mode, zig_lib_dir: []const u8, cache_dir: []const u8) !&Module - { + pub fn create(allocator: &mem.Allocator, name: []const u8, root_src_path: ?[]const u8, target: &const Target, kind: Kind, build_mode: builtin.Mode, zig_lib_dir: []const u8, cache_dir: []const u8) !&Module { var name_buffer = try Buffer.init(allocator, name); errdefer name_buffer.deinit(); @@ -148,14 +147,14 @@ pub const Module = struct { const module_ptr = try allocator.create(Module); errdefer allocator.destroy(module_ptr); - *module_ptr = Module { + module_ptr.* = Module{ .allocator = allocator, .name = name_buffer, .root_src_path = root_src_path, .module = module, .context = context, .builder = builder, - .target = *target, + .target = target.*, .kind = kind, .build_mode = build_mode, .zig_lib_dir = zig_lib_dir, @@ -221,8 +220,10 @@ pub const Module = struct { pub fn build(self: &Module) !void { if (self.llvm_argv.len != 0) { - var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.allocator, - [][]const []const u8 { [][]const u8{"zig (LLVM option parsing)"}, self.llvm_argv, }); + var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.allocator, [][]const []const u8{ + [][]const u8{"zig (LLVM option parsing)"}, + self.llvm_argv, + }); defer c_compatible_args.deinit(); c.ZigLLVMParseCommandLineOptions(self.llvm_argv.len + 1, c_compatible_args.ptr); } @@ -261,7 +262,6 @@ pub const Module = struct { warn("====llvm ir:====\n"); self.dump(); - } pub fn link(self: &Module, out_file: ?[]const u8) !void { @@ -285,7 +285,7 @@ pub const Module = struct { } const link_lib = try self.allocator.create(LinkLib); - *link_lib = LinkLib { + link_lib.* = LinkLib{ .name = name, .path = null, .provided_explicitly = provided_explicitly, diff --git a/src-self-hosted/target.zig b/src-self-hosted/target.zig index 375b48f10d..27a90bd096 100644 --- a/src-self-hosted/target.zig +++ b/src-self-hosted/target.zig @@ -12,7 +12,7 @@ pub const Target = union(enum) { Cross: CrossTarget, pub fn oFileExt(self: &const Target) []const u8 { - const environ = switch (*self) { + const environ = switch (self.*) { Target.Native => builtin.environ, Target.Cross => |t| t.environ, }; @@ -30,7 +30,7 @@ pub const Target = union(enum) { } pub fn getOs(self: &const Target) builtin.Os { - return switch (*self) { + return switch (self.*) { Target.Native => builtin.os, Target.Cross => |t| t.os, }; @@ -38,7 +38,8 @@ pub const Target = union(enum) { pub fn isDarwin(self: &const Target) bool { return switch (self.getOs()) { - builtin.Os.ios, builtin.Os.macosx => true, + builtin.Os.ios, + builtin.Os.macosx => true, else => false, }; } diff --git a/std/zig/ast.zig b/std/zig/ast.zig index 86135fe100..3c1d6a5e2e 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -1485,6 +1485,7 @@ pub const Node = struct { BitNot, BoolNot, Cancel, + PointerType, MaybeType, Negation, NegationWrap, diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 154cfc0e46..f4e819e544 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -3134,7 +3134,7 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op { Token.Id.Minus => ast.Node.PrefixOp.Op{ .Negation = void{} }, Token.Id.MinusPercent => ast.Node.PrefixOp.Op{ .NegationWrap = void{} }, Token.Id.Asterisk, - Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .Deref = void{} }, + Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .PointerType = void{} }, Token.Id.Ampersand => ast.Node.PrefixOp.Op{ .AddrOf = ast.Node.PrefixOp.AddrOfInfo{ .align_expr = null, .bit_offset_start_token = null, diff --git a/std/zig/render.zig b/std/zig/render.zig index f240be8716..91e76e1c5f 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -311,6 +311,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.PrefixOp.Op.Try => try stream.write("try "), ast.Node.PrefixOp.Op.UnwrapMaybe => try stream.write("??"), ast.Node.PrefixOp.Op.MaybeType => try stream.write("?"), + ast.Node.PrefixOp.Op.PointerType => try stream.write("*"), ast.Node.PrefixOp.Op.Await => try stream.write("await "), ast.Node.PrefixOp.Op.Cancel => try stream.write("cancel "), ast.Node.PrefixOp.Op.Resume => try stream.write("resume "), @@ -350,7 +351,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.write("]"); }, - ast.Node.SuffixOp.Op.SuffixOp => { + ast.Node.SuffixOp.Op.Deref => { try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); try stream.write(".*"); }, diff --git a/test/compare_output.zig b/test/compare_output.zig index 9595bf8259..b01e87d4eb 100644 --- a/test/compare_output.zig +++ b/test/compare_output.zig @@ -287,9 +287,9 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\export fn compare_fn(a: ?&const c_void, b: ?&const c_void) c_int { \\ const a_int = @ptrCast(&align(1) const i32, a ?? unreachable); \\ const b_int = @ptrCast(&align(1) const i32, b ?? unreachable); - \\ if (*a_int < *b_int) { + \\ if (a_int.* < b_int.*) { \\ return -1; - \\ } else if (*a_int > *b_int) { + \\ } else if (a_int.* > b_int.*) { \\ return 1; \\ } else { \\ return 0; diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 300f27cb6a..904ba6d9d8 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -4,7 +4,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add("invalid deref on switch target", \\comptime { \\ var tile = Tile.Empty; - \\ switch (*tile) { + \\ switch (tile.*) { \\ Tile.Empty => {}, \\ Tile.Filled => {}, \\ } @@ -14,7 +14,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ Filled, \\}; , - ".tmp_source.zig:3:13: error: invalid deref on switch target"); + ".tmp_source.zig:3:17: error: invalid deref on switch target"); cases.add("invalid field access in comptime", \\comptime { var x = doesnt_exist.whatever; } @@ -1408,14 +1408,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ Two: i32, \\}; \\fn bad_eql_2(a: &const EnumWithData, b: &const EnumWithData) bool { - \\ return *a == *b; + \\ return a.* == b.*; \\} \\ \\export fn entry1() usize { return @sizeOf(@typeOf(bad_eql_1)); } \\export fn entry2() usize { return @sizeOf(@typeOf(bad_eql_2)); } , ".tmp_source.zig:2:14: error: operator not allowed for type '[]u8'", - ".tmp_source.zig:9:15: error: operator not allowed for type 'EnumWithData'"); + ".tmp_source.zig:9:16: error: operator not allowed for type 'EnumWithData'"); cases.add("non-const switch number literal", \\export fn foo() void { @@ -1513,7 +1513,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\var bytes: [ext()]u8 = undefined; \\export fn f() void { \\ for (bytes) |*b, i| { - \\ *b = u8(i); + \\ b.* = u8(i); \\ } \\} , ".tmp_source.zig:2:13: error: unable to evaluate constant expression"); @@ -1819,7 +1819,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\fn bar(x: &const u3) u3 { - \\ return *x; + \\ return x.*; \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } @@ -1903,12 +1903,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\var s_buffer: [10]u8 = undefined; \\pub fn pass(in: []u8) []u8 { \\ var out = &s_buffer; - \\ *out[0] = in[0]; - \\ return (*out)[0..1]; + \\ out[0].* = in[0]; + \\ return out.*[0..1]; \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(pass)); } - , ".tmp_source.zig:4:5: error: attempt to dereference non pointer type '[10]u8'"); + , ".tmp_source.zig:4:11: error: attempt to dereference non pointer type '[10]u8'"); cases.add("pass const ptr to mutable ptr fn", \\fn foo() bool { @@ -2434,7 +2434,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\fn bar(x: &u32) void { - \\ *x += 1; + \\ x.* += 1; \\} , ".tmp_source.zig:8:13: error: expected type '&u32', found '&align(1) u32'"); @@ -2461,7 +2461,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry() u32 { \\ var bytes: [4]u8 = []u8{0x01, 0x02, 0x03, 0x04}; \\ const ptr = @ptrCast(&u32, &bytes[0]); - \\ return *ptr; + \\ return ptr.*; \\} , ".tmp_source.zig:3:17: error: cast increases pointer alignment", @@ -2540,14 +2540,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry(opaque: &Opaque) void { \\ var m2 = &2; - \\ const y: u32 = *m2; + \\ const y: u32 = m2.*; \\ \\ var a = undefined; \\ var b = 1; \\ var c = 1.0; \\ var d = this; \\ var e = null; - \\ var f = *opaque; + \\ var f = opaque.*; \\ var g = i32; \\ var h = @import("std"); \\ var i = (Foo {}).bar; @@ -3136,13 +3136,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ foo(a); \\} \\fn foo(a: &const Payload) void { - \\ switch (*a) { + \\ switch (a.*) { \\ Payload.A => {}, \\ else => unreachable, \\ } \\} , - ".tmp_source.zig:11:13: error: switch on union which has no attached enum", + ".tmp_source.zig:11:14: error: switch on union which has no attached enum", ".tmp_source.zig:1:17: note: consider 'union(enum)' here"); cases.add("enum in field count range but not matching tag", diff --git a/test/standalone/brace_expansion/main.zig b/test/standalone/brace_expansion/main.zig index d4d86ae12c..93089ae1ff 100644 --- a/test/standalone/brace_expansion/main.zig +++ b/test/standalone/brace_expansion/main.zig @@ -16,7 +16,7 @@ const Token = union(enum) { var global_allocator: &mem.Allocator = undefined; -fn tokenize(input:[] const u8) !ArrayList(Token) { +fn tokenize(input: []const u8) !ArrayList(Token) { const State = enum { Start, Word, @@ -29,7 +29,8 @@ fn tokenize(input:[] const u8) !ArrayList(Token) { for (input) |b, i| { switch (state) { State.Start => switch (b) { - 'a'...'z', 'A'...'Z' => { + 'a' ... 'z', + 'A' ... 'Z' => { state = State.Word; tok_begin = i; }, @@ -39,9 +40,12 @@ fn tokenize(input:[] const u8) !ArrayList(Token) { else => return error.InvalidInput, }, State.Word => switch (b) { - 'a'...'z', 'A'...'Z' => {}, - '{', '}', ',' => { - try token_list.append(Token { .Word = input[tok_begin..i] }); + 'a' ... 'z', + 'A' ... 'Z' => {}, + '{', + '}', + ',' => { + try token_list.append(Token{ .Word = input[tok_begin..i] }); switch (b) { '{' => try token_list.append(Token.OpenBrace), '}' => try token_list.append(Token.CloseBrace), @@ -56,7 +60,7 @@ fn tokenize(input:[] const u8) !ArrayList(Token) { } switch (state) { State.Start => {}, - State.Word => try token_list.append(Token {.Word = input[tok_begin..] }), + State.Word => try token_list.append(Token{ .Word = input[tok_begin..] }), } try token_list.append(Token.Eof); return token_list; @@ -68,24 +72,24 @@ const Node = union(enum) { Combine: []Node, }; -const ParseError = error { +const ParseError = error{ InvalidInput, OutOfMemory, }; fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node { - const first_token = tokens.items[*token_index]; - *token_index += 1; + const first_token = tokens.items[token_index.*]; + token_index.* += 1; const result_node = switch (first_token) { - Token.Word => |word| Node { .Scalar = word }, + Token.Word => |word| Node{ .Scalar = word }, Token.OpenBrace => blk: { var list = ArrayList(Node).init(global_allocator); while (true) { try list.append(try parse(tokens, token_index)); - const token = tokens.items[*token_index]; - *token_index += 1; + const token = tokens.items[token_index.*]; + token_index.* += 1; switch (token) { Token.CloseBrace => break, @@ -93,17 +97,18 @@ fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node { else => return error.InvalidInput, } } - break :blk Node { .List = list }; + break :blk Node{ .List = list }; }, else => return error.InvalidInput, }; - switch (tokens.items[*token_index]) { - Token.Word, Token.OpenBrace => { + switch (tokens.items[token_index.*]) { + Token.Word, + Token.OpenBrace => { const pair = try global_allocator.alloc(Node, 2); pair[0] = result_node; pair[1] = try parse(tokens, token_index); - return Node { .Combine = pair }; + return Node{ .Combine = pair }; }, else => return result_node, } @@ -137,13 +142,11 @@ fn expandString(input: []const u8, output: &Buffer) !void { } } -const ExpandNodeError = error { - OutOfMemory, -}; +const ExpandNodeError = error{OutOfMemory}; fn expandNode(node: &const Node, output: &ArrayList(Buffer)) ExpandNodeError!void { assert(output.len == 0); - switch (*node) { + switch (node.*) { Node.Scalar => |scalar| { try output.append(try Buffer.init(global_allocator, scalar)); }, diff --git a/test/tests.zig b/test/tests.zig index 5fbb56b736..b59b954122 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -27,18 +27,18 @@ const TestTarget = struct { environ: builtin.Environ, }; -const test_targets = []TestTarget { - TestTarget { +const test_targets = []TestTarget{ + TestTarget{ .os = builtin.Os.linux, .arch = builtin.Arch.x86_64, .environ = builtin.Environ.gnu, }, - TestTarget { + TestTarget{ .os = builtin.Os.macosx, .arch = builtin.Arch.x86_64, .environ = builtin.Environ.unknown, }, - TestTarget { + TestTarget{ .os = builtin.Os.windows, .arch = builtin.Arch.x86_64, .environ = builtin.Environ.msvc, @@ -49,7 +49,7 @@ const max_stdout_size = 1 * 1024 * 1024; // 1 MB pub fn addCompareOutputTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; - *cases = CompareOutputContext { + cases.* = CompareOutputContext{ .b = b, .step = b.step("test-compare-output", "Run the compare output tests"), .test_index = 0, @@ -63,7 +63,7 @@ pub fn addCompareOutputTests(b: &build.Builder, test_filter: ?[]const u8) &build pub fn addRuntimeSafetyTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; - *cases = CompareOutputContext { + cases.* = CompareOutputContext{ .b = b, .step = b.step("test-runtime-safety", "Run the runtime safety tests"), .test_index = 0, @@ -77,7 +77,7 @@ pub fn addRuntimeSafetyTests(b: &build.Builder, test_filter: ?[]const u8) &build pub fn addCompileErrorTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { const cases = b.allocator.create(CompileErrorContext) catch unreachable; - *cases = CompileErrorContext { + cases.* = CompileErrorContext{ .b = b, .step = b.step("test-compile-errors", "Run the compile error tests"), .test_index = 0, @@ -91,7 +91,7 @@ pub fn addCompileErrorTests(b: &build.Builder, test_filter: ?[]const u8) &build. pub fn addBuildExampleTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { const cases = b.allocator.create(BuildExamplesContext) catch unreachable; - *cases = BuildExamplesContext { + cases.* = BuildExamplesContext{ .b = b, .step = b.step("test-build-examples", "Build the examples"), .test_index = 0, @@ -105,7 +105,7 @@ pub fn addBuildExampleTests(b: &build.Builder, test_filter: ?[]const u8) &build. pub fn addAssembleAndLinkTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; - *cases = CompareOutputContext { + cases.* = CompareOutputContext{ .b = b, .step = b.step("test-asm-link", "Run the assemble and link tests"), .test_index = 0, @@ -119,7 +119,7 @@ pub fn addAssembleAndLinkTests(b: &build.Builder, test_filter: ?[]const u8) &bui pub fn addTranslateCTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { const cases = b.allocator.create(TranslateCContext) catch unreachable; - *cases = TranslateCContext { + cases.* = TranslateCContext{ .b = b, .step = b.step("test-translate-c", "Run the C transation tests"), .test_index = 0, @@ -133,7 +133,7 @@ pub fn addTranslateCTests(b: &build.Builder, test_filter: ?[]const u8) &build.St pub fn addGenHTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { const cases = b.allocator.create(GenHContext) catch unreachable; - *cases = GenHContext { + cases.* = GenHContext{ .b = b, .step = b.step("test-gen-h", "Run the C header file generation tests"), .test_index = 0, @@ -145,22 +145,26 @@ pub fn addGenHTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { return cases.step; } - -pub fn addPkgTests(b: &build.Builder, test_filter: ?[]const u8, root_src: []const u8, - name:[] const u8, desc: []const u8, with_lldb: bool) &build.Step -{ +pub fn addPkgTests(b: &build.Builder, test_filter: ?[]const u8, root_src: []const u8, name: []const u8, desc: []const u8, with_lldb: bool) &build.Step { const step = b.step(b.fmt("test-{}", name), desc); for (test_targets) |test_target| { const is_native = (test_target.os == builtin.os and test_target.arch == builtin.arch); - for ([]Mode{Mode.Debug, Mode.ReleaseSafe, Mode.ReleaseFast, Mode.ReleaseSmall}) |mode| { - for ([]bool{false, true}) |link_libc| { + for ([]Mode{ + Mode.Debug, + Mode.ReleaseSafe, + Mode.ReleaseFast, + Mode.ReleaseSmall, + }) |mode| { + for ([]bool{ + false, + true, + }) |link_libc| { if (link_libc and !is_native) { // don't assume we have a cross-compiling libc set up continue; } const these_tests = b.addTest(root_src); - these_tests.setNamePrefix(b.fmt("{}-{}-{}-{}-{} ", name, @tagName(test_target.os), - @tagName(test_target.arch), @tagName(mode), if (link_libc) "c" else "bare")); + these_tests.setNamePrefix(b.fmt("{}-{}-{}-{}-{} ", name, @tagName(test_target.os), @tagName(test_target.arch), @tagName(mode), if (link_libc) "c" else "bare")); these_tests.setFilter(test_filter); these_tests.setBuildMode(mode); if (!is_native) { @@ -171,7 +175,15 @@ pub fn addPkgTests(b: &build.Builder, test_filter: ?[]const u8, root_src: []cons } if (with_lldb) { these_tests.setExecCmd([]?[]const u8{ - "lldb", null, "-o", "run", "-o", "bt", "-o", "exit"}); + "lldb", + null, + "-o", + "run", + "-o", + "bt", + "-o", + "exit", + }); } step.dependOn(&these_tests.step); } @@ -206,7 +218,7 @@ pub const CompareOutputContext = struct { }; pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void { - self.sources.append(SourceFile { + self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; @@ -226,13 +238,10 @@ pub const CompareOutputContext = struct { test_index: usize, cli_args: []const []const u8, - pub fn create(context: &CompareOutputContext, exe_path: []const u8, - name: []const u8, expected_output: []const u8, - cli_args: []const []const u8) &RunCompareOutputStep - { + pub fn create(context: &CompareOutputContext, exe_path: []const u8, name: []const u8, expected_output: []const u8, cli_args: []const []const u8) &RunCompareOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(RunCompareOutputStep) catch unreachable; - *ptr = RunCompareOutputStep { + ptr.* = RunCompareOutputStep{ .context = context, .exe_path = exe_path, .name = name, @@ -258,7 +267,7 @@ pub const CompareOutputContext = struct { args.append(arg) catch unreachable; } - warn("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name); + warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); const child = os.ChildProcess.init(args.toSliceConst(), b.allocator) catch unreachable; defer child.deinit(); @@ -295,7 +304,6 @@ pub const CompareOutputContext = struct { }, } - if (!mem.eql(u8, self.expected_output, stdout.toSliceConst())) { warn( \\ @@ -318,12 +326,10 @@ pub const CompareOutputContext = struct { name: []const u8, test_index: usize, - pub fn create(context: &CompareOutputContext, exe_path: []const u8, - name: []const u8) &RuntimeSafetyRunStep - { + pub fn create(context: &CompareOutputContext, exe_path: []const u8, name: []const u8) &RuntimeSafetyRunStep { const allocator = context.b.allocator; const ptr = allocator.create(RuntimeSafetyRunStep) catch unreachable; - *ptr = RuntimeSafetyRunStep { + ptr.* = RuntimeSafetyRunStep{ .context = context, .exe_path = exe_path, .name = name, @@ -340,7 +346,7 @@ pub const CompareOutputContext = struct { const full_exe_path = b.pathFromRoot(self.exe_path); - warn("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name); + warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); const child = os.ChildProcess.init([][]u8{full_exe_path}, b.allocator) catch unreachable; defer child.deinit(); @@ -358,19 +364,16 @@ pub const CompareOutputContext = struct { switch (term) { Term.Exited => |code| { if (code != expected_exit_code) { - warn("\nProgram expected to exit with code {} " ++ - "but exited with code {}\n", expected_exit_code, code); + warn("\nProgram expected to exit with code {} " ++ "but exited with code {}\n", expected_exit_code, code); return error.TestFailed; } }, Term.Signal => |sig| { - warn("\nProgram expected to exit with code {} " ++ - "but instead signaled {}\n", expected_exit_code, sig); + warn("\nProgram expected to exit with code {} " ++ "but instead signaled {}\n", expected_exit_code, sig); return error.TestFailed; }, else => { - warn("\nProgram expected to exit with code {}" ++ - " but exited in an unexpected way\n", expected_exit_code); + warn("\nProgram expected to exit with code {}" ++ " but exited in an unexpected way\n", expected_exit_code); return error.TestFailed; }, } @@ -379,10 +382,8 @@ pub const CompareOutputContext = struct { } }; - pub fn createExtra(self: &CompareOutputContext, name: []const u8, source: []const u8, - expected_output: []const u8, special: Special) TestCase - { - var tc = TestCase { + pub fn createExtra(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8, special: Special) TestCase { + var tc = TestCase{ .name = name, .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator), .expected_output = expected_output, @@ -395,9 +396,7 @@ pub const CompareOutputContext = struct { return tc; } - pub fn create(self: &CompareOutputContext, name: []const u8, source: []const u8, - expected_output: []const u8) TestCase - { + pub fn create(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) TestCase { return createExtra(self, name, source, expected_output, Special.None); } @@ -431,8 +430,7 @@ pub const CompareOutputContext = struct { Special.Asm => { const annotated_case_name = fmt.allocPrint(self.b.allocator, "assemble-and-link {}", case.name) catch unreachable; if (self.test_filter) |filter| { - if (mem.indexOf(u8, annotated_case_name, filter) == null) - return; + if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const exe = b.addExecutable("test", null); @@ -444,19 +442,21 @@ pub const CompareOutputContext = struct { exe.step.dependOn(&write_src.step); } - const run_and_cmp_output = RunCompareOutputStep.create(self, exe.getOutputPath(), annotated_case_name, - case.expected_output, case.cli_args); + const run_and_cmp_output = RunCompareOutputStep.create(self, exe.getOutputPath(), annotated_case_name, case.expected_output, case.cli_args); run_and_cmp_output.step.dependOn(&exe.step); self.step.dependOn(&run_and_cmp_output.step); }, Special.None => { - for ([]Mode{Mode.Debug, Mode.ReleaseSafe, Mode.ReleaseFast, Mode.ReleaseSmall}) |mode| { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", - "compare-output", case.name, @tagName(mode)) catch unreachable; + for ([]Mode{ + Mode.Debug, + Mode.ReleaseSafe, + Mode.ReleaseFast, + Mode.ReleaseSmall, + }) |mode| { + const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", "compare-output", case.name, @tagName(mode)) catch unreachable; if (self.test_filter) |filter| { - if (mem.indexOf(u8, annotated_case_name, filter) == null) - continue; + if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } const exe = b.addExecutable("test", root_src); @@ -471,8 +471,7 @@ pub const CompareOutputContext = struct { exe.step.dependOn(&write_src.step); } - const run_and_cmp_output = RunCompareOutputStep.create(self, exe.getOutputPath(), - annotated_case_name, case.expected_output, case.cli_args); + const run_and_cmp_output = RunCompareOutputStep.create(self, exe.getOutputPath(), annotated_case_name, case.expected_output, case.cli_args); run_and_cmp_output.step.dependOn(&exe.step); self.step.dependOn(&run_and_cmp_output.step); @@ -481,8 +480,7 @@ pub const CompareOutputContext = struct { Special.RuntimeSafety => { const annotated_case_name = fmt.allocPrint(self.b.allocator, "safety {}", case.name) catch unreachable; if (self.test_filter) |filter| { - if (mem.indexOf(u8, annotated_case_name, filter) == null) - return; + if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const exe = b.addExecutable("test", root_src); @@ -524,7 +522,7 @@ pub const CompileErrorContext = struct { }; pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void { - self.sources.append(SourceFile { + self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; @@ -543,12 +541,10 @@ pub const CompileErrorContext = struct { case: &const TestCase, build_mode: Mode, - pub fn create(context: &CompileErrorContext, name: []const u8, - case: &const TestCase, build_mode: Mode) &CompileCmpOutputStep - { + pub fn create(context: &CompileErrorContext, name: []const u8, case: &const TestCase, build_mode: Mode) &CompileCmpOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(CompileCmpOutputStep) catch unreachable; - *ptr = CompileCmpOutputStep { + ptr.* = CompileCmpOutputStep{ .step = build.Step.init("CompileCmpOutput", allocator, make), .context = context, .name = name, @@ -586,7 +582,7 @@ pub const CompileErrorContext = struct { Mode.ReleaseSmall => zig_args.append("--release-small") catch unreachable, } - warn("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name); + warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); if (b.verbose) { printInvocation(zig_args.toSliceConst()); @@ -626,7 +622,6 @@ pub const CompileErrorContext = struct { }, } - const stdout = stdout_buf.toSliceConst(); const stderr = stderr_buf.toSliceConst(); @@ -666,11 +661,9 @@ pub const CompileErrorContext = struct { warn("\n"); } - pub fn create(self: &CompileErrorContext, name: []const u8, source: []const u8, - expected_lines: ...) &TestCase - { + pub fn create(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) &TestCase { const tc = self.b.allocator.create(TestCase) catch unreachable; - *tc = TestCase { + tc.* = TestCase{ .name = name, .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator), .expected_errors = ArrayList([]const u8).init(self.b.allocator), @@ -705,12 +698,13 @@ pub const CompileErrorContext = struct { pub fn addCase(self: &CompileErrorContext, case: &const TestCase) void { const b = self.b; - for ([]Mode{Mode.Debug, Mode.ReleaseFast}) |mode| { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {} ({})", - case.name, @tagName(mode)) catch unreachable; + for ([]Mode{ + Mode.Debug, + Mode.ReleaseFast, + }) |mode| { + const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {} ({})", case.name, @tagName(mode)) catch unreachable; if (self.test_filter) |filter| { - if (mem.indexOf(u8, annotated_case_name, filter) == null) - continue; + if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } const compile_and_cmp_errors = CompileCmpOutputStep.create(self, annotated_case_name, case, mode); @@ -744,8 +738,7 @@ pub const BuildExamplesContext = struct { const annotated_case_name = b.fmt("build {} (Debug)", build_file); if (self.test_filter) |filter| { - if (mem.indexOf(u8, annotated_case_name, filter) == null) - return; + if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } var zig_args = ArrayList([]const u8).init(b.allocator); @@ -773,12 +766,15 @@ pub const BuildExamplesContext = struct { pub fn addAllArgs(self: &BuildExamplesContext, root_src: []const u8, link_libc: bool) void { const b = self.b; - for ([]Mode{Mode.Debug, Mode.ReleaseSafe, Mode.ReleaseFast, Mode.ReleaseSmall}) |mode| { - const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {} ({})", - root_src, @tagName(mode)) catch unreachable; + for ([]Mode{ + Mode.Debug, + Mode.ReleaseSafe, + Mode.ReleaseFast, + Mode.ReleaseSmall, + }) |mode| { + const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {} ({})", root_src, @tagName(mode)) catch unreachable; if (self.test_filter) |filter| { - if (mem.indexOf(u8, annotated_case_name, filter) == null) - continue; + if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } const exe = b.addExecutable("test", root_src); @@ -813,7 +809,7 @@ pub const TranslateCContext = struct { }; pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void { - self.sources.append(SourceFile { + self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; @@ -834,7 +830,7 @@ pub const TranslateCContext = struct { pub fn create(context: &TranslateCContext, name: []const u8, case: &const TestCase) &TranslateCCmpOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(TranslateCCmpOutputStep) catch unreachable; - *ptr = TranslateCCmpOutputStep { + ptr.* = TranslateCCmpOutputStep{ .step = build.Step.init("ParseCCmpOutput", allocator, make), .context = context, .name = name, @@ -857,7 +853,7 @@ pub const TranslateCContext = struct { zig_args.append("translate-c") catch unreachable; zig_args.append(b.pathFromRoot(root_src)) catch unreachable; - warn("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name); + warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); if (b.verbose) { printInvocation(zig_args.toSliceConst()); @@ -939,11 +935,9 @@ pub const TranslateCContext = struct { warn("\n"); } - pub fn create(self: &TranslateCContext, allow_warnings: bool, filename: []const u8, name: []const u8, - source: []const u8, expected_lines: ...) &TestCase - { + pub fn create(self: &TranslateCContext, allow_warnings: bool, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) &TestCase { const tc = self.b.allocator.create(TestCase) catch unreachable; - *tc = TestCase { + tc.* = TestCase{ .name = name, .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator), .expected_lines = ArrayList([]const u8).init(self.b.allocator), @@ -977,8 +971,7 @@ pub const TranslateCContext = struct { const annotated_case_name = fmt.allocPrint(self.b.allocator, "translate-c {}", case.name) catch unreachable; if (self.test_filter) |filter| { - if (mem.indexOf(u8, annotated_case_name, filter) == null) - return; + if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const translate_c_and_cmp = TranslateCCmpOutputStep.create(self, annotated_case_name, case); @@ -1009,7 +1002,7 @@ pub const GenHContext = struct { }; pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void { - self.sources.append(SourceFile { + self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; @@ -1031,7 +1024,7 @@ pub const GenHContext = struct { pub fn create(context: &GenHContext, h_path: []const u8, name: []const u8, case: &const TestCase) &GenHCmpOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(GenHCmpOutputStep) catch unreachable; - *ptr = GenHCmpOutputStep { + ptr.* = GenHCmpOutputStep{ .step = build.Step.init("ParseCCmpOutput", allocator, make), .context = context, .h_path = h_path, @@ -1047,7 +1040,7 @@ pub const GenHContext = struct { const self = @fieldParentPtr(GenHCmpOutputStep, "step", step); const b = self.context.b; - warn("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name); + warn("Test {}/{} {}...", self.test_index + 1, self.context.test_index, self.name); const full_h_path = b.pathFromRoot(self.h_path); const actual_h = try io.readFileAlloc(b.allocator, full_h_path); @@ -1076,11 +1069,9 @@ pub const GenHContext = struct { warn("\n"); } - pub fn create(self: &GenHContext, filename: []const u8, name: []const u8, - source: []const u8, expected_lines: ...) &TestCase - { + pub fn create(self: &GenHContext, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) &TestCase { const tc = self.b.allocator.create(TestCase) catch unreachable; - *tc = TestCase { + tc.* = TestCase{ .name = name, .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator), .expected_lines = ArrayList([]const u8).init(self.b.allocator), @@ -1105,8 +1096,7 @@ pub const GenHContext = struct { const mode = builtin.Mode.Debug; const annotated_case_name = fmt.allocPrint(self.b.allocator, "gen-h {} ({})", case.name, @tagName(mode)) catch unreachable; if (self.test_filter) |filter| { - if (mem.indexOf(u8, annotated_case_name, filter) == null) - return; + if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const obj = b.addObject("test", root_src); diff --git a/test/translate_c.zig b/test/translate_c.zig index 2cd59f6f75..2054cfa246 100644 --- a/test/translate_c.zig +++ b/test/translate_c.zig @@ -720,43 +720,43 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ var a: c_int = 0; \\ a += x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) + 1); - \\ break :x *_ref; + \\ _ref.* = (_ref.* + 1); + \\ break :x _ref.*; \\ }; \\ a -= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) - 1); - \\ break :x *_ref; + \\ _ref.* = (_ref.* - 1); + \\ break :x _ref.*; \\ }; \\ a *= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) * 1); - \\ break :x *_ref; + \\ _ref.* = (_ref.* * 1); + \\ break :x _ref.*; \\ }; \\ a &= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) & 1); - \\ break :x *_ref; + \\ _ref.* = (_ref.* & 1); + \\ break :x _ref.*; \\ }; \\ a |= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) | 1); - \\ break :x *_ref; + \\ _ref.* = (_ref.* | 1); + \\ break :x _ref.*; \\ }; \\ a ^= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) ^ 1); - \\ break :x *_ref; + \\ _ref.* = (_ref.* ^ 1); + \\ break :x _ref.*; \\ }; \\ a >>= @import("std").math.Log2Int(c_int)(x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) >> @import("std").math.Log2Int(c_int)(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* >> @import("std").math.Log2Int(c_int)(1)); + \\ break :x _ref.*; \\ }); \\ a <<= @import("std").math.Log2Int(c_int)(x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) << @import("std").math.Log2Int(c_int)(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* << @import("std").math.Log2Int(c_int)(1)); + \\ break :x _ref.*; \\ }); \\} ); @@ -778,43 +778,43 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ var a: c_uint = c_uint(0); \\ a +%= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) +% c_uint(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* +% c_uint(1)); + \\ break :x _ref.*; \\ }; \\ a -%= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) -% c_uint(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* -% c_uint(1)); + \\ break :x _ref.*; \\ }; \\ a *%= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) *% c_uint(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* *% c_uint(1)); + \\ break :x _ref.*; \\ }; \\ a &= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) & c_uint(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* & c_uint(1)); + \\ break :x _ref.*; \\ }; \\ a |= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) | c_uint(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* | c_uint(1)); + \\ break :x _ref.*; \\ }; \\ a ^= x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) ^ c_uint(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* ^ c_uint(1)); + \\ break :x _ref.*; \\ }; \\ a >>= @import("std").math.Log2Int(c_uint)(x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) >> @import("std").math.Log2Int(c_uint)(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* >> @import("std").math.Log2Int(c_uint)(1)); + \\ break :x _ref.*; \\ }); \\ a <<= @import("std").math.Log2Int(c_uint)(x: { \\ const _ref = &a; - \\ (*_ref) = ((*_ref) << @import("std").math.Log2Int(c_uint)(1)); - \\ break :x *_ref; + \\ _ref.* = (_ref.* << @import("std").math.Log2Int(c_uint)(1)); + \\ break :x _ref.*; \\ }); \\} ); @@ -853,26 +853,26 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ u -%= 1; \\ i = x: { \\ const _ref = &i; - \\ const _tmp = *_ref; - \\ (*_ref) += 1; + \\ const _tmp = _ref.*; + \\ _ref.* += 1; \\ break :x _tmp; \\ }; \\ i = x: { \\ const _ref = &i; - \\ const _tmp = *_ref; - \\ (*_ref) -= 1; + \\ const _tmp = _ref.*; + \\ _ref.* -= 1; \\ break :x _tmp; \\ }; \\ u = x: { \\ const _ref = &u; - \\ const _tmp = *_ref; - \\ (*_ref) +%= 1; + \\ const _tmp = _ref.*; + \\ _ref.* +%= 1; \\ break :x _tmp; \\ }; \\ u = x: { \\ const _ref = &u; - \\ const _tmp = *_ref; - \\ (*_ref) -%= 1; + \\ const _tmp = _ref.*; + \\ _ref.* -%= 1; \\ break :x _tmp; \\ }; \\} @@ -901,23 +901,23 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ u -%= 1; \\ i = x: { \\ const _ref = &i; - \\ (*_ref) += 1; - \\ break :x *_ref; + \\ _ref.* += 1; + \\ break :x _ref.*; \\ }; \\ i = x: { \\ const _ref = &i; - \\ (*_ref) -= 1; - \\ break :x *_ref; + \\ _ref.* -= 1; + \\ break :x _ref.*; \\ }; \\ u = x: { \\ const _ref = &u; - \\ (*_ref) +%= 1; - \\ break :x *_ref; + \\ _ref.* +%= 1; + \\ break :x _ref.*; \\ }; \\ u = x: { \\ const _ref = &u; - \\ (*_ref) -%= 1; - \\ break :x *_ref; + \\ _ref.* -%= 1; + \\ break :x _ref.*; \\ }; \\} ); @@ -985,7 +985,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\} , \\pub export fn foo(x: ?&c_int) void { - \\ (*??x) = 1; + \\ (??x).* = 1; \\} ); @@ -1013,7 +1013,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\pub fn foo() c_int { \\ var x: c_int = 1234; \\ var ptr: ?&c_int = &x; - \\ return *??ptr; + \\ return (??ptr).*; \\} ); From bfbe26734d4167977fff0d675ff55c68d75dd3be Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 20 May 2018 14:50:27 -0400 Subject: [PATCH 28/75] zig fmt: add pointer deref syntax --- std/zig/parse.zig | 11 +++++++++++ std/zig/parser_test.zig | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/std/zig/parse.zig b/std/zig/parse.zig index f4e819e544..865ece6f5d 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -2195,6 +2195,17 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Period => { + if (eatToken(&tok_it, &tree, Token.Id.Asterisk)) |asterisk_token| { + const node = try arena.construct(ast.Node.SuffixOp{ + .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, + .lhs = lhs, + .op = ast.Node.SuffixOp.Op.Deref, + .rtoken = asterisk_token, + }); + opt_ctx.store(&node.base); + stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + continue; + } const node = try arena.construct(ast.Node.InfixOp{ .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 094c4d51f7..63d56167e8 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,10 @@ +test "zig fmt: ptr deref operator" { + try testCanonical( + \\const a = b.*; + \\ + ); +} + test "zig fmt: comment after if before another if" { try testCanonical( \\test "aoeu" { From 698c52e7961a78e68be39f4a6216f5c3d55f4f3f Mon Sep 17 00:00:00 2001 From: Marc Tiehuis Date: Tue, 22 May 2018 15:32:17 +1200 Subject: [PATCH 29/75] Make StreamingJsonParser public --- std/json.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/std/json.zig b/std/json.zig index 2ea9083e2f..b73397cd26 100644 --- a/std/json.zig +++ b/std/json.zig @@ -86,7 +86,7 @@ pub const Token = struct { // parsing state requires ~40-50 bytes of stack space. // // Conforms strictly to RFC8529. -const StreamingJsonParser = struct { +pub const StreamingJsonParser = struct { // Current state state: State, // How many bytes we have counted for the current token From 4f4afe186d854fb81aca7db4862c366271f24d06 Mon Sep 17 00:00:00 2001 From: Marc Tiehuis Date: Tue, 22 May 2018 15:34:17 +1200 Subject: [PATCH 30/75] Make JsonParser public --- std/json.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/std/json.zig b/std/json.zig index b73397cd26..e969899403 100644 --- a/std/json.zig +++ b/std/json.zig @@ -1053,7 +1053,7 @@ pub const Value = union(enum) { }; // A non-stream JSON parser which constructs a tree of Value's. -const JsonParser = struct { +pub const JsonParser = struct { allocator: &Allocator, state: State, copy_strings: bool, From b132a17a749c27040c7fed43b268c2f0d9a401ce Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 20 May 2018 21:59:20 -0400 Subject: [PATCH 31/75] std.zig.parse ignores comments std.zig.render handles comments by looking at nearby tokens --- README.md | 3 + std/zig/ast.zig | 81 ++- std/zig/parse.zig | 255 ++++----- std/zig/parser_test.zig | 89 ++- std/zig/render.zig | 1170 ++++++++++++++++++++++----------------- 5 files changed, 898 insertions(+), 700 deletions(-) diff --git a/README.md b/README.md index 552b784a50..cf4d8179c7 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,9 @@ binary. This is the actual compiler binary that we will install to the system. +*Note: Stage 2 compiler is not yet able to build Stage 3. Building Stage 3 is +not yet supported.* + #### Debug / Development Build ``` diff --git a/std/zig/ast.zig b/std/zig/ast.zig index 3c1d6a5e2e..c1552b0220 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -71,6 +71,24 @@ pub const Tree = struct { pub fn dump(self: &Tree) void { self.root_node.base.dump(0); } + + /// Skips over comments + pub fn prevToken(self: &Tree, token_index: TokenIndex) TokenIndex { + var index = token_index - 1; + while (self.tokens.at(index).id == Token.Id.LineComment) { + index -= 1; + } + return index; + } + + /// Skips over comments + pub fn nextToken(self: &Tree, token_index: TokenIndex) TokenIndex { + var index = token_index + 1; + while (self.tokens.at(index).id == Token.Id.LineComment) { + index += 1; + } + return index; + } }; pub const Error = union(enum) { @@ -272,7 +290,6 @@ pub const Node = struct { Block, // Misc - LineComment, DocComment, SwitchCase, SwitchElse, @@ -359,7 +376,6 @@ pub const Node = struct { Id.SwitchElse, Id.FieldInitializer, Id.DocComment, - Id.LineComment, Id.TestDecl => return false, Id.While => { const while_node = @fieldParentPtr(While, "base", n); @@ -506,6 +522,7 @@ pub const Node = struct { base: Node, doc_comments: ?&DocComment, visib_token: ?TokenIndex, + use_token: TokenIndex, expr: &Node, semicolon_token: TokenIndex, @@ -520,7 +537,7 @@ pub const Node = struct { pub fn firstToken(self: &Use) TokenIndex { if (self.visib_token) |visib_token| return visib_token; - return self.expr.firstToken(); + return self.use_token; } pub fn lastToken(self: &Use) TokenIndex { @@ -556,27 +573,15 @@ pub const Node = struct { pub const ContainerDecl = struct { base: Node, - ltoken: TokenIndex, - layout: Layout, - kind: Kind, + layout_token: ?TokenIndex, + kind_token: TokenIndex, init_arg_expr: InitArg, fields_and_decls: DeclList, + lbrace_token: TokenIndex, rbrace_token: TokenIndex, pub const DeclList = Root.DeclList; - const Layout = enum { - Auto, - Extern, - Packed, - }; - - const Kind = enum { - Struct, - Enum, - Union, - }; - const InitArg = union(enum) { None, Enum: ?&Node, @@ -602,7 +607,10 @@ pub const Node = struct { } pub fn firstToken(self: &ContainerDecl) TokenIndex { - return self.ltoken; + if (self.layout_token) |layout_token| { + return layout_token; + } + return self.kind_token; } pub fn lastToken(self: &ContainerDecl) TokenIndex { @@ -1113,7 +1121,7 @@ pub const Node = struct { switch_token: TokenIndex, expr: &Node, - /// these can be SwitchCase nodes or LineComment nodes + /// these must be SwitchCase nodes cases: CaseList, rbrace: TokenIndex, @@ -1143,6 +1151,7 @@ pub const Node = struct { pub const SwitchCase = struct { base: Node, items: ItemList, + arrow_token: TokenIndex, payload: ?&Node, expr: &Node, @@ -1963,9 +1972,11 @@ pub const Node = struct { pub const AsmOutput = struct { base: Node, + lbracket: TokenIndex, symbolic_name: &Node, constraint: &Node, kind: Kind, + rparen: TokenIndex, const Kind = union(enum) { Variable: &Identifier, @@ -1996,22 +2007,21 @@ pub const Node = struct { } pub fn firstToken(self: &AsmOutput) TokenIndex { - return self.symbolic_name.firstToken(); + return self.lbracket; } pub fn lastToken(self: &AsmOutput) TokenIndex { - return switch (self.kind) { - Kind.Variable => |variable_name| variable_name.lastToken(), - Kind.Return => |return_type| return_type.lastToken(), - }; + return self.rparen; } }; pub const AsmInput = struct { base: Node, + lbracket: TokenIndex, symbolic_name: &Node, constraint: &Node, expr: &Node, + rparen: TokenIndex, pub fn iterate(self: &AsmInput, index: usize) ?&Node { var i = index; @@ -2029,11 +2039,11 @@ pub const Node = struct { } pub fn firstToken(self: &AsmInput) TokenIndex { - return self.symbolic_name.firstToken(); + return self.lbracket; } pub fn lastToken(self: &AsmInput) TokenIndex { - return self.expr.lastToken(); + return self.rparen; } }; @@ -2126,23 +2136,6 @@ pub const Node = struct { } }; - pub const LineComment = struct { - base: Node, - token: TokenIndex, - - pub fn iterate(self: &LineComment, index: usize) ?&Node { - return null; - } - - pub fn firstToken(self: &LineComment) TokenIndex { - return self.token; - } - - pub fn lastToken(self: &LineComment) TokenIndex { - return self.token; - } - }; - pub const DocComment = struct { base: Node, lines: LineList, diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 865ece6f5d..826ea2c3e1 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -49,10 +49,6 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { switch (state) { State.TopLevel => { - while (try eatLineComment(arena, &tok_it, &tree)) |line_comment| { - try root_node.decls.push(&line_comment.base); - } - const comments = try eatDocComments(arena, &tok_it, &tree); const token = nextToken(&tok_it, &tree); @@ -80,7 +76,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .Block = block }); try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ .id = Token.Id.LBrace, - .ptr = &block.rbrace, + .ptr = &block.lbrace, } }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &test_node.name } }); continue; @@ -121,12 +117,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .Block = block }); try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ .id = Token.Id.LBrace, - .ptr = &block.rbrace, + .ptr = &block.lbrace, } }); continue; }, else => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); stack.append(State.TopLevel) catch unreachable; try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ .decls = &root_node.decls, @@ -172,7 +168,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); stack.append(State{ .TopLevelDecl = ctx }) catch unreachable; continue; }, @@ -184,7 +180,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lib_name_token_index = lib_name_token.index; const lib_name_token_ptr = lib_name_token.ptr; break :blk (try parseStringLiteral(arena, &tok_it, lib_name_token_ptr, lib_name_token_index, &tree)) ?? { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); break :blk null; }; }; @@ -211,6 +207,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const node = try arena.construct(ast.Node.Use{ .base = ast.Node{ .id = ast.Node.Id.Use }, + .use_token = token_index, .visib_token = ctx.visib_token, .expr = undefined, .semicolon_token = undefined, @@ -310,7 +307,6 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.TopLevelExternOrField => |ctx| { if (eatToken(&tok_it, &tree, Token.Id.Identifier)) |identifier| { - std.debug.assert(ctx.container_decl.kind == ast.Node.ContainerDecl.Kind.Struct); const node = try arena.construct(ast.Node.StructField{ .base = ast.Node{ .id = ast.Node.Id.StructField }, .doc_comments = ctx.comments, @@ -343,7 +339,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const eq_tok_index = eq_tok.index; const eq_tok_ptr = eq_tok.ptr; if (eq_tok_ptr.id != Token.Id.Equal) { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } stack.append(State{ .Expression = ctx }) catch unreachable; @@ -356,12 +352,11 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; const node = try arena.construct(ast.Node.ContainerDecl{ .base = ast.Node{ .id = ast.Node.Id.ContainerDecl }, - .ltoken = ctx.ltoken, - .layout = ctx.layout, - .kind = switch (token_ptr.id) { - Token.Id.Keyword_struct => ast.Node.ContainerDecl.Kind.Struct, - Token.Id.Keyword_union => ast.Node.ContainerDecl.Kind.Union, - Token.Id.Keyword_enum => ast.Node.ContainerDecl.Kind.Enum, + .layout_token = ctx.layout_token, + .kind_token = switch (token_ptr.id) { + Token.Id.Keyword_struct, + Token.Id.Keyword_union, + Token.Id.Keyword_enum => token_index, else => { ((try tree.errors.addOne())).* = Error{ .ExpectedAggregateKw = Error.ExpectedAggregateKw{ .token = token_index } }; return tree; @@ -369,12 +364,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, .init_arg_expr = ast.Node.ContainerDecl.InitArg.None, .fields_and_decls = ast.Node.ContainerDecl.DeclList.init(arena), + .lbrace_token = undefined, .rbrace_token = undefined, }); ctx.opt_ctx.store(&node.base); stack.append(State{ .ContainerDecl = node }) catch unreachable; - try stack.append(State{ .ExpectToken = Token.Id.LBrace }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &node.lbrace_token, + } }); try stack.append(State{ .ContainerInitArgStart = node }); continue; }, @@ -403,11 +402,11 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .ExpectToken = Token.Id.RParen }); try stack.append(State{ .Expression = OptionalCtx{ .RequiredNull = &container_decl.init_arg_expr.Enum } }); } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); } }, else => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); container_decl.init_arg_expr = ast.Node.ContainerDecl.InitArg{ .Type = undefined }; stack.append(State{ .Expression = OptionalCtx{ .Required = &container_decl.init_arg_expr.Type } }) catch unreachable; }, @@ -416,18 +415,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.ContainerDecl => |container_decl| { - while (try eatLineComment(arena, &tok_it, &tree)) |line_comment| { - try container_decl.fields_and_decls.push(&line_comment.base); - } - const comments = try eatDocComments(arena, &tok_it, &tree); const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Identifier => { - switch (container_decl.kind) { - ast.Node.ContainerDecl.Kind.Struct => { + switch (tree.tokens.at(container_decl.kind_token).id) { + Token.Id.Keyword_struct => { const node = try arena.construct(ast.Node.StructField{ .base = ast.Node{ .id = ast.Node.Id.StructField }, .doc_comments = comments, @@ -443,7 +438,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .ExpectToken = Token.Id.Colon }); continue; }, - ast.Node.ContainerDecl.Kind.Union => { + Token.Id.Keyword_union => { const node = try arena.construct(ast.Node.UnionTag{ .base = ast.Node{ .id = ast.Node.Id.UnionTag }, .name_token = token_index, @@ -459,7 +454,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .IfToken = Token.Id.Colon }); continue; }, - ast.Node.ContainerDecl.Kind.Enum => { + Token.Id.Keyword_enum => { const node = try arena.construct(ast.Node.EnumTag{ .base = ast.Node{ .id = ast.Node.Id.EnumTag }, .name_token = token_index, @@ -473,11 +468,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .IfToken = Token.Id.Equal }); continue; }, + else => unreachable, } }, Token.Id.Keyword_pub => { - switch (container_decl.kind) { - ast.Node.ContainerDecl.Kind.Struct => { + switch (tree.tokens.at(container_decl.kind_token).id) { + Token.Id.Keyword_struct => { try stack.append(State{ .TopLevelExternOrField = TopLevelExternOrFieldCtx{ .visib_token = token_index, .container_decl = container_decl, @@ -518,7 +514,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ .decls = &container_decl.fields_and_decls, @@ -573,7 +569,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; }, State.VarDeclEq => |var_decl| { @@ -616,7 +612,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { if (loc.line == 0) { try pushDocComment(arena, doc_comment_token, &var_decl.doc_comments); } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); } } }, @@ -688,7 +684,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } } - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); fn_proto.return_type = ast.Node.FnProto.ReturnType{ .Explicit = undefined }; stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &fn_proto.return_type.Explicit } }) catch unreachable; continue; @@ -733,7 +729,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { if (eatToken(&tok_it, &tree, Token.Id.Colon)) |_| { param_decl.name_token = ident_token; } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); } } continue; @@ -838,7 +834,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { return tree; } - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; }, } @@ -872,7 +868,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { return tree; } - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; }, } @@ -927,11 +923,6 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, State.Else => |dest| { - const old_index = tok_it.index; - var need_index_restore = false; - while (try eatLineComment(arena, &tok_it, &tree)) |_| { - need_index_restore = true; - } if (eatToken(&tok_it, &tree, Token.Id.Keyword_else)) |else_token| { const node = try arena.construct(ast.Node.Else{ .base = ast.Node{ .id = ast.Node.Id.Else }, @@ -945,9 +936,6 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .Payload = OptionalCtx{ .Optional = &node.payload } }); continue; } else { - if (need_index_restore) { - tok_it.set(old_index); - } continue; } }, @@ -962,16 +950,9 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); stack.append(State{ .Block = block }) catch unreachable; - var any_comments = false; - while (try eatLineComment(arena, &tok_it, &tree)) |line_comment| { - try block.statements.push(&line_comment.base); - any_comments = true; - } - if (any_comments) continue; - try stack.append(State{ .Statement = block }); continue; }, @@ -1035,7 +1016,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); const statement = try block.statements.addOne(); try stack.append(State{ .Semicolon = statement }); try stack.append(State{ .AssignmentExpressionBegin = OptionalCtx{ .Required = statement } }); @@ -1062,8 +1043,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - putBackToken(&tok_it, &tree); - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); + prevToken(&tok_it, &tree); const statement = try ctx.block.statements.addOne(); try stack.append(State{ .Semicolon = statement }); try stack.append(State{ .Expression = OptionalCtx{ .Required = statement } }); @@ -1085,21 +1066,26 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lbracket_index = lbracket.index; const lbracket_ptr = lbracket.ptr; if (lbracket_ptr.id != Token.Id.LBracket) { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } const node = try arena.construct(ast.Node.AsmOutput{ .base = ast.Node{ .id = ast.Node.Id.AsmOutput }, + .lbracket = lbracket_index, .symbolic_name = undefined, .constraint = undefined, .kind = undefined, + .rparen = undefined, }); try items.push(node); stack.append(State{ .AsmOutputItems = items }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.Comma }); - try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + } }); try stack.append(State{ .AsmOutputReturnOrType = node }); try stack.append(State{ .ExpectToken = Token.Id.LParen }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } }); @@ -1132,21 +1118,26 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const lbracket_index = lbracket.index; const lbracket_ptr = lbracket.ptr; if (lbracket_ptr.id != Token.Id.LBracket) { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } const node = try arena.construct(ast.Node.AsmInput{ .base = ast.Node{ .id = ast.Node.Id.AsmInput }, + .lbracket = lbracket_index, .symbolic_name = undefined, .constraint = undefined, .expr = undefined, + .rparen = undefined, }); try items.push(node); stack.append(State{ .AsmInputItems = items }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.Comma }); - try stack.append(State{ .ExpectToken = Token.Id.RParen }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + } }); try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); try stack.append(State{ .ExpectToken = Token.Id.LParen }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } }); @@ -1187,10 +1178,6 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, State.FieldInitListItemOrEnd => |list_state| { - while (try eatLineComment(arena, &tok_it, &tree)) |line_comment| { - try list_state.list.push(&line_comment.base); - } - if (eatToken(&tok_it, &tree, Token.Id.RBrace)) |rbrace| { (list_state.ptr).* = rbrace; continue; @@ -1248,10 +1235,6 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, State.ErrorTagListItemOrEnd => |list_state| { - while (try eatLineComment(arena, &tok_it, &tree)) |line_comment| { - try list_state.list.push(&line_comment.base); - } - if (eatToken(&tok_it, &tree, Token.Id.RBrace)) |rbrace| { (list_state.ptr).* = rbrace; continue; @@ -1279,10 +1262,6 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, State.SwitchCaseOrEnd => |list_state| { - while (try eatLineComment(arena, &tok_it, &tree)) |line_comment| { - try list_state.list.push(&line_comment.base); - } - if (eatToken(&tok_it, &tree, Token.Id.RBrace)) |rbrace| { (list_state.ptr).* = rbrace; continue; @@ -1294,12 +1273,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .items = ast.Node.SwitchCase.ItemList.init(arena), .payload = null, .expr = undefined, + .arrow_token = undefined, }); try list_state.list.push(&node.base); try stack.append(State{ .SwitchCaseCommaOrEnd = list_state }); try stack.append(State{ .AssignmentExpressionBegin = OptionalCtx{ .Required = &node.expr } }); try stack.append(State{ .PointerPayload = OptionalCtx{ .Optional = &node.payload } }); - try stack.append(State{ .SwitchCaseFirstItem = &node.items }); + try stack.append(State{ .SwitchCaseFirstItem = node }); continue; }, @@ -1320,7 +1300,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }, - State.SwitchCaseFirstItem => |case_items| { + State.SwitchCaseFirstItem => |switch_case| { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; @@ -1329,25 +1309,30 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .base = ast.Node{ .id = ast.Node.Id.SwitchElse }, .token = token_index, }); - try case_items.push(&else_node.base); + try switch_case.items.push(&else_node.base); - try stack.append(State{ .ExpectToken = Token.Id.EqualAngleBracketRight }); + try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.EqualAngleBracketRight, + .ptr = &switch_case.arrow_token, + } }); continue; } else { - putBackToken(&tok_it, &tree); - try stack.append(State{ .SwitchCaseItem = case_items }); + prevToken(&tok_it, &tree); + try stack.append(State{ .SwitchCaseItem = switch_case }); continue; } }, - State.SwitchCaseItem => |case_items| { - stack.append(State{ .SwitchCaseItemCommaOrEnd = case_items }) catch unreachable; - try stack.append(State{ .RangeExpressionBegin = OptionalCtx{ .Required = try case_items.addOne() } }); + State.SwitchCaseItem => |node| { + stack.append(State{ .SwitchCaseItemCommaOrEnd = node }) catch unreachable; + try stack.append(State{ .RangeExpressionBegin = OptionalCtx{ .Required = try node.items.addOne() } }); }, - State.SwitchCaseItemCommaOrEnd => |case_items| { + State.SwitchCaseItemCommaOrEnd => |node| { switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.EqualAngleBracketRight)) { - ExpectCommaOrEndResult.end_token => |t| { - if (t == null) { - stack.append(State{ .SwitchCaseItem = case_items }) catch unreachable; + ExpectCommaOrEndResult.end_token => |end_token| { + if (end_token) |t| { + node.arrow_token = t; + } else { + stack.append(State{ .SwitchCaseItem = node }) catch unreachable; } continue; }, @@ -1429,8 +1414,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .ContainerKind = ContainerKindCtx{ .opt_ctx = ctx.opt_ctx, - .ltoken = ctx.extern_token, - .layout = ast.Node.ContainerDecl.Layout.Extern, + .layout_token = ctx.extern_token, } }) catch unreachable; continue; }, @@ -1518,7 +1502,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; }, } @@ -1537,7 +1521,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { return tree; } - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } @@ -1569,7 +1553,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { return tree; } - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } @@ -1606,7 +1590,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { return tree; } - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } @@ -1691,7 +1675,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, else => { if (!try parseBlockExpr(&stack, arena, opt_ctx, token_ptr, token_index)) { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); stack.append(State{ .UnwrapExpressionBegin = opt_ctx }) catch unreachable; } continue; @@ -1744,7 +1728,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.rhs } }); continue; } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } }, @@ -1779,7 +1763,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } continue; } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } }, @@ -1857,7 +1841,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .BinaryOrExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } }, @@ -1959,7 +1943,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .AdditionExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } }, @@ -1989,7 +1973,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .MultiplyExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } }, @@ -2019,7 +2003,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .CurlySuffixExpressionBegin = OptionalCtx{ .Required = &node.rhs } }); continue; } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } }, @@ -2124,7 +2108,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } continue; } else { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); stack.append(State{ .SuffixOpExpressionBegin = opt_ctx }) catch unreachable; continue; } @@ -2220,7 +2204,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, else => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; }, } @@ -2277,7 +2261,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const next_token_index = next_token.index; const next_token_ptr = next_token.ptr; if (next_token_ptr.id != Token.Id.Arrow) { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); continue; } node.result = ast.Node.PromiseType.Result{ @@ -2348,8 +2332,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_packed => { stack.append(State{ .ContainerKind = ContainerKindCtx{ .opt_ctx = opt_ctx, - .ltoken = token.index, - .layout = ast.Node.ContainerDecl.Layout.Packed, + .layout_token = token.index, } }) catch unreachable; continue; }, @@ -2364,11 +2347,10 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_struct, Token.Id.Keyword_union, Token.Id.Keyword_enum => { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); stack.append(State{ .ContainerKind = ContainerKindCtx{ .opt_ctx = opt_ctx, - .ltoken = token.index, - .layout = ast.Node.ContainerDecl.Layout.Auto, + .layout_token = null, } }) catch unreachable; continue; }, @@ -2466,7 +2448,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, else => { if (!try parseBlockExpr(&stack, arena, opt_ctx, token.ptr, token.index)) { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); if (opt_ctx != OptionalCtx.Optional) { ((try tree.errors.addOne())).* = Error{ .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr{ .token = token.index } }; return tree; @@ -2502,7 +2484,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; opt_ctx.store((try parseStringLiteral(arena, &tok_it, token_ptr, token_index, &tree)) ?? { - putBackToken(&tok_it, &tree); + prevToken(&tok_it, &tree); if (opt_ctx != OptionalCtx.Optional) { ((try tree.errors.addOne())).* = Error{ .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr{ .token = token_index } }; return tree; @@ -2576,7 +2558,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } }; return tree; } - (expect_token_save.ptr).* = token_index; + expect_token_save.ptr.* = token_index; continue; }, State.IfToken => |token_id| { @@ -2645,8 +2627,7 @@ const ExternTypeCtx = struct { const ContainerKindCtx = struct { opt_ctx: OptionalCtx, - ltoken: TokenIndex, - layout: ast.Node.ContainerDecl.Layout, + layout_token: ?TokenIndex, }; const ExpectTokenSave = struct { @@ -2808,9 +2789,9 @@ const State = union(enum) { ErrorTagListCommaOrEnd: ListSave(ast.Node.ErrorSetDecl.DeclList), SwitchCaseOrEnd: ListSave(ast.Node.Switch.CaseList), SwitchCaseCommaOrEnd: ListSave(ast.Node.Switch.CaseList), - SwitchCaseFirstItem: &ast.Node.SwitchCase.ItemList, - SwitchCaseItem: &ast.Node.SwitchCase.ItemList, - SwitchCaseItemCommaOrEnd: &ast.Node.SwitchCase.ItemList, + SwitchCaseFirstItem: &ast.Node.SwitchCase, + SwitchCaseItem: &ast.Node.SwitchCase, + SwitchCaseItemCommaOrEnd: &ast.Node.SwitchCase, SuspendBody: &ast.Node.Suspend, AsyncAllocator: &ast.Node.AsyncAttribute, @@ -2899,14 +2880,6 @@ fn eatDocComments(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, t return result; } -fn eatLineComment(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) !?&ast.Node.LineComment { - const token = eatToken(tok_it, tree, Token.Id.LineComment) ?? return null; - return try arena.construct(ast.Node.LineComment{ - .base = ast.Node{ .id = ast.Node.Id.LineComment }, - .token = token, - }); -} - fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, token_ptr: &const Token, token_index: TokenIndex, tree: &ast.Tree) !?&ast.Node { switch (token_ptr.id) { Token.Id.StringLiteral => { @@ -2923,7 +2896,7 @@ fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterato const multiline_str_index = multiline_str.index; const multiline_str_ptr = multiline_str.ptr; if (multiline_str_ptr.id != Token.Id.MultilineStringLiteralLine) { - putBackToken(tok_it, tree); + prevToken(tok_it, tree); break; } @@ -3176,11 +3149,12 @@ fn createToCtxLiteral(arena: &mem.Allocator, opt_ctx: &const OptionalCtx, compti } fn eatToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, id: @TagType(Token.Id)) ?TokenIndex { - const token = nextToken(tok_it, tree); + const token = ??tok_it.peek(); - if (token.ptr.id == id) return token.index; + if (token.id == id) { + return nextToken(tok_it, tree).index; + } - putBackToken(tok_it, tree); return null; } @@ -3189,27 +3163,20 @@ fn nextToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) AnnotatedTok .index = tok_it.index, .ptr = ??tok_it.next(), }; - // possibly skip a following same line token - const token = tok_it.next() ?? return result; - if (token.id != Token.Id.LineComment) { - putBackToken(tok_it, tree); - return result; + assert(result.ptr.id != Token.Id.LineComment); + + while (true) { + const next_tok = tok_it.peek() ?? return result; + if (next_tok.id != Token.Id.LineComment) return result; + _ = tok_it.next(); } - const loc = tree.tokenLocationPtr(result.ptr.end, token); - if (loc.line != 0) { - putBackToken(tok_it, tree); - } - return result; } -fn putBackToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) void { - const prev_tok = ??tok_it.prev(); - if (prev_tok.id == Token.Id.LineComment) { - const minus2_tok = tok_it.prev() ?? return; - const loc = tree.tokenLocationPtr(minus2_tok.end, prev_tok); - if (loc.line != 0) { - _ = tok_it.next(); - } +fn prevToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) void { + while (true) { + const prev_tok = tok_it.prev() ?? return; + if (prev_tok.id == Token.Id.LineComment) continue; + return; } } diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 63d56167e8..38ffee8aaf 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,64 @@ +test "zig fmt: if-else end of comptime" { + try testCanonical( + \\comptime { + \\ if (a) { + \\ b(); + \\ } else { + \\ b(); + \\ } + \\} + \\ + ); +} + +test "zig fmt: nested blocks" { + try testCanonical( + \\comptime { + \\ { + \\ { + \\ { + \\ a(); + \\ } + \\ } + \\ } + \\} + \\ + ); +} + +test "zig fmt: block with same line comment after end brace" { + try testCanonical( + \\comptime { + \\ { + \\ b(); + \\ } // comment + \\} + \\ + ); +} + +test "zig fmt: statements with comment between" { + try testCanonical( + \\comptime { + \\ a = b; + \\ // comment + \\ a = b; + \\} + \\ + ); +} + +test "zig fmt: statements with empty line between" { + try testCanonical( + \\comptime { + \\ a = b; + \\ + \\ a = b; + \\} + \\ + ); +} + test "zig fmt: ptr deref operator" { try testCanonical( \\const a = b.*; @@ -7,6 +68,13 @@ test "zig fmt: ptr deref operator" { test "zig fmt: comment after if before another if" { try testCanonical( + \\test "aoeu" { + \\ // comment + \\ if (x) { + \\ bar(); + \\ } + \\} + \\ \\test "aoeu" { \\ if (x) { \\ foo(); @@ -21,7 +89,7 @@ test "zig fmt: comment after if before another if" { } test "zig fmt: line comment between if block and else keyword" { - try testTransform( + try testCanonical( \\test "aoeu" { \\ // cexp(finite|nan +- i inf|nan) = nan + i nan \\ if ((hx & 0x7fffffff) != 0x7f800000) { @@ -37,20 +105,6 @@ test "zig fmt: line comment between if block and else keyword" { \\ return Complex(f32).new(x, y - y); \\ } \\} - , - \\test "aoeu" { - \\ // cexp(finite|nan +- i inf|nan) = nan + i nan - \\ if ((hx & 0x7fffffff) != 0x7f800000) { - \\ return Complex(f32).new(y - y, y - y); - \\ } // cexp(-inf +- i inf|nan) = 0 + i0 - \\ else if (hx & 0x80000000 != 0) { - \\ return Complex(f32).new(0, 0); - \\ } // cexp(+inf +- i inf|nan) = inf + i nan - \\ // another comment - \\ else { - \\ return Complex(f32).new(x, y - y); - \\ } - \\} \\ ); } @@ -652,6 +706,11 @@ test "zig fmt: multiline string" { \\ c\\two) \\ c\\three \\ ; + \\ const s3 = // hi + \\ \\one + \\ \\two) + \\ \\three + \\ ; \\} \\ ); diff --git a/std/zig/render.zig b/std/zig/render.zig index 91e76e1c5f..f48b13c987 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -19,17 +19,21 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf( while (it.next()) |decl| { try renderTopLevelDecl(allocator, stream, tree, 0, decl.*); if (it.peek()) |next_decl| { - const n = if (nodeLineOffset(tree, decl.*, next_decl.*) >= 2) u8(2) else u8(1); - try stream.writeByteNTimes('\n', n); + try renderExtraNewline(tree, stream, next_decl.*); } } - try stream.write("\n"); } -fn nodeLineOffset(tree: &ast.Tree, a: &ast.Node, b: &ast.Node) usize { - const a_last_token = tree.tokens.at(a.lastToken()); - const loc = tree.tokenLocation(a_last_token.end, b.firstToken()); - return loc.line; +fn renderExtraNewline(tree: &ast.Tree, stream: var, node: &ast.Node) !void { + var first_token = node.firstToken(); + while (tree.tokens.at(first_token - 1).id == Token.Id.DocComment) { + first_token -= 1; + } + const prev_token_end = tree.tokens.at(first_token - 1).end; + const loc = tree.tokenLocation(prev_token_end, first_token); + if (loc.line >= 2) { + try stream.writeByte('\n'); + } } fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, decl: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { @@ -37,119 +41,124 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i ast.Node.Id.FnProto => { const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl); - try renderComments(tree, stream, fn_proto, indent); - try renderExpression(allocator, stream, tree, indent, decl); + try renderDocComments(tree, stream, fn_proto, indent); if (fn_proto.body_node) |body_node| { - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, body_node); + try renderExpression(allocator, stream, tree, indent, decl, Space.Space); + try renderExpression(allocator, stream, tree, indent, body_node, Space.Newline); } else { - try stream.write(";"); + try renderExpression(allocator, stream, tree, indent, decl, Space.None); + try renderToken(tree, stream, tree.nextToken(decl.lastToken()), indent, Space.Newline); } }, + ast.Node.Id.Use => { const use_decl = @fieldParentPtr(ast.Node.Use, "base", decl); if (use_decl.visib_token) |visib_token| { - try stream.print("{} ", tree.tokenSlice(visib_token)); + try renderToken(tree, stream, visib_token, indent, Space.Space); // pub } - try stream.write("use "); - try renderExpression(allocator, stream, tree, indent, use_decl.expr); - try stream.write(";"); + try renderToken(tree, stream, use_decl.use_token, indent, Space.Space); // use + try renderExpression(allocator, stream, tree, indent, use_decl.expr, Space.None); + try renderToken(tree, stream, use_decl.semicolon_token, indent, Space.Newline); // ; }, + ast.Node.Id.VarDecl => { const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", decl); - try renderComments(tree, stream, var_decl, indent); + try renderDocComments(tree, stream, var_decl, indent); try renderVarDecl(allocator, stream, tree, indent, var_decl); }, + ast.Node.Id.TestDecl => { const test_decl = @fieldParentPtr(ast.Node.TestDecl, "base", decl); - try renderComments(tree, stream, test_decl, indent); - try stream.write("test "); - try renderExpression(allocator, stream, tree, indent, test_decl.name); - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, test_decl.body_node); + try renderDocComments(tree, stream, test_decl, indent); + try renderToken(tree, stream, test_decl.test_token, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, test_decl.name, Space.Space); + try renderExpression(allocator, stream, tree, indent, test_decl.body_node, Space.Newline); }, + ast.Node.Id.StructField => { const field = @fieldParentPtr(ast.Node.StructField, "base", decl); - try renderComments(tree, stream, field, indent); + try renderDocComments(tree, stream, field, indent); if (field.visib_token) |visib_token| { - try stream.print("{} ", tree.tokenSlice(visib_token)); + try renderToken(tree, stream, visib_token, indent, Space.Space); // pub } - try stream.print("{}: ", tree.tokenSlice(field.name_token)); - try renderExpression(allocator, stream, tree, indent, field.type_expr); - try renderToken(tree, stream, field.lastToken() + 1, indent, true, true); + try renderToken(tree, stream, field.name_token, indent, Space.None); // name + try renderToken(tree, stream, tree.nextToken(field.name_token), indent, Space.Space); // : + try renderExpression(allocator, stream, tree, indent, field.type_expr, Space.None); // type + try renderToken(tree, stream, tree.nextToken(field.lastToken()), indent, Space.Newline); // , }, + ast.Node.Id.UnionTag => { const tag = @fieldParentPtr(ast.Node.UnionTag, "base", decl); - try renderComments(tree, stream, tag, indent); - try stream.print("{}", tree.tokenSlice(tag.name_token)); + try renderDocComments(tree, stream, tag, indent); + + const name_space = if (tag.type_expr == null and tag.value_expr != null) Space.Space else Space.None; + try renderToken(tree, stream, tag.name_token, indent, name_space); // name if (tag.type_expr) |type_expr| { - try stream.print(": "); - try renderExpression(allocator, stream, tree, indent, type_expr); + try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // : + + const after_type_space = if (tag.value_expr == null) Space.None else Space.Space; + try renderExpression(allocator, stream, tree, indent, type_expr, after_type_space); } if (tag.value_expr) |value_expr| { - try stream.print(" = "); - try renderExpression(allocator, stream, tree, indent, value_expr); + try renderToken(tree, stream, tree.prevToken(value_expr.firstToken()), indent, Space.Space); // = + try renderExpression(allocator, stream, tree, indent, value_expr, Space.None); } - try stream.write(","); + try renderToken(tree, stream, tree.nextToken(decl.lastToken()), indent, Space.Newline); // , }, + ast.Node.Id.EnumTag => { const tag = @fieldParentPtr(ast.Node.EnumTag, "base", decl); - try renderComments(tree, stream, tag, indent); - try stream.print("{}", tree.tokenSlice(tag.name_token)); + try renderDocComments(tree, stream, tag, indent); + + const after_name_space = if (tag.value == null) Space.None else Space.Space; + try renderToken(tree, stream, tag.name_token, indent, after_name_space); // name if (tag.value) |value| { - try stream.print(" = "); - try renderExpression(allocator, stream, tree, indent, value); + try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // = + try renderExpression(allocator, stream, tree, indent, value, Space.None); } - try stream.write(","); + try renderToken(tree, stream, tree.nextToken(decl.lastToken()), indent, Space.Newline); // , }, - ast.Node.Id.ErrorTag => { - const tag = @fieldParentPtr(ast.Node.ErrorTag, "base", decl); - try renderComments(tree, stream, tag, indent); - try stream.print("{}", tree.tokenSlice(tag.name_token)); - }, ast.Node.Id.Comptime => { - try renderExpression(allocator, stream, tree, indent, decl); - try maybeRenderSemicolon(stream, tree, indent, decl); - }, - ast.Node.Id.LineComment => { - const line_comment_node = @fieldParentPtr(ast.Node.LineComment, "base", decl); - - try stream.write(tree.tokenSlice(line_comment_node.token)); + assert(!decl.requireSemiColon()); + try renderExpression(allocator, stream, tree, indent, decl, Space.Newline); }, else => unreachable, } } -fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { +fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node, space: Space) (@typeOf(stream).Child.Error || Error)!void { switch (base.id) { ast.Node.Id.Identifier => { const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base); - try stream.print("{}", tree.tokenSlice(identifier.token)); + try renderToken(tree, stream, identifier.token, indent, space); }, ast.Node.Id.Block => { const block = @fieldParentPtr(ast.Node.Block, "base", base); + if (block.label) |label| { - try stream.print("{}: ", tree.tokenSlice(label)); + try renderToken(tree, stream, label, indent, Space.None); + try renderToken(tree, stream, tree.nextToken(label), indent, Space.Space); } if (block.statements.len == 0) { - try stream.write("{}"); + try renderToken(tree, stream, block.lbrace, indent + indent_delta, Space.None); + try renderToken(tree, stream, block.rbrace, indent, space); } else { - try stream.write("{\n"); const block_indent = indent + indent_delta; + try renderToken(tree, stream, block.lbrace, block_indent, Space.Newline); var it = block.statements.iterator(0); while (it.next()) |statement| { @@ -157,114 +166,85 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderStatement(allocator, stream, tree, block_indent, statement.*); if (it.peek()) |next_statement| { - const n = if (nodeLineOffset(tree, statement.*, next_statement.*) >= 2) u8(2) else u8(1); - try stream.writeByteNTimes('\n', n); + try renderExtraNewline(tree, stream, next_statement.*); } } - try stream.write("\n"); try stream.writeByteNTimes(' ', indent); - try stream.write("}"); + try renderToken(tree, stream, block.rbrace, indent, space); } }, ast.Node.Id.Defer => { const defer_node = @fieldParentPtr(ast.Node.Defer, "base", base); - try stream.print("{} ", tree.tokenSlice(defer_node.defer_token)); - try renderExpression(allocator, stream, tree, indent, defer_node.expr); + + try renderToken(tree, stream, defer_node.defer_token, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, defer_node.expr, space); }, ast.Node.Id.Comptime => { const comptime_node = @fieldParentPtr(ast.Node.Comptime, "base", base); - try stream.print("{} ", tree.tokenSlice(comptime_node.comptime_token)); - try renderExpression(allocator, stream, tree, indent, comptime_node.expr); + + try renderToken(tree, stream, comptime_node.comptime_token, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, comptime_node.expr, space); }, + ast.Node.Id.AsyncAttribute => { const async_attr = @fieldParentPtr(ast.Node.AsyncAttribute, "base", base); - try stream.print("{}", tree.tokenSlice(async_attr.async_token)); if (async_attr.allocator_type) |allocator_type| { - try stream.write("<"); - try renderExpression(allocator, stream, tree, indent, allocator_type); - try stream.write(">"); + try renderToken(tree, stream, async_attr.async_token, indent, Space.None); + + try renderToken(tree, stream, tree.nextToken(async_attr.async_token), indent, Space.None); + try renderExpression(allocator, stream, tree, indent, allocator_type, Space.None); + try renderToken(tree, stream, tree.nextToken(allocator_type.lastToken()), indent, space); + } else { + try renderToken(tree, stream, async_attr.async_token, indent, space); } }, + ast.Node.Id.Suspend => { const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base); + if (suspend_node.label) |label| { - try stream.print("{}: ", tree.tokenSlice(label)); + try renderToken(tree, stream, label, indent, Space.None); + try renderToken(tree, stream, tree.nextToken(label), indent, Space.Space); } - try stream.print("{}", tree.tokenSlice(suspend_node.suspend_token)); if (suspend_node.payload) |payload| { - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, payload); - } - - if (suspend_node.body) |body| { - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, body); + if (suspend_node.body) |body| { + try renderToken(tree, stream, suspend_node.suspend_token, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + try renderExpression(allocator, stream, tree, indent, body, space); + } else { + try renderToken(tree, stream, suspend_node.suspend_token, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, payload, space); + } + } else if (suspend_node.body) |body| { + try renderToken(tree, stream, suspend_node.suspend_token, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, body, space); + } else { + try renderToken(tree, stream, suspend_node.suspend_token, indent, space); } }, ast.Node.Id.InfixOp => { const infix_op_node = @fieldParentPtr(ast.Node.InfixOp, "base", base); - try renderExpression(allocator, stream, tree, indent, infix_op_node.lhs); - - const text = switch (infix_op_node.op) { - ast.Node.InfixOp.Op.Add => " + ", - ast.Node.InfixOp.Op.AddWrap => " +% ", - ast.Node.InfixOp.Op.ArrayCat => " ++ ", - ast.Node.InfixOp.Op.ArrayMult => " ** ", - ast.Node.InfixOp.Op.Assign => " = ", - ast.Node.InfixOp.Op.AssignBitAnd => " &= ", - ast.Node.InfixOp.Op.AssignBitOr => " |= ", - ast.Node.InfixOp.Op.AssignBitShiftLeft => " <<= ", - ast.Node.InfixOp.Op.AssignBitShiftRight => " >>= ", - ast.Node.InfixOp.Op.AssignBitXor => " ^= ", - ast.Node.InfixOp.Op.AssignDiv => " /= ", - ast.Node.InfixOp.Op.AssignMinus => " -= ", - ast.Node.InfixOp.Op.AssignMinusWrap => " -%= ", - ast.Node.InfixOp.Op.AssignMod => " %= ", - ast.Node.InfixOp.Op.AssignPlus => " += ", - ast.Node.InfixOp.Op.AssignPlusWrap => " +%= ", - ast.Node.InfixOp.Op.AssignTimes => " *= ", - ast.Node.InfixOp.Op.AssignTimesWarp => " *%= ", - ast.Node.InfixOp.Op.BangEqual => " != ", - ast.Node.InfixOp.Op.BitAnd => " & ", - ast.Node.InfixOp.Op.BitOr => " | ", - ast.Node.InfixOp.Op.BitShiftLeft => " << ", - ast.Node.InfixOp.Op.BitShiftRight => " >> ", - ast.Node.InfixOp.Op.BitXor => " ^ ", - ast.Node.InfixOp.Op.BoolAnd => " and ", - ast.Node.InfixOp.Op.BoolOr => " or ", - ast.Node.InfixOp.Op.Div => " / ", - ast.Node.InfixOp.Op.EqualEqual => " == ", - ast.Node.InfixOp.Op.ErrorUnion => "!", - ast.Node.InfixOp.Op.GreaterOrEqual => " >= ", - ast.Node.InfixOp.Op.GreaterThan => " > ", - ast.Node.InfixOp.Op.LessOrEqual => " <= ", - ast.Node.InfixOp.Op.LessThan => " < ", - ast.Node.InfixOp.Op.MergeErrorSets => " || ", - ast.Node.InfixOp.Op.Mod => " % ", - ast.Node.InfixOp.Op.Mult => " * ", - ast.Node.InfixOp.Op.MultWrap => " *% ", - ast.Node.InfixOp.Op.Period => ".", - ast.Node.InfixOp.Op.Sub => " - ", - ast.Node.InfixOp.Op.SubWrap => " -% ", - ast.Node.InfixOp.Op.UnwrapMaybe => " ?? ", - ast.Node.InfixOp.Op.Range => " ... ", - ast.Node.InfixOp.Op.Catch => |maybe_payload| blk: { - try stream.write(" catch "); - if (maybe_payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload); - try stream.write(" "); - } - break :blk ""; - }, + const op_token = tree.tokens.at(infix_op_node.op_token); + const op_space = switch (infix_op_node.op) { + ast.Node.InfixOp.Op.Period, ast.Node.InfixOp.Op.ErrorUnion => Space.None, + else => Space.Space, }; + try renderExpression(allocator, stream, tree, indent, infix_op_node.lhs, op_space); + try renderToken(tree, stream, infix_op_node.op_token, indent, op_space); - try stream.write(text); - try renderExpression(allocator, stream, tree, indent, infix_op_node.rhs); + switch (infix_op_node.op) { + ast.Node.InfixOp.Op.Catch => |maybe_payload| if (maybe_payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + }, + else => {}, + } + + try renderExpression(allocator, stream, tree, indent, infix_op_node.rhs, space); }, ast.Node.Id.PrefixOp => { @@ -272,52 +252,73 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind switch (prefix_op_node.op) { ast.Node.PrefixOp.Op.AddrOf => |addr_of_info| { - try stream.write("&"); + try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // & if (addr_of_info.align_expr) |align_expr| { - try stream.write("align("); - try renderExpression(allocator, stream, tree, indent, align_expr); - try stream.write(") "); + const align_token = tree.nextToken(prefix_op_node.op_token); + try renderToken(tree, stream, align_token, indent, Space.None); // align + + const lparen_token = tree.prevToken(align_expr.firstToken()); + try renderToken(tree, stream, lparen_token, indent, Space.None); // ( + + try renderExpression(allocator, stream, tree, indent, align_expr, Space.None); + + const rparen_token = tree.nextToken(align_expr.lastToken()); + try renderToken(tree, stream, rparen_token, indent, Space.Space); // ) } - if (addr_of_info.const_token != null) { - try stream.write("const "); + if (addr_of_info.const_token) |const_token| { + try renderToken(tree, stream, const_token, indent, Space.Space); // const } - if (addr_of_info.volatile_token != null) { - try stream.write("volatile "); + if (addr_of_info.volatile_token) |volatile_token| { + try renderToken(tree, stream, volatile_token, indent, Space.Space); // volatile } }, ast.Node.PrefixOp.Op.SliceType => |addr_of_info| { - try stream.write("[]"); + try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // [ + try renderToken(tree, stream, tree.nextToken(prefix_op_node.op_token), indent, Space.None); // ] + if (addr_of_info.align_expr) |align_expr| { - try stream.print("align("); - try renderExpression(allocator, stream, tree, indent, align_expr); - try stream.print(") "); + const align_token = tree.nextToken(prefix_op_node.op_token); + try renderToken(tree, stream, align_token, indent, Space.None); // align + + const lparen_token = tree.prevToken(align_expr.firstToken()); + try renderToken(tree, stream, lparen_token, indent, Space.None); // ( + + try renderExpression(allocator, stream, tree, indent, align_expr, Space.None); + + const rparen_token = tree.nextToken(align_expr.lastToken()); + try renderToken(tree, stream, rparen_token, indent, Space.Space); // ) } - if (addr_of_info.const_token != null) { - try stream.print("const "); + if (addr_of_info.const_token) |const_token| { + try renderToken(tree, stream, const_token, indent, Space.Space); } - if (addr_of_info.volatile_token != null) { - try stream.print("volatile "); + if (addr_of_info.volatile_token) |volatile_token| { + try renderToken(tree, stream, volatile_token, indent, Space.Space); } }, ast.Node.PrefixOp.Op.ArrayType => |array_index| { - try stream.print("["); - try renderExpression(allocator, stream, tree, indent, array_index); - try stream.print("]"); + try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // [ + try renderExpression(allocator, stream, tree, indent, array_index, Space.None); + try renderToken(tree, stream, tree.nextToken(array_index.lastToken()), indent, Space.None); // ] + }, + ast.Node.PrefixOp.Op.BitNot, + ast.Node.PrefixOp.Op.BoolNot, + ast.Node.PrefixOp.Op.Negation, + ast.Node.PrefixOp.Op.NegationWrap, + ast.Node.PrefixOp.Op.UnwrapMaybe, + ast.Node.PrefixOp.Op.MaybeType, + ast.Node.PrefixOp.Op.PointerType => { + try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); + }, + + ast.Node.PrefixOp.Op.Try, + ast.Node.PrefixOp.Op.Await, + ast.Node.PrefixOp.Op.Cancel, + ast.Node.PrefixOp.Op.Resume => { + try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.Space); }, - ast.Node.PrefixOp.Op.BitNot => try stream.write("~"), - ast.Node.PrefixOp.Op.BoolNot => try stream.write("!"), - ast.Node.PrefixOp.Op.Negation => try stream.write("-"), - ast.Node.PrefixOp.Op.NegationWrap => try stream.write("-%"), - ast.Node.PrefixOp.Op.Try => try stream.write("try "), - ast.Node.PrefixOp.Op.UnwrapMaybe => try stream.write("??"), - ast.Node.PrefixOp.Op.MaybeType => try stream.write("?"), - ast.Node.PrefixOp.Op.PointerType => try stream.write("*"), - ast.Node.PrefixOp.Op.Await => try stream.write("await "), - ast.Node.PrefixOp.Op.Cancel => try stream.write("cancel "), - ast.Node.PrefixOp.Op.Resume => try stream.write("resume "), } - try renderExpression(allocator, stream, tree, indent, prefix_op_node.rhs); + try renderExpression(allocator, stream, tree, indent, prefix_op_node.rhs, space); }, ast.Node.Id.SuffixOp => { @@ -326,123 +327,139 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind switch (suffix_op.op) { @TagType(ast.Node.SuffixOp.Op).Call => |*call_info| { if (call_info.async_attr) |async_attr| { - try renderExpression(allocator, stream, tree, indent, &async_attr.base); - try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, &async_attr.base, Space.Space); } - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write("("); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + + const lparen = tree.nextToken(suffix_op.lhs.lastToken()); + try renderToken(tree, stream, lparen, indent, Space.None); var it = call_info.params.iterator(0); while (it.next()) |param_node| { - try renderExpression(allocator, stream, tree, indent, param_node.*); + try renderExpression(allocator, stream, tree, indent, param_node.*, Space.None); + if (it.peek() != null) { - try stream.write(", "); + const comma = tree.nextToken(param_node.*.lastToken()); + try renderToken(tree, stream, comma, indent, Space.Space); } } - try stream.write(")"); + try renderToken(tree, stream, suffix_op.rtoken, indent, space); }, ast.Node.SuffixOp.Op.ArrayAccess => |index_expr| { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write("["); - try renderExpression(allocator, stream, tree, indent, index_expr); - try stream.write("]"); + const lbracket = tree.prevToken(index_expr.firstToken()); + const rbracket = tree.nextToken(index_expr.lastToken()); + + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbracket, indent, Space.None); // [ + try renderExpression(allocator, stream, tree, indent, index_expr, Space.None); + try renderToken(tree, stream, rbracket, indent, space); // ] }, ast.Node.SuffixOp.Op.Deref => { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write(".*"); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderToken(tree, stream, tree.prevToken(suffix_op.rtoken), indent, Space.None); // . + try renderToken(tree, stream, suffix_op.rtoken, indent, space); // * }, @TagType(ast.Node.SuffixOp.Op).Slice => |range| { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write("["); - try renderExpression(allocator, stream, tree, indent, range.start); - try stream.write(".."); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + + const lbracket = tree.prevToken(range.start.firstToken()); + const dotdot = tree.nextToken(range.start.lastToken()); + + try renderToken(tree, stream, lbracket, indent, Space.None); // [ + try renderExpression(allocator, stream, tree, indent, range.start, Space.None); + try renderToken(tree, stream, dotdot, indent, Space.None); // .. if (range.end) |end| { - try renderExpression(allocator, stream, tree, indent, end); + try renderExpression(allocator, stream, tree, indent, end, Space.None); } - try stream.write("]"); + try renderToken(tree, stream, suffix_op.rtoken, indent, space); // ] }, ast.Node.SuffixOp.Op.StructInitializer => |*field_inits| { + const lbrace = tree.nextToken(suffix_op.lhs.lastToken()); + if (field_inits.len == 0) { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write("{}"); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, Space.None); + try renderToken(tree, stream, suffix_op.rtoken, indent, space); return; } if (field_inits.len == 1) { const field_init = field_inits.at(0).*; - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write("{ "); - try renderExpression(allocator, stream, tree, indent, field_init); - try stream.write(" }"); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, field_init, Space.Space); + try renderToken(tree, stream, suffix_op.rtoken, indent, space); return; } - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write("{\n"); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, Space.Newline); const new_indent = indent + indent_delta; var it = field_inits.iterator(0); while (it.next()) |field_init| { try stream.writeByteNTimes(' ', new_indent); - try renderExpression(allocator, stream, tree, new_indent, field_init.*); - if ((field_init.*).id != ast.Node.Id.LineComment) { - try stream.write(","); - } + try renderExpression(allocator, stream, tree, new_indent, field_init.*, Space.None); + + const comma = tree.nextToken(field_init.*.lastToken()); + try renderToken(tree, stream, comma, new_indent, Space.Newline); + if (it.peek()) |next_field_init| { - const n = if (nodeLineOffset(tree, field_init.*, next_field_init.*) >= 2) u8(2) else u8(1); - try stream.writeByteNTimes('\n', n); + try renderExtraNewline(tree, stream, next_field_init.*); } } - try stream.write("\n"); try stream.writeByteNTimes(' ', indent); - try stream.write("}"); + try renderToken(tree, stream, suffix_op.rtoken, indent, space); }, ast.Node.SuffixOp.Op.ArrayInitializer => |*exprs| { + const lbrace = tree.nextToken(suffix_op.lhs.lastToken()); + if (exprs.len == 0) { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write("{}"); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, Space.None); + try renderToken(tree, stream, suffix_op.rtoken, indent, space); return; } if (exprs.len == 1) { const expr = exprs.at(0).*; - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); - try stream.write("{"); - try renderExpression(allocator, stream, tree, indent, expr); - try stream.write("}"); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, Space.None); + try renderExpression(allocator, stream, tree, indent, expr, Space.None); + try renderToken(tree, stream, suffix_op.rtoken, indent, space); return; } - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs); + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); const new_indent = indent + indent_delta; - try stream.write("{\n"); + try renderToken(tree, stream, lbrace, new_indent, Space.Newline); var it = exprs.iterator(0); while (it.next()) |expr| { try stream.writeByteNTimes(' ', new_indent); - try renderExpression(allocator, stream, tree, new_indent, expr.*); - try stream.write(","); + try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.None); + + const comma = tree.nextToken(expr.*.lastToken()); + try renderToken(tree, stream, comma, new_indent, Space.Newline); // , if (it.peek()) |next_expr| { - const n = if (nodeLineOffset(tree, expr.*, next_expr.*) >= 2) u8(2) else u8(1); - try stream.writeByteNTimes('\n', n); + try renderExtraNewline(tree, stream, next_expr.*); } } - try stream.write("\n"); try stream.writeByteNTimes(' ', indent); - try stream.write("}"); + try renderToken(tree, stream, suffix_op.rtoken, indent, space); }, } }, @@ -452,159 +469,182 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind switch (flow_expr.kind) { ast.Node.ControlFlowExpression.Kind.Break => |maybe_label| { - try stream.print("break"); + const kw_space = if (maybe_label != null or flow_expr.rhs != null) Space.Space else space; + try renderToken(tree, stream, flow_expr.ltoken, indent, kw_space); if (maybe_label) |label| { - try stream.print(" :"); - try renderExpression(allocator, stream, tree, indent, label); + const colon = tree.nextToken(flow_expr.ltoken); + try renderToken(tree, stream, colon, indent, Space.None); + + const expr_space = if (flow_expr.rhs != null) Space.Space else space; + try renderExpression(allocator, stream, tree, indent, label, expr_space); } }, ast.Node.ControlFlowExpression.Kind.Continue => |maybe_label| { - try stream.print("continue"); + const kw_space = if (maybe_label != null or flow_expr.rhs != null) Space.Space else space; + try renderToken(tree, stream, flow_expr.ltoken, indent, kw_space); if (maybe_label) |label| { - try stream.print(" :"); - try renderExpression(allocator, stream, tree, indent, label); + const colon = tree.nextToken(flow_expr.ltoken); + try renderToken(tree, stream, colon, indent, Space.None); + + const expr_space = if (flow_expr.rhs != null) Space.Space else space; + try renderExpression(allocator, stream, tree, indent, label, space); } }, ast.Node.ControlFlowExpression.Kind.Return => { - try stream.print("return"); + const kw_space = if (flow_expr.rhs != null) Space.Space else space; + try renderToken(tree, stream, flow_expr.ltoken, indent, kw_space); }, } if (flow_expr.rhs) |rhs| { - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, rhs); + try renderExpression(allocator, stream, tree, indent, rhs, space); } }, ast.Node.Id.Payload => { const payload = @fieldParentPtr(ast.Node.Payload, "base", base); - try stream.write("|"); - try renderExpression(allocator, stream, tree, indent, payload.error_symbol); - try stream.write("|"); + try renderToken(tree, stream, payload.lpipe, indent, Space.None); + try renderExpression(allocator, stream, tree, indent, payload.error_symbol, Space.None); + try renderToken(tree, stream, payload.rpipe, indent, space); }, ast.Node.Id.PointerPayload => { const payload = @fieldParentPtr(ast.Node.PointerPayload, "base", base); - try stream.write("|"); + try renderToken(tree, stream, payload.lpipe, indent, Space.None); if (payload.ptr_token) |ptr_token| { - try stream.write(tree.tokenSlice(ptr_token)); + try renderToken(tree, stream, ptr_token, indent, Space.None); } - try renderExpression(allocator, stream, tree, indent, payload.value_symbol); - try stream.write("|"); + try renderExpression(allocator, stream, tree, indent, payload.value_symbol, Space.None); + try renderToken(tree, stream, payload.rpipe, indent, space); }, ast.Node.Id.PointerIndexPayload => { const payload = @fieldParentPtr(ast.Node.PointerIndexPayload, "base", base); - try stream.write("|"); + try renderToken(tree, stream, payload.lpipe, indent, Space.None); if (payload.ptr_token) |ptr_token| { - try stream.write(tree.tokenSlice(ptr_token)); + try renderToken(tree, stream, ptr_token, indent, Space.None); } - try renderExpression(allocator, stream, tree, indent, payload.value_symbol); + try renderExpression(allocator, stream, tree, indent, payload.value_symbol, Space.None); if (payload.index_symbol) |index_symbol| { - try stream.write(", "); - try renderExpression(allocator, stream, tree, indent, index_symbol); + const comma = tree.nextToken(payload.value_symbol.lastToken()); + + try renderToken(tree, stream, comma, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, index_symbol, Space.None); } - try stream.write("|"); + try renderToken(tree, stream, payload.rpipe, indent, space); }, ast.Node.Id.GroupedExpression => { const grouped_expr = @fieldParentPtr(ast.Node.GroupedExpression, "base", base); - try renderToken(tree, stream, grouped_expr.lparen, indent, false, false); - try renderExpression(allocator, stream, tree, indent, grouped_expr.expr); - try renderToken(tree, stream, grouped_expr.rparen, indent, false, false); + try renderToken(tree, stream, grouped_expr.lparen, indent, Space.None); + try renderExpression(allocator, stream, tree, indent, grouped_expr.expr, Space.None); + try renderToken(tree, stream, grouped_expr.rparen, indent, space); }, ast.Node.Id.FieldInitializer => { const field_init = @fieldParentPtr(ast.Node.FieldInitializer, "base", base); - try stream.print(".{} = ", tree.tokenSlice(field_init.name_token)); - try renderExpression(allocator, stream, tree, indent, field_init.expr); + try renderToken(tree, stream, field_init.period_token, indent, Space.None); // . + try renderToken(tree, stream, field_init.name_token, indent, Space.Space); // name + try renderToken(tree, stream, tree.nextToken(field_init.name_token), indent, Space.Space); // = + try renderExpression(allocator, stream, tree, indent, field_init.expr, space); }, ast.Node.Id.IntegerLiteral => { const integer_literal = @fieldParentPtr(ast.Node.IntegerLiteral, "base", base); - try renderToken(tree, stream, integer_literal.token, indent, false, false); + try renderToken(tree, stream, integer_literal.token, indent, space); }, ast.Node.Id.FloatLiteral => { const float_literal = @fieldParentPtr(ast.Node.FloatLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(float_literal.token)); + try renderToken(tree, stream, float_literal.token, indent, space); }, ast.Node.Id.StringLiteral => { const string_literal = @fieldParentPtr(ast.Node.StringLiteral, "base", base); - try renderToken(tree, stream, string_literal.token, indent, false, false); + try renderToken(tree, stream, string_literal.token, indent, space); }, ast.Node.Id.CharLiteral => { const char_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(char_literal.token)); + try renderToken(tree, stream, char_literal.token, indent, space); }, ast.Node.Id.BoolLiteral => { const bool_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(bool_literal.token)); + try renderToken(tree, stream, bool_literal.token, indent, space); }, ast.Node.Id.NullLiteral => { const null_literal = @fieldParentPtr(ast.Node.NullLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(null_literal.token)); + try renderToken(tree, stream, null_literal.token, indent, space); }, ast.Node.Id.ThisLiteral => { const this_literal = @fieldParentPtr(ast.Node.ThisLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(this_literal.token)); + try renderToken(tree, stream, this_literal.token, indent, space); }, ast.Node.Id.Unreachable => { const unreachable_node = @fieldParentPtr(ast.Node.Unreachable, "base", base); - try stream.print("{}", tree.tokenSlice(unreachable_node.token)); + try renderToken(tree, stream, unreachable_node.token, indent, space); }, ast.Node.Id.ErrorType => { const error_type = @fieldParentPtr(ast.Node.ErrorType, "base", base); - try stream.print("{}", tree.tokenSlice(error_type.token)); + try renderToken(tree, stream, error_type.token, indent, space); }, ast.Node.Id.VarType => { const var_type = @fieldParentPtr(ast.Node.VarType, "base", base); - try stream.print("{}", tree.tokenSlice(var_type.token)); + try renderToken(tree, stream, var_type.token, indent, space); }, ast.Node.Id.ContainerDecl => { const container_decl = @fieldParentPtr(ast.Node.ContainerDecl, "base", base); - switch (container_decl.layout) { - ast.Node.ContainerDecl.Layout.Packed => try stream.print("packed "), - ast.Node.ContainerDecl.Layout.Extern => try stream.print("extern "), - ast.Node.ContainerDecl.Layout.Auto => {}, - } - - switch (container_decl.kind) { - ast.Node.ContainerDecl.Kind.Struct => try stream.print("struct"), - ast.Node.ContainerDecl.Kind.Enum => try stream.print("enum"), - ast.Node.ContainerDecl.Kind.Union => try stream.print("union"), + if (container_decl.layout_token) |layout_token| { + try renderToken(tree, stream, layout_token, indent, Space.Space); } switch (container_decl.init_arg_expr) { - ast.Node.ContainerDecl.InitArg.None => try stream.write(" "), + ast.Node.ContainerDecl.InitArg.None => { + try renderToken(tree, stream, container_decl.kind_token, indent, Space.Space); // union + }, ast.Node.ContainerDecl.InitArg.Enum => |enum_tag_type| { + try renderToken(tree, stream, container_decl.kind_token, indent, Space.None); // union + + const lparen = tree.nextToken(container_decl.kind_token); + const enum_token = tree.nextToken(lparen); + + try renderToken(tree, stream, lparen, indent, Space.None); // ( + try renderToken(tree, stream, enum_token, indent, Space.None); // enum + if (enum_tag_type) |expr| { - try stream.write("(enum("); - try renderExpression(allocator, stream, tree, indent, expr); - try stream.write(")) "); + try renderToken(tree, stream, tree.nextToken(enum_token), indent, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, expr, Space.None); + + const rparen = tree.nextToken(expr.lastToken()); + try renderToken(tree, stream, rparen, indent, Space.None); // ) + try renderToken(tree, stream, tree.nextToken(rparen), indent, Space.Space); // ) } else { - try stream.write("(enum) "); + try renderToken(tree, stream, tree.nextToken(enum_token), indent, Space.Space); // ) } }, ast.Node.ContainerDecl.InitArg.Type => |type_expr| { - try stream.write("("); - try renderExpression(allocator, stream, tree, indent, type_expr); - try stream.write(") "); + try renderToken(tree, stream, container_decl.kind_token, indent, Space.None); // union + + const lparen = tree.nextToken(container_decl.kind_token); + const rparen = tree.nextToken(type_expr.lastToken()); + + try renderToken(tree, stream, lparen, indent, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, type_expr, Space.None); + try renderToken(tree, stream, rparen, indent, Space.Space); // ) }, } if (container_decl.fields_and_decls.len == 0) { - try stream.write("{}"); + try renderToken(tree, stream, container_decl.lbrace_token, indent + indent_delta, Space.None); // { + try renderToken(tree, stream, container_decl.rbrace_token, indent, space); // } } else { - try stream.write("{\n"); const new_indent = indent + indent_delta; + try renderToken(tree, stream, container_decl.lbrace_token, new_indent, Space.Newline); // { var it = container_decl.fields_and_decls.iterator(0); while (it.next()) |decl| { @@ -612,22 +652,24 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderTopLevelDecl(allocator, stream, tree, new_indent, decl.*); if (it.peek()) |next_decl| { - const n = if (nodeLineOffset(tree, decl.*, next_decl.*) >= 2) u8(2) else u8(1); - try stream.writeByteNTimes('\n', n); + try renderExtraNewline(tree, stream, next_decl.*); } } - try stream.write("\n"); try stream.writeByteNTimes(' ', indent); - try stream.write("}"); + try renderToken(tree, stream, container_decl.rbrace_token, indent, space); // } } }, ast.Node.Id.ErrorSetDecl => { const err_set_decl = @fieldParentPtr(ast.Node.ErrorSetDecl, "base", base); + const lbrace = tree.nextToken(err_set_decl.error_token); + if (err_set_decl.decls.len == 0) { - try stream.write("error{}"); + try renderToken(tree, stream, err_set_decl.error_token, indent, Space.None); + try renderToken(tree, stream, lbrace, indent, Space.None); + try renderToken(tree, stream, err_set_decl.rbrace_token, indent, space); return; } @@ -642,62 +684,80 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind break :blk; } - try stream.write("error{"); - try renderTopLevelDecl(allocator, stream, tree, indent, node); - try stream.write("}"); + try renderToken(tree, stream, err_set_decl.error_token, indent, Space.None); // error + try renderToken(tree, stream, lbrace, indent, Space.None); // { + try renderExpression(allocator, stream, tree, indent, node, Space.None); + try renderToken(tree, stream, err_set_decl.rbrace_token, indent, space); // } return; } - try stream.write("error{\n"); + try renderToken(tree, stream, err_set_decl.error_token, indent, Space.None); // error + try renderToken(tree, stream, lbrace, indent, Space.Newline); // { const new_indent = indent + indent_delta; var it = err_set_decl.decls.iterator(0); while (it.next()) |node| { try stream.writeByteNTimes(' ', new_indent); - try renderTopLevelDecl(allocator, stream, tree, new_indent, node.*); - if ((node.*).id != ast.Node.Id.LineComment) { - try stream.write(","); - } + try renderExpression(allocator, stream, tree, new_indent, node.*, Space.None); + try renderToken(tree, stream, tree.nextToken(node.*.lastToken()), new_indent, Space.Newline); // , + if (it.peek()) |next_node| { - const n = if (nodeLineOffset(tree, node.*, next_node.*) >= 2) u8(2) else u8(1); - try stream.writeByteNTimes('\n', n); + try renderExtraNewline(tree, stream, next_node.*); } } - try stream.write("\n"); try stream.writeByteNTimes(' ', indent); - try stream.write("}"); + try renderToken(tree, stream, err_set_decl.rbrace_token, indent, space); // } + }, + + ast.Node.Id.ErrorTag => { + const tag = @fieldParentPtr(ast.Node.ErrorTag, "base", base); + + try renderDocComments(tree, stream, tag, indent); + try renderToken(tree, stream, tag.name_token, indent, space); // name }, ast.Node.Id.MultilineStringLiteral => { const multiline_str_literal = @fieldParentPtr(ast.Node.MultilineStringLiteral, "base", base); - try stream.print("\n"); + + var skip_first_indent = true; + if (tree.tokens.at(multiline_str_literal.firstToken() - 1).id != Token.Id.LineComment) { + try stream.print("\n"); + skip_first_indent = false; + } var i: usize = 0; while (i < multiline_str_literal.lines.len) : (i += 1) { const t = multiline_str_literal.lines.at(i).*; - try stream.writeByteNTimes(' ', indent + indent_delta); - try stream.print("{}", tree.tokenSlice(t)); + if (!skip_first_indent) { + try stream.writeByteNTimes(' ', indent + indent_delta); + } + try renderToken(tree, stream, t, indent, Space.None); + skip_first_indent = false; } try stream.writeByteNTimes(' ', indent); }, ast.Node.Id.UndefinedLiteral => { const undefined_literal = @fieldParentPtr(ast.Node.UndefinedLiteral, "base", base); - try stream.print("{}", tree.tokenSlice(undefined_literal.token)); + try renderToken(tree, stream, undefined_literal.token, indent, space); }, ast.Node.Id.BuiltinCall => { const builtin_call = @fieldParentPtr(ast.Node.BuiltinCall, "base", base); - try stream.print("{}(", tree.tokenSlice(builtin_call.builtin_token)); + + try renderToken(tree, stream, builtin_call.builtin_token, indent, Space.None); // @name + try renderToken(tree, stream, tree.nextToken(builtin_call.builtin_token), indent, Space.None); // ( var it = builtin_call.params.iterator(0); while (it.next()) |param_node| { - try renderExpression(allocator, stream, tree, indent, param_node.*); + try renderExpression(allocator, stream, tree, indent, param_node.*, Space.None); + if (it.peek() != null) { - try stream.write(", "); + const comma_token = tree.nextToken(param_node.*.lastToken()); + try renderToken(tree, stream, comma_token, indent, Space.Space); // , } } - try stream.write(")"); + try renderToken(tree, stream, builtin_call.rparen_token, indent, space); // ) }, ast.Node.Id.FnProto => { @@ -706,75 +766,83 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind if (fn_proto.visib_token) |visib_token_index| { const visib_token = tree.tokens.at(visib_token_index); assert(visib_token.id == Token.Id.Keyword_pub or visib_token.id == Token.Id.Keyword_export); - try stream.print("{} ", tree.tokenSlice(visib_token_index)); + + try renderToken(tree, stream, visib_token_index, indent, Space.Space); // pub } if (fn_proto.extern_export_inline_token) |extern_export_inline_token| { - try stream.print("{} ", tree.tokenSlice(extern_export_inline_token)); + try renderToken(tree, stream, extern_export_inline_token, indent, Space.Space); // extern/export } if (fn_proto.lib_name) |lib_name| { - try renderExpression(allocator, stream, tree, indent, lib_name); - try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, lib_name, Space.Space); } if (fn_proto.cc_token) |cc_token| { - try stream.print("{} ", tree.tokenSlice(cc_token)); + try renderToken(tree, stream, cc_token, indent, Space.Space); // stdcallcc } if (fn_proto.async_attr) |async_attr| { - try renderExpression(allocator, stream, tree, indent, &async_attr.base); - try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, &async_attr.base, Space.Space); } - try stream.write("fn"); - - if (fn_proto.name_token) |name_token| { - try stream.print(" {}", tree.tokenSlice(name_token)); + if (fn_proto.name_token) |name_token| blk: { + try renderToken(tree, stream, fn_proto.fn_token, indent, Space.Space); // fn + try renderToken(tree, stream, name_token, indent, Space.None); // name + try renderToken(tree, stream, tree.nextToken(name_token), indent, Space.None); // ( + } else blk: { + try renderToken(tree, stream, fn_proto.fn_token, indent, Space.None); // fn + try renderToken(tree, stream, tree.nextToken(fn_proto.fn_token), indent, Space.None); // ( } - try stream.write("("); - var it = fn_proto.params.iterator(0); while (it.next()) |param_decl_node| { try renderParamDecl(allocator, stream, tree, indent, param_decl_node.*); if (it.peek() != null) { - try stream.write(", "); + const comma = tree.nextToken(param_decl_node.*.lastToken()); + try renderToken(tree, stream, comma, indent, Space.Space); // , } } - try stream.write(") "); + const rparen = tree.prevToken(switch (fn_proto.return_type) { + ast.Node.FnProto.ReturnType.Explicit => |node| node.firstToken(), + ast.Node.FnProto.ReturnType.InferErrorSet => |node| tree.prevToken(node.firstToken()), + }); + try renderToken(tree, stream, rparen, indent, Space.Space); // ) if (fn_proto.align_expr) |align_expr| { - try stream.write("align("); - try renderExpression(allocator, stream, tree, indent, align_expr); - try stream.write(") "); + const align_rparen = tree.nextToken(align_expr.lastToken()); + const align_lparen = tree.prevToken(align_expr.firstToken()); + const align_kw = tree.prevToken(align_lparen); + + try renderToken(tree, stream, align_kw, indent, Space.None); // align + try renderToken(tree, stream, align_lparen, indent, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, align_expr, Space.None); + try renderToken(tree, stream, align_rparen, indent, Space.Space); // ) } switch (fn_proto.return_type) { ast.Node.FnProto.ReturnType.Explicit => |node| { - try renderExpression(allocator, stream, tree, indent, node); + try renderExpression(allocator, stream, tree, indent, node, space); }, ast.Node.FnProto.ReturnType.InferErrorSet => |node| { - try stream.write("!"); - try renderExpression(allocator, stream, tree, indent, node); + try renderToken(tree, stream, tree.prevToken(node.firstToken()), indent, Space.None); // ! + try renderExpression(allocator, stream, tree, indent, node, space); }, } }, ast.Node.Id.PromiseType => { const promise_type = @fieldParentPtr(ast.Node.PromiseType, "base", base); - try stream.write(tree.tokenSlice(promise_type.promise_token)); - if (promise_type.result) |result| { - try stream.write(tree.tokenSlice(result.arrow_token)); - try renderExpression(allocator, stream, tree, indent, result.return_type); - } - }, - ast.Node.Id.LineComment => { - const line_comment_node = @fieldParentPtr(ast.Node.LineComment, "base", base); - try stream.write(tree.tokenSlice(line_comment_node.token)); + if (promise_type.result) |result| { + try renderToken(tree, stream, promise_type.promise_token, indent, Space.None); // promise + try renderToken(tree, stream, result.arrow_token, indent, Space.None); // -> + try renderExpression(allocator, stream, tree, indent, result.return_type, space); + } else { + try renderToken(tree, stream, promise_type.promise_token, indent, space); // promise + } }, ast.Node.Id.DocComment => unreachable, // doc comments are attached to nodes @@ -782,32 +850,39 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.Switch => { const switch_node = @fieldParentPtr(ast.Node.Switch, "base", base); - try stream.print("{} (", tree.tokenSlice(switch_node.switch_token)); + try renderToken(tree, stream, switch_node.switch_token, indent, Space.Space); // switch + try renderToken(tree, stream, tree.nextToken(switch_node.switch_token), indent, Space.None); // ( + + const rparen = tree.nextToken(switch_node.expr.lastToken()); + const lbrace = tree.nextToken(rparen); + if (switch_node.cases.len == 0) { - try renderExpression(allocator, stream, tree, indent, switch_node.expr); - try stream.write(") {}"); + try renderExpression(allocator, stream, tree, indent, switch_node.expr, Space.None); + try renderToken(tree, stream, rparen, indent, Space.Space); // ) + try renderToken(tree, stream, lbrace, indent, Space.None); // { + try renderToken(tree, stream, switch_node.rbrace, indent, space); // } return; } - try renderExpression(allocator, stream, tree, indent, switch_node.expr); - try stream.write(") {\n"); + try renderExpression(allocator, stream, tree, indent, switch_node.expr, Space.None); + + try renderToken(tree, stream, rparen, indent, Space.Space); // ) + try renderToken(tree, stream, lbrace, indent, Space.Newline); // { const new_indent = indent + indent_delta; var it = switch_node.cases.iterator(0); while (it.next()) |node| { try stream.writeByteNTimes(' ', new_indent); - try renderExpression(allocator, stream, tree, new_indent, node.*); + try renderExpression(allocator, stream, tree, new_indent, node.*, Space.Newline); if (it.peek()) |next_node| { - const n = if (nodeLineOffset(tree, node.*, next_node.*) >= 2) u8(2) else u8(1); - try stream.writeByteNTimes('\n', n); + try renderExtraNewline(tree, stream, next_node.*); } } - try stream.write("\n"); try stream.writeByteNTimes(' ', indent); - try stream.write("}"); + try renderToken(tree, stream, switch_node.rbrace, indent, space); // } }, ast.Node.Id.SwitchCase => { @@ -815,54 +890,50 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = switch_case.items.iterator(0); while (it.next()) |node| { - try renderExpression(allocator, stream, tree, indent, node.*); + if (it.peek()) |next_node| { + try renderExpression(allocator, stream, tree, indent, node.*, Space.None); - if (it.peek() != null) { - try stream.write(",\n"); + const comma_token = tree.nextToken(node.*.lastToken()); + try renderToken(tree, stream, comma_token, indent, Space.Newline); // , + try renderExtraNewline(tree, stream, next_node.*); try stream.writeByteNTimes(' ', indent); + } else { + try renderExpression(allocator, stream, tree, indent, node.*, Space.Space); } } - try stream.write(" => "); + try renderToken(tree, stream, switch_case.arrow_token, indent, Space.Space); // => if (switch_case.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload); - try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); } - try renderExpression(allocator, stream, tree, indent, switch_case.expr); - { - // Handle missing comma after last switch case - var index = switch_case.lastToken() + 1; - switch (tree.tokens.at(index).id) { - Token.Id.RBrace => { - try stream.write(","); - }, - Token.Id.LineComment => { - try stream.write(", "); - try renderToken(tree, stream, index, indent, true, true); - }, - else => try renderToken(tree, stream, index, indent, true, true), - } + // add a trailing comma if necessary + const end_token = switch_case.lastToken() + 1; + switch (tree.tokens.at(end_token).id) { + Token.Id.Comma => { + try renderExpression(allocator, stream, tree, indent, switch_case.expr, Space.None); + try renderToken(tree, stream, end_token, indent, space); // , + }, + Token.Id.LineComment => { + try renderExpression(allocator, stream, tree, indent, switch_case.expr, Space.NoComment); + try stream.write(", "); + try renderToken(tree, stream, end_token, indent, space); + }, + else => { + try renderExpression(allocator, stream, tree, indent, switch_case.expr, Space.None); + try stream.write(",\n"); + assert(space == Space.Newline); + }, } }, ast.Node.Id.SwitchElse => { const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base); - try stream.print("{}", tree.tokenSlice(switch_else.token)); + try renderToken(tree, stream, switch_else.token, indent, space); }, ast.Node.Id.Else => { const else_node = @fieldParentPtr(ast.Node.Else, "base", base); - var prev_tok_index = else_node.else_token - 1; - while (tree.tokens.at(prev_tok_index).id == Token.Id.LineComment) : (prev_tok_index -= 1) { } - prev_tok_index += 1; - while (prev_tok_index < else_node.else_token) : (prev_tok_index += 1) { - try stream.print("{}\n", tree.tokenSlice(prev_tok_index)); - try stream.writeByteNTimes(' ', indent); - } - - try stream.print("{}", tree.tokenSlice(else_node.else_token)); - const block_body = switch (else_node.body.id) { ast.Node.Id.Block, ast.Node.Id.If, @@ -872,21 +943,19 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind else => false, }; - if (block_body) { - try stream.write(" "); - } + const after_else_space = if (block_body or else_node.payload != null) Space.Space else Space.Newline; + try renderToken(tree, stream, else_node.else_token, indent, after_else_space); if (else_node.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload); - try stream.write(" "); + const payload_space = if (block_body) Space.Space else Space.Newline; + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); } if (block_body) { - try renderExpression(allocator, stream, tree, indent, else_node.body); + try renderExpression(allocator, stream, tree, indent, else_node.body, space); } else { - try stream.write("\n"); try stream.writeByteNTimes(' ', indent + indent_delta); - try renderExpression(allocator, stream, tree, indent, else_node.body); + try renderExpression(allocator, stream, tree, indent, else_node.body, space); } }, @@ -894,103 +963,134 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const while_node = @fieldParentPtr(ast.Node.While, "base", base); if (while_node.label) |label| { - try stream.print("{}: ", tree.tokenSlice(label)); + try renderToken(tree, stream, label, indent, Space.None); // label + try renderToken(tree, stream, tree.nextToken(label), indent, Space.Space); // : } if (while_node.inline_token) |inline_token| { - try stream.print("{} ", tree.tokenSlice(inline_token)); + try renderToken(tree, stream, inline_token, indent, Space.Space); // inline } - try stream.print("{} (", tree.tokenSlice(while_node.while_token)); - try renderExpression(allocator, stream, tree, indent, while_node.condition); - try stream.write(")"); + try renderToken(tree, stream, while_node.while_token, indent, Space.Space); // while + try renderToken(tree, stream, tree.nextToken(while_node.while_token), indent, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, while_node.condition, Space.None); + + { + const rparen = tree.nextToken(while_node.condition.lastToken()); + const rparen_space = if (while_node.payload != null or while_node.continue_expr != null or + while_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; + try renderToken(tree, stream, rparen, indent, rparen_space); // ) + } if (while_node.payload) |payload| { - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, payload); + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); } if (while_node.continue_expr) |continue_expr| { - try stream.write(" : ("); - try renderExpression(allocator, stream, tree, indent, continue_expr); - try stream.write(")"); + const rparen = tree.nextToken(continue_expr.lastToken()); + const lparen = tree.prevToken(continue_expr.firstToken()); + const colon = tree.prevToken(lparen); + + try renderToken(tree, stream, colon, indent, Space.Space); // : + try renderToken(tree, stream, lparen, indent, Space.None); // ( + + try renderExpression(allocator, stream, tree, indent, continue_expr, Space.None); + + const rparen_space = if (while_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; + try renderToken(tree, stream, rparen, indent, rparen_space); // ) } + const body_space = blk: { + if (while_node.@"else" != null) { + break :blk if (while_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; + } else { + break :blk space; + } + }; + if (while_node.body.id == ast.Node.Id.Block) { - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, while_node.body); + try renderExpression(allocator, stream, tree, indent, while_node.body, body_space); } else { - try stream.write("\n"); try stream.writeByteNTimes(' ', indent + indent_delta); - try renderExpression(allocator, stream, tree, indent, while_node.body); + try renderExpression(allocator, stream, tree, indent, while_node.body, body_space); } if (while_node.@"else") |@"else"| { if (while_node.body.id == ast.Node.Id.Block) { - try stream.write(" "); } else { - try stream.write("\n"); try stream.writeByteNTimes(' ', indent); } - try renderExpression(allocator, stream, tree, indent, &@"else".base); + try renderExpression(allocator, stream, tree, indent, &@"else".base, space); } }, ast.Node.Id.For => { const for_node = @fieldParentPtr(ast.Node.For, "base", base); + if (for_node.label) |label| { - try stream.print("{}: ", tree.tokenSlice(label)); + try renderToken(tree, stream, label, indent, Space.None); // label + try renderToken(tree, stream, tree.nextToken(label), indent, Space.Space); // : } if (for_node.inline_token) |inline_token| { - try stream.print("{} ", tree.tokenSlice(inline_token)); + try renderToken(tree, stream, inline_token, indent, Space.Space); // inline } - try stream.print("{} (", tree.tokenSlice(for_node.for_token)); - try renderExpression(allocator, stream, tree, indent, for_node.array_expr); - try stream.write(")"); + try renderToken(tree, stream, for_node.for_token, indent, Space.Space); // for + try renderToken(tree, stream, tree.nextToken(for_node.for_token), indent, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, for_node.array_expr, Space.None); + + const rparen = tree.nextToken(for_node.array_expr.lastToken()); + const rparen_space = if (for_node.payload != null or + for_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; + try renderToken(tree, stream, rparen, indent, rparen_space); // ) if (for_node.payload) |payload| { - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, payload); + const payload_space = if (for_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; + try renderExpression(allocator, stream, tree, indent, payload, payload_space); } + const body_space = blk: { + if (for_node.@"else" != null) { + if (for_node.body.id == ast.Node.Id.Block) { + break :blk Space.Space; + } else { + break :blk Space.Newline; + } + } else { + break :blk space; + } + }; if (for_node.body.id == ast.Node.Id.Block) { - try stream.write(" "); - try renderExpression(allocator, stream, tree, indent, for_node.body); + try renderExpression(allocator, stream, tree, indent, for_node.body, body_space); } else { - try stream.write("\n"); try stream.writeByteNTimes(' ', indent + indent_delta); - try renderExpression(allocator, stream, tree, indent, for_node.body); + try renderExpression(allocator, stream, tree, indent, for_node.body, body_space); } if (for_node.@"else") |@"else"| { - if (for_node.body.id == ast.Node.Id.Block) { - try stream.write(" "); - } else { - try stream.write("\n"); + if (for_node.body.id != ast.Node.Id.Block) { try stream.writeByteNTimes(' ', indent); } - try renderExpression(allocator, stream, tree, indent, &@"else".base); + try renderExpression(allocator, stream, tree, indent, &@"else".base, space); } }, ast.Node.Id.If => { const if_node = @fieldParentPtr(ast.Node.If, "base", base); - try stream.print("{} (", tree.tokenSlice(if_node.if_token)); - try renderExpression(allocator, stream, tree, indent, if_node.condition); - try renderToken(tree, stream, if_node.condition.lastToken() + 1, indent, false, true); + try renderToken(tree, stream, if_node.if_token, indent, Space.Space); + try renderToken(tree, stream, tree.prevToken(if_node.condition.firstToken()), indent, Space.None); + + try renderExpression(allocator, stream, tree, indent, if_node.condition, Space.None); + try renderToken(tree, stream, tree.nextToken(if_node.condition.lastToken()), indent, Space.Space); if (if_node.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload); - try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); } - try renderExpression(allocator, stream, tree, indent, if_node.body); - switch (if_node.body.id) { ast.Node.Id.Block, ast.Node.Id.If, @@ -999,25 +1099,29 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.Switch => { if (if_node.@"else") |@"else"| { if (if_node.body.id == ast.Node.Id.Block) { - try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Space); } else { - try stream.write("\n"); + try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Newline); try stream.writeByteNTimes(' ', indent); } - try renderExpression(allocator, stream, tree, indent, &@"else".base); + try renderExpression(allocator, stream, tree, indent, &@"else".base, space); + } else { + try renderExpression(allocator, stream, tree, indent, if_node.body, space); } }, else => { if (if_node.@"else") |@"else"| { - try stream.print(" {} ", tree.tokenSlice(@"else".else_token)); + try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Space); + try renderToken(tree, stream, @"else".else_token, indent, Space.Space); if (@"else".payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload); - try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); } - try renderExpression(allocator, stream, tree, indent, @"else".body); + try renderExpression(allocator, stream, tree, indent, @"else".body, space); + } else { + try renderExpression(allocator, stream, tree, indent, if_node.body, space); } }, } @@ -1025,15 +1129,17 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.Asm => { const asm_node = @fieldParentPtr(ast.Node.Asm, "base", base); - try stream.print("{} ", tree.tokenSlice(asm_node.asm_token)); + + try renderToken(tree, stream, asm_node.asm_token, indent, Space.Space); // asm if (asm_node.volatile_token) |volatile_token| { - try stream.print("{} ", tree.tokenSlice(volatile_token)); + try renderToken(tree, stream, volatile_token, indent, Space.Space); // volatile + try renderToken(tree, stream, tree.nextToken(volatile_token), indent, Space.None); // ( + } else { + try renderToken(tree, stream, tree.nextToken(asm_node.asm_token), indent, Space.None); // ( } - try stream.print("("); - try renderExpression(allocator, stream, tree, indent, asm_node.template); - try stream.print("\n"); + try renderExpression(allocator, stream, tree, indent, asm_node.template, Space.Newline); const indent_once = indent + indent_delta; try stream.writeByteNTimes(' ', indent_once); try stream.print(": "); @@ -1043,13 +1149,15 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = asm_node.outputs.iterator(0); while (it.next()) |asm_output| { const node = &(asm_output.*).base; - try renderExpression(allocator, stream, tree, indent_extra, node); + try renderExpression(allocator, stream, tree, indent_extra, node, Space.None); if (it.peek()) |next_asm_output| { const next_node = &(next_asm_output.*).base; - const n = if (nodeLineOffset(tree, node, next_node) >= 2) u8(2) else u8(1); - try stream.writeByte(','); - try stream.writeByteNTimes('\n', n); + + const comma = tree.prevToken(next_asm_output.*.firstToken()); + try renderToken(tree, stream, comma, indent_extra, Space.Newline); // , + try renderExtraNewline(tree, stream, next_node); + try stream.writeByteNTimes(' ', indent_extra); } } @@ -1063,13 +1171,15 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = asm_node.inputs.iterator(0); while (it.next()) |asm_input| { const node = &(asm_input.*).base; - try renderExpression(allocator, stream, tree, indent_extra, node); + try renderExpression(allocator, stream, tree, indent_extra, node, Space.None); if (it.peek()) |next_asm_input| { const next_node = &(next_asm_input.*).base; - const n = if (nodeLineOffset(tree, node, next_node) >= 2) u8(2) else u8(1); - try stream.writeByte(','); - try stream.writeByteNTimes('\n', n); + + const comma = tree.prevToken(next_asm_input.*.firstToken()); + try renderToken(tree, stream, comma, indent_extra, Space.Newline); // , + try renderExtraNewline(tree, stream, next_node); + try stream.writeByteNTimes(' ', indent_extra); } } @@ -1082,7 +1192,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind { var it = asm_node.clobbers.iterator(0); while (it.next()) |node| { - try renderExpression(allocator, stream, tree, indent_once, node.*); + try renderExpression(allocator, stream, tree, indent_once, node.*, Space.None); if (it.peek() != null) { try stream.write(", "); @@ -1090,47 +1200,46 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } } - try stream.write(")"); + try renderToken(tree, stream, asm_node.rparen, indent, space); }, ast.Node.Id.AsmInput => { const asm_input = @fieldParentPtr(ast.Node.AsmInput, "base", base); try stream.write("["); - try renderExpression(allocator, stream, tree, indent, asm_input.symbolic_name); + try renderExpression(allocator, stream, tree, indent, asm_input.symbolic_name, Space.None); try stream.write("] "); - try renderExpression(allocator, stream, tree, indent, asm_input.constraint); + try renderExpression(allocator, stream, tree, indent, asm_input.constraint, Space.None); try stream.write(" ("); - try renderExpression(allocator, stream, tree, indent, asm_input.expr); - try stream.write(")"); + try renderExpression(allocator, stream, tree, indent, asm_input.expr, Space.None); + try renderToken(tree, stream, asm_input.lastToken(), indent, space); // ) }, ast.Node.Id.AsmOutput => { const asm_output = @fieldParentPtr(ast.Node.AsmOutput, "base", base); try stream.write("["); - try renderExpression(allocator, stream, tree, indent, asm_output.symbolic_name); + try renderExpression(allocator, stream, tree, indent, asm_output.symbolic_name, Space.None); try stream.write("] "); - try renderExpression(allocator, stream, tree, indent, asm_output.constraint); + try renderExpression(allocator, stream, tree, indent, asm_output.constraint, Space.None); try stream.write(" ("); switch (asm_output.kind) { ast.Node.AsmOutput.Kind.Variable => |variable_name| { - try renderExpression(allocator, stream, tree, indent, &variable_name.base); + try renderExpression(allocator, stream, tree, indent, &variable_name.base, Space.None); }, ast.Node.AsmOutput.Kind.Return => |return_type| { try stream.write("-> "); - try renderExpression(allocator, stream, tree, indent, return_type); + try renderExpression(allocator, stream, tree, indent, return_type, Space.None); }, } - try stream.write(")"); + try renderToken(tree, stream, asm_output.lastToken(), indent, space); // ) }, ast.Node.Id.StructField, ast.Node.Id.UnionTag, ast.Node.Id.EnumTag, - ast.Node.Id.ErrorTag, ast.Node.Id.Root, ast.Node.Id.VarDecl, ast.Node.Id.Use, @@ -1139,70 +1248,74 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } } -fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, var_decl: &ast.Node.VarDecl) (@typeOf(stream).Child.Error || Error)!void { +fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, + var_decl: &ast.Node.VarDecl) (@typeOf(stream).Child.Error || Error)!void +{ if (var_decl.visib_token) |visib_token| { - try renderToken(tree, stream, visib_token, indent, false, true); + try renderToken(tree, stream, visib_token, indent, Space.Space); // pub } if (var_decl.extern_export_token) |extern_export_token| { - try renderToken(tree, stream, extern_export_token, indent, false, true); + try renderToken(tree, stream, extern_export_token, indent, Space.Space); // extern if (var_decl.lib_name) |lib_name| { - try renderExpression(allocator, stream, tree, indent, lib_name); - try stream.write(" "); + try renderExpression(allocator, stream, tree, indent, lib_name, Space.Space); // "lib" } } if (var_decl.comptime_token) |comptime_token| { - try renderToken(tree, stream, comptime_token, indent, false, true); + try renderToken(tree, stream, comptime_token, indent, Space.Space); // comptime } - try renderToken(tree, stream, var_decl.mut_token, indent, false, true); - try renderToken(tree, stream, var_decl.name_token, indent, false, false); + try renderToken(tree, stream, var_decl.mut_token, indent, Space.Space); // var + + const name_space = if (var_decl.type_node == null and (var_decl.align_node != null or + var_decl.init_node != null)) Space.Space else Space.None; + try renderToken(tree, stream, var_decl.name_token, indent, name_space); if (var_decl.type_node) |type_node| { - try stream.write(": "); - try renderExpression(allocator, stream, tree, indent, type_node); + try renderToken(tree, stream, tree.nextToken(var_decl.name_token), indent, Space.Space); + const s = if (var_decl.align_node != null or var_decl.init_node != null) Space.Space else Space.None; + try renderExpression(allocator, stream, tree, indent, type_node, s); } if (var_decl.align_node) |align_node| { - try stream.write(" align("); - try renderExpression(allocator, stream, tree, indent, align_node); - try stream.write(")"); + const lparen = tree.prevToken(align_node.firstToken()); + const align_kw = tree.prevToken(lparen); + const rparen = tree.nextToken(align_node.lastToken()); + try renderToken(tree, stream, align_kw, indent, Space.None); // align + try renderToken(tree, stream, lparen, indent, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, align_node, Space.None); + const s = if (var_decl.init_node != null) Space.Space else Space.None; + try renderToken(tree, stream, rparen, indent, s); // ) } if (var_decl.init_node) |init_node| { - const text = if (init_node.id == ast.Node.Id.MultilineStringLiteral) " =" else " = "; - try stream.write(text); - try renderExpression(allocator, stream, tree, indent, init_node); + const s = if (init_node.id == ast.Node.Id.MultilineStringLiteral) Space.None else Space.Space; + try renderToken(tree, stream, var_decl.eq_token, indent, s); // = + try renderExpression(allocator, stream, tree, indent, init_node, Space.None); } - try renderToken(tree, stream, var_decl.semicolon_token, indent, true, false); -} - -fn maybeRenderSemicolon(stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { - if (base.requireSemiColon()) { - const semicolon_index = base.lastToken() + 1; - assert(tree.tokens.at(semicolon_index).id == Token.Id.Semicolon); - try renderToken(tree, stream, semicolon_index, indent, true, true); - } + try renderToken(tree, stream, var_decl.semicolon_token, indent, Space.Newline); } fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base); + if (param_decl.comptime_token) |comptime_token| { - try stream.print("{} ", tree.tokenSlice(comptime_token)); + try renderToken(tree, stream, comptime_token, indent, Space.Space); } if (param_decl.noalias_token) |noalias_token| { - try stream.print("{} ", tree.tokenSlice(noalias_token)); + try renderToken(tree, stream, noalias_token, indent, Space.Space); } if (param_decl.name_token) |name_token| { - try stream.print("{}: ", tree.tokenSlice(name_token)); + try renderToken(tree, stream, name_token, indent, Space.None); + try renderToken(tree, stream, tree.nextToken(name_token), indent, Space.Space); // : } if (param_decl.var_args_token) |var_args_token| { - try stream.print("{}", tree.tokenSlice(var_args_token)); + try renderToken(tree, stream, var_args_token, indent, Space.None); } else { - try renderExpression(allocator, stream, tree, indent, param_decl.type_node); + try renderExpression(allocator, stream, tree, indent, param_decl.type_node, Space.None); } } @@ -1213,41 +1326,104 @@ fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, inde try renderVarDecl(allocator, stream, tree, indent, var_decl); }, else => { - try renderExpression(allocator, stream, tree, indent, base); - try maybeRenderSemicolon(stream, tree, indent, base); + if (base.requireSemiColon()) { + try renderExpression(allocator, stream, tree, indent, base, Space.None); + + const semicolon_index = tree.nextToken(base.lastToken()); + assert(tree.tokens.at(semicolon_index).id == Token.Id.Semicolon); + try renderToken(tree, stream, semicolon_index, indent, Space.Newline); + } else { + try renderExpression(allocator, stream, tree, indent, base, Space.Newline); + } }, } } -fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, line_break: bool, space: bool) (@typeOf(stream).Child.Error || Error)!void { - const token = tree.tokens.at(token_index); +const Space = enum { + None, + Newline, + Space, + NoNewline, + NoIndent, + NoComment, +}; + +fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, space: Space) (@typeOf(stream).Child.Error || Error)!void { + var token = tree.tokens.at(token_index); try stream.write(tree.tokenSlicePtr(token)); - const next_token = tree.tokens.at(token_index + 1); - if (next_token.id == Token.Id.LineComment) { - const loc = tree.tokenLocationPtr(token.end, next_token); - if (loc.line == 0) { - try stream.print(" {}", tree.tokenSlicePtr(next_token)); - if (!line_break) { - try stream.write("\n"); + if (space == Space.NoComment) return; - const after_comment_token = tree.tokens.at(token_index + 2); - const next_line_indent = switch (after_comment_token.id) { - Token.Id.RParen, Token.Id.RBrace, Token.Id.RBracket => indent, - else => indent + indent_delta, - }; - try stream.writeByteNTimes(' ', next_line_indent); - return; - } + var next_token = tree.tokens.at(token_index + 1); + if (next_token.id != Token.Id.LineComment) { + switch (space) { + Space.None, Space.NoNewline, Space.NoIndent => return, + Space.Newline => return stream.write("\n"), + Space.Space => return stream.writeByte(' '), + Space.NoComment => unreachable, } } - if (!line_break and space) { - try stream.writeByte(' '); + var loc = tree.tokenLocationPtr(token.end, next_token); + var offset: usize = 1; + if (loc.line == 0) { + try stream.print(" {}", tree.tokenSlicePtr(next_token)); + offset = 2; + token = next_token; + next_token = tree.tokens.at(token_index + offset); + if (next_token.id != Token.Id.LineComment) { + switch (space) { + Space.None, Space.Space => { + try stream.writeByte('\n'); + const after_comment_token = tree.tokens.at(token_index + offset); + const next_line_indent = switch (after_comment_token.id) { + Token.Id.RParen, Token.Id.RBrace, Token.Id.RBracket => indent, + else => indent + indent_delta, + }; + try stream.writeByteNTimes(' ', next_line_indent); + }, + Space.Newline, Space.NoIndent => try stream.write("\n"), + Space.NoNewline => {}, + Space.NoComment => unreachable, + } + return; + } + loc = tree.tokenLocationPtr(token.end, next_token); + } + + while (true) { + assert(loc.line != 0); + const newline_count = if (loc.line == 1) u8(1) else u8(2); + try stream.writeByteNTimes('\n', newline_count); + try stream.writeByteNTimes(' ', indent); + try stream.write(tree.tokenSlicePtr(next_token)); + + offset += 1; + token = next_token; + next_token = tree.tokens.at(token_index + offset); + if (next_token.id != Token.Id.LineComment) { + switch (space) { + Space.Newline, Space.NoIndent => try stream.writeByte('\n'), + Space.None, Space.Space => { + try stream.writeByte('\n'); + + const after_comment_token = tree.tokens.at(token_index + offset); + const next_line_indent = switch (after_comment_token.id) { + Token.Id.RParen, Token.Id.RBrace, Token.Id.RBracket => indent, + else => indent, + }; + try stream.writeByteNTimes(' ', next_line_indent); + }, + Space.NoNewline => {}, + Space.NoComment => unreachable, + } + return; + } + loc = tree.tokenLocationPtr(token.end, next_token); } } -fn renderComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@typeOf(stream).Child.Error || Error)!void { +fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@typeOf(stream).Child.Error || Error)!void { const comment = node.doc_comments ?? return; var it = comment.lines.iterator(0); while (it.next()) |line_token_index| { From 54e887ed9e774c6fd68f51d97e2c5c760e48be30 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 24 May 2018 01:15:50 -0400 Subject: [PATCH 32/75] std.zig.tokenizer: fix tokenization of hex floats --- std/zig/parser_test.zig | 15 +++++---- std/zig/tokenizer.zig | 75 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 77 insertions(+), 13 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 38ffee8aaf..c11db78775 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,11 @@ +test "zig fmt: float literal with exponent" { + try testCanonical( + \\pub const f64_true_min = 4.94065645841246544177e-324; + \\const threshold = 0x1.a827999fcef32p+1022; + \\ + ); +} + test "zig fmt: if-else end of comptime" { try testCanonical( \\comptime { @@ -238,13 +246,6 @@ test "zig fmt: switch with empty body" { ); } -test "zig fmt: float literal with exponent" { - try testCanonical( - \\pub const f64_true_min = 4.94065645841246544177e-324; - \\ - ); -} - test "zig fmt: line comments in struct initializer" { try testCanonical( \\fn foo() void { diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig index b0e5014a1a..afea7fc899 100644 --- a/std/zig/tokenizer.zig +++ b/std/zig/tokenizer.zig @@ -6,12 +6,12 @@ pub const Token = struct { start: usize, end: usize, - const Keyword = struct { + pub const Keyword = struct { bytes: []const u8, id: Id, }; - const keywords = []Keyword { + pub const keywords = []Keyword { Keyword{.bytes="align", .id = Id.Keyword_align}, Keyword{.bytes="and", .id = Id.Keyword_and}, Keyword{.bytes="asm", .id = Id.Keyword_asm}, @@ -62,6 +62,7 @@ pub const Token = struct { Keyword{.bytes="while", .id = Id.Keyword_while}, }; + // TODO perfect hash at comptime fn getKeyword(bytes: []const u8) ?Id { for (keywords) |kw| { if (mem.eql(u8, kw.bytes, bytes)) { @@ -236,10 +237,15 @@ pub const Tokenizer = struct { Zero, IntegerLiteral, IntegerLiteralWithRadix, + IntegerLiteralWithRadixHex, NumberDot, + NumberDotHex, FloatFraction, + FloatFractionHex, FloatExponentUnsigned, + FloatExponentUnsignedHex, FloatExponentNumber, + FloatExponentNumberHex, Ampersand, Caret, Percent, @@ -839,9 +845,12 @@ pub const Tokenizer = struct { else => self.checkLiteralCharacter(), }, State.Zero => switch (c) { - 'b', 'o', 'x' => { + 'b', 'o' => { state = State.IntegerLiteralWithRadix; }, + 'x' => { + state = State.IntegerLiteralWithRadixHex; + }, else => { // reinterpret as a normal number self.index -= 1; @@ -862,8 +871,15 @@ pub const Tokenizer = struct { '.' => { state = State.NumberDot; }, + '0'...'9' => {}, + else => break, + }, + State.IntegerLiteralWithRadixHex => switch (c) { + '.' => { + state = State.NumberDotHex; + }, 'p', 'P' => { - state = State.FloatExponentUnsigned; + state = State.FloatExponentUnsignedHex; }, '0'...'9', 'a'...'f', 'A'...'F' => {}, else => break, @@ -880,13 +896,32 @@ pub const Tokenizer = struct { state = State.FloatFraction; }, }, + State.NumberDotHex => switch (c) { + '.' => { + self.index -= 1; + state = State.Start; + break; + }, + else => { + self.index -= 1; + result.id = Token.Id.FloatLiteral; + state = State.FloatFractionHex; + }, + }, State.FloatFraction => switch (c) { - 'p', 'P', 'e', 'E' => { + 'e', 'E' => { state = State.FloatExponentUnsigned; }, '0'...'9' => {}, else => break, }, + State.FloatFractionHex => switch (c) { + 'p', 'P' => { + state = State.FloatExponentUnsignedHex; + }, + '0'...'9', 'a'...'f', 'A'...'F' => {}, + else => break, + }, State.FloatExponentUnsigned => switch (c) { '+', '-' => { state = State.FloatExponentNumber; @@ -897,7 +932,21 @@ pub const Tokenizer = struct { state = State.FloatExponentNumber; } }, + State.FloatExponentUnsignedHex => switch (c) { + '+', '-' => { + state = State.FloatExponentNumberHex; + }, + else => { + // reinterpret as a normal exponent number + self.index -= 1; + state = State.FloatExponentNumberHex; + } + }, State.FloatExponentNumber => switch (c) { + '0'...'9' => {}, + else => break, + }, + State.FloatExponentNumberHex => switch (c) { '0'...'9', 'a'...'f', 'A'...'F' => {}, else => break, }, @@ -908,8 +957,11 @@ pub const Tokenizer = struct { State.C, State.IntegerLiteral, State.IntegerLiteralWithRadix, + State.IntegerLiteralWithRadixHex, State.FloatFraction, + State.FloatFractionHex, State.FloatExponentNumber, + State.FloatExponentNumberHex, State.StringLiteral, // find this error later State.MultilineStringLiteralLine, State.Builtin => {}, @@ -928,7 +980,9 @@ pub const Tokenizer = struct { }, State.NumberDot, + State.NumberDotHex, State.FloatExponentUnsigned, + State.FloatExponentUnsignedHex, State.SawAtSign, State.Backslash, State.MultilineStringLiteralLineBackslash, @@ -1073,7 +1127,7 @@ test "tokenizer" { }); } -test "tokenizer - float literal" { +test "tokenizer - float literal e exponent" { testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id { Token.Id.Identifier, Token.Id.Equal, @@ -1082,6 +1136,15 @@ test "tokenizer - float literal" { }); } +test "tokenizer - float literal p exponent" { + testTokenize("a = 0x1.a827999fcef32p+1022;\n", []Token.Id { + Token.Id.Identifier, + Token.Id.Equal, + Token.Id.FloatLiteral, + Token.Id.Semicolon, + }); +} + test "tokenizer - chars" { testTokenize("'c'", []Token.Id {Token.Id.CharLiteral}); } From 938d791b23d58abf2bad4aa90ae3496ae9bb2435 Mon Sep 17 00:00:00 2001 From: "braedonww@gmail.com" Date: Thu, 17 May 2018 10:43:59 +1000 Subject: [PATCH 33/75] Added argtype and error inferring info --- doc/langref.html.in | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/doc/langref.html.in b/doc/langref.html.in index d047c7d9f2..6995cbab33 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -3111,7 +3111,40 @@ test "error union" { {#code_end#}

    TODO the || operator for error sets

    {#header_open|Inferred Error Sets#} -

    TODO

    +{#code_begin|syntax#} +// Defining error set +const NumberError = error { + Zero, + Negative, +}; + +// While you could define it like this explicitly saying the error domain. +// Which means you can return an error like `error.InvalidX` as it is not +// within the NumberError error enum. +fn positiveAdd(a: i32, b: i32) NumberError!i32 { + if (a == 0 or b == 0) return NumberError.Zero; + if (a < 0 or b < 0) return NumberError.Negative; + return a + b; +} + +// You could also just infer the error set from the given thrown errors +fn inferAdd(a: i32, b: i32) !i32 { + // Note: you could either do NumberError.Zero here or just error.Zero + if (a == 0 or b == 0) return error.Zero; + if (a < 0 or b < 0) return error.Negative; + return a + b; +} + +// Quick note: inferAdd creates a definition that has a return type that is; +const InferAddErrorSet = error { + Zero, + Negative, +}; +// Which since it contains only errors from NumberError it can be passed to functions like; +fn printNumberError(err: NumberError) void { } +// However if it also returned an error outside NumberError it would produce a compile error +// if passed into the above function. +{#code_end#} {#header_close#} {#header_close#} {#header_open|Error Return Traces#} @@ -3878,7 +3911,12 @@ pub fn main() void {

    {#header_close#} {#header_open|@ArgType#} -

    TODO

    +
    @ArgType(comptime T: type, comptime n: usize) -> type
    +

    + This builtin function takes a function type and returns the type of the 'n'th parameter. +

    +

    + T must be a function type, and n must be an usize integer. {#header_close#} {#header_open|@atomicLoad#}

    @atomicLoad(comptime T: type, ptr: &const T, comptime ordering: builtin.AtomicOrder) -> T
    From fa5b0ef54fe7a612754c796a899020c73d5fb191 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 24 May 2018 20:59:19 -0400 Subject: [PATCH 34/75] doc fixups --- doc/langref.html.in | 72 ++++++++++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 30 deletions(-) diff --git a/doc/langref.html.in b/doc/langref.html.in index 6995cbab33..c3c50b117b 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -3111,40 +3111,48 @@ test "error union" { {#code_end#}

    TODO the || operator for error sets

    {#header_open|Inferred Error Sets#} -{#code_begin|syntax#} -// Defining error set -const NumberError = error { - Zero, - Negative, -}; - -// While you could define it like this explicitly saying the error domain. -// Which means you can return an error like `error.InvalidX` as it is not -// within the NumberError error enum. -fn positiveAdd(a: i32, b: i32) NumberError!i32 { - if (a == 0 or b == 0) return NumberError.Zero; - if (a < 0 or b < 0) return NumberError.Negative; - return a + b; +

    + Because many functions in Zig return a possible error, Zig supports inferring the error set. + To infer the error set for a function, use this syntax: +

    +{#code_begin|test#} +// With an inferred error set +pub fn add_inferred(comptime T: type, a: T, b: T) !T { + var answer: T = undefined; + return if (@addWithOverflow(T, a, b, &answer)) error.Overflow else answer; } -// You could also just infer the error set from the given thrown errors -fn inferAdd(a: i32, b: i32) !i32 { - // Note: you could either do NumberError.Zero here or just error.Zero - if (a == 0 or b == 0) return error.Zero; - if (a < 0 or b < 0) return error.Negative; - return a + b; +// With an explicit error set +pub fn add_explicit(comptime T: type, a: T, b: T) Error!T { + var answer: T = undefined; + return if (@addWithOverflow(T, a, b, &answer)) error.Overflow else answer; } -// Quick note: inferAdd creates a definition that has a return type that is; -const InferAddErrorSet = error { - Zero, - Negative, +const Error = error { + Overflow, }; -// Which since it contains only errors from NumberError it can be passed to functions like; -fn printNumberError(err: NumberError) void { } -// However if it also returned an error outside NumberError it would produce a compile error -// if passed into the above function. + +const std = @import("std"); + +test "inferred error set" { + if (add_inferred(u8, 255, 1)) |_| unreachable else |err| switch (err) { + error.Overflow => {}, // ok + } +} {#code_end#} +

    + When a function has an inferred error set, that function becomes generic and thus it becomes + trickier to do certain things with it, such as obtain a function pointer, or have an error + set that is consistent across different build targets. Additionally, inferred error sets + are incompatible with recursion. +

    +

    + In these situations, it is recommended to use an explicit error set. You can generally start + with an empty error set and let compile errors guide you toward completing the set. +

    +

    + These limitations may be overcome in a future version of Zig. +

    {#header_close#} {#header_close#} {#header_open|Error Return Traces#} @@ -3913,10 +3921,14 @@ pub fn main() void { {#header_open|@ArgType#}
    @ArgType(comptime T: type, comptime n: usize) -> type

    - This builtin function takes a function type and returns the type of the 'n'th parameter. + This builtin function takes a function type and returns the type of the parameter at index n.

    - T must be a function type, and n must be an usize integer. + T must be a function type. +

    +

    + Note: This function is deprecated. Use {#link|@typeInfo#} instead. +

    {#header_close#} {#header_open|@atomicLoad#}
    @atomicLoad(comptime T: type, ptr: &const T, comptime ordering: builtin.AtomicOrder) -> T
    From 43085417bec447ab31f3454e180213f102885cc8 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 24 May 2018 21:27:44 -0400 Subject: [PATCH 35/75] update github.com/zig-lang to github.com/ziglang --- README.md | 4 ++-- doc/langref.html.in | 8 ++++---- example/hello_world/hello_libc.zig | 2 +- src/analyze.cpp | 4 ++-- src/codegen.cpp | 6 +++--- src/ir.cpp | 8 ++++---- std/atomic/queue.zig | 2 +- std/event.zig | 8 ++++---- std/fmt/index.zig | 2 +- std/mem.zig | 2 +- std/os/index.zig | 6 +++--- std/os/test.zig | 2 +- std/os/time.zig | 2 +- std/special/compiler_rt/comparetf2.zig | 4 ++-- std/zig/ast.zig | 4 ++-- test/build_examples.zig | 2 +- test/cases/coroutines.zig | 2 +- test/cases/misc.zig | 2 +- test/compare_output.zig | 4 ++-- 19 files changed, 37 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index cf4d8179c7..b5bf13f095 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ libc. Create demo games using Zig. ## Building -[![Build Status](https://travis-ci.org/zig-lang/zig.svg?branch=master)](https://travis-ci.org/zig-lang/zig) +[![Build Status](https://travis-ci.org/ziglang/zig.svg?branch=master)](https://travis-ci.org/ziglang/zig) [![Build status](https://ci.appveyor.com/api/projects/status/4t80mk2dmucrc38i/branch/master?svg=true)](https://ci.appveyor.com/project/andrewrk/zig-d3l86/branch/master) ### Stage 1: Build Zig from C++ Source Code @@ -161,7 +161,7 @@ bin/zig build --build-file ../build.zig test ##### Windows -See https://github.com/zig-lang/zig/wiki/Building-Zig-on-Windows +See https://github.com/ziglang/zig/wiki/Building-Zig-on-Windows ### Stage 2: Build Self-Hosted Zig from Zig Source Code diff --git a/doc/langref.html.in b/doc/langref.html.in index c3c50b117b..d63c38d0fe 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -96,7 +96,7 @@

    If you search for something specific in this documentation and do not find it, - please file an issue or say something on IRC. + please file an issue or say something on IRC.

    The code samples in this document are compiled and tested as part of the main test suite of Zig. @@ -2827,7 +2827,7 @@ test "fn reflection" {

    The number of unique error values across the entire compilation should determine the size of the error set type. - However right now it is hard coded to be a u16. See #768. + However right now it is hard coded to be a u16. See #768.

    You can implicitly cast an error from a subset to its superset: @@ -5958,7 +5958,7 @@ pub fn main() void { {#code_begin|exe#} {#link_libc#} const c = @cImport({ - // See https://github.com/zig-lang/zig/issues/515 + // See https://github.com/ziglang/zig/issues/515 @cDefine("_NO_CRT_STDIO_INLINE", "1"); @cInclude("stdio.h"); }); @@ -6301,7 +6301,7 @@ fn readU32Be() u32 {}

  • Non-Ascii Unicode line endings: U+0085 (NEL), U+2028 (LS), U+2029 (PS).

The codepoint U+000a (LF) (which is encoded as the single-byte value 0x0a) is the line terminator character. This character always terminates a line of zig source code (except possbly the last line of the file).

-

For some discussion on the rationale behind these design decisions, see issue #663

+

For some discussion on the rationale behind these design decisions, see issue #663

{#header_close#} {#header_open|Grammar#}
Root = many(TopLevelItem) EOF
diff --git a/example/hello_world/hello_libc.zig b/example/hello_world/hello_libc.zig
index 60123c6fd8..4a35e47b15 100644
--- a/example/hello_world/hello_libc.zig
+++ b/example/hello_world/hello_libc.zig
@@ -1,5 +1,5 @@
 const c = @cImport({
-    // See https://github.com/zig-lang/zig/issues/515
+    // See https://github.com/ziglang/zig/issues/515
     @cDefine("_NO_CRT_STDIO_INLINE", "1");
     @cInclude("stdio.h");
     @cInclude("string.h");
diff --git a/src/analyze.cpp b/src/analyze.cpp
index d6137a4286..c59fde8ef6 100644
--- a/src/analyze.cpp
+++ b/src/analyze.cpp
@@ -1007,7 +1007,7 @@ TypeTableEntry *get_fn_type(CodeGen *g, FnTypeId *fn_type_id) {
     if (fn_type_id->return_type != nullptr) {
         ensure_complete_type(g, fn_type_id->return_type);
     } else {
-        zig_panic("TODO implement inferred return types https://github.com/zig-lang/zig/issues/447");
+        zig_panic("TODO implement inferred return types https://github.com/ziglang/zig/issues/447");
     }
 
     TypeTableEntry *fn_type = new_type_table_entry(TypeTableEntryIdFn);
@@ -1556,7 +1556,7 @@ static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *c
             return g->builtin_types.entry_invalid;
         }
         add_node_error(g, proto_node,
-            buf_sprintf("TODO implement inferred return types https://github.com/zig-lang/zig/issues/447"));
+            buf_sprintf("TODO implement inferred return types https://github.com/ziglang/zig/issues/447"));
         return g->builtin_types.entry_invalid;
         //return get_generic_fn_type(g, &fn_type_id);
     }
diff --git a/src/codegen.cpp b/src/codegen.cpp
index f1e102392a..69542b3e67 100644
--- a/src/codegen.cpp
+++ b/src/codegen.cpp
@@ -582,7 +582,7 @@ static LLVMValueRef fn_llvm_value(CodeGen *g, FnTableEntry *fn_table_entry) {
             addLLVMArgAttr(fn_table_entry->llvm_value, (unsigned)gen_index, "nonnull");
         }
         // Note: byval is disabled on windows due to an LLVM bug:
-        // https://github.com/zig-lang/zig/issues/536
+        // https://github.com/ziglang/zig/issues/536
         if (is_byval && g->zig_target.os != OsWindows) {
             addLLVMArgAttr(fn_table_entry->llvm_value, (unsigned)gen_index, "byval");
         }
@@ -3067,7 +3067,7 @@ static LLVMValueRef ir_render_call(CodeGen *g, IrExecutable *executable, IrInstr
     for (size_t param_i = 0; param_i < fn_type_id->param_count; param_i += 1) {
         FnGenParamInfo *gen_info = &fn_type->data.fn.gen_param_info[param_i];
         // Note: byval is disabled on windows due to an LLVM bug:
-        // https://github.com/zig-lang/zig/issues/536
+        // https://github.com/ziglang/zig/issues/536
         if (gen_info->is_byval && g->zig_target.os != OsWindows) {
             addLLVMCallsiteAttr(result, (unsigned)gen_info->gen_index, "byval");
         }
@@ -6730,7 +6730,7 @@ static void init(CodeGen *g) {
     const char *target_specific_features;
     if (g->is_native_target) {
         // LLVM creates invalid binaries on Windows sometimes.
-        // See https://github.com/zig-lang/zig/issues/508
+        // See https://github.com/ziglang/zig/issues/508
         // As a workaround we do not use target native features on Windows.
         if (g->zig_target.os == OsWindows) {
             target_specific_cpu_args = "";
diff --git a/src/ir.cpp b/src/ir.cpp
index e2cbba48a7..440063d58d 100644
--- a/src/ir.cpp
+++ b/src/ir.cpp
@@ -12130,7 +12130,7 @@ static bool ir_analyze_fn_call_generic_arg(IrAnalyze *ira, AstNode *fn_proto_nod
             casted_arg->value.type->id == TypeTableEntryIdNumLitFloat)
     {
         ir_add_error(ira, casted_arg,
-            buf_sprintf("compiler bug: integer and float literals in var args function must be casted. https://github.com/zig-lang/zig/issues/557"));
+            buf_sprintf("compiler bug: integer and float literals in var args function must be casted. https://github.com/ziglang/zig/issues/557"));
         return false;
     }
 
@@ -12331,7 +12331,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal
 
         if (fn_proto_node->data.fn_proto.is_var_args) {
             ir_add_error(ira, &call_instruction->base,
-                    buf_sprintf("compiler bug: unable to call var args function at compile time. https://github.com/zig-lang/zig/issues/313"));
+                    buf_sprintf("compiler bug: unable to call var args function at compile time. https://github.com/ziglang/zig/issues/313"));
             return ira->codegen->builtin_types.entry_invalid;
         }
 
@@ -12424,7 +12424,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal
         }
         if (call_instruction->is_async && fn_type_id->is_var_args) {
             ir_add_error(ira, call_instruction->fn_ref,
-                buf_sprintf("compiler bug: TODO: implement var args async functions. https://github.com/zig-lang/zig/issues/557"));
+                buf_sprintf("compiler bug: TODO: implement var args async functions. https://github.com/ziglang/zig/issues/557"));
             return ira->codegen->builtin_types.entry_invalid;
         }
 
@@ -12507,7 +12507,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal
                     VariableTableEntry *arg_var = get_fn_var_by_index(parent_fn_entry, arg_tuple_i);
                     if (arg_var == nullptr) {
                         ir_add_error(ira, arg,
-                            buf_sprintf("compiler bug: var args can't handle void. https://github.com/zig-lang/zig/issues/557"));
+                            buf_sprintf("compiler bug: var args can't handle void. https://github.com/ziglang/zig/issues/557"));
                         return ira->codegen->builtin_types.entry_invalid;
                     }
                     IrInstruction *arg_var_ptr_inst = ir_get_var_ptr(ira, arg, arg_var, true, false);
diff --git a/std/atomic/queue.zig b/std/atomic/queue.zig
index 288a2b3b48..35180da8d1 100644
--- a/std/atomic/queue.zig
+++ b/std/atomic/queue.zig
@@ -16,7 +16,7 @@ pub fn Queue(comptime T: type) type {
             data: T,
         };
 
-        // TODO: well defined copy elision: https://github.com/zig-lang/zig/issues/287
+        // TODO: well defined copy elision: https://github.com/ziglang/zig/issues/287
         pub fn init(self: &Self) void {
             self.root.next = null;
             self.head = &self.root;
diff --git a/std/event.zig b/std/event.zig
index b2e7e3ae38..558bd2a188 100644
--- a/std/event.zig
+++ b/std/event.zig
@@ -148,7 +148,7 @@ pub const Loop = struct {
 };
 
 pub async fn connect(loop: &Loop, _address: &const std.net.Address) !std.os.File {
-    var address = _address.*; // TODO https://github.com/zig-lang/zig/issues/733
+    var address = _address.*; // TODO https://github.com/ziglang/zig/issues/733
 
     const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp);
     errdefer std.os.close(sockfd);
@@ -172,7 +172,7 @@ test "listen on a port, send bytes, receive bytes" {
 
         async<&mem.Allocator> fn handler(tcp_server: &TcpServer, _addr: &const std.net.Address, _socket: &const std.os.File) void {
             const self = @fieldParentPtr(Self, "tcp_server", tcp_server);
-            var socket = _socket.*; // TODO https://github.com/zig-lang/zig/issues/733
+            var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733
             defer socket.close();
             const next_handler = async errorableHandler(self, _addr, socket) catch |err| switch (err) {
                 error.OutOfMemory => @panic("unable to handle connection: out of memory"),
@@ -186,8 +186,8 @@ test "listen on a port, send bytes, receive bytes" {
         }
 
         async fn errorableHandler(self: &Self, _addr: &const std.net.Address, _socket: &const std.os.File) !void {
-            const addr = _addr.*; // TODO https://github.com/zig-lang/zig/issues/733
-            var socket = _socket.*; // TODO https://github.com/zig-lang/zig/issues/733
+            const addr = _addr.*; // TODO https://github.com/ziglang/zig/issues/733
+            var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733
 
             var adapter = std.io.FileOutStream.init(&socket);
             var stream = &adapter.stream;
diff --git a/std/fmt/index.zig b/std/fmt/index.zig
index 0af772b7dc..624751822a 100644
--- a/std/fmt/index.zig
+++ b/std/fmt/index.zig
@@ -824,7 +824,7 @@ test "fmt.format" {
     try testFmt("file size: 63MiB\n", "file size: {Bi}\n", usize(63 * 1024 * 1024));
     try testFmt("file size: 66.06MB\n", "file size: {B2}\n", usize(63 * 1024 * 1024));
     {
-        // Dummy field because of https://github.com/zig-lang/zig/issues/557.
+        // Dummy field because of https://github.com/ziglang/zig/issues/557.
         const Struct = struct {
             unused: u8,
         };
diff --git a/std/mem.zig b/std/mem.zig
index 3ca87b35d3..617c1de2f5 100644
--- a/std/mem.zig
+++ b/std/mem.zig
@@ -702,7 +702,7 @@ test "std.mem.rotate" {
     }));
 }
 
-// TODO: When https://github.com/zig-lang/zig/issues/649 is solved these can be done by
+// TODO: When https://github.com/ziglang/zig/issues/649 is solved these can be done by
 // endian-casting the pointer and then dereferencing
 
 pub fn endianSwapIfLe(comptime T: type, x: T) T {
diff --git a/std/os/index.zig b/std/os/index.zig
index 7d19cd82c6..01e2092e1c 100644
--- a/std/os/index.zig
+++ b/std/os/index.zig
@@ -239,7 +239,7 @@ pub fn close(handle: FileHandle) void {
 /// Calls POSIX read, and keeps trying if it gets interrupted.
 pub fn posixRead(fd: i32, buf: []u8) !void {
     // Linux can return EINVAL when read amount is > 0x7ffff000
-    // See https://github.com/zig-lang/zig/pull/743#issuecomment-363158274
+    // See https://github.com/ziglang/zig/pull/743#issuecomment-363158274
     const max_buf_len = 0x7ffff000;
 
     var index: usize = 0;
@@ -281,7 +281,7 @@ pub const PosixWriteError = error{
 /// Calls POSIX write, and keeps trying if it gets interrupted.
 pub fn posixWrite(fd: i32, bytes: []const u8) !void {
     // Linux can return EINVAL when write amount is > 0x7ffff000
-    // See https://github.com/zig-lang/zig/pull/743#issuecomment-363165856
+    // See https://github.com/ziglang/zig/pull/743#issuecomment-363165856
     const max_bytes_len = 0x7ffff000;
 
     var index: usize = 0;
@@ -2513,7 +2513,7 @@ pub const SpawnThreadError = error{
 /// caller must call wait on the returned thread
 pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread {
     // TODO compile-time call graph analysis to determine stack upper bound
-    // https://github.com/zig-lang/zig/issues/157
+    // https://github.com/ziglang/zig/issues/157
     const default_stack_size = 8 * 1024 * 1024;
 
     const Context = @typeOf(context);
diff --git a/std/os/test.zig b/std/os/test.zig
index 56d6e8b309..4dfe76224a 100644
--- a/std/os/test.zig
+++ b/std/os/test.zig
@@ -12,7 +12,7 @@ const AtomicOrder = builtin.AtomicOrder;
 test "makePath, put some files in it, deleteTree" {
     if (builtin.os == builtin.Os.windows) {
         // TODO implement os.Dir for windows
-        // https://github.com/zig-lang/zig/issues/709
+        // https://github.com/ziglang/zig/issues/709
         return;
     }
     try os.makePath(a, "os_test_tmp/b/c");
diff --git a/std/os/time.zig b/std/os/time.zig
index 4fd2c4e924..3af150ab6a 100644
--- a/std/os/time.zig
+++ b/std/os/time.zig
@@ -135,7 +135,7 @@ pub const Timer = struct {
     
     //At some point we may change our minds on RAW, but for now we're
     //  sticking with posix standard MONOTONIC. For more information, see: 
-    //  https://github.com/zig-lang/zig/pull/933
+    //  https://github.com/ziglang/zig/pull/933
     //
     //const monotonic_clock_id = switch(builtin.os) {
     //    Os.linux => linux.CLOCK_MONOTONIC_RAW,
diff --git a/std/special/compiler_rt/comparetf2.zig b/std/special/compiler_rt/comparetf2.zig
index c189e5803b..760c3689c0 100644
--- a/std/special/compiler_rt/comparetf2.zig
+++ b/std/special/compiler_rt/comparetf2.zig
@@ -1,4 +1,4 @@
-// TODO https://github.com/zig-lang/zig/issues/305
+// TODO https://github.com/ziglang/zig/issues/305
 // and then make the return types of some of these functions the enum instead of c_int
 const LE_LESS = c_int(-1);
 const LE_EQUAL = c_int(0);
@@ -59,7 +59,7 @@ pub extern fn __letf2(a: f128, b: f128) c_int {
     ;
 }
 
-// TODO https://github.com/zig-lang/zig/issues/305
+// TODO https://github.com/ziglang/zig/issues/305
 // and then make the return types of some of these functions the enum instead of c_int
 const GE_LESS = c_int(-1);
 const GE_EQUAL = c_int(0);
diff --git a/std/zig/ast.zig b/std/zig/ast.zig
index c1552b0220..1f15046a79 100644
--- a/std/zig/ast.zig
+++ b/std/zig/ast.zig
@@ -113,7 +113,7 @@ pub const Error = union(enum) {
 
     pub fn render(self: &Error, tokens: &Tree.TokenList, stream: var) !void {
         switch (self.*) {
-            // TODO https://github.com/zig-lang/zig/issues/683
+            // TODO https://github.com/ziglang/zig/issues/683
             @TagType(Error).InvalidToken => |*x| return x.render(tokens, stream),
             @TagType(Error).ExpectedVarDeclOrFn => |*x| return x.render(tokens, stream),
             @TagType(Error).ExpectedAggregateKw => |*x| return x.render(tokens, stream),
@@ -137,7 +137,7 @@ pub const Error = union(enum) {
 
     pub fn loc(self: &Error) TokenIndex {
         switch (self.*) {
-            // TODO https://github.com/zig-lang/zig/issues/683
+            // TODO https://github.com/ziglang/zig/issues/683
             @TagType(Error).InvalidToken => |x| return x.token,
             @TagType(Error).ExpectedVarDeclOrFn => |x| return x.token,
             @TagType(Error).ExpectedAggregateKw => |x| return x.token,
diff --git a/test/build_examples.zig b/test/build_examples.zig
index a3b44b9136..7a4c0f35d9 100644
--- a/test/build_examples.zig
+++ b/test/build_examples.zig
@@ -9,7 +9,7 @@ pub fn addCases(cases: &tests.BuildExamplesContext) void {
     cases.add("example/guess_number/main.zig");
     if (!is_windows) {
         // TODO get this test passing on windows
-        // See https://github.com/zig-lang/zig/issues/538
+        // See https://github.com/ziglang/zig/issues/538
         cases.addBuildFile("example/shared_library/build.zig");
         cases.addBuildFile("example/mix_o_files/build.zig");
     }
diff --git a/test/cases/coroutines.zig b/test/cases/coroutines.zig
index 4aa97861ac..e983947a4c 100644
--- a/test/cases/coroutines.zig
+++ b/test/cases/coroutines.zig
@@ -204,7 +204,7 @@ test "error return trace across suspend points - async return" {
     cancel p2;
 }
 
-// TODO https://github.com/zig-lang/zig/issues/760
+// TODO https://github.com/ziglang/zig/issues/760
 fn nonFailing() (promise->error!void) {
     return async suspendThenFail() catch unreachable;
 }
diff --git a/test/cases/misc.zig b/test/cases/misc.zig
index 66487a4946..deeeca8c3a 100644
--- a/test/cases/misc.zig
+++ b/test/cases/misc.zig
@@ -543,7 +543,7 @@ test "@typeName" {
     comptime {
         assert(mem.eql(u8, @typeName(i64), "i64"));
         assert(mem.eql(u8, @typeName(&usize), "&usize"));
-        // https://github.com/zig-lang/zig/issues/675
+        // https://github.com/ziglang/zig/issues/675
         assert(mem.eql(u8, @typeName(TypeFromFn(u8)), "TypeFromFn(u8)"));
         assert(mem.eql(u8, @typeName(Struct), "Struct"));
         assert(mem.eql(u8, @typeName(Union), "Union"));
diff --git a/test/compare_output.zig b/test/compare_output.zig
index b01e87d4eb..905ffd37a9 100644
--- a/test/compare_output.zig
+++ b/test/compare_output.zig
@@ -131,7 +131,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
         \\const is_windows = builtin.os == builtin.Os.windows;
         \\const c = @cImport({
         \\    if (is_windows) {
-        \\        // See https://github.com/zig-lang/zig/issues/515
+        \\        // See https://github.com/ziglang/zig/issues/515
         \\        @cDefine("_NO_CRT_STDIO_INLINE", "1");
         \\        @cInclude("io.h");
         \\        @cInclude("fcntl.h");
@@ -316,7 +316,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
         \\const is_windows = builtin.os == builtin.Os.windows;
         \\const c = @cImport({
         \\    if (is_windows) {
-        \\        // See https://github.com/zig-lang/zig/issues/515
+        \\        // See https://github.com/ziglang/zig/issues/515
         \\        @cDefine("_NO_CRT_STDIO_INLINE", "1");
         \\        @cInclude("io.h");
         \\        @cInclude("fcntl.h");

From b74dda34b6a8b5f04d1865e2f23aab43229815f9 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Thu, 24 May 2018 21:51:58 -0400
Subject: [PATCH 36/75] std.zig.tokenizer: support hex escape in char literals

---
 std/zig/parser_test.zig | 13 +++++++++++++
 std/zig/tokenizer.zig   | 34 ++++++++++++++++++++++++++++++++++
 2 files changed, 47 insertions(+)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index c11db78775..d114179bf7 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,16 @@
+test "zig fmt: float literal with exponent" {
+    try testCanonical(
+        \\test "aoeu" {
+        \\    switch (state) {
+        \\        TermState.Start => switch (c) {
+        \\            '\x1b' => state = TermState.Escape,
+        \\            else => try out.writeByte(c),
+        \\        },
+        \\    }
+        \\}
+        \\
+    );
+}
 test "zig fmt: float literal with exponent" {
     try testCanonical(
         \\pub const f64_true_min = 4.94065645841246544177e-324;
diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig
index afea7fc899..f4cd847dff 100644
--- a/std/zig/tokenizer.zig
+++ b/std/zig/tokenizer.zig
@@ -220,6 +220,8 @@ pub const Tokenizer = struct {
         MultilineStringLiteralLineBackslash,
         CharLiteral,
         CharLiteralBackslash,
+        CharLiteralEscape1,
+        CharLiteralEscape2,
         CharLiteralEnd,
         Backslash,
         Equal,
@@ -612,11 +614,34 @@ pub const Tokenizer = struct {
                         result.id = Token.Id.Invalid;
                         break;
                     },
+                    'x' => {
+                        state = State.CharLiteralEscape1;
+                    },
                     else => {
                         state = State.CharLiteralEnd;
                     },
                 },
 
+                State.CharLiteralEscape1 => switch (c) {
+                    '0'...'9', 'a'...'z', 'A'...'F' => {
+                        state = State.CharLiteralEscape2;
+                    },
+                    else => {
+                        result.id = Token.Id.Invalid;
+                        break;
+                    },
+                },
+
+                State.CharLiteralEscape2 => switch (c) {
+                    '0'...'9', 'a'...'z', 'A'...'F' => {
+                        state = State.CharLiteralEnd;
+                    },
+                    else => {
+                        result.id = Token.Id.Invalid;
+                        break;
+                    },
+                },
+
                 State.CharLiteralEnd => switch (c) {
                     '\'' => {
                         result.id = Token.Id.CharLiteral;
@@ -988,6 +1013,8 @@ pub const Tokenizer = struct {
                 State.MultilineStringLiteralLineBackslash,
                 State.CharLiteral,
                 State.CharLiteralBackslash,
+                State.CharLiteralEscape1,
+                State.CharLiteralEscape2,
                 State.CharLiteralEnd,
                 State.StringLiteralBackslash => {
                     result.id = Token.Id.Invalid;
@@ -1127,6 +1154,13 @@ test "tokenizer" {
     });
 }
 
+test "tokenizer - char literal with hex escape" {
+    testTokenize( \\'\x1b'
+    , []Token.Id {
+        Token.Id.CharLiteral,
+    });
+}
+
 test "tokenizer - float literal e exponent" {
     testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id {
         Token.Id.Identifier,

From e6afea99a9642a4fe12b65ef94fee0ee34d7a36b Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 00:37:58 -0400
Subject: [PATCH 37/75] zig fmt: support aligned ptr with bit fields

---
 std/zig/ast.zig         | 22 ++++++++++++++-----
 std/zig/parse.zig       | 48 +++++++++++++++++++++++++++++++++--------
 std/zig/parser_test.zig |  9 ++++++++
 std/zig/render.zig      | 48 ++++++++++++++++++++++++++++++++---------
 4 files changed, 103 insertions(+), 24 deletions(-)

diff --git a/std/zig/ast.zig b/std/zig/ast.zig
index 1f15046a79..6c848b4a54 100644
--- a/std/zig/ast.zig
+++ b/std/zig/ast.zig
@@ -98,6 +98,7 @@ pub const Error = union(enum) {
     UnattachedDocComment: UnattachedDocComment,
     ExpectedEqOrSemi: ExpectedEqOrSemi,
     ExpectedSemiOrLBrace: ExpectedSemiOrLBrace,
+    ExpectedColonOrRParen: ExpectedColonOrRParen,
     ExpectedLabelable: ExpectedLabelable,
     ExpectedInlinable: ExpectedInlinable,
     ExpectedAsmOutputReturnOrType: ExpectedAsmOutputReturnOrType,
@@ -120,6 +121,7 @@ pub const Error = union(enum) {
             @TagType(Error).UnattachedDocComment => |*x| return x.render(tokens, stream),
             @TagType(Error).ExpectedEqOrSemi => |*x| return x.render(tokens, stream),
             @TagType(Error).ExpectedSemiOrLBrace => |*x| return x.render(tokens, stream),
+            @TagType(Error).ExpectedColonOrRParen => |*x| return x.render(tokens, stream),
             @TagType(Error).ExpectedLabelable => |*x| return x.render(tokens, stream),
             @TagType(Error).ExpectedInlinable => |*x| return x.render(tokens, stream),
             @TagType(Error).ExpectedAsmOutputReturnOrType => |*x| return x.render(tokens, stream),
@@ -144,6 +146,7 @@ pub const Error = union(enum) {
             @TagType(Error).UnattachedDocComment => |x| return x.token,
             @TagType(Error).ExpectedEqOrSemi => |x| return x.token,
             @TagType(Error).ExpectedSemiOrLBrace => |x| return x.token,
+            @TagType(Error).ExpectedColonOrRParen => |x| return x.token,
             @TagType(Error).ExpectedLabelable => |x| return x.token,
             @TagType(Error).ExpectedInlinable => |x| return x.token,
             @TagType(Error).ExpectedAsmOutputReturnOrType => |x| return x.token,
@@ -164,6 +167,7 @@ pub const Error = union(enum) {
     pub const ExpectedAggregateKw = SingleTokenError("Expected " ++ @tagName(Token.Id.Keyword_struct) ++ ", " ++ @tagName(Token.Id.Keyword_union) ++ ", or " ++ @tagName(Token.Id.Keyword_enum) ++ ", found {}");
     pub const ExpectedEqOrSemi = SingleTokenError("Expected '=' or ';', found {}");
     pub const ExpectedSemiOrLBrace = SingleTokenError("Expected ';' or '{{', found {}");
+    pub const ExpectedColonOrRParen = SingleTokenError("Expected ':' or ')', found {}");
     pub const ExpectedLabelable = SingleTokenError("Expected 'while', 'for', 'inline', 'suspend', or '{{', found {}");
     pub const ExpectedInlinable = SingleTokenError("Expected 'while' or 'for', found {}");
     pub const ExpectedAsmOutputReturnOrType = SingleTokenError("Expected '->' or " ++ @tagName(Token.Id.Identifier) ++ ", found {}");
@@ -1487,7 +1491,7 @@ pub const Node = struct {
         op: Op,
         rhs: &Node,
 
-        const Op = union(enum) {
+        pub const Op = union(enum) {
             AddrOf: AddrOfInfo,
             ArrayType: &Node,
             Await,
@@ -1504,12 +1508,20 @@ pub const Node = struct {
             UnwrapMaybe,
         };
 
-        const AddrOfInfo = struct {
-            align_expr: ?&Node,
-            bit_offset_start_token: ?TokenIndex,
-            bit_offset_end_token: ?TokenIndex,
+        pub const AddrOfInfo = struct {
+            align_info: ?Align,
             const_token: ?TokenIndex,
             volatile_token: ?TokenIndex,
+
+            pub const Align = struct {
+                node: &Node,
+                bit_range: ?BitRange,
+
+                pub const BitRange = struct {
+                    start: &Node,
+                    end: &Node,
+                };
+            };
         };
 
         pub fn iterate(self: &PrefixOp, index: usize) ?&Node {
diff --git a/std/zig/parse.zig b/std/zig/parse.zig
index 826ea2c3e1..d60f03c55e 100644
--- a/std/zig/parse.zig
+++ b/std/zig/parse.zig
@@ -1450,9 +1450,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
             State.SliceOrArrayType => |node| {
                 if (eatToken(&tok_it, &tree, Token.Id.RBracket)) |_| {
                     node.op = ast.Node.PrefixOp.Op{ .SliceType = ast.Node.PrefixOp.AddrOfInfo{
-                        .align_expr = null,
-                        .bit_offset_start_token = null,
-                        .bit_offset_end_token = null,
+                        .align_info = null,
                         .const_token = null,
                         .volatile_token = null,
                     } };
@@ -1467,6 +1465,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
                 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.op.ArrayType } });
                 continue;
             },
+
             State.AddrOfModifiers => |addr_of_info| {
                 const token = nextToken(&tok_it, &tree);
                 const token_index = token.index;
@@ -1474,12 +1473,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
                 switch (token_ptr.id) {
                     Token.Id.Keyword_align => {
                         stack.append(state) catch unreachable;
-                        if (addr_of_info.align_expr != null) {
+                        if (addr_of_info.align_info != null) {
                             ((try tree.errors.addOne())).* = Error{ .ExtraAlignQualifier = Error.ExtraAlignQualifier{ .token = token_index } };
                             return tree;
                         }
-                        try stack.append(State{ .ExpectToken = Token.Id.RParen });
-                        try stack.append(State{ .Expression = OptionalCtx{ .RequiredNull = &addr_of_info.align_expr } });
+                        addr_of_info.align_info = ast.Node.PrefixOp.AddrOfInfo.Align {
+                            .node = undefined,
+                            .bit_range = null,
+                        };
+                        // TODO https://github.com/ziglang/zig/issues/1022
+                        const align_info = &??addr_of_info.align_info;
+
+                        try stack.append(State{ .AlignBitRange = align_info });
+                        try stack.append(State{ .Expression = OptionalCtx{ .Required = &align_info.node } });
                         try stack.append(State{ .ExpectToken = Token.Id.LParen });
                         continue;
                     },
@@ -1508,6 +1514,31 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
                 }
             },
 
+            State.AlignBitRange => |align_info| {
+                const token = nextToken(&tok_it, &tree);
+                switch (token.ptr.id) {
+                    Token.Id.Colon => {
+                        align_info.bit_range = ast.Node.PrefixOp.AddrOfInfo.Align.BitRange(undefined);
+                        const bit_range = &??align_info.bit_range;
+
+                        try stack.append(State{ .ExpectToken = Token.Id.RParen });
+                        try stack.append(State{ .Expression = OptionalCtx{ .Required = &bit_range.end } });
+                        try stack.append(State{ .ExpectToken = Token.Id.Colon });
+                        try stack.append(State{ .Expression = OptionalCtx{ .Required = &bit_range.start } });
+                        continue;
+                    },
+                    Token.Id.RParen => continue,
+                    else => {
+                        (try tree.errors.addOne()).* = Error{
+                            .ExpectedColonOrRParen = Error.ExpectedColonOrRParen{
+                                .token = token.index,
+                            }
+                        };
+                        return tree;
+                    },
+                }
+            },
+
             State.Payload => |opt_ctx| {
                 const token = nextToken(&tok_it, &tree);
                 const token_index = token.index;
@@ -2801,6 +2832,7 @@ const State = union(enum) {
     SliceOrArrayAccess: &ast.Node.SuffixOp,
     SliceOrArrayType: &ast.Node.PrefixOp,
     AddrOfModifiers: &ast.Node.PrefixOp.AddrOfInfo,
+    AlignBitRange: &ast.Node.PrefixOp.AddrOfInfo.Align,
 
     Payload: OptionalCtx,
     PointerPayload: OptionalCtx,
@@ -3120,9 +3152,7 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op {
         Token.Id.Asterisk,
         Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .PointerType = void{} },
         Token.Id.Ampersand => ast.Node.PrefixOp.Op{ .AddrOf = ast.Node.PrefixOp.AddrOfInfo{
-            .align_expr = null,
-            .bit_offset_start_token = null,
-            .bit_offset_end_token = null,
+            .align_info = null,
             .const_token = null,
             .volatile_token = null,
         } },
diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index d114179bf7..a29b8c2547 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,12 @@
+test "zig fmt: float literal with exponent" {
+    try testCanonical(
+        \\test "bit field alignment" {
+        \\    assert(@typeOf(&blah.b) == &align(1:3:6) const u3);
+        \\}
+        \\
+    );
+}
+
 test "zig fmt: float literal with exponent" {
     try testCanonical(
         \\test "aoeu" {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index f48b13c987..3940a61fc1 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -253,17 +253,30 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
             switch (prefix_op_node.op) {
                 ast.Node.PrefixOp.Op.AddrOf => |addr_of_info| {
                     try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // &
-                    if (addr_of_info.align_expr) |align_expr| {
+                    if (addr_of_info.align_info) |align_info| {
                         const align_token = tree.nextToken(prefix_op_node.op_token);
                         try renderToken(tree, stream, align_token, indent, Space.None); // align
 
-                        const lparen_token = tree.prevToken(align_expr.firstToken());
+                        const lparen_token = tree.prevToken(align_info.node.firstToken());
                         try renderToken(tree, stream, lparen_token, indent, Space.None); // (
 
-                        try renderExpression(allocator, stream, tree, indent, align_expr, Space.None);
+                        try renderExpression(allocator, stream, tree, indent, align_info.node, Space.None);
 
-                        const rparen_token = tree.nextToken(align_expr.lastToken());
-                        try renderToken(tree, stream, rparen_token, indent, Space.Space); // )
+                        if (align_info.bit_range) |bit_range| {
+                            const colon1 = tree.prevToken(bit_range.start.firstToken());
+                            const colon2 = tree.prevToken(bit_range.end.firstToken());
+
+                            try renderToken(tree, stream, colon1, indent, Space.None); // :
+                            try renderExpression(allocator, stream, tree, indent, bit_range.start, Space.None);
+                            try renderToken(tree, stream, colon2, indent, Space.None); // :
+                            try renderExpression(allocator, stream, tree, indent, bit_range.end, Space.None);
+
+                            const rparen_token = tree.nextToken(bit_range.end.lastToken());
+                            try renderToken(tree, stream, rparen_token, indent, Space.Space); // )
+                        } else {
+                            const rparen_token = tree.nextToken(align_info.node.lastToken());
+                            try renderToken(tree, stream, rparen_token, indent, Space.Space); // )
+                        }
                     }
                     if (addr_of_info.const_token) |const_token| {
                         try renderToken(tree, stream, const_token, indent, Space.Space); // const
@@ -272,21 +285,35 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                         try renderToken(tree, stream, volatile_token, indent, Space.Space); // volatile
                     }
                 },
+
                 ast.Node.PrefixOp.Op.SliceType => |addr_of_info| {
                     try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // [
                     try renderToken(tree, stream, tree.nextToken(prefix_op_node.op_token), indent, Space.None); // ]
 
-                    if (addr_of_info.align_expr) |align_expr| {
+                    if (addr_of_info.align_info) |align_info| {
                         const align_token = tree.nextToken(prefix_op_node.op_token);
                         try renderToken(tree, stream, align_token, indent, Space.None); // align
 
-                        const lparen_token = tree.prevToken(align_expr.firstToken());
+                        const lparen_token = tree.prevToken(align_info.node.firstToken());
                         try renderToken(tree, stream, lparen_token, indent, Space.None); // (
 
-                        try renderExpression(allocator, stream, tree, indent, align_expr, Space.None);
+                        try renderExpression(allocator, stream, tree, indent, align_info.node, Space.None);
 
-                        const rparen_token = tree.nextToken(align_expr.lastToken());
-                        try renderToken(tree, stream, rparen_token, indent, Space.Space); // )
+                        if (align_info.bit_range) |bit_range| {
+                            const colon1 = tree.prevToken(bit_range.start.firstToken());
+                            const colon2 = tree.prevToken(bit_range.end.firstToken());
+
+                            try renderToken(tree, stream, colon1, indent, Space.None); // :
+                            try renderExpression(allocator, stream, tree, indent, bit_range.start, Space.None);
+                            try renderToken(tree, stream, colon2, indent, Space.None); // :
+                            try renderExpression(allocator, stream, tree, indent, bit_range.end, Space.None);
+
+                            const rparen_token = tree.nextToken(bit_range.end.lastToken());
+                            try renderToken(tree, stream, rparen_token, indent, Space.Space); // )
+                        } else {
+                            const rparen_token = tree.nextToken(align_info.node.lastToken());
+                            try renderToken(tree, stream, rparen_token, indent, Space.Space); // )
+                        }
                     }
                     if (addr_of_info.const_token) |const_token| {
                         try renderToken(tree, stream, const_token, indent, Space.Space);
@@ -295,6 +322,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                         try renderToken(tree, stream, volatile_token, indent, Space.Space);
                     }
                 },
+
                 ast.Node.PrefixOp.Op.ArrayType => |array_index| {
                     try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // [
                     try renderExpression(allocator, stream, tree, indent, array_index, Space.None);

From ca49b6f6b4ffa3ff4324a45501eef98848a2d141 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 00:39:05 -0400
Subject: [PATCH 38/75] struct fields with no explicit type are not supported

the c++ codebase lets it slide

the self hosted parser correctly reports a parse error
---
 test/cases/syntax.zig | 1 -
 1 file changed, 1 deletion(-)

diff --git a/test/cases/syntax.zig b/test/cases/syntax.zig
index 6c851c0ff3..140a86d5c1 100644
--- a/test/cases/syntax.zig
+++ b/test/cases/syntax.zig
@@ -2,7 +2,6 @@
 
 const struct_trailing_comma = struct { x: i32, y: i32, };
 const struct_no_comma = struct { x: i32, y: i32 };
-const struct_no_comma_void_type = struct { x: i32, y };
 const struct_fn_no_comma = struct { fn m() void {} y: i32 };
 
 const enum_no_comma = enum { A, B };

From dfc3e11748615f10cf6958c61a934ef852b5aa94 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 01:03:15 -0400
Subject: [PATCH 39/75] zig fmt: fix handling of comments at top of file

---
 std/zig/parse.zig       |  7 +++++++
 std/zig/parser_test.zig | 20 ++++++++++++++++++++
 std/zig/render.zig      | 16 +++++++++++++++-
 3 files changed, 42 insertions(+), 1 deletion(-)

diff --git a/std/zig/parse.zig b/std/zig/parse.zig
index d60f03c55e..5d6897a0bc 100644
--- a/std/zig/parse.zig
+++ b/std/zig/parse.zig
@@ -41,6 +41,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
     }
     var tok_it = tree.tokens.iterator(0);
 
+    // skip over line comments at the top of the file
+    while (true) {
+        const next_tok = tok_it.peek() ?? break;
+        if (next_tok.id != Token.Id.LineComment) break;
+        _ = tok_it.next();
+    }
+
     try stack.append(State.TopLevel);
 
     while (true) {
diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index a29b8c2547..bd1d142a23 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,23 @@
+test "zig fmt: first thing in file is line comment" {
+    try testCanonical(
+        \\// Introspection and determination of system libraries needed by zig.
+        \\
+        \\// Introspection and determination of system libraries needed by zig.
+        \\
+        \\const std = @import("std");
+        \\
+    );
+}
+
+test "zig fmt: line comment after doc comment" {
+    try testCanonical(
+        \\/// doc comment
+        \\// line comment
+        \\fn foo() void {}
+        \\
+    );
+}
+
 test "zig fmt: float literal with exponent" {
     try testCanonical(
         \\test "bit field alignment" {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index 3940a61fc1..c2545bddfd 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -15,6 +15,20 @@ pub const Error = error{
 pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(stream).Child.Error || Error)!void {
     comptime assert(@typeId(@typeOf(stream)) == builtin.TypeId.Pointer);
 
+    // render all the line comments at the beginning of the file
+    var tok_it = tree.tokens.iterator(0);
+    while (tok_it.next()) |token| {
+        if (token.id != Token.Id.LineComment) break;
+        try stream.print("{}\n", tree.tokenSlicePtr(token));
+        if (tok_it.peek()) |next_token| {
+            const loc = tree.tokenLocationPtr(token.end, next_token);
+            if (loc.line >= 2) {
+                try stream.writeByte('\n');
+            }
+        }
+    }
+
+
     var it = tree.root_node.decls.iterator(0);
     while (it.next()) |decl| {
         try renderTopLevelDecl(allocator, stream, tree, 0, decl.*);
@@ -1455,7 +1469,7 @@ fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@t
     const comment = node.doc_comments ?? return;
     var it = comment.lines.iterator(0);
     while (it.next()) |line_token_index| {
-        try stream.print("{}\n", tree.tokenSlice(line_token_index.*));
+        try renderToken(tree, stream, line_token_index.*, indent, Space.Newline);
         try stream.writeByteNTimes(' ', indent);
     }
 }

From 08f95d0c2fac127558c84f7dfb469ac43fb4f425 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 01:10:54 -0400
Subject: [PATCH 40/75] enum fields with a type are not supported

the c++ codebase lets it slide

the self hosted parser correctly reports a parse error
---
 test/cases/syntax.zig | 1 -
 1 file changed, 1 deletion(-)

diff --git a/test/cases/syntax.zig b/test/cases/syntax.zig
index 140a86d5c1..9512834f5a 100644
--- a/test/cases/syntax.zig
+++ b/test/cases/syntax.zig
@@ -5,7 +5,6 @@ const struct_no_comma = struct { x: i32, y: i32 };
 const struct_fn_no_comma = struct { fn m() void {} y: i32 };
 
 const enum_no_comma = enum { A, B };
-const enum_no_comma_type = enum { A, B: i32 };
 
 fn container_init() void {
     const S = struct { x: i32, y: i32 };

From 000c01a36aeef162d743ebf4bd8ee67380f26672 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 01:45:14 -0400
Subject: [PATCH 41/75] zig fmt: handle missing trailing comma in array
 literals

---
 std/zig/parser_test.zig | 20 ++++++++++++++++
 std/zig/render.zig      | 52 ++++++++++++++++++++++++-----------------
 2 files changed, 50 insertions(+), 22 deletions(-)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index bd1d142a23..cabfb48387 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,23 @@
+test "zig fmt: first thing in file is line comment" {
+    try testTransform(
+        \\comptime {
+        \\    return []u16{'m', 's', 'y', 's', '-' // hi
+        \\   };
+        \\}
+    ,
+        \\comptime {
+        \\    return []u16{
+        \\        'm',
+        \\        's',
+        \\        'y',
+        \\        's',
+        \\        '-', // hi
+        \\    };
+        \\}
+        \\
+    );
+}
+
 test "zig fmt: first thing in file is line comment" {
     try testCanonical(
         \\// Introspection and determination of system libraries needed by zig.
diff --git a/std/zig/render.zig b/std/zig/render.zig
index c2545bddfd..87debcb5f0 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -490,13 +490,16 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                     var it = exprs.iterator(0);
                     while (it.next()) |expr| {
                         try stream.writeByteNTimes(' ', new_indent);
-                        try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.None);
-
-                        const comma = tree.nextToken(expr.*.lastToken());
-                        try renderToken(tree, stream, comma, new_indent, Space.Newline); // ,
 
                         if (it.peek()) |next_expr| {
+                            try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.None);
+
+                            const comma = tree.nextToken(expr.*.lastToken());
+                            try renderToken(tree, stream, comma, new_indent, Space.Newline); // ,
+
                             try renderExtraNewline(tree, stream, next_expr.*);
+                        } else {
+                            try renderTrailingComma(allocator, stream, tree, indent, expr.*, Space.Newline);
                         }
                     }
 
@@ -950,24 +953,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                 try renderExpression(allocator, stream, tree, indent, payload, Space.Space);
             }
 
-            // add a trailing comma if necessary
-            const end_token = switch_case.lastToken() + 1;
-            switch (tree.tokens.at(end_token).id) {
-                Token.Id.Comma => {
-                    try renderExpression(allocator, stream, tree, indent, switch_case.expr, Space.None);
-                    try renderToken(tree, stream, end_token, indent, space); // ,
-                },
-                Token.Id.LineComment => {
-                    try renderExpression(allocator, stream, tree, indent, switch_case.expr, Space.NoComment);
-                    try stream.write(", ");
-                    try renderToken(tree, stream, end_token, indent, space);
-                },
-                else => {
-                    try renderExpression(allocator, stream, tree, indent, switch_case.expr, Space.None);
-                    try stream.write(",\n");
-                    assert(space == Space.Newline);
-                },
-            }
+            try renderTrailingComma(allocator, stream, tree, indent, switch_case.expr, space);
         },
         ast.Node.Id.SwitchElse => {
             const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base);
@@ -1473,3 +1459,25 @@ fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@t
         try stream.writeByteNTimes(' ', indent);
     }
 }
+
+fn renderTrailingComma(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node,
+    space: Space) (@typeOf(stream).Child.Error || Error)!void
+{
+    const end_token = base.lastToken() + 1;
+    switch (tree.tokens.at(end_token).id) {
+        Token.Id.Comma => {
+            try renderExpression(allocator, stream, tree, indent, base, Space.None);
+            try renderToken(tree, stream, end_token, indent, space); // ,
+        },
+        Token.Id.LineComment => {
+            try renderExpression(allocator, stream, tree, indent, base, Space.NoComment);
+            try stream.write(", ");
+            try renderToken(tree, stream, end_token, indent, space);
+        },
+        else => {
+            try renderExpression(allocator, stream, tree, indent, base, Space.None);
+            try stream.write(",\n");
+            assert(space == Space.Newline);
+        },
+    }
+}

From 3f302f841136ebbcc4da0707fff6faaac4c03e55 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 01:52:59 -0400
Subject: [PATCH 42/75] handle more cases of inserting trailing commas

---
 std/zig/render.zig | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/std/zig/render.zig b/std/zig/render.zig
index 87debcb5f0..61c66aaaf8 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -449,13 +449,16 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                     var it = field_inits.iterator(0);
                     while (it.next()) |field_init| {
                         try stream.writeByteNTimes(' ', new_indent);
-                        try renderExpression(allocator, stream, tree, new_indent, field_init.*, Space.None);
-
-                        const comma = tree.nextToken(field_init.*.lastToken());
-                        try renderToken(tree, stream, comma, new_indent, Space.Newline);
 
                         if (it.peek()) |next_field_init| {
+                            try renderExpression(allocator, stream, tree, new_indent, field_init.*, Space.None);
+
+                            const comma = tree.nextToken(field_init.*.lastToken());
+                            try renderToken(tree, stream, comma, new_indent, Space.Newline);
+
                             try renderExtraNewline(tree, stream, next_field_init.*);
+                        } else {
+                            try renderTrailingComma(allocator, stream, tree, new_indent, field_init.*, Space.Newline);
                         }
                     }
 
@@ -499,7 +502,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
 
                             try renderExtraNewline(tree, stream, next_expr.*);
                         } else {
-                            try renderTrailingComma(allocator, stream, tree, indent, expr.*, Space.Newline);
+                            try renderTrailingComma(allocator, stream, tree, new_indent, expr.*, Space.Newline);
                         }
                     }
 
@@ -743,11 +746,14 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
             var it = err_set_decl.decls.iterator(0);
             while (it.next()) |node| {
                 try stream.writeByteNTimes(' ', new_indent);
-                try renderExpression(allocator, stream, tree, new_indent, node.*, Space.None);
-                try renderToken(tree, stream, tree.nextToken(node.*.lastToken()), new_indent, Space.Newline); // ,
 
                 if (it.peek()) |next_node| {
+                    try renderExpression(allocator, stream, tree, new_indent, node.*, Space.None);
+                    try renderToken(tree, stream, tree.nextToken(node.*.lastToken()), new_indent, Space.Newline); // ,
+
                     try renderExtraNewline(tree, stream, next_node.*);
+                } else {
+                    try renderTrailingComma(allocator, stream, tree, new_indent, node.*, Space.Newline);
                 }
             }
 

From 56cb7f1740bf369b7cd2cac29db559c5c6bccc22 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 02:08:43 -0400
Subject: [PATCH 43/75] update json_test to be compliant with zig source
 encoding

See #663
---
 std/json_test.zig | 60 ++++++++++++-----------------------------------
 1 file changed, 15 insertions(+), 45 deletions(-)

diff --git a/std/json_test.zig b/std/json_test.zig
index 90a2ddbd50..60a5d1288c 100644
--- a/std/json_test.zig
+++ b/std/json_test.zig
@@ -431,15 +431,11 @@ test "y_string_two-byte-utf-8" {
 }
 
 test "y_string_u+2028_line_sep" {
-    ok(
-        \\["
"]
-    );
+    ok("[\"\xe2\x80\xa8\"]");
 }
 
 test "y_string_u+2029_par_sep" {
-    ok(
-        \\["
"]
-    );
+    ok("[\"\xe2\x80\xa9\"]");
 }
 
 test "y_string_uescaped_newline" {
@@ -455,9 +451,7 @@ test "y_string_uEscape" {
 }
 
 test "y_string_unescaped_char_delete" {
-    ok(
-        \\[""]
-    );
+    ok("[\"\x7f\"]");
 }
 
 test "y_string_unicode_2" {
@@ -527,9 +521,7 @@ test "y_string_utf8" {
 }
 
 test "y_string_with_del_character" {
-    ok(
-        \\["aa"]
-    );
+    ok("[\"a\x7fa\"]");
 }
 
 test "y_structure_lonely_false" {
@@ -718,9 +710,7 @@ test "n_array_number_and_several_commas" {
 }
 
 test "n_array_spaces_vertical_tab_formfeed" {
-    err(
-        \\["a"\f]
-    );
+    err("[\"\x0aa\"\\f]");
 }
 
 test "n_array_star_inside" {
@@ -774,9 +764,7 @@ test "n_incomplete_true" {
 }
 
 test "n_multidigit_number_then_00" {
-    err(
-        \\123
-    );
+    err("123\x00");
 }
 
 test "n_number_0.1.2" {
@@ -1309,9 +1297,7 @@ test "n_string_escaped_ctrl_char_tab" {
 }
 
 test "n_string_escaped_emoji" {
-    err(
-        \\["\🌀"]
-    );
+    err("[\"\x5c\xc3\xb0\xc2\x9f\xc2\x8c\xc2\x80\"]");
 }
 
 test "n_string_escape_x" {
@@ -1357,9 +1343,7 @@ test "n_string_invalid_unicode_escape" {
 }
 
 test "n_string_invalid_utf8_after_escape" {
-    err(
-        \\["\å"]
-    );
+    err("[\"\\\x75\xc3\xa5\"]");
 }
 
 test "n_string_invalid-utf-8-in-escape" {
@@ -1405,9 +1389,7 @@ test "n_string_start_escape_unclosed" {
 }
 
 test "n_string_unescaped_crtl_char" {
-    err(
-        \\["aa"]
-    );
+    err("[\"a\x00a\"]");
 }
 
 test "n_string_unescaped_newline" {
@@ -1418,9 +1400,7 @@ test "n_string_unescaped_newline" {
 }
 
 test "n_string_unescaped_tab" {
-    err(
-        \\["	"]
-    );
+    err("[\"\t\"]");
 }
 
 test "n_string_unicode_CapitalU" {
@@ -1532,9 +1512,7 @@ test "n_structure_no_data" {
 }
 
 test "n_structure_null-byte-outside-string" {
-    err(
-        \\[]
-    );
+    err("[\x00]");
 }
 
 test "n_structure_number_with_trailing_garbage" {
@@ -1718,9 +1696,7 @@ test "n_structure_UTF8_BOM_no_data" {
 }
 
 test "n_structure_whitespace_formfeed" {
-    err(
-        \\[]
-    );
+    err("[\x0c]");
 }
 
 test "n_structure_whitespace_U+2060_word_joiner" {
@@ -1900,21 +1876,15 @@ test "i_string_truncated-utf-8" {
 }
 
 test "i_string_utf16BE_no_BOM" {
-    any(
-        \\["é"]
-    );
+    any("\x00\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d");
 }
 
 test "i_string_utf16LE_no_BOM" {
-    any(
-        \\["é"]
-    );
+    any("\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d\x00");
 }
 
 test "i_string_UTF-16LE_with_BOM" {
-    any(
-        \\ÿþ["é"]
-    );
+    any("\xc3\xbf\xc3\xbe\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d\x00");
 }
 
 test "i_string_UTF-8_invalid_sequence" {

From a630d3e851a62c0e8971cbd2183e215606f35ab1 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 02:19:53 -0400
Subject: [PATCH 44/75] zig fmt: fix rendering of align keyword of slice type

---
 std/zig/parser_test.zig |  9 +++++++++
 std/zig/render.zig      | 12 ++++++------
 2 files changed, 15 insertions(+), 6 deletions(-)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index cabfb48387..ada132e775 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,12 @@
+test "zig fmt: slice align" {
+    try testCanonical(
+        \\const A = struct {
+        \\    items: []align(A) T,
+        \\};
+        \\
+    );
+}
+
 test "zig fmt: first thing in file is line comment" {
     try testTransform(
         \\comptime {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index 61c66aaaf8..215e57ceb8 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -268,10 +268,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                 ast.Node.PrefixOp.Op.AddrOf => |addr_of_info| {
                     try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // &
                     if (addr_of_info.align_info) |align_info| {
-                        const align_token = tree.nextToken(prefix_op_node.op_token);
-                        try renderToken(tree, stream, align_token, indent, Space.None); // align
-
                         const lparen_token = tree.prevToken(align_info.node.firstToken());
+                        const align_token = tree.prevToken(lparen_token);
+
+                        try renderToken(tree, stream, align_token, indent, Space.None); // align
                         try renderToken(tree, stream, lparen_token, indent, Space.None); // (
 
                         try renderExpression(allocator, stream, tree, indent, align_info.node, Space.None);
@@ -305,10 +305,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                     try renderToken(tree, stream, tree.nextToken(prefix_op_node.op_token), indent, Space.None); // ]
 
                     if (addr_of_info.align_info) |align_info| {
-                        const align_token = tree.nextToken(prefix_op_node.op_token);
-                        try renderToken(tree, stream, align_token, indent, Space.None); // align
-
                         const lparen_token = tree.prevToken(align_info.node.firstToken());
+                        const align_token = tree.prevToken(lparen_token);
+
+                        try renderToken(tree, stream, align_token, indent, Space.None); // align
                         try renderToken(tree, stream, lparen_token, indent, Space.None); // (
 
                         try renderExpression(allocator, stream, tree, indent, align_info.node, Space.None);

From 4405897cbd9105fddb512545594f336b597d91e9 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 20:34:53 -0400
Subject: [PATCH 45/75] zig fmt: support trailing comma on switch case items

---
 std/zig/parse.zig       | 25 +++++++++++++++--------
 std/zig/parser_test.zig | 35 +++++++++++++++++++++++++-------
 std/zig/render.zig      | 44 +++++++++++++++++++++++++++++++----------
 3 files changed, 79 insertions(+), 25 deletions(-)

diff --git a/std/zig/parse.zig b/std/zig/parse.zig
index 5d6897a0bc..a6eb22a2d0 100644
--- a/std/zig/parse.zig
+++ b/std/zig/parse.zig
@@ -1325,21 +1325,30 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
                     continue;
                 } else {
                     prevToken(&tok_it, &tree);
-                    try stack.append(State{ .SwitchCaseItem = switch_case });
+                    stack.append(State{ .SwitchCaseItemCommaOrEnd = switch_case }) catch unreachable;
+                    try stack.append(State{ .RangeExpressionBegin = OptionalCtx{ .Required = try switch_case.items.addOne() } });
                     continue;
                 }
             },
-            State.SwitchCaseItem => |node| {
-                stack.append(State{ .SwitchCaseItemCommaOrEnd = node }) catch unreachable;
-                try stack.append(State{ .RangeExpressionBegin = OptionalCtx{ .Required = try node.items.addOne() } });
+            State.SwitchCaseItemOrEnd => |switch_case| {
+                const token = nextToken(&tok_it, &tree);
+                if (token.ptr.id == Token.Id.EqualAngleBracketRight) {
+                    switch_case.arrow_token = token.index;
+                    continue;
+                } else {
+                    prevToken(&tok_it, &tree);
+                    stack.append(State{ .SwitchCaseItemCommaOrEnd = switch_case }) catch unreachable;
+                    try stack.append(State{ .RangeExpressionBegin = OptionalCtx{ .Required = try switch_case.items.addOne() } });
+                    continue;
+                }
             },
-            State.SwitchCaseItemCommaOrEnd => |node| {
+            State.SwitchCaseItemCommaOrEnd => |switch_case| {
                 switch (expectCommaOrEnd(&tok_it, &tree, Token.Id.EqualAngleBracketRight)) {
                     ExpectCommaOrEndResult.end_token => |end_token| {
                         if (end_token) |t| {
-                            node.arrow_token = t;
+                            switch_case.arrow_token = t;
                         } else {
-                            stack.append(State{ .SwitchCaseItem = node }) catch unreachable;
+                            stack.append(State{ .SwitchCaseItemOrEnd = switch_case }) catch unreachable;
                         }
                         continue;
                     },
@@ -2828,8 +2837,8 @@ const State = union(enum) {
     SwitchCaseOrEnd: ListSave(ast.Node.Switch.CaseList),
     SwitchCaseCommaOrEnd: ListSave(ast.Node.Switch.CaseList),
     SwitchCaseFirstItem: &ast.Node.SwitchCase,
-    SwitchCaseItem: &ast.Node.SwitchCase,
     SwitchCaseItemCommaOrEnd: &ast.Node.SwitchCase,
+    SwitchCaseItemOrEnd: &ast.Node.SwitchCase,
 
     SuspendBody: &ast.Node.Suspend,
     AsyncAllocator: &ast.Node.AsyncAttribute,
diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index ada132e775..9d5e64a66f 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,27 @@
+test "zig fmt: switch cases trailing comma" {
+    try testTransform(
+        \\fn switch_cases(x: i32) void {
+        \\    switch (x) {
+        \\        1,2,3 => {},
+        \\        4,5, => {},
+        \\        6...8, => {},
+        \\        else => {},
+        \\    }
+        \\}
+    ,
+        \\fn switch_cases(x: i32) void {
+        \\    switch (x) {
+        \\        1, 2, 3 => {},
+        \\        4,
+        \\        5, => {},
+        \\        6 ... 8 => {},
+        \\        else => {},
+        \\    }
+        \\}
+        \\
+    );
+}
+
 test "zig fmt: slice align" {
     try testCanonical(
         \\const A = struct {
@@ -7,7 +31,7 @@ test "zig fmt: slice align" {
     );
 }
 
-test "zig fmt: first thing in file is line comment" {
+test "zig fmt: add trailing comma to array literal" {
     try testTransform(
         \\comptime {
         \\    return []u16{'m', 's', 'y', 's', '-' // hi
@@ -217,13 +241,11 @@ test "zig fmt: add comma on last switch prong" {
         \\test "aoeu" {
         \\    switch (self.init_arg_expr) {
         \\        InitArg.Type => |t| {},
-        \\        InitArg.None,
-        \\        InitArg.Enum => {},
+        \\        InitArg.None, InitArg.Enum => {},
         \\    }
         \\    switch (self.init_arg_expr) {
         \\        InitArg.Type => |t| {},
-        \\        InitArg.None,
-        \\        InitArg.Enum => {}, //line comment
+        \\        InitArg.None, InitArg.Enum => {}, //line comment
         \\    }
         \\}
         \\
@@ -1003,8 +1025,7 @@ test "zig fmt: switch" {
         \\    switch (0) {
         \\        0 => {},
         \\        1 => unreachable,
-        \\        2,
-        \\        3 => {},
+        \\        2, 3 => {},
         \\        4 ... 7 => {},
         \\        1 + 4 * 3 + 22 => {},
         \\        else => {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index 215e57ceb8..4691d836c3 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -939,17 +939,41 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
         ast.Node.Id.SwitchCase => {
             const switch_case = @fieldParentPtr(ast.Node.SwitchCase, "base", base);
 
-            var it = switch_case.items.iterator(0);
-            while (it.next()) |node| {
-                if (it.peek()) |next_node| {
-                    try renderExpression(allocator, stream, tree, indent, node.*, Space.None);
+            assert(switch_case.items.len != 0);
+            const src_has_trailing_comma = blk: {
+                const last_node = switch_case.items.at(switch_case.items.len - 1).*;
+                const maybe_comma = tree.nextToken(last_node.lastToken());
+                break :blk tree.tokens.at(maybe_comma).id == Token.Id.Comma;
+            };
 
-                    const comma_token = tree.nextToken(node.*.lastToken());
-                    try renderToken(tree, stream, comma_token, indent, Space.Newline); // ,
-                    try renderExtraNewline(tree, stream, next_node.*);
-                    try stream.writeByteNTimes(' ', indent);
-                } else {
-                    try renderExpression(allocator, stream, tree, indent, node.*, Space.Space);
+            if (switch_case.items.len == 1 or !src_has_trailing_comma) {
+                var it = switch_case.items.iterator(0);
+                while (it.next()) |node| {
+                    if (it.peek()) |next_node| {
+                        try renderExpression(allocator, stream, tree, indent, node.*, Space.None);
+
+                        const comma_token = tree.nextToken(node.*.lastToken());
+                        try renderToken(tree, stream, comma_token, indent, Space.Space); // ,
+                        try renderExtraNewline(tree, stream, next_node.*);
+                    } else {
+                        try renderExpression(allocator, stream, tree, indent, node.*, Space.Space);
+                    }
+                }
+            } else {
+                var it = switch_case.items.iterator(0);
+                while (true) {
+                    const node = ??it.next();
+                    if (it.peek()) |next_node| {
+                        try renderExpression(allocator, stream, tree, indent, node.*, Space.None);
+
+                        const comma_token = tree.nextToken(node.*.lastToken());
+                        try renderToken(tree, stream, comma_token, indent, Space.Newline); // ,
+                        try renderExtraNewline(tree, stream, next_node.*);
+                        try stream.writeByteNTimes(' ', indent);
+                    } else {
+                        try renderTrailingComma(allocator, stream, tree, indent, node.*, Space.Space);
+                        break;
+                    }
                 }
             }
 

From c029f4bfc47b5d6d825f7ae7a3f224e9e9d6ce0b Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Fri, 25 May 2018 20:41:14 -0400
Subject: [PATCH 46/75] trailing comma after var args is not supported

---
 test/cases/syntax.zig | 5 -----
 1 file changed, 5 deletions(-)

diff --git a/test/cases/syntax.zig b/test/cases/syntax.zig
index 9512834f5a..20fb6cd203 100644
--- a/test/cases/syntax.zig
+++ b/test/cases/syntax.zig
@@ -34,16 +34,11 @@ fn switch_prongs(x: i32) void {
 
 const fn_no_comma = fn(i32, i32)void;
 const fn_trailing_comma = fn(i32, i32,)void;
-const fn_vararg_trailing_comma = fn(i32, i32, ...,)void;
 
 fn fn_calls() void {
     fn add(x: i32, y: i32,) i32 { x + y };
     _ = add(1, 2);
     _ = add(1, 2,);
-
-    fn swallow(x: ...,) void {};
-    _ = swallow(1,2,3,);
-    _ = swallow();
 }
 
 fn asm_lists() void {

From 85ca611af1d7401dd336f4655a0ab15640cc8424 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 15:37:47 -0400
Subject: [PATCH 47/75] zig fmt: put nested struct inits on newlines

See #1003
---
 std/zig/parser_test.zig |  9 +++++++++
 std/zig/render.zig      | 12 +++++++++---
 2 files changed, 18 insertions(+), 3 deletions(-)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index 9d5e64a66f..d321f78668 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,12 @@
+test "zig fmt: nested struct literal with one item" {
+    try testCanonical(
+        \\const a = foo{
+        \\    .item = bar{ .a = b },
+        \\};
+        \\
+    );
+}
+
 test "zig fmt: switch cases trailing comma" {
     try testTransform(
         \\fn switch_cases(x: i32) void {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index 4691d836c3..04939324a8 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -431,12 +431,18 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                         return;
                     }
 
-                    if (field_inits.len == 1) {
-                        const field_init = field_inits.at(0).*;
+                    if (field_inits.len == 1) blk: {
+                        const field_init = ??field_inits.at(0).*.cast(ast.Node.FieldInitializer);
+
+                        if (field_init.expr.cast(ast.Node.SuffixOp)) |nested_suffix_op| {
+                            if (nested_suffix_op.op == ast.Node.SuffixOp.Op.StructInitializer) {
+                                break :blk;
+                            }
+                        }
 
                         try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None);
                         try renderToken(tree, stream, lbrace, indent, Space.Space);
-                        try renderExpression(allocator, stream, tree, indent, field_init, Space.Space);
+                        try renderExpression(allocator, stream, tree, indent, &field_init.base, Space.Space);
                         try renderToken(tree, stream, suffix_op.rtoken, indent, space);
                         return;
                     }

From 0ab888c639dffcc48bc08a6ff186aa3da0ecbf74 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 16:37:55 -0400
Subject: [PATCH 48/75] zig fmt: parse extra comma in asm expressions

---
 std/zig/ast.zig         |  2 +-
 std/zig/parse.zig       |  8 ++--
 std/zig/parser_test.zig | 44 ++++++++++++++++++-
 std/zig/render.zig      | 95 ++++++++++++++++++++++++++++++-----------
 4 files changed, 120 insertions(+), 29 deletions(-)

diff --git a/std/zig/ast.zig b/std/zig/ast.zig
index 6c848b4a54..addd3a37e8 100644
--- a/std/zig/ast.zig
+++ b/std/zig/ast.zig
@@ -2071,7 +2071,7 @@ pub const Node = struct {
 
         const OutputList = SegmentedList(&AsmOutput, 2);
         const InputList = SegmentedList(&AsmInput, 2);
-        const ClobberList = SegmentedList(&Node, 2);
+        const ClobberList = SegmentedList(TokenIndex, 2);
 
         pub fn iterate(self: &Asm, index: usize) ?&Node {
             var i = index;
diff --git a/std/zig/parse.zig b/std/zig/parse.zig
index a6eb22a2d0..1bc64c3ddb 100644
--- a/std/zig/parse.zig
+++ b/std/zig/parse.zig
@@ -1153,9 +1153,11 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
                 continue;
             },
             State.AsmClobberItems => |items| {
-                stack.append(State{ .AsmClobberItems = items }) catch unreachable;
-                try stack.append(State{ .IfToken = Token.Id.Comma });
-                try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = try items.addOne() } });
+                while (eatToken(&tok_it, &tree, Token.Id.StringLiteral)) |strlit| {
+                    try items.push(strlit);
+                    if (eatToken(&tok_it, &tree, Token.Id.Comma) == null)
+                        break;
+                }
                 continue;
             },
 
diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index d321f78668..ab15ca3a58 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,44 @@
+test "zig fmt: simple asm" {
+    try testTransform(
+        \\comptime {
+        \\    asm volatile (
+        \\        \\.globl aoeu;
+        \\        \\.type aoeu, @function;
+        \\        \\.set aoeu, derp;
+        \\    );
+        \\
+        \\    asm ("not real assembly"
+        \\        :[a] "x" (x),);
+        \\    asm ("not real assembly"
+        \\        :[a] "x" (->i32),:[a] "x" (1),);
+        \\    asm ("still not real assembly"
+        \\        :::"a","b",);
+        \\}
+    ,
+        \\comptime {
+        \\    asm volatile (
+        \\        \\.globl aoeu;
+        \\        \\.type aoeu, @function;
+        \\        \\.set aoeu, derp;
+        \\    );
+        \\
+        \\    asm ("not real assembly"
+        \\        : [a] "x" (x)
+        \\    );
+        \\    asm ("not real assembly"
+        \\        : [a] "x" (-> i32)
+        \\        : [a] "x" (1)
+        \\    );
+        \\    asm ("still not real assembly"
+        \\        :
+        \\        :
+        \\        : "a", "b"
+        \\    );
+        \\}
+        \\
+    );
+}
+
 test "zig fmt: nested struct literal with one item" {
     try testCanonical(
         \\const a = foo{
@@ -1295,7 +1336,8 @@ test "zig fmt: inline asm" {
         \\        : [ret] "={rax}" (-> usize)
         \\        : [number] "{rax}" (number),
         \\          [arg1] "{rdi}" (arg1)
-        \\        : "rcx", "r11");
+        \\        : "rcx", "r11"
+        \\    );
         \\}
         \\
     );
diff --git a/std/zig/render.zig b/std/zig/render.zig
index 04939324a8..c37f6e37c7 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -1203,19 +1203,35 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                 try renderToken(tree, stream, tree.nextToken(asm_node.asm_token), indent, Space.None); // (
             }
 
+            if (asm_node.outputs.len == 0 and asm_node.inputs.len == 0 and asm_node.clobbers.len == 0) {
+                try renderExpression(allocator, stream, tree, indent, asm_node.template, Space.None);
+                try renderToken(tree, stream, asm_node.rparen, indent, space);
+                return;
+            }
+
             try renderExpression(allocator, stream, tree, indent, asm_node.template, Space.Newline);
+
             const indent_once = indent + indent_delta;
             try stream.writeByteNTimes(' ', indent_once);
-            try stream.print(": ");
+
+            const colon1 = tree.nextToken(asm_node.template.lastToken());
             const indent_extra = indent_once + 2;
 
-            {
+            const colon2 = if (asm_node.outputs.len == 0) blk: {
+                try renderToken(tree, stream, colon1, indent, Space.Newline); // :
+                try stream.writeByteNTimes(' ', indent_once);
+
+                break :blk tree.nextToken(colon1);
+            } else blk: {
+                try renderToken(tree, stream, colon1, indent, Space.Space); // :
+
                 var it = asm_node.outputs.iterator(0);
-                while (it.next()) |asm_output| {
+                while (true) {
+                    const asm_output = ??it.next();
                     const node = &(asm_output.*).base;
-                    try renderExpression(allocator, stream, tree, indent_extra, node, Space.None);
 
                     if (it.peek()) |next_asm_output| {
+                        try renderExpression(allocator, stream, tree, indent_extra, node, Space.None);
                         const next_node = &(next_asm_output.*).base;
 
                         const comma = tree.prevToken(next_asm_output.*.firstToken());
@@ -1223,21 +1239,38 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                         try renderExtraNewline(tree, stream, next_node);
 
                         try stream.writeByteNTimes(' ', indent_extra);
+                    } else if (asm_node.inputs.len == 0 and asm_node.clobbers.len == 0) {
+                        try renderExpression(allocator, stream, tree, indent_extra, node, Space.Newline);
+                        try stream.writeByteNTimes(' ', indent);
+                        try renderToken(tree, stream, asm_node.rparen, indent, space);
+                        return;
+                    } else {
+                        try renderExpression(allocator, stream, tree, indent_extra, node, Space.Newline);
+                        try stream.writeByteNTimes(' ', indent_once);
+                        const comma_or_colon = tree.nextToken(node.lastToken());
+                        break :blk switch (tree.tokens.at(comma_or_colon).id) {
+                            Token.Id.Comma => tree.nextToken(comma_or_colon),
+                            else => comma_or_colon,
+                        };
                     }
                 }
-            }
+            };
 
-            try stream.write("\n");
-            try stream.writeByteNTimes(' ', indent_once);
-            try stream.write(": ");
+            const colon3 = if (asm_node.inputs.len == 0) blk: {
+                try renderToken(tree, stream, colon2, indent, Space.Newline); // :
+                try stream.writeByteNTimes(' ', indent_once);
+
+                break :blk tree.nextToken(colon2);
+            } else blk: {
+                try renderToken(tree, stream, colon2, indent, Space.Space); // :
 
-            {
                 var it = asm_node.inputs.iterator(0);
-                while (it.next()) |asm_input| {
+                while (true) {
+                    const asm_input = ??it.next();
                     const node = &(asm_input.*).base;
-                    try renderExpression(allocator, stream, tree, indent_extra, node, Space.None);
 
                     if (it.peek()) |next_asm_input| {
+                        try renderExpression(allocator, stream, tree, indent_extra, node, Space.None);
                         const next_node = &(next_asm_input.*).base;
 
                         const comma = tree.prevToken(next_asm_input.*.firstToken());
@@ -1245,26 +1278,40 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                         try renderExtraNewline(tree, stream, next_node);
 
                         try stream.writeByteNTimes(' ', indent_extra);
+                    } else if (asm_node.clobbers.len == 0) {
+                        try renderExpression(allocator, stream, tree, indent_extra, node, Space.Newline);
+                        try stream.writeByteNTimes(' ', indent);
+                        try renderToken(tree, stream, asm_node.rparen, indent, space); // )
+                        return;
+                    } else {
+                        try renderExpression(allocator, stream, tree, indent_extra, node, Space.Newline);
+                        try stream.writeByteNTimes(' ', indent_once);
+                        const comma_or_colon = tree.nextToken(node.lastToken());
+                        break :blk switch (tree.tokens.at(comma_or_colon).id) {
+                            Token.Id.Comma => tree.nextToken(comma_or_colon),
+                            else => comma_or_colon,
+                        };
                     }
                 }
-            }
+            };
 
-            try stream.write("\n");
-            try stream.writeByteNTimes(' ', indent_once);
-            try stream.write(": ");
+            try renderToken(tree, stream, colon3, indent, Space.Space); // :
 
-            {
-                var it = asm_node.clobbers.iterator(0);
-                while (it.next()) |node| {
-                    try renderExpression(allocator, stream, tree, indent_once, node.*, Space.None);
+            var it = asm_node.clobbers.iterator(0);
+            while (true) {
+                const clobber_token = ??it.next();
 
-                    if (it.peek() != null) {
-                        try stream.write(", ");
-                    }
+                if (it.peek() == null) {
+                    try renderToken(tree, stream, clobber_token.*, indent_once, Space.Newline);
+                    try stream.writeByteNTimes(' ', indent);
+                    try renderToken(tree, stream, asm_node.rparen, indent, space);
+                    return;
+                } else {
+                    try renderToken(tree, stream, clobber_token.*, indent_once, Space.None);
+                    const comma = tree.nextToken(clobber_token.*);
+                    try renderToken(tree, stream, comma, indent_once, Space.Space); // ,
                 }
             }
-
-            try renderToken(tree, stream, asm_node.rparen, indent, space);
         },
 
         ast.Node.Id.AsmInput => {

From 0bef1f98247160cbd5101c763404c76ae287b2bd Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 16:43:33 -0400
Subject: [PATCH 49/75] zig fmt: fix rendering of struct with no trailing comma
 on last field

---
 std/zig/parser_test.zig | 15 +++++++++++++++
 std/zig/render.zig      |  3 +--
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index ab15ca3a58..e76d588088 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,18 @@
+test "zig fmt: no trailing comma on struct decl" {
+    try testTransform(
+        \\const RoundParam = struct {
+        \\    k: usize, s: u32, t: u32
+        \\};
+    ,
+        \\const RoundParam = struct {
+        \\    k: usize,
+        \\    s: u32,
+        \\    t: u32,
+        \\};
+        \\
+    );
+}
+
 test "zig fmt: simple asm" {
     try testTransform(
         \\comptime {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index c37f6e37c7..dea06e3a7d 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -102,8 +102,7 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i
             }
             try renderToken(tree, stream, field.name_token, indent, Space.None); // name
             try renderToken(tree, stream, tree.nextToken(field.name_token), indent, Space.Space); // :
-            try renderExpression(allocator, stream, tree, indent, field.type_expr, Space.None); // type
-            try renderToken(tree, stream, tree.nextToken(field.lastToken()), indent, Space.Newline); // ,
+            try renderTrailingComma(allocator, stream, tree, indent, field.type_expr, Space.Newline); // type,
         },
 
         ast.Node.Id.UnionTag => {

From 7e900d28be00e03eee2ec3703c0c45247b4748b1 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 18:10:06 -0400
Subject: [PATCH 50/75] zig fmt: no space on switch range operator

---
 std/zig/parser_test.zig | 6 +++---
 std/zig/render.zig      | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index e76d588088..dfef594df7 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -69,7 +69,7 @@ test "zig fmt: switch cases trailing comma" {
         \\    switch (x) {
         \\        1,2,3 => {},
         \\        4,5, => {},
-        \\        6...8, => {},
+        \\        6... 8, => {},
         \\        else => {},
         \\    }
         \\}
@@ -79,7 +79,7 @@ test "zig fmt: switch cases trailing comma" {
         \\        1, 2, 3 => {},
         \\        4,
         \\        5, => {},
-        \\        6 ... 8 => {},
+        \\        6...8 => {},
         \\        else => {},
         \\    }
         \\}
@@ -1091,7 +1091,7 @@ test "zig fmt: switch" {
         \\        0 => {},
         \\        1 => unreachable,
         \\        2, 3 => {},
-        \\        4 ... 7 => {},
+        \\        4...7 => {},
         \\        1 + 4 * 3 + 22 => {},
         \\        else => {
         \\            const a = 1;
diff --git a/std/zig/render.zig b/std/zig/render.zig
index dea06e3a7d..67ec8f7632 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -244,7 +244,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
 
             const op_token = tree.tokens.at(infix_op_node.op_token);
             const op_space = switch (infix_op_node.op) {
-                ast.Node.InfixOp.Op.Period, ast.Node.InfixOp.Op.ErrorUnion => Space.None,
+                ast.Node.InfixOp.Op.Period, ast.Node.InfixOp.Op.ErrorUnion, ast.Node.InfixOp.Op.Range => Space.None,
                 else => Space.Space,
             };
             try renderExpression(allocator, stream, tree, indent, infix_op_node.lhs, op_space);

From b8d4e05361d6a01ae1c0bf931e27e2bfdb25551d Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 18:29:14 -0400
Subject: [PATCH 51/75] zig fmt: handle empty block with comment inside

---
 std/zig/parser_test.zig | 11 +++++++++++
 std/zig/render.zig      |  2 +-
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index dfef594df7..c115c5848f 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,14 @@
+test "zig fmt: empty block with only comment" {
+    try testCanonical(
+        \\comptime {
+        \\    {
+        \\        // comment
+        \\    }
+        \\}
+        \\
+    );
+}
+
 test "zig fmt: no trailing comma on struct decl" {
     try testTransform(
         \\const RoundParam = struct {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index 67ec8f7632..90acb0e412 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -1519,7 +1519,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
 
                     const after_comment_token = tree.tokens.at(token_index + offset);
                     const next_line_indent = switch (after_comment_token.id) {
-                        Token.Id.RParen, Token.Id.RBrace, Token.Id.RBracket => indent,
+                        Token.Id.RParen, Token.Id.RBrace, Token.Id.RBracket => indent - indent_delta,
                         else => indent,
                     };
                     try stream.writeByteNTimes(' ', next_line_indent);

From cabf7fa93b7250a69a3cfad417537c2a46414779 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 18:44:10 -0400
Subject: [PATCH 52/75] zig fmt: fn calls with trailing comma with params on
 new lines

---
 std/zig/parser_test.zig | 13 +++++++++++++
 std/zig/render.zig      | 38 ++++++++++++++++++++++++++++++++++++--
 2 files changed, 49 insertions(+), 2 deletions(-)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index c115c5848f..4ce355dc87 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,16 @@
+test "zig fmt: trailing comma on fn call" {
+    try testCanonical(
+        \\comptime {
+        \\    var module = try Module.create(
+        \\        allocator,
+        \\        zig_lib_dir,
+        \\        full_cache_dir,
+        \\    );
+        \\}
+        \\
+    );
+}
+
 test "zig fmt: empty block with only comment" {
     try testCanonical(
         \\comptime {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index 90acb0e412..f068e652bb 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -374,7 +374,42 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                     try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None);
 
                     const lparen = tree.nextToken(suffix_op.lhs.lastToken());
-                    try renderToken(tree, stream, lparen, indent, Space.None);
+
+                    if (call_info.params.len == 0) {
+                        try renderToken(tree, stream, lparen, indent, Space.None);
+                        try renderToken(tree, stream, suffix_op.rtoken, indent, space);
+                        return;
+                    }
+
+                    const src_has_trailing_comma = blk: {
+                        const maybe_comma = tree.prevToken(suffix_op.rtoken);
+                        break :blk tree.tokens.at(maybe_comma).id == Token.Id.Comma;
+                    };
+
+                    if (src_has_trailing_comma) {
+                        const new_indent = indent + indent_delta;
+                        try renderToken(tree, stream, lparen, new_indent, Space.Newline);
+
+                        var it = call_info.params.iterator(0);
+                        while (true) {
+                            const param_node = ??it.next();
+                            try stream.writeByteNTimes(' ', new_indent);
+
+                            if (it.peek()) |next_node| {
+                                try renderExpression(allocator, stream, tree, new_indent, param_node.*, Space.None);
+                                const comma = tree.nextToken(param_node.*.lastToken());
+                                try renderToken(tree, stream, comma, new_indent, Space.Newline); // ,
+                                try renderExtraNewline(tree, stream, next_node.*);
+                            } else {
+                                try renderTrailingComma(allocator, stream, tree, new_indent, param_node.*, Space.Newline);
+                                try stream.writeByteNTimes(' ', indent);
+                                try renderToken(tree, stream, suffix_op.rtoken, indent, space);
+                                return;
+                            }
+                        }
+                    }
+
+                    try renderToken(tree, stream, lparen, indent, Space.None); // (
 
                     var it = call_info.params.iterator(0);
                     while (it.next()) |param_node| {
@@ -385,7 +420,6 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                             try renderToken(tree, stream, comma, indent, Space.Space);
                         }
                     }
-
                     try renderToken(tree, stream, suffix_op.rtoken, indent, space);
                 },
 

From 349365d9a483bc6be8c1677149ec1a31a789e4b2 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 19:32:28 -0400
Subject: [PATCH 53/75] zig fmt: better multiline string formatting

---
 std/zig/parser_test.zig | 29 +++++++++++++++++++++++++++++
 std/zig/render.zig      | 36 ++++++++++++++++++++++++++++++------
 std/zig/tokenizer.zig   | 12 ------------
 3 files changed, 59 insertions(+), 18 deletions(-)

diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index 4ce355dc87..152056c6b4 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,32 @@
+test "zig fmt: multiline string with backslash at end of line" {
+    try testCanonical(
+        \\comptime {
+        \\    err(
+        \\        \\\
+        \\    );
+        \\}
+        \\
+    );
+}
+
+test "zig fmt: multiline string parameter in fn call with trailing comma" {
+    try testCanonical(
+        \\fn foo() void {
+        \\    try stdout.print(
+        \\        \\ZIG_CMAKE_BINARY_DIR {}
+        \\        \\ZIG_C_HEADER_FILES   {}
+        \\        \\ZIG_DIA_GUIDS_LIB    {}
+        \\        \\
+        \\    ,
+        \\        std.cstr.toSliceConst(c.ZIG_CMAKE_BINARY_DIR),
+        \\        std.cstr.toSliceConst(c.ZIG_CXX_COMPILER),
+        \\        std.cstr.toSliceConst(c.ZIG_DIA_GUIDS_LIB),
+        \\    );
+        \\}
+        \\
+    );
+}
+
 test "zig fmt: trailing comma on fn call" {
     try testCanonical(
         \\comptime {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index f068e652bb..409828e070 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -393,15 +393,21 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                         var it = call_info.params.iterator(0);
                         while (true) {
                             const param_node = ??it.next();
-                            try stream.writeByteNTimes(' ', new_indent);
+
+                            const param_node_new_indent = if (param_node.*.id == ast.Node.Id.MultilineStringLiteral) blk: {
+                                break :blk indent;
+                            } else blk: {
+                                try stream.writeByteNTimes(' ', new_indent);
+                                break :blk new_indent;
+                            };
 
                             if (it.peek()) |next_node| {
-                                try renderExpression(allocator, stream, tree, new_indent, param_node.*, Space.None);
+                                try renderExpression(allocator, stream, tree, param_node_new_indent, param_node.*, Space.None);
                                 const comma = tree.nextToken(param_node.*.lastToken());
                                 try renderToken(tree, stream, comma, new_indent, Space.Newline); // ,
                                 try renderExtraNewline(tree, stream, next_node.*);
                             } else {
-                                try renderTrailingComma(allocator, stream, tree, new_indent, param_node.*, Space.Newline);
+                                try renderTrailingComma(allocator, stream, tree, param_node_new_indent, param_node.*, Space.Newline);
                                 try stream.writeByteNTimes(' ', indent);
                                 try renderToken(tree, stream, suffix_op.rtoken, indent, space);
                                 return;
@@ -1502,7 +1508,13 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
     if (next_token.id != Token.Id.LineComment) {
         switch (space) {
             Space.None, Space.NoNewline, Space.NoIndent => return,
-            Space.Newline => return stream.write("\n"),
+            Space.Newline => {
+                if (next_token.id == Token.Id.MultilineStringLiteralLine) {
+                    return;
+                } else {
+                    return stream.write("\n");
+                }
+            },
             Space.Space => return stream.writeByte(' '),
             Space.NoComment => unreachable,
         }
@@ -1526,7 +1538,13 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
                     };
                     try stream.writeByteNTimes(' ', next_line_indent);
                 },
-                Space.Newline, Space.NoIndent => try stream.write("\n"),
+                Space.Newline, Space.NoIndent => {
+                    if (next_token.id == Token.Id.MultilineStringLiteralLine) {
+                        return;
+                    } else {
+                        return stream.write("\n");
+                    }
+                },
                 Space.NoNewline => {},
                 Space.NoComment => unreachable,
             }
@@ -1547,7 +1565,13 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
         next_token = tree.tokens.at(token_index + offset);
         if (next_token.id != Token.Id.LineComment) {
             switch (space) {
-                Space.Newline, Space.NoIndent => try stream.writeByte('\n'),
+                Space.Newline, Space.NoIndent => {
+                    if (next_token.id == Token.Id.MultilineStringLiteralLine) {
+                        return;
+                    } else {
+                        return stream.write("\n");
+                    }
+                },
                 Space.None, Space.Space => {
                     try stream.writeByte('\n');
 
diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig
index f4cd847dff..b90a40108f 100644
--- a/std/zig/tokenizer.zig
+++ b/std/zig/tokenizer.zig
@@ -217,7 +217,6 @@ pub const Tokenizer = struct {
         StringLiteral,
         StringLiteralBackslash,
         MultilineStringLiteralLine,
-        MultilineStringLiteralLineBackslash,
         CharLiteral,
         CharLiteralBackslash,
         CharLiteralEscape1,
@@ -655,9 +654,6 @@ pub const Tokenizer = struct {
                 },
 
                 State.MultilineStringLiteralLine => switch (c) {
-                    '\\' => {
-                        state = State.MultilineStringLiteralLineBackslash;
-                    },
                     '\n' => {
                         self.index += 1;
                         break;
@@ -665,13 +661,6 @@ pub const Tokenizer = struct {
                     else => self.checkLiteralCharacter(),
                 },
 
-                State.MultilineStringLiteralLineBackslash => switch (c) {
-                    '\n' => break, // Look for this error later.
-                    else => {
-                        state = State.MultilineStringLiteralLine;
-                    },
-                },
-
                 State.Bang => switch (c) {
                     '=' => {
                         result.id = Token.Id.BangEqual;
@@ -1010,7 +999,6 @@ pub const Tokenizer = struct {
                 State.FloatExponentUnsignedHex,
                 State.SawAtSign,
                 State.Backslash,
-                State.MultilineStringLiteralLineBackslash,
                 State.CharLiteral,
                 State.CharLiteralBackslash,
                 State.CharLiteralEscape1,

From 118d41ef8325b4c1ca8be1fea66c2e8368b67e32 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 22:59:46 -0400
Subject: [PATCH 54/75] zig fmt: support array literal row size hint

See #1003
---
 std/mem.zig             |   8 +++
 std/zig/parser_test.zig |  59 ++++++++++++++++++++++
 std/zig/render.zig      | 108 +++++++++++++++++++++++++++++++++++++---
 3 files changed, 167 insertions(+), 8 deletions(-)

diff --git a/std/mem.zig b/std/mem.zig
index 617c1de2f5..70f2fe22ac 100644
--- a/std/mem.zig
+++ b/std/mem.zig
@@ -177,6 +177,14 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
     return true;
 }
 
+/// Returns true if all elements in a slice are equal to the scalar value provided
+pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool {
+    for (slice) |item| {
+        if (item != scalar) return false;
+    }
+    return true;
+}
+
 /// Copies ::m to newly allocated memory. Caller is responsible to free it.
 pub fn dupe(allocator: &Allocator, comptime T: type, m: []const T) ![]T {
     const new_buf = try allocator.alloc(T, m.len);
diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig
index 152056c6b4..909220a6f6 100644
--- a/std/zig/parser_test.zig
+++ b/std/zig/parser_test.zig
@@ -1,3 +1,62 @@
+test "zig fmt: array literal with hint" {
+    try testTransform(
+        \\const a = []u8{
+        \\    1, 2, //
+        \\    3,
+        \\    4,
+        \\    5,
+        \\    6,
+        \\    7 };
+        \\const a = []u8{
+        \\    1, 2, //
+        \\    3,
+        \\    4,
+        \\    5,
+        \\    6,
+        \\    7, 8 };
+        \\const a = []u8{
+        \\    1, 2, //
+        \\    3,
+        \\    4,
+        \\    5,
+        \\    6, // blah
+        \\    7, 8 };
+        \\const a = []u8{
+        \\    1, 2, //
+        \\    3, //
+        \\    4,
+        \\    5,
+        \\    6,
+        \\    7 };
+    ,
+        \\const a = []u8{
+        \\    1, 2, //
+        \\    3, 4, //
+        \\    5, 6, //
+        \\    7,
+        \\};
+        \\const a = []u8{
+        \\    1, 2, //
+        \\    3, 4, //
+        \\    5, 6, //
+        \\    7, 8, //
+        \\};
+        \\const a = []u8{
+        \\    1, 2, //
+        \\    3, 4, //
+        \\    5, 6, // blah
+        \\    7, 8, //
+        \\};
+        \\const a = []u8{
+        \\    1, 2, //
+        \\    3, 4, //
+        \\    5, 6, //
+        \\    7,
+        \\};
+        \\
+    );
+}
+
 test "zig fmt: multiline string with backslash at end of line" {
     try testCanonical(
         \\comptime {
diff --git a/std/zig/render.zig b/std/zig/render.zig
index 409828e070..fa3755b719 100644
--- a/std/zig/render.zig
+++ b/std/zig/render.zig
@@ -19,7 +19,7 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(
     var tok_it = tree.tokens.iterator(0);
     while (tok_it.next()) |token| {
         if (token.id != Token.Id.LineComment) break;
-        try stream.print("{}\n", tree.tokenSlicePtr(token));
+        try stream.print("{}\n", mem.trimRight(u8, tree.tokenSlicePtr(token), " "));
         if (tok_it.peek()) |next_token| {
             const loc = tree.tokenLocationPtr(token.end, next_token);
             if (loc.line >= 2) {
@@ -532,12 +532,73 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
 
                     try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None);
 
+                    // scan to find row size
+                    const maybe_row_size: ?usize = blk: {
+                        var count: usize = 0;
+                        var it = exprs.iterator(0);
+                        var prev_token = (??it.peek()).*.lastToken() + 1;
+                        while (it.next()) |expr| {
+                            const expr_last_token = expr.*.lastToken() + 1;
+                            const next_token = tree.tokens.at(expr_last_token + 1);
+                            const loc = tree.tokenLocationPtr(tree.tokens.at(prev_token).end, next_token);
+                            if (loc.line != 0) break :blk null;
+                            if (next_token.id == Token.Id.LineComment) {
+                                const trimmed = mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ");
+                                if (trimmed.len == 2) {
+                                    break :blk count;
+                                } else {
+                                    break :blk null;
+                                }
+                            }
+                            prev_token = expr_last_token;
+                            count += 1;
+                        }
+                        break :blk null;
+                    };
+
+
                     const new_indent = indent + indent_delta;
                     try renderToken(tree, stream, lbrace, new_indent, Space.Newline);
+                    try stream.writeByteNTimes(' ', new_indent);
+
+                    if (maybe_row_size) |row_size| {
+                        var it = exprs.iterator(0);
+                        var i: usize = 0;
+                        while (it.next()) |expr| {
+                            if (it.peek()) |next_expr| {
+                                try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.None);
+
+                                const comma = tree.nextToken(expr.*.lastToken());
+
+                                if (i != row_size) {
+                                    try renderToken(tree, stream, comma, new_indent, Space.IgnoreEmptyComment); // ,
+                                    i += 1;
+                                    continue;
+                                }
+                                i = 0;
+
+                                try renderToken(tree, stream, comma, new_indent, Space.NoIndent); // ,
+
+                                const next_token = tree.tokens.at(comma + 1);
+                                if (next_token.id != Token.Id.LineComment) {
+                                    try stream.print(" //\n");
+                                }
+
+                                try renderExtraNewline(tree, stream, next_expr.*);
+                                try stream.writeByteNTimes(' ', new_indent);
+                            } else if (i == row_size) {
+                                try renderTrailingCommaAndEmptyComment(allocator, stream, tree, new_indent, expr.*); // , //
+                            } else {
+                                try renderTrailingComma(allocator, stream, tree, new_indent, expr.*, Space.Newline); // ,
+                            }
+                        }
+                        try stream.writeByteNTimes(' ', indent);
+                        try renderToken(tree, stream, suffix_op.rtoken, indent, space);
+                        return;
+                    }
 
                     var it = exprs.iterator(0);
                     while (it.next()) |expr| {
-                        try stream.writeByteNTimes(' ', new_indent);
 
                         if (it.peek()) |next_expr| {
                             try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.None);
@@ -546,6 +607,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
                             try renderToken(tree, stream, comma, new_indent, Space.Newline); // ,
 
                             try renderExtraNewline(tree, stream, next_expr.*);
+                            try stream.writeByteNTimes(' ', new_indent);
                         } else {
                             try renderTrailingComma(allocator, stream, tree, new_indent, expr.*, Space.Newline);
                         }
@@ -1496,11 +1558,12 @@ const Space = enum {
     NoNewline,
     NoIndent,
     NoComment,
+    IgnoreEmptyComment,
 };
 
 fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, space: Space) (@typeOf(stream).Child.Error || Error)!void {
     var token = tree.tokens.at(token_index);
-    try stream.write(tree.tokenSlicePtr(token));
+    try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(token), " "));
 
     if (space == Space.NoComment) return;
 
@@ -1515,15 +1578,19 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
                     return stream.write("\n");
                 }
             },
-            Space.Space => return stream.writeByte(' '),
+            Space.Space, Space.IgnoreEmptyComment => return stream.writeByte(' '),
             Space.NoComment => unreachable,
         }
     }
 
+    if (space == Space.IgnoreEmptyComment and mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ").len == 2) {
+        return stream.writeByte(' ');
+    }
+
     var loc = tree.tokenLocationPtr(token.end, next_token);
     var offset: usize = 1;
     if (loc.line == 0) {
-        try stream.print(" {}", tree.tokenSlicePtr(next_token));
+        try stream.print(" {}", mem.trimRight(u8, tree.tokenSlicePtr(next_token), " "));
         offset = 2;
         token = next_token;
         next_token = tree.tokens.at(token_index + offset);
@@ -1546,7 +1613,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
                     }
                 },
                 Space.NoNewline => {},
-                Space.NoComment => unreachable,
+                Space.NoComment, Space.IgnoreEmptyComment => unreachable,
             }
             return;
         }
@@ -1558,7 +1625,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
         const newline_count = if (loc.line == 1) u8(1) else u8(2);
         try stream.writeByteNTimes('\n', newline_count);
         try stream.writeByteNTimes(' ', indent);
-        try stream.write(tree.tokenSlicePtr(next_token));
+        try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(next_token), " "));
 
         offset += 1;
         token = next_token;
@@ -1583,7 +1650,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
                     try stream.writeByteNTimes(' ', next_line_indent);
                 },
                 Space.NoNewline => {},
-                Space.NoComment => unreachable,
+                Space.NoComment, Space.IgnoreEmptyComment => unreachable,
             }
             return;
         }
@@ -1621,3 +1688,28 @@ fn renderTrailingComma(allocator: &mem.Allocator, stream: var, tree: &ast.Tree,
         },
     }
 }
+
+fn renderTrailingCommaAndEmptyComment(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void
+{
+    const end_token = base.lastToken() + 1;
+    switch (tree.tokens.at(end_token).id) {
+        Token.Id.Comma => {
+            try renderExpression(allocator, stream, tree, indent, base, Space.None);
+            try renderToken(tree, stream, end_token, indent, Space.Space); // ,
+
+            const next_token = tree.tokens.at(end_token + 1);
+            if (next_token.id != Token.Id.LineComment) {
+                try stream.print("//\n");
+            }
+        },
+        Token.Id.LineComment => {
+            try renderExpression(allocator, stream, tree, indent, base, Space.NoComment);
+            try stream.write(", ");
+            try renderToken(tree, stream, end_token, indent, Space.Newline);
+        },
+        else => {
+            try renderExpression(allocator, stream, tree, indent, base, Space.None);
+            try stream.write(", //\n");
+        },
+    }
+}

From b184ae5ca5d3d3c0a4b9de564a6e30555e596e65 Mon Sep 17 00:00:00 2001
From: Andrew Kelley 
Date: Sat, 26 May 2018 18:16:39 -0400
Subject: [PATCH 55/75] run zig fmt on some of the codebase

See #1003
---
 doc/docgen.zig                     | 182 +++---
 example/guess_number/main.zig      |   2 +-
 example/hello_world/hello_libc.zig |   3 +-
 example/mix_o_files/build.zig      |   4 +-
 example/shared_library/build.zig   |   4 +-
 src-self-hosted/introspect.zig     |   4 +-
 src-self-hosted/ir.zig             |   1 -
 src-self-hosted/main.zig           | 169 +++---
 src-self-hosted/target.zig         |   3 +-
 std/array_list.zig                 |   9 +-
 std/base64.zig                     | 117 ++--
 std/buf_map.zig                    |   4 +-
 std/buf_set.zig                    |   4 +-
 std/build.zig                      |  59 +-
 std/c/darwin.zig                   |   2 +-
 std/c/index.zig                    |  12 +-
 std/crypto/md5.zig                 | 138 +++--
 std/crypto/sha1.zig                |  86 +--
 std/crypto/sha2.zig                | 875 +++++++++++++++--------------
 std/crypto/test.zig                |   2 +-
 std/crypto/throughput_test.zig     |   2 +-
 std/cstr.zig                       |   4 +-
 std/debug/failing_allocator.zig    |   4 +-
 std/debug/index.zig                |  18 +-
 std/dwarf.zig                      |   2 -
 std/elf.zig                        |  42 +-
 std/event.zig                      |  13 +-
 std/fmt/errol/enum3.zig            |   7 +-
 28 files changed, 920 insertions(+), 852 deletions(-)

diff --git a/doc/docgen.zig b/doc/docgen.zig
index bd9dc6c147..7dc444f127 100644
--- a/doc/docgen.zig
+++ b/doc/docgen.zig
@@ -95,7 +95,7 @@ const Tokenizer = struct {
     };
 
     fn init(source_file_name: []const u8, buffer: []const u8) Tokenizer {
-        return Tokenizer {
+        return Tokenizer{
             .buffer = buffer,
             .index = 0,
             .state = State.Start,
@@ -105,7 +105,7 @@ const Tokenizer = struct {
     }
 
     fn next(self: &Tokenizer) Token {
-        var result = Token {
+        var result = Token{
             .id = Token.Id.Eof,
             .start = self.index,
             .end = undefined,
@@ -197,7 +197,7 @@ const Tokenizer = struct {
     };
 
     fn getTokenLocation(self: &Tokenizer, token: &const Token) Location {
-        var loc = Location {
+        var loc = Location{
             .line = 0,
             .column = 0,
             .line_start = 0,
@@ -346,7 +346,7 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {
                 break;
             },
             Token.Id.Content => {
-                try nodes.append(Node {.Content = tokenizer.buffer[token.start..token.end] });
+                try nodes.append(Node{ .Content = tokenizer.buffer[token.start..token.end] });
             },
             Token.Id.BracketOpen => {
                 const tag_token = try eatToken(tokenizer, Token.Id.TagContent);
@@ -365,11 +365,13 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {
                     header_stack_size += 1;
 
                     const urlized = try urlize(allocator, content);
-                    try nodes.append(Node{.HeaderOpen = HeaderOpen {
-                        .name = content,
-                        .url = urlized,
-                        .n = header_stack_size,
-                    }});
+                    try nodes.append(Node{
+                        .HeaderOpen = HeaderOpen{
+                            .name = content,
+                            .url = urlized,
+                            .n = header_stack_size,
+                        },
+                    });
                     if (try urls.put(urlized, tag_token)) |other_tag_token| {
                         parseError(tokenizer, tag_token, "duplicate header url: #{}", urlized) catch {};
                         parseError(tokenizer, other_tag_token, "other tag here") catch {};
@@ -407,14 +409,14 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {
                         switch (see_also_tok.id) {
                             Token.Id.TagContent => {
                                 const content = tokenizer.buffer[see_also_tok.start..see_also_tok.end];
-                                try list.append(SeeAlsoItem {
+                                try list.append(SeeAlsoItem{
                                     .name = content,
                                     .token = see_also_tok,
                                 });
                             },
                             Token.Id.Separator => {},
                             Token.Id.BracketClose => {
-                                try nodes.append(Node {.SeeAlso = list.toOwnedSlice() } );
+                                try nodes.append(Node{ .SeeAlso = list.toOwnedSlice() });
                                 break;
                             },
                             else => return parseError(tokenizer, see_also_tok, "invalid see_also token"),
@@ -438,8 +440,8 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {
                         }
                     };
 
-                    try nodes.append(Node {
-                        .Link = Link {
+                    try nodes.append(Node{
+                        .Link = Link{
                             .url = try urlize(allocator, url_name),
                             .name = name,
                             .token = name_tok,
@@ -463,24 +465,24 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {
                     var code_kind_id: Code.Id = undefined;
                     var is_inline = false;
                     if (mem.eql(u8, code_kind_str, "exe")) {
-                        code_kind_id = Code.Id { .Exe = ExpectedOutcome.Succeed };
+                        code_kind_id = Code.Id{ .Exe = ExpectedOutcome.Succeed };
                     } else if (mem.eql(u8, code_kind_str, "exe_err")) {
-                        code_kind_id = Code.Id { .Exe = ExpectedOutcome.Fail };
+                        code_kind_id = Code.Id{ .Exe = ExpectedOutcome.Fail };
                     } else if (mem.eql(u8, code_kind_str, "test")) {
                         code_kind_id = Code.Id.Test;
                     } else if (mem.eql(u8, code_kind_str, "test_err")) {
-                        code_kind_id = Code.Id { .TestError = name};
+                        code_kind_id = Code.Id{ .TestError = name };
                         name = "test";
                     } else if (mem.eql(u8, code_kind_str, "test_safety")) {
-                        code_kind_id = Code.Id { .TestSafety = name};
+                        code_kind_id = Code.Id{ .TestSafety = name };
                         name = "test";
                     } else if (mem.eql(u8, code_kind_str, "obj")) {
-                        code_kind_id = Code.Id { .Obj = null };
+                        code_kind_id = Code.Id{ .Obj = null };
                     } else if (mem.eql(u8, code_kind_str, "obj_err")) {
-                        code_kind_id = Code.Id { .Obj = name };
+                        code_kind_id = Code.Id{ .Obj = name };
                         name = "test";
                     } else if (mem.eql(u8, code_kind_str, "syntax")) {
-                        code_kind_id = Code.Id { .Obj = null };
+                        code_kind_id = Code.Id{ .Obj = null };
                         is_inline = true;
                     } else {
                         return parseError(tokenizer, code_kind_tok, "unrecognized code kind: {}", code_kind_str);
@@ -514,17 +516,20 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {
                             return parseError(tokenizer, end_code_tag, "invalid token inside code_begin: {}", end_tag_name);
                         }
                         _ = try eatToken(tokenizer, Token.Id.BracketClose);
-                    } else unreachable; // TODO issue #707
-                    try nodes.append(Node {.Code = Code {
-                        .id = code_kind_id,
-                        .name = name,
-                        .source_token = source_token,
-                        .is_inline = is_inline,
-                        .mode = mode,
-                        .link_objects = link_objects.toOwnedSlice(),
-                        .target_windows = target_windows,
-                        .link_libc = link_libc,
-                    }});
+                    } else
+                        unreachable; // TODO issue #707
+                    try nodes.append(Node{
+                        .Code = Code{
+                            .id = code_kind_id,
+                            .name = name,
+                            .source_token = source_token,
+                            .is_inline = is_inline,
+                            .mode = mode,
+                            .link_objects = link_objects.toOwnedSlice(),
+                            .target_windows = target_windows,
+                            .link_libc = link_libc,
+                        },
+                    });
                     tokenizer.code_node_count += 1;
                 } else {
                     return parseError(tokenizer, tag_token, "unrecognized tag name: {}", tag_name);
@@ -534,7 +539,7 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {
         }
     }
 
-    return Toc {
+    return Toc{
         .nodes = nodes.toOwnedSlice(),
         .toc = toc_buf.toOwnedSlice(),
         .urls = urls,
@@ -727,16 +732,19 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                 const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", code.name);
                 const tmp_source_file_name = try os.path.join(allocator, tmp_dir_name, name_plus_ext);
                 try io.writeFile(allocator, tmp_source_file_name, trimmed_raw_source);
-                
+
                 switch (code.id) {
                     Code.Id.Exe => |expected_outcome| {
                         const name_plus_bin_ext = try std.fmt.allocPrint(allocator, "{}{}", code.name, exe_ext);
                         const tmp_bin_file_name = try os.path.join(allocator, tmp_dir_name, name_plus_bin_ext);
                         var build_args = std.ArrayList([]const u8).init(allocator);
                         defer build_args.deinit();
-                        try build_args.appendSlice([][]const u8 {zig_exe,
-                            "build-exe", tmp_source_file_name,
-                            "--output", tmp_bin_file_name,
+                        try build_args.appendSlice([][]const u8{
+                            zig_exe,
+                            "build-exe",
+                            tmp_source_file_name,
+                            "--output",
+                            tmp_bin_file_name,
                         });
                         try out.print("
$ zig build-exe {}.zig", code.name);
                         switch (code.mode) {
@@ -766,10 +774,9 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                             try build_args.append("c");
                             try out.print(" --library c");
                         }
-                        _ = exec(allocator, build_args.toSliceConst()) catch return parseError(
-                            tokenizer, code.source_token, "example failed to compile");
+                        _ = exec(allocator, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile");
 
-                        const run_args = [][]const u8 {tmp_bin_file_name};
+                        const run_args = [][]const u8{tmp_bin_file_name};
 
                         const result = if (expected_outcome == ExpectedOutcome.Fail) blk: {
                             const result = try os.ChildProcess.exec(allocator, run_args, null, null, max_doc_file_size);
@@ -777,7 +784,10 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                                 os.ChildProcess.Term.Exited => |exit_code| {
                                     if (exit_code == 0) {
                                         warn("{}\nThe following command incorrectly succeeded:\n", result.stderr);
-                                        for (run_args) |arg| warn("{} ", arg) else warn("\n");
+                                        for (run_args) |arg|
+                                            warn("{} ", arg)
+                                        else
+                                            warn("\n");
                                         return parseError(tokenizer, code.source_token, "example incorrectly compiled");
                                     }
                                 },
@@ -785,11 +795,9 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                             }
                             break :blk result;
                         } else blk: {
-                            break :blk exec(allocator, run_args) catch return parseError(
-                                tokenizer, code.source_token, "example crashed");
+                            break :blk exec(allocator, run_args) catch return parseError(tokenizer, code.source_token, "example crashed");
                         };
 
-                        
                         const escaped_stderr = try escapeHtml(allocator, result.stderr);
                         const escaped_stdout = try escapeHtml(allocator, result.stdout);
 
@@ -802,7 +810,11 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                         var test_args = std.ArrayList([]const u8).init(allocator);
                         defer test_args.deinit();
 
-                        try test_args.appendSlice([][]const u8 {zig_exe, "test", tmp_source_file_name});
+                        try test_args.appendSlice([][]const u8{
+                            zig_exe,
+                            "test",
+                            tmp_source_file_name,
+                        });
                         try out.print("
$ zig test {}.zig", code.name);
                         switch (code.mode) {
                             builtin.Mode.Debug => {},
@@ -821,13 +833,15 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                         }
                         if (code.target_windows) {
                             try test_args.appendSlice([][]const u8{
-                                "--target-os", "windows",
-                                "--target-arch", "x86_64",
-                                "--target-environ", "msvc",
+                                "--target-os",
+                                "windows",
+                                "--target-arch",
+                                "x86_64",
+                                "--target-environ",
+                                "msvc",
                             });
                         }
-                        const result = exec(allocator, test_args.toSliceConst()) catch return parseError(
-                            tokenizer, code.source_token, "test failed");
+                        const result = exec(allocator, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed");
                         const escaped_stderr = try escapeHtml(allocator, result.stderr);
                         const escaped_stdout = try escapeHtml(allocator, result.stdout);
                         try out.print("\n{}{}
\n", escaped_stderr, escaped_stdout); @@ -836,7 +850,13 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var var test_args = std.ArrayList([]const u8).init(allocator); defer test_args.deinit(); - try test_args.appendSlice([][]const u8 {zig_exe, "test", "--color", "on", tmp_source_file_name}); + try test_args.appendSlice([][]const u8{ + zig_exe, + "test", + "--color", + "on", + tmp_source_file_name, + }); try out.print("
$ zig test {}.zig", code.name);
                         switch (code.mode) {
                             builtin.Mode.Debug => {},
@@ -858,13 +878,19 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                             os.ChildProcess.Term.Exited => |exit_code| {
                                 if (exit_code == 0) {
                                     warn("{}\nThe following command incorrectly succeeded:\n", result.stderr);
-                                    for (test_args.toSliceConst()) |arg| warn("{} ", arg) else warn("\n");
+                                    for (test_args.toSliceConst()) |arg|
+                                        warn("{} ", arg)
+                                    else
+                                        warn("\n");
                                     return parseError(tokenizer, code.source_token, "example incorrectly compiled");
                                 }
                             },
                             else => {
                                 warn("{}\nThe following command crashed:\n", result.stderr);
-                                for (test_args.toSliceConst()) |arg| warn("{} ", arg) else warn("\n");
+                                for (test_args.toSliceConst()) |arg|
+                                    warn("{} ", arg)
+                                else
+                                    warn("\n");
                                 return parseError(tokenizer, code.source_token, "example compile crashed");
                             },
                         }
@@ -881,7 +907,11 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                         var test_args = std.ArrayList([]const u8).init(allocator);
                         defer test_args.deinit();
 
-                        try test_args.appendSlice([][]const u8 {zig_exe, "test", tmp_source_file_name});
+                        try test_args.appendSlice([][]const u8{
+                            zig_exe,
+                            "test",
+                            tmp_source_file_name,
+                        });
                         switch (code.mode) {
                             builtin.Mode.Debug => {},
                             builtin.Mode.ReleaseSafe => try test_args.append("--release-safe"),
@@ -894,13 +924,19 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                             os.ChildProcess.Term.Exited => |exit_code| {
                                 if (exit_code == 0) {
                                     warn("{}\nThe following command incorrectly succeeded:\n", result.stderr);
-                                    for (test_args.toSliceConst()) |arg| warn("{} ", arg) else warn("\n");
+                                    for (test_args.toSliceConst()) |arg|
+                                        warn("{} ", arg)
+                                    else
+                                        warn("\n");
                                     return parseError(tokenizer, code.source_token, "example test incorrectly succeeded");
                                 }
                             },
                             else => {
                                 warn("{}\nThe following command crashed:\n", result.stderr);
-                                for (test_args.toSliceConst()) |arg| warn("{} ", arg) else warn("\n");
+                                for (test_args.toSliceConst()) |arg|
+                                    warn("{} ", arg)
+                                else
+                                    warn("\n");
                                 return parseError(tokenizer, code.source_token, "example compile crashed");
                             },
                         }
@@ -918,9 +954,15 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                         var build_args = std.ArrayList([]const u8).init(allocator);
                         defer build_args.deinit();
 
-                        try build_args.appendSlice([][]const u8 {zig_exe, "build-obj", tmp_source_file_name,
-                            "--color", "on",
-                            "--output", tmp_obj_file_name});
+                        try build_args.appendSlice([][]const u8{
+                            zig_exe,
+                            "build-obj",
+                            tmp_source_file_name,
+                            "--color",
+                            "on",
+                            "--output",
+                            tmp_obj_file_name,
+                        });
 
                         if (!code.is_inline) {
                             try out.print("
$ zig build-obj {}.zig", code.name);
@@ -954,13 +996,19 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                                 os.ChildProcess.Term.Exited => |exit_code| {
                                     if (exit_code == 0) {
                                         warn("{}\nThe following command incorrectly succeeded:\n", result.stderr);
-                                        for (build_args.toSliceConst()) |arg| warn("{} ", arg) else warn("\n");
+                                        for (build_args.toSliceConst()) |arg|
+                                            warn("{} ", arg)
+                                        else
+                                            warn("\n");
                                         return parseError(tokenizer, code.source_token, "example build incorrectly succeeded");
                                     }
                                 },
                                 else => {
                                     warn("{}\nThe following command crashed:\n", result.stderr);
-                                    for (build_args.toSliceConst()) |arg| warn("{} ", arg) else warn("\n");
+                                    for (build_args.toSliceConst()) |arg|
+                                        warn("{} ", arg)
+                                    else
+                                        warn("\n");
                                     return parseError(tokenizer, code.source_token, "example compile crashed");
                                 },
                             }
@@ -975,8 +1023,7 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
                                 try out.print("
\n"); } } else { - _ = exec(allocator, build_args.toSliceConst()) catch return parseError( - tokenizer, code.source_token, "example failed to compile"); + _ = exec(allocator, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile"); } if (!code.is_inline) { try out.print("
\n"); @@ -987,7 +1034,6 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var }, } } - } fn exec(allocator: &mem.Allocator, args: []const []const u8) !os.ChildProcess.ExecResult { @@ -996,13 +1042,19 @@ fn exec(allocator: &mem.Allocator, args: []const []const u8) !os.ChildProcess.Ex os.ChildProcess.Term.Exited => |exit_code| { if (exit_code != 0) { warn("{}\nThe following command exited with code {}:\n", result.stderr, exit_code); - for (args) |arg| warn("{} ", arg) else warn("\n"); + for (args) |arg| + warn("{} ", arg) + else + warn("\n"); return error.ChildExitError; } }, else => { warn("{}\nThe following command crashed:\n", result.stderr); - for (args) |arg| warn("{} ", arg) else warn("\n"); + for (args) |arg| + warn("{} ", arg) + else + warn("\n"); return error.ChildCrashed; }, } diff --git a/example/guess_number/main.zig b/example/guess_number/main.zig index 7178c5274a..bed132b25c 100644 --- a/example/guess_number/main.zig +++ b/example/guess_number/main.zig @@ -23,7 +23,7 @@ pub fn main() !void { while (true) { try stdout.print("\nGuess a number between 1 and 100: "); - var line_buf : [20]u8 = undefined; + var line_buf: [20]u8 = undefined; const line_len = io.readLine(line_buf[0..]) catch |err| switch (err) { error.InputTooLong => { diff --git a/example/hello_world/hello_libc.zig b/example/hello_world/hello_libc.zig index 4a35e47b15..1df8f04ce4 100644 --- a/example/hello_world/hello_libc.zig +++ b/example/hello_world/hello_libc.zig @@ -8,8 +8,7 @@ const c = @cImport({ const msg = c"Hello, world!\n"; export fn main(argc: c_int, argv: &&u8) c_int { - if (c.printf(msg) != c_int(c.strlen(msg))) - return -1; + if (c.printf(msg) != c_int(c.strlen(msg))) return -1; return 0; } diff --git a/example/mix_o_files/build.zig b/example/mix_o_files/build.zig index 4380486867..e5d2e6a446 100644 --- a/example/mix_o_files/build.zig +++ b/example/mix_o_files/build.zig @@ -4,9 +4,7 @@ pub fn build(b: &Builder) void { const obj = b.addObject("base64", "base64.zig"); const exe = b.addCExecutable("test"); - exe.addCompileFlags([][]const u8 { - "-std=c99", - }); + exe.addCompileFlags([][]const u8{"-std=c99"}); exe.addSourceFile("test.c"); exe.addObject(obj); diff --git a/example/shared_library/build.zig b/example/shared_library/build.zig index 2b5a178b35..30c714c6c6 100644 --- a/example/shared_library/build.zig +++ b/example/shared_library/build.zig @@ -4,9 +4,7 @@ pub fn build(b: &Builder) void { const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0)); const exe = b.addCExecutable("test"); - exe.addCompileFlags([][]const u8 { - "-std=c99", - }); + exe.addCompileFlags([][]const u8{"-std=c99"}); exe.addSourceFile("test.c"); exe.linkLibrary(lib); diff --git a/src-self-hosted/introspect.zig b/src-self-hosted/introspect.zig index 3f1fefdd5a..adab00286b 100644 --- a/src-self-hosted/introspect.zig +++ b/src-self-hosted/introspect.zig @@ -48,9 +48,7 @@ pub fn resolveZigLibDir(allocator: &mem.Allocator) ![]u8 { \\Unable to find zig lib directory: {}. \\Reinstall Zig or use --zig-install-prefix. \\ - , - @errorName(err) - ); + , @errorName(err)); return error.ZigLibDirNotFound; }; diff --git a/src-self-hosted/ir.zig b/src-self-hosted/ir.zig index b66a0abdee..c4550b5179 100644 --- a/src-self-hosted/ir.zig +++ b/src-self-hosted/ir.zig @@ -108,5 +108,4 @@ pub const Instruction = struct { ArgType, Export, }; - }; diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index 22f49e80d9..f54bdbdaf0 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -37,7 +37,7 @@ const usage = \\ zen Print zen of zig and exit \\ \\ - ; +; const Command = struct { name: []const u8, @@ -63,22 +63,61 @@ pub fn main() !void { os.exit(1); } - const commands = []Command { - Command { .name = "build", .exec = cmdBuild }, - Command { .name = "build-exe", .exec = cmdBuildExe }, - Command { .name = "build-lib", .exec = cmdBuildLib }, - Command { .name = "build-obj", .exec = cmdBuildObj }, - Command { .name = "fmt", .exec = cmdFmt }, - Command { .name = "run", .exec = cmdRun }, - Command { .name = "targets", .exec = cmdTargets }, - Command { .name = "test", .exec = cmdTest }, - Command { .name = "translate-c", .exec = cmdTranslateC }, - Command { .name = "version", .exec = cmdVersion }, - Command { .name = "zen", .exec = cmdZen }, + const commands = []Command{ + Command{ + .name = "build", + .exec = cmdBuild, + }, + Command{ + .name = "build-exe", + .exec = cmdBuildExe, + }, + Command{ + .name = "build-lib", + .exec = cmdBuildLib, + }, + Command{ + .name = "build-obj", + .exec = cmdBuildObj, + }, + Command{ + .name = "fmt", + .exec = cmdFmt, + }, + Command{ + .name = "run", + .exec = cmdRun, + }, + Command{ + .name = "targets", + .exec = cmdTargets, + }, + Command{ + .name = "test", + .exec = cmdTest, + }, + Command{ + .name = "translate-c", + .exec = cmdTranslateC, + }, + Command{ + .name = "version", + .exec = cmdVersion, + }, + Command{ + .name = "zen", + .exec = cmdZen, + }, // undocumented commands - Command { .name = "help", .exec = cmdHelp }, - Command { .name = "internal", .exec = cmdInternal }, + Command{ + .name = "help", + .exec = cmdHelp, + }, + Command{ + .name = "internal", + .exec = cmdInternal, + }, }; for (commands) |command| { @@ -120,9 +159,9 @@ const usage_build = \\ --verbose-cimport Enable compiler debug output for C imports \\ \\ - ; +; -const args_build_spec = []Flag { +const args_build_spec = []Flag{ Flag.Bool("--help"), Flag.Bool("--init"), Flag.Arg1("--build-file"), @@ -148,7 +187,7 @@ const missing_build_file = \\ \\See: `zig build --help` or `zig help` for more options. \\ - ; +; fn cmdBuild(allocator: &Allocator, args: []const []const u8) !void { var flags = try Args.parse(allocator, args_build_spec, args); @@ -317,15 +356,23 @@ const usage_build_generic = \\ --ver-patch [ver] Dynamic library semver patch version \\ \\ - ; +; -const args_build_generic = []Flag { +const args_build_generic = []Flag{ Flag.Bool("--help"), - Flag.Option("--color", []const []const u8 { "auto", "off", "on" }), + Flag.Option("--color", []const []const u8{ + "auto", + "off", + "on", + }), Flag.ArgMergeN("--assembly", 1), Flag.Arg1("--cache-dir"), - Flag.Option("--emit", []const []const u8 { "asm", "bin", "llvm-ir" }), + Flag.Option("--emit", []const []const u8{ + "asm", + "bin", + "llvm-ir", + }), Flag.Bool("--enable-timing-info"), Flag.Arg1("--libc-include-dir"), Flag.Arg1("--name"), @@ -471,7 +518,7 @@ fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Mo os.exit(1); }; - const asm_a= flags.many("assembly"); + const asm_a = flags.many("assembly"); const obj_a = flags.many("object"); if (in_file == null and (obj_a == null or (??obj_a).len == 0) and (asm_a == null or (??asm_a).len == 0)) { try stderr.write("Expected source file argument or at least one --object or --assembly argument\n"); @@ -493,17 +540,16 @@ fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Mo const zig_lib_dir = introspect.resolveZigLibDir(allocator) catch os.exit(1); defer allocator.free(zig_lib_dir); - var module = - try Module.create( - allocator, - root_name, - zig_root_source_file, - Target.Native, - out_type, - build_mode, - zig_lib_dir, - full_cache_dir - ); + var module = try Module.create( + allocator, + root_name, + zig_root_source_file, + Target.Native, + out_type, + build_mode, + zig_lib_dir, + full_cache_dir, + ); defer module.destroy(); module.version_major = try std.fmt.parseUnsigned(u32, flags.single("ver-major") ?? "0", 10); @@ -588,10 +634,10 @@ fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Mo } if (flags.single("mmacosx-version-min")) |ver| { - module.darwin_version_min = Module.DarwinVersionMin { .MacOS = ver }; + module.darwin_version_min = Module.DarwinVersionMin{ .MacOS = ver }; } if (flags.single("mios-version-min")) |ver| { - module.darwin_version_min = Module.DarwinVersionMin { .Ios = ver }; + module.darwin_version_min = Module.DarwinVersionMin{ .Ios = ver }; } module.emit_file_type = emit_type; @@ -639,11 +685,9 @@ const usage_fmt = \\ --help Print this help and exit \\ \\ - ; +; -const args_fmt_spec = []Flag { - Flag.Bool("--help"), -}; +const args_fmt_spec = []Flag{Flag.Bool("--help")}; fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void { var flags = try Args.parse(allocator, args_fmt_spec, args); @@ -675,7 +719,6 @@ fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void { }; defer tree.deinit(); - var error_it = tree.errors.iterator(0); while (error_it.next()) |parse_error| { const token = tree.tokens.at(parse_error.loc()); @@ -721,8 +764,7 @@ fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void { inline while (i < @memberCount(builtin.Arch)) : (i += 1) { comptime const arch_tag = @memberName(builtin.Arch, i); // NOTE: Cannot use empty string, see #918. - comptime const native_str = - if (comptime mem.eql(u8, arch_tag, @tagName(builtin.arch))) " (native)\n" else "\n"; + comptime const native_str = if (comptime mem.eql(u8, arch_tag, @tagName(builtin.arch))) " (native)\n" else "\n"; try stdout.print(" {}{}", arch_tag, native_str); } @@ -735,8 +777,7 @@ fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void { inline while (i < @memberCount(builtin.Os)) : (i += 1) { comptime const os_tag = @memberName(builtin.Os, i); // NOTE: Cannot use empty string, see #918. - comptime const native_str = - if (comptime mem.eql(u8, os_tag, @tagName(builtin.os))) " (native)\n" else "\n"; + comptime const native_str = if (comptime mem.eql(u8, os_tag, @tagName(builtin.os))) " (native)\n" else "\n"; try stdout.print(" {}{}", os_tag, native_str); } @@ -749,8 +790,7 @@ fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void { inline while (i < @memberCount(builtin.Environ)) : (i += 1) { comptime const environ_tag = @memberName(builtin.Environ, i); // NOTE: Cannot use empty string, see #918. - comptime const native_str = - if (comptime mem.eql(u8, environ_tag, @tagName(builtin.environ))) " (native)\n" else "\n"; + comptime const native_str = if (comptime mem.eql(u8, environ_tag, @tagName(builtin.environ))) " (native)\n" else "\n"; try stdout.print(" {}{}", environ_tag, native_str); } @@ -772,12 +812,9 @@ const usage_test = \\ --help Print this help and exit \\ \\ - ; - -const args_test_spec = []Flag { - Flag.Bool("--help"), -}; +; +const args_test_spec = []Flag{Flag.Bool("--help")}; fn cmdTest(allocator: &Allocator, args: []const []const u8) !void { var flags = try Args.parse(allocator, args_build_spec, args); @@ -810,21 +847,18 @@ const usage_run = \\ --help Print this help and exit \\ \\ - ; - -const args_run_spec = []Flag { - Flag.Bool("--help"), -}; +; +const args_run_spec = []Flag{Flag.Bool("--help")}; fn cmdRun(allocator: &Allocator, args: []const []const u8) !void { var compile_args = args; - var runtime_args: []const []const u8 = []const []const u8 {}; + var runtime_args: []const []const u8 = []const []const u8{}; for (args) |argv, i| { if (mem.eql(u8, argv, "--")) { compile_args = args[0..i]; - runtime_args = args[i+1..]; + runtime_args = args[i + 1..]; break; } } @@ -858,9 +892,9 @@ const usage_translate_c = \\ --output [path] Output file to write generated zig file (default: stdout) \\ \\ - ; +; -const args_translate_c_spec = []Flag { +const args_translate_c_spec = []Flag{ Flag.Bool("--help"), Flag.Bool("--enable-timing-info"), Flag.Arg1("--libc-include-dir"), @@ -934,7 +968,7 @@ const info_zen = \\ * Together we serve end users. \\ \\ - ; +; fn cmdZen(allocator: &Allocator, args: []const []const u8) !void { try stdout.write(info_zen); @@ -949,7 +983,7 @@ const usage_internal = \\ build-info Print static compiler build-info \\ \\ - ; +; fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void { if (args.len == 0) { @@ -957,9 +991,10 @@ fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void { os.exit(1); } - const sub_commands = []Command { - Command { .name = "build-info", .exec = cmdInternalBuildInfo }, - }; + const sub_commands = []Command{Command{ + .name = "build-info", + .exec = cmdInternalBuildInfo, + }}; for (sub_commands) |sub_command| { if (mem.eql(u8, sub_command.name, args[0])) { @@ -983,7 +1018,7 @@ fn cmdInternalBuildInfo(allocator: &Allocator, args: []const []const u8) !void { \\ZIG_C_HEADER_FILES {} \\ZIG_DIA_GUIDS_LIB {} \\ - , + , std.cstr.toSliceConst(c.ZIG_CMAKE_BINARY_DIR), std.cstr.toSliceConst(c.ZIG_CXX_COMPILER), std.cstr.toSliceConst(c.ZIG_LLVM_CONFIG_EXE), diff --git a/src-self-hosted/target.zig b/src-self-hosted/target.zig index 27a90bd096..7983a3ddec 100644 --- a/src-self-hosted/target.zig +++ b/src-self-hosted/target.zig @@ -38,8 +38,7 @@ pub const Target = union(enum) { pub fn isDarwin(self: &const Target) bool { return switch (self.getOs()) { - builtin.Os.ios, - builtin.Os.macosx => true, + builtin.Os.ios, builtin.Os.macosx => true, else => false, }; } diff --git a/std/array_list.zig b/std/array_list.zig index d1165c626d..679f7d73b8 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -150,7 +150,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { }; pub fn iterator(self: &const Self) Iterator { - return Iterator { .list = self, .count = 0 }; + return Iterator{ + .list = self, + .count = 0, + }; } }; } @@ -207,7 +210,7 @@ test "iterator ArrayList test" { try list.append(2); try list.append(3); - var count : i32 = 0; + var count: i32 = 0; var it = list.iterator(); while (it.next()) |next| { assert(next == count + 1); @@ -225,7 +228,7 @@ test "iterator ArrayList test" { } it.reset(); - assert(?? it.next() == 1); + assert(??it.next() == 1); } test "insert ArrayList test" { diff --git a/std/base64.zig b/std/base64.zig index 13f3ea5714..515738a99e 100644 --- a/std/base64.zig +++ b/std/base64.zig @@ -41,12 +41,10 @@ pub const Base64Encoder = struct { dest[out_index] = encoder.alphabet_chars[(source[i] >> 2) & 0x3f]; out_index += 1; - dest[out_index] = encoder.alphabet_chars[((source[i] & 0x3) << 4) | - ((source[i + 1] & 0xf0) >> 4)]; + dest[out_index] = encoder.alphabet_chars[((source[i] & 0x3) << 4) | ((source[i + 1] & 0xf0) >> 4)]; out_index += 1; - dest[out_index] = encoder.alphabet_chars[((source[i + 1] & 0xf) << 2) | - ((source[i + 2] & 0xc0) >> 6)]; + dest[out_index] = encoder.alphabet_chars[((source[i + 1] & 0xf) << 2) | ((source[i + 2] & 0xc0) >> 6)]; out_index += 1; dest[out_index] = encoder.alphabet_chars[source[i + 2] & 0x3f]; @@ -64,8 +62,7 @@ pub const Base64Encoder = struct { dest[out_index] = encoder.pad_char; out_index += 1; } else { - dest[out_index] = encoder.alphabet_chars[((source[i] & 0x3) << 4) | - ((source[i + 1] & 0xf0) >> 4)]; + dest[out_index] = encoder.alphabet_chars[((source[i] & 0x3) << 4) | ((source[i + 1] & 0xf0) >> 4)]; out_index += 1; dest[out_index] = encoder.alphabet_chars[(source[i + 1] & 0xf) << 2]; @@ -131,26 +128,20 @@ pub const Base64Decoder = struct { // common case if (!decoder.char_in_alphabet[source[src_cursor + 2]]) return error.InvalidCharacter; if (!decoder.char_in_alphabet[source[src_cursor + 3]]) return error.InvalidCharacter; - dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | - decoder.char_to_index[source[src_cursor + 1]] >> 4; - dest[dest_cursor + 1] = decoder.char_to_index[source[src_cursor + 1]] << 4 | - decoder.char_to_index[source[src_cursor + 2]] >> 2; - dest[dest_cursor + 2] = decoder.char_to_index[source[src_cursor + 2]] << 6 | - decoder.char_to_index[source[src_cursor + 3]]; + dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | decoder.char_to_index[source[src_cursor + 1]] >> 4; + dest[dest_cursor + 1] = decoder.char_to_index[source[src_cursor + 1]] << 4 | decoder.char_to_index[source[src_cursor + 2]] >> 2; + dest[dest_cursor + 2] = decoder.char_to_index[source[src_cursor + 2]] << 6 | decoder.char_to_index[source[src_cursor + 3]]; dest_cursor += 3; } else if (source[src_cursor + 2] != decoder.pad_char) { // one pad char if (!decoder.char_in_alphabet[source[src_cursor + 2]]) return error.InvalidCharacter; - dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | - decoder.char_to_index[source[src_cursor + 1]] >> 4; - dest[dest_cursor + 1] = decoder.char_to_index[source[src_cursor + 1]] << 4 | - decoder.char_to_index[source[src_cursor + 2]] >> 2; + dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | decoder.char_to_index[source[src_cursor + 1]] >> 4; + dest[dest_cursor + 1] = decoder.char_to_index[source[src_cursor + 1]] << 4 | decoder.char_to_index[source[src_cursor + 2]] >> 2; if (decoder.char_to_index[source[src_cursor + 2]] << 6 != 0) return error.InvalidPadding; dest_cursor += 2; } else { // two pad chars - dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | - decoder.char_to_index[source[src_cursor + 1]] >> 4; + dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | decoder.char_to_index[source[src_cursor + 1]] >> 4; if (decoder.char_to_index[source[src_cursor + 1]] << 4 != 0) return error.InvalidPadding; dest_cursor += 1; } @@ -165,7 +156,7 @@ pub const Base64DecoderWithIgnore = struct { decoder: Base64Decoder, char_is_ignored: [256]bool, pub fn init(alphabet_chars: []const u8, pad_char: u8, ignore_chars: []const u8) Base64DecoderWithIgnore { - var result = Base64DecoderWithIgnore { + var result = Base64DecoderWithIgnore{ .decoder = Base64Decoder.init(alphabet_chars, pad_char), .char_is_ignored = []bool{false} ** 256, }; @@ -223,10 +214,12 @@ pub const Base64DecoderWithIgnore = struct { } else if (decoder_with_ignore.char_is_ignored[c]) { // we can even ignore chars during the padding continue; - } else return error.InvalidCharacter; + } else + return error.InvalidCharacter; } break; - } else return error.InvalidCharacter; + } else + return error.InvalidCharacter; } switch (available_chars) { @@ -234,22 +227,17 @@ pub const Base64DecoderWithIgnore = struct { // common case if (dest_cursor + 3 > dest.len) return error.OutputTooSmall; assert(pad_char_count == 0); - dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | - decoder.char_to_index[next_4_chars[1]] >> 4; - dest[dest_cursor + 1] = decoder.char_to_index[next_4_chars[1]] << 4 | - decoder.char_to_index[next_4_chars[2]] >> 2; - dest[dest_cursor + 2] = decoder.char_to_index[next_4_chars[2]] << 6 | - decoder.char_to_index[next_4_chars[3]]; + dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | decoder.char_to_index[next_4_chars[1]] >> 4; + dest[dest_cursor + 1] = decoder.char_to_index[next_4_chars[1]] << 4 | decoder.char_to_index[next_4_chars[2]] >> 2; + dest[dest_cursor + 2] = decoder.char_to_index[next_4_chars[2]] << 6 | decoder.char_to_index[next_4_chars[3]]; dest_cursor += 3; continue; }, 3 => { if (dest_cursor + 2 > dest.len) return error.OutputTooSmall; if (pad_char_count != 1) return error.InvalidPadding; - dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | - decoder.char_to_index[next_4_chars[1]] >> 4; - dest[dest_cursor + 1] = decoder.char_to_index[next_4_chars[1]] << 4 | - decoder.char_to_index[next_4_chars[2]] >> 2; + dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | decoder.char_to_index[next_4_chars[1]] >> 4; + dest[dest_cursor + 1] = decoder.char_to_index[next_4_chars[1]] << 4 | decoder.char_to_index[next_4_chars[2]] >> 2; if (decoder.char_to_index[next_4_chars[2]] << 6 != 0) return error.InvalidPadding; dest_cursor += 2; break; @@ -257,8 +245,7 @@ pub const Base64DecoderWithIgnore = struct { 2 => { if (dest_cursor + 1 > dest.len) return error.OutputTooSmall; if (pad_char_count != 2) return error.InvalidPadding; - dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | - decoder.char_to_index[next_4_chars[1]] >> 4; + dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | decoder.char_to_index[next_4_chars[1]] >> 4; if (decoder.char_to_index[next_4_chars[1]] << 4 != 0) return error.InvalidPadding; dest_cursor += 1; break; @@ -280,7 +267,6 @@ pub const Base64DecoderWithIgnore = struct { } }; - pub const standard_decoder_unsafe = Base64DecoderUnsafe.init(standard_alphabet_chars, standard_pad_char); pub const Base64DecoderUnsafe = struct { @@ -291,7 +277,7 @@ pub const Base64DecoderUnsafe = struct { pub fn init(alphabet_chars: []const u8, pad_char: u8) Base64DecoderUnsafe { assert(alphabet_chars.len == 64); - var result = Base64DecoderUnsafe { + var result = Base64DecoderUnsafe{ .char_to_index = undefined, .pad_char = pad_char, }; @@ -321,16 +307,13 @@ pub const Base64DecoderUnsafe = struct { } while (in_buf_len > 4) { - dest[dest_index] = decoder.char_to_index[source[src_index + 0]] << 2 | - decoder.char_to_index[source[src_index + 1]] >> 4; + dest[dest_index] = decoder.char_to_index[source[src_index + 0]] << 2 | decoder.char_to_index[source[src_index + 1]] >> 4; dest_index += 1; - dest[dest_index] = decoder.char_to_index[source[src_index + 1]] << 4 | - decoder.char_to_index[source[src_index + 2]] >> 2; + dest[dest_index] = decoder.char_to_index[source[src_index + 1]] << 4 | decoder.char_to_index[source[src_index + 2]] >> 2; dest_index += 1; - dest[dest_index] = decoder.char_to_index[source[src_index + 2]] << 6 | - decoder.char_to_index[source[src_index + 3]]; + dest[dest_index] = decoder.char_to_index[source[src_index + 2]] << 6 | decoder.char_to_index[source[src_index + 3]]; dest_index += 1; src_index += 4; @@ -338,18 +321,15 @@ pub const Base64DecoderUnsafe = struct { } if (in_buf_len > 1) { - dest[dest_index] = decoder.char_to_index[source[src_index + 0]] << 2 | - decoder.char_to_index[source[src_index + 1]] >> 4; + dest[dest_index] = decoder.char_to_index[source[src_index + 0]] << 2 | decoder.char_to_index[source[src_index + 1]] >> 4; dest_index += 1; } if (in_buf_len > 2) { - dest[dest_index] = decoder.char_to_index[source[src_index + 1]] << 4 | - decoder.char_to_index[source[src_index + 2]] >> 2; + dest[dest_index] = decoder.char_to_index[source[src_index + 1]] << 4 | decoder.char_to_index[source[src_index + 2]] >> 2; dest_index += 1; } if (in_buf_len > 3) { - dest[dest_index] = decoder.char_to_index[source[src_index + 2]] << 6 | - decoder.char_to_index[source[src_index + 3]]; + dest[dest_index] = decoder.char_to_index[source[src_index + 2]] << 6 | decoder.char_to_index[source[src_index + 3]]; dest_index += 1; } } @@ -367,7 +347,6 @@ fn calcDecodedSizeExactUnsafe(source: []const u8, pad_char: u8) usize { return result; } - test "base64" { @setEvalBranchQuota(8000); testBase64() catch unreachable; @@ -375,26 +354,26 @@ test "base64" { } fn testBase64() !void { - try testAllApis("", ""); - try testAllApis("f", "Zg=="); - try testAllApis("fo", "Zm8="); - try testAllApis("foo", "Zm9v"); - try testAllApis("foob", "Zm9vYg=="); - try testAllApis("fooba", "Zm9vYmE="); + try testAllApis("", ""); + try testAllApis("f", "Zg=="); + try testAllApis("fo", "Zm8="); + try testAllApis("foo", "Zm9v"); + try testAllApis("foob", "Zm9vYg=="); + try testAllApis("fooba", "Zm9vYmE="); try testAllApis("foobar", "Zm9vYmFy"); - try testDecodeIgnoreSpace("", " "); - try testDecodeIgnoreSpace("f", "Z g= ="); - try testDecodeIgnoreSpace("fo", " Zm8="); - try testDecodeIgnoreSpace("foo", "Zm9v "); - try testDecodeIgnoreSpace("foob", "Zm9vYg = = "); - try testDecodeIgnoreSpace("fooba", "Zm9v YmE="); + try testDecodeIgnoreSpace("", " "); + try testDecodeIgnoreSpace("f", "Z g= ="); + try testDecodeIgnoreSpace("fo", " Zm8="); + try testDecodeIgnoreSpace("foo", "Zm9v "); + try testDecodeIgnoreSpace("foob", "Zm9vYg = = "); + try testDecodeIgnoreSpace("fooba", "Zm9v YmE="); try testDecodeIgnoreSpace("foobar", " Z m 9 v Y m F y "); // test getting some api errors - try testError("A", error.InvalidPadding); - try testError("AA", error.InvalidPadding); - try testError("AAA", error.InvalidPadding); + try testError("A", error.InvalidPadding); + try testError("AA", error.InvalidPadding); + try testError("AAA", error.InvalidPadding); try testError("A..A", error.InvalidCharacter); try testError("AA=A", error.InvalidCharacter); try testError("AA/=", error.InvalidPadding); @@ -427,8 +406,7 @@ fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) !void // Base64DecoderWithIgnore { - const standard_decoder_ignore_nothing = Base64DecoderWithIgnore.init( - standard_alphabet_chars, standard_pad_char, ""); + const standard_decoder_ignore_nothing = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, ""); var buffer: [0x100]u8 = undefined; var decoded = buffer[0..Base64DecoderWithIgnore.calcSizeUpperBound(expected_encoded.len)]; var written = try standard_decoder_ignore_nothing.decode(decoded, expected_encoded); @@ -446,8 +424,7 @@ fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) !void } fn testDecodeIgnoreSpace(expected_decoded: []const u8, encoded: []const u8) !void { - const standard_decoder_ignore_space = Base64DecoderWithIgnore.init( - standard_alphabet_chars, standard_pad_char, " "); + const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " "); var buffer: [0x100]u8 = undefined; var decoded = buffer[0..Base64DecoderWithIgnore.calcSizeUpperBound(encoded.len)]; var written = try standard_decoder_ignore_space.decode(decoded, encoded); @@ -455,8 +432,7 @@ fn testDecodeIgnoreSpace(expected_decoded: []const u8, encoded: []const u8) !voi } fn testError(encoded: []const u8, expected_err: error) !void { - const standard_decoder_ignore_space = Base64DecoderWithIgnore.init( - standard_alphabet_chars, standard_pad_char, " "); + const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " "); var buffer: [0x100]u8 = undefined; if (standard_decoder.calcSize(encoded)) |decoded_size| { var decoded = buffer[0..decoded_size]; @@ -471,8 +447,7 @@ fn testError(encoded: []const u8, expected_err: error) !void { } fn testOutputTooSmallError(encoded: []const u8) !void { - const standard_decoder_ignore_space = Base64DecoderWithIgnore.init( - standard_alphabet_chars, standard_pad_char, " "); + const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " "); var buffer: [0x100]u8 = undefined; var decoded = buffer[0..calcDecodedSizeExactUnsafe(encoded, standard_pad_char) - 1]; if (standard_decoder_ignore_space.decode(decoded, encoded)) |_| { diff --git a/std/buf_map.zig b/std/buf_map.zig index 57c5830bbe..930fc36a78 100644 --- a/std/buf_map.zig +++ b/std/buf_map.zig @@ -12,9 +12,7 @@ pub const BufMap = struct { const BufMapHashMap = HashMap([]const u8, []const u8, mem.hash_slice_u8, mem.eql_slice_u8); pub fn init(allocator: &Allocator) BufMap { - var self = BufMap { - .hash_map = BufMapHashMap.init(allocator), - }; + var self = BufMap{ .hash_map = BufMapHashMap.init(allocator) }; return self; } diff --git a/std/buf_set.zig b/std/buf_set.zig index 1badb5bf18..c5a80e16fb 100644 --- a/std/buf_set.zig +++ b/std/buf_set.zig @@ -10,9 +10,7 @@ pub const BufSet = struct { const BufSetHashMap = HashMap([]const u8, void, mem.hash_slice_u8, mem.eql_slice_u8); pub fn init(a: &Allocator) BufSet { - var self = BufSet { - .hash_map = BufSetHashMap.init(a), - }; + var self = BufSet{ .hash_map = BufSetHashMap.init(a) }; return self; } diff --git a/std/build.zig b/std/build.zig index 276176c63c..f86c3d394f 100644 --- a/std/build.zig +++ b/std/build.zig @@ -420,15 +420,7 @@ pub const Builder = struct { const release_fast = self.option(bool, "release-fast", "optimizations on and safety off") ?? false; const release_small = self.option(bool, "release-small", "size optimizations on and safety off") ?? false; - const mode = if (release_safe and !release_fast and !release_small) - builtin.Mode.ReleaseSafe - else if (release_fast and !release_safe and !release_small) - builtin.Mode.ReleaseFast - else if (release_small and !release_fast and !release_safe) - builtin.Mode.ReleaseSmall - else if (!release_fast and !release_safe and !release_small) - builtin.Mode.Debug - else x: { + const mode = if (release_safe and !release_fast and !release_small) builtin.Mode.ReleaseSafe else if (release_fast and !release_safe and !release_small) builtin.Mode.ReleaseFast else if (release_small and !release_fast and !release_safe) builtin.Mode.ReleaseSmall else if (!release_fast and !release_safe and !release_small) builtin.Mode.Debug else x: { warn("Multiple release modes (of -Drelease-safe, -Drelease-fast and -Drelease-small)"); self.markInvalidUserInput(); break :x builtin.Mode.Debug; @@ -649,11 +641,7 @@ pub const Builder = struct { if (builtin.environ == builtin.Environ.msvc) { return "cl.exe"; } else { - return os.getEnvVarOwned(self.allocator, "CC") catch |err| - if (err == error.EnvironmentVariableNotFound) - ([]const u8)("cc") - else - debug.panic("Unable to get environment variable: {}", err); + return os.getEnvVarOwned(self.allocator, "CC") catch |err| if (err == error.EnvironmentVariableNotFound) ([]const u8)("cc") else debug.panic("Unable to get environment variable: {}", err); } } @@ -782,8 +770,7 @@ pub const Target = union(enum) { pub fn isDarwin(self: &const Target) bool { return switch (self.getOs()) { - builtin.Os.ios, - builtin.Os.macosx => true, + builtin.Os.ios, builtin.Os.macosx => true, else => false, }; } @@ -990,8 +977,7 @@ pub const LibExeObjStep = struct { self.out_filename = self.builder.fmt("lib{}.a", self.name); } else { switch (self.target.getOs()) { - builtin.Os.ios, - builtin.Os.macosx => { + builtin.Os.ios, builtin.Os.macosx => { self.out_filename = self.builder.fmt("lib{}.{d}.{d}.{d}.dylib", self.name, self.version.major, self.version.minor, self.version.patch); self.major_only_filename = self.builder.fmt("lib{}.{d}.dylib", self.name, self.version.major); self.name_only_filename = self.builder.fmt("lib{}.dylib", self.name); @@ -1011,11 +997,13 @@ pub const LibExeObjStep = struct { } pub fn setTarget(self: &LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { - self.target = Target{ .Cross = CrossTarget{ - .arch = target_arch, - .os = target_os, - .environ = target_environ, - } }; + self.target = Target{ + .Cross = CrossTarget{ + .arch = target_arch, + .os = target_os, + .environ = target_environ, + }, + }; self.computeOutFileNames(); } @@ -1079,10 +1067,7 @@ pub const LibExeObjStep = struct { } pub fn getOutputPath(self: &LibExeObjStep) []const u8 { - return if (self.output_path) |output_path| - output_path - else - os.path.join(self.builder.allocator, self.builder.cache_root, self.out_filename) catch unreachable; + return if (self.output_path) |output_path| output_path else os.path.join(self.builder.allocator, self.builder.cache_root, self.out_filename) catch unreachable; } pub fn setOutputHPath(self: &LibExeObjStep, file_path: []const u8) void { @@ -1095,10 +1080,7 @@ pub const LibExeObjStep = struct { } pub fn getOutputHPath(self: &LibExeObjStep) []const u8 { - return if (self.output_h_path) |output_h_path| - output_h_path - else - os.path.join(self.builder.allocator, self.builder.cache_root, self.out_h_filename) catch unreachable; + return if (self.output_h_path) |output_h_path| output_h_path else os.path.join(self.builder.allocator, self.builder.cache_root, self.out_h_filename) catch unreachable; } pub fn addAssemblyFile(self: &LibExeObjStep, path: []const u8) void { @@ -1352,8 +1334,7 @@ pub const LibExeObjStep = struct { args.append("ssp-buffer-size=4") catch unreachable; } }, - builtin.Mode.ReleaseFast, - builtin.Mode.ReleaseSmall => { + builtin.Mode.ReleaseFast, builtin.Mode.ReleaseSmall => { args.append("-O2") catch unreachable; args.append("-fno-stack-protector") catch unreachable; }, @@ -1652,11 +1633,13 @@ pub const TestStep = struct { } pub fn setTarget(self: &TestStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { - self.target = Target{ .Cross = CrossTarget{ - .arch = target_arch, - .os = target_os, - .environ = target_environ, - } }; + self.target = Target{ + .Cross = CrossTarget{ + .arch = target_arch, + .os = target_os, + .environ = target_environ, + }, + }; } pub fn setExecCmd(self: &TestStep, args: []const ?[]const u8) void { diff --git a/std/c/darwin.zig b/std/c/darwin.zig index 7ac57514c9..24be832d01 100644 --- a/std/c/darwin.zig +++ b/std/c/darwin.zig @@ -60,7 +60,7 @@ pub const sigset_t = u32; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with function name. pub const Sigaction = extern struct { - handler: extern fn(c_int)void, + handler: extern fn(c_int) void, sa_mask: sigset_t, sa_flags: c_int, }; diff --git a/std/c/index.zig b/std/c/index.zig index 34269d2aa2..b5e6b48751 100644 --- a/std/c/index.zig +++ b/std/c/index.zig @@ -1,7 +1,7 @@ const builtin = @import("builtin"); const Os = builtin.Os; -pub use switch(builtin.os) { +pub use switch (builtin.os) { Os.linux => @import("linux.zig"), Os.windows => @import("windows.zig"), Os.macosx, Os.ios => @import("darwin.zig"), @@ -21,8 +21,7 @@ pub extern "c" fn raise(sig: c_int) c_int; pub extern "c" fn read(fd: c_int, buf: &c_void, nbyte: usize) isize; pub extern "c" fn stat(noalias path: &const u8, noalias buf: &Stat) c_int; pub extern "c" fn write(fd: c_int, buf: &const c_void, nbyte: usize) isize; -pub extern "c" fn mmap(addr: ?&c_void, len: usize, prot: c_int, flags: c_int, - fd: c_int, offset: isize) ?&c_void; +pub extern "c" fn mmap(addr: ?&c_void, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: isize) ?&c_void; pub extern "c" fn munmap(addr: &c_void, len: usize) c_int; pub extern "c" fn unlink(path: &const u8) c_int; pub extern "c" fn getcwd(buf: &u8, size: usize) ?&u8; @@ -34,8 +33,7 @@ pub extern "c" fn mkdir(path: &const u8, mode: c_uint) c_int; pub extern "c" fn symlink(existing: &const u8, new: &const u8) c_int; pub extern "c" fn rename(old: &const u8, new: &const u8) c_int; pub extern "c" fn chdir(path: &const u8) c_int; -pub extern "c" fn execve(path: &const u8, argv: &const ?&const u8, - envp: &const ?&const u8) c_int; +pub extern "c" fn execve(path: &const u8, argv: &const ?&const u8, envp: &const ?&const u8) c_int; pub extern "c" fn dup(fd: c_int) c_int; pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int; pub extern "c" fn readlink(noalias path: &const u8, noalias buf: &u8, bufsize: usize) isize; @@ -54,9 +52,7 @@ pub extern "c" fn realloc(&c_void, usize) ?&c_void; pub extern "c" fn free(&c_void) void; pub extern "c" fn posix_memalign(memptr: &&c_void, alignment: usize, size: usize) c_int; -pub extern "pthread" fn pthread_create(noalias newthread: &pthread_t, - noalias attr: ?&const pthread_attr_t, start_routine: extern fn(?&c_void) ?&c_void, - noalias arg: ?&c_void) c_int; +pub extern "pthread" fn pthread_create(noalias newthread: &pthread_t, noalias attr: ?&const pthread_attr_t, start_routine: extern fn(?&c_void) ?&c_void, noalias arg: ?&c_void) c_int; pub extern "pthread" fn pthread_attr_init(attr: &pthread_attr_t) c_int; pub extern "pthread" fn pthread_attr_setstack(attr: &pthread_attr_t, stackaddr: &c_void, stacksize: usize) c_int; pub extern "pthread" fn pthread_attr_destroy(attr: &pthread_attr_t) c_int; diff --git a/std/crypto/md5.zig b/std/crypto/md5.zig index 705b2428a7..e0473884cd 100644 --- a/std/crypto/md5.zig +++ b/std/crypto/md5.zig @@ -6,12 +6,25 @@ const debug = @import("../debug/index.zig"); const fmt = @import("../fmt/index.zig"); const RoundParam = struct { - a: usize, b: usize, c: usize, d: usize, - k: usize, s: u32, t: u32 + a: usize, + b: usize, + c: usize, + d: usize, + k: usize, + s: u32, + t: u32, }; fn Rp(a: usize, b: usize, c: usize, d: usize, k: usize, s: u32, t: u32) RoundParam { - return RoundParam { .a = a, .b = b, .c = c, .d = d, .k = k, .s = s, .t = t }; + return RoundParam{ + .a = a, + .b = b, + .c = c, + .d = d, + .k = k, + .s = s, + .t = t, + }; } pub const Md5 = struct { @@ -99,7 +112,7 @@ pub const Md5 = struct { d.round(d.buf[0..]); for (d.s) |s, j| { - mem.writeInt(out[4*j .. 4*j + 4], s, builtin.Endian.Little); + mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Little); } } @@ -112,30 +125,33 @@ pub const Md5 = struct { while (i < 16) : (i += 1) { // NOTE: Performing or's separately improves perf by ~10% s[i] = 0; - s[i] |= u32(b[i*4+0]); - s[i] |= u32(b[i*4+1]) << 8; - s[i] |= u32(b[i*4+2]) << 16; - s[i] |= u32(b[i*4+3]) << 24; + s[i] |= u32(b[i * 4 + 0]); + s[i] |= u32(b[i * 4 + 1]) << 8; + s[i] |= u32(b[i * 4 + 2]) << 16; + s[i] |= u32(b[i * 4 + 3]) << 24; } - var v: [4]u32 = []u32 { - d.s[0], d.s[1], d.s[2], d.s[3], + var v: [4]u32 = []u32{ + d.s[0], + d.s[1], + d.s[2], + d.s[3], }; - const round0 = comptime []RoundParam { - Rp(0, 1, 2, 3, 0, 7, 0xD76AA478), - Rp(3, 0, 1, 2, 1, 12, 0xE8C7B756), - Rp(2, 3, 0, 1, 2, 17, 0x242070DB), - Rp(1, 2, 3, 0, 3, 22, 0xC1BDCEEE), - Rp(0, 1, 2, 3, 4, 7, 0xF57C0FAF), - Rp(3, 0, 1, 2, 5, 12, 0x4787C62A), - Rp(2, 3, 0, 1, 6, 17, 0xA8304613), - Rp(1, 2, 3, 0, 7, 22, 0xFD469501), - Rp(0, 1, 2, 3, 8, 7, 0x698098D8), - Rp(3, 0, 1, 2, 9, 12, 0x8B44F7AF), + const round0 = comptime []RoundParam{ + Rp(0, 1, 2, 3, 0, 7, 0xD76AA478), + Rp(3, 0, 1, 2, 1, 12, 0xE8C7B756), + Rp(2, 3, 0, 1, 2, 17, 0x242070DB), + Rp(1, 2, 3, 0, 3, 22, 0xC1BDCEEE), + Rp(0, 1, 2, 3, 4, 7, 0xF57C0FAF), + Rp(3, 0, 1, 2, 5, 12, 0x4787C62A), + Rp(2, 3, 0, 1, 6, 17, 0xA8304613), + Rp(1, 2, 3, 0, 7, 22, 0xFD469501), + Rp(0, 1, 2, 3, 8, 7, 0x698098D8), + Rp(3, 0, 1, 2, 9, 12, 0x8B44F7AF), Rp(2, 3, 0, 1, 10, 17, 0xFFFF5BB1), Rp(1, 2, 3, 0, 11, 22, 0x895CD7BE), - Rp(0, 1, 2, 3, 12, 7, 0x6B901122), + Rp(0, 1, 2, 3, 12, 7, 0x6B901122), Rp(3, 0, 1, 2, 13, 12, 0xFD987193), Rp(2, 3, 0, 1, 14, 17, 0xA679438E), Rp(1, 2, 3, 0, 15, 22, 0x49B40821), @@ -145,22 +161,22 @@ pub const Md5 = struct { v[r.a] = v[r.b] +% math.rotl(u32, v[r.a], r.s); } - const round1 = comptime []RoundParam { - Rp(0, 1, 2, 3, 1, 5, 0xF61E2562), - Rp(3, 0, 1, 2, 6, 9, 0xC040B340), + const round1 = comptime []RoundParam{ + Rp(0, 1, 2, 3, 1, 5, 0xF61E2562), + Rp(3, 0, 1, 2, 6, 9, 0xC040B340), Rp(2, 3, 0, 1, 11, 14, 0x265E5A51), - Rp(1, 2, 3, 0, 0, 20, 0xE9B6C7AA), - Rp(0, 1, 2, 3, 5, 5, 0xD62F105D), - Rp(3, 0, 1, 2, 10, 9, 0x02441453), + Rp(1, 2, 3, 0, 0, 20, 0xE9B6C7AA), + Rp(0, 1, 2, 3, 5, 5, 0xD62F105D), + Rp(3, 0, 1, 2, 10, 9, 0x02441453), Rp(2, 3, 0, 1, 15, 14, 0xD8A1E681), - Rp(1, 2, 3, 0, 4, 20, 0xE7D3FBC8), - Rp(0, 1, 2, 3, 9, 5, 0x21E1CDE6), - Rp(3, 0, 1, 2, 14, 9, 0xC33707D6), - Rp(2, 3, 0, 1, 3, 14, 0xF4D50D87), - Rp(1, 2, 3, 0, 8, 20, 0x455A14ED), - Rp(0, 1, 2, 3, 13, 5, 0xA9E3E905), - Rp(3, 0, 1, 2, 2, 9, 0xFCEFA3F8), - Rp(2, 3, 0, 1, 7, 14, 0x676F02D9), + Rp(1, 2, 3, 0, 4, 20, 0xE7D3FBC8), + Rp(0, 1, 2, 3, 9, 5, 0x21E1CDE6), + Rp(3, 0, 1, 2, 14, 9, 0xC33707D6), + Rp(2, 3, 0, 1, 3, 14, 0xF4D50D87), + Rp(1, 2, 3, 0, 8, 20, 0x455A14ED), + Rp(0, 1, 2, 3, 13, 5, 0xA9E3E905), + Rp(3, 0, 1, 2, 2, 9, 0xFCEFA3F8), + Rp(2, 3, 0, 1, 7, 14, 0x676F02D9), Rp(1, 2, 3, 0, 12, 20, 0x8D2A4C8A), }; inline for (round1) |r| { @@ -168,46 +184,46 @@ pub const Md5 = struct { v[r.a] = v[r.b] +% math.rotl(u32, v[r.a], r.s); } - const round2 = comptime []RoundParam { - Rp(0, 1, 2, 3, 5, 4, 0xFFFA3942), - Rp(3, 0, 1, 2, 8, 11, 0x8771F681), + const round2 = comptime []RoundParam{ + Rp(0, 1, 2, 3, 5, 4, 0xFFFA3942), + Rp(3, 0, 1, 2, 8, 11, 0x8771F681), Rp(2, 3, 0, 1, 11, 16, 0x6D9D6122), Rp(1, 2, 3, 0, 14, 23, 0xFDE5380C), - Rp(0, 1, 2, 3, 1, 4, 0xA4BEEA44), - Rp(3, 0, 1, 2, 4, 11, 0x4BDECFA9), - Rp(2, 3, 0, 1, 7, 16, 0xF6BB4B60), + Rp(0, 1, 2, 3, 1, 4, 0xA4BEEA44), + Rp(3, 0, 1, 2, 4, 11, 0x4BDECFA9), + Rp(2, 3, 0, 1, 7, 16, 0xF6BB4B60), Rp(1, 2, 3, 0, 10, 23, 0xBEBFBC70), - Rp(0, 1, 2, 3, 13, 4, 0x289B7EC6), - Rp(3, 0, 1, 2, 0, 11, 0xEAA127FA), - Rp(2, 3, 0, 1, 3, 16, 0xD4EF3085), - Rp(1, 2, 3, 0, 6, 23, 0x04881D05), - Rp(0, 1, 2, 3, 9, 4, 0xD9D4D039), + Rp(0, 1, 2, 3, 13, 4, 0x289B7EC6), + Rp(3, 0, 1, 2, 0, 11, 0xEAA127FA), + Rp(2, 3, 0, 1, 3, 16, 0xD4EF3085), + Rp(1, 2, 3, 0, 6, 23, 0x04881D05), + Rp(0, 1, 2, 3, 9, 4, 0xD9D4D039), Rp(3, 0, 1, 2, 12, 11, 0xE6DB99E5), Rp(2, 3, 0, 1, 15, 16, 0x1FA27CF8), - Rp(1, 2, 3, 0, 2, 23, 0xC4AC5665), + Rp(1, 2, 3, 0, 2, 23, 0xC4AC5665), }; inline for (round2) |r| { v[r.a] = v[r.a] +% (v[r.b] ^ v[r.c] ^ v[r.d]) +% r.t +% s[r.k]; v[r.a] = v[r.b] +% math.rotl(u32, v[r.a], r.s); } - const round3 = comptime []RoundParam { - Rp(0, 1, 2, 3, 0, 6, 0xF4292244), - Rp(3, 0, 1, 2, 7, 10, 0x432AFF97), + const round3 = comptime []RoundParam{ + Rp(0, 1, 2, 3, 0, 6, 0xF4292244), + Rp(3, 0, 1, 2, 7, 10, 0x432AFF97), Rp(2, 3, 0, 1, 14, 15, 0xAB9423A7), - Rp(1, 2, 3, 0, 5, 21, 0xFC93A039), - Rp(0, 1, 2, 3, 12, 6, 0x655B59C3), - Rp(3, 0, 1, 2, 3, 10, 0x8F0CCC92), + Rp(1, 2, 3, 0, 5, 21, 0xFC93A039), + Rp(0, 1, 2, 3, 12, 6, 0x655B59C3), + Rp(3, 0, 1, 2, 3, 10, 0x8F0CCC92), Rp(2, 3, 0, 1, 10, 15, 0xFFEFF47D), - Rp(1, 2, 3, 0, 1, 21, 0x85845DD1), - Rp(0, 1, 2, 3, 8, 6, 0x6FA87E4F), + Rp(1, 2, 3, 0, 1, 21, 0x85845DD1), + Rp(0, 1, 2, 3, 8, 6, 0x6FA87E4F), Rp(3, 0, 1, 2, 15, 10, 0xFE2CE6E0), - Rp(2, 3, 0, 1, 6, 15, 0xA3014314), + Rp(2, 3, 0, 1, 6, 15, 0xA3014314), Rp(1, 2, 3, 0, 13, 21, 0x4E0811A1), - Rp(0, 1, 2, 3, 4, 6, 0xF7537E82), + Rp(0, 1, 2, 3, 4, 6, 0xF7537E82), Rp(3, 0, 1, 2, 11, 10, 0xBD3AF235), - Rp(2, 3, 0, 1, 2, 15, 0x2AD7D2BB), - Rp(1, 2, 3, 0, 9, 21, 0xEB86D391), + Rp(2, 3, 0, 1, 2, 15, 0x2AD7D2BB), + Rp(1, 2, 3, 0, 9, 21, 0xEB86D391), }; inline for (round3) |r| { v[r.a] = v[r.a] +% (v[r.c] ^ (v[r.b] | ~v[r.d])) +% r.t +% s[r.k]; @@ -255,7 +271,7 @@ test "md5 streaming" { } test "md5 aligned final" { - var block = []u8 {0} ** Md5.block_size; + var block = []u8{0} ** Md5.block_size; var out: [Md5.digest_size]u8 = undefined; var h = Md5.init(); diff --git a/std/crypto/sha1.zig b/std/crypto/sha1.zig index 333597b12d..77324b482f 100644 --- a/std/crypto/sha1.zig +++ b/std/crypto/sha1.zig @@ -7,11 +7,23 @@ const builtin = @import("builtin"); pub const u160 = @IntType(false, 160); const RoundParam = struct { - a: usize, b: usize, c: usize, d: usize, e: usize, i: u32, + a: usize, + b: usize, + c: usize, + d: usize, + e: usize, + i: u32, }; fn Rp(a: usize, b: usize, c: usize, d: usize, e: usize, i: u32) RoundParam { - return RoundParam { .a = a, .b = b, .c = c, .d = d, .e = e, .i = i }; + return RoundParam{ + .a = a, + .b = b, + .c = c, + .d = d, + .e = e, + .i = i, + }; } pub const Sha1 = struct { @@ -99,7 +111,7 @@ pub const Sha1 = struct { d.round(d.buf[0..]); for (d.s) |s, j| { - mem.writeInt(out[4*j .. 4*j + 4], s, builtin.Endian.Big); + mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Big); } } @@ -108,21 +120,25 @@ pub const Sha1 = struct { var s: [16]u32 = undefined; - var v: [5]u32 = []u32 { - d.s[0], d.s[1], d.s[2], d.s[3], d.s[4], + var v: [5]u32 = []u32{ + d.s[0], + d.s[1], + d.s[2], + d.s[3], + d.s[4], }; - const round0a = comptime []RoundParam { - Rp(0, 1, 2, 3, 4, 0), - Rp(4, 0, 1, 2, 3, 1), - Rp(3, 4, 0, 1, 2, 2), - Rp(2, 3, 4, 0, 1, 3), - Rp(1, 2, 3, 4, 0, 4), - Rp(0, 1, 2, 3, 4, 5), - Rp(4, 0, 1, 2, 3, 6), - Rp(3, 4, 0, 1, 2, 7), - Rp(2, 3, 4, 0, 1, 8), - Rp(1, 2, 3, 4, 0, 9), + const round0a = comptime []RoundParam{ + Rp(0, 1, 2, 3, 4, 0), + Rp(4, 0, 1, 2, 3, 1), + Rp(3, 4, 0, 1, 2, 2), + Rp(2, 3, 4, 0, 1, 3), + Rp(1, 2, 3, 4, 0, 4), + Rp(0, 1, 2, 3, 4, 5), + Rp(4, 0, 1, 2, 3, 6), + Rp(3, 4, 0, 1, 2, 7), + Rp(2, 3, 4, 0, 1, 8), + Rp(1, 2, 3, 4, 0, 9), Rp(0, 1, 2, 3, 4, 10), Rp(4, 0, 1, 2, 3, 11), Rp(3, 4, 0, 1, 2, 12), @@ -131,32 +147,27 @@ pub const Sha1 = struct { Rp(0, 1, 2, 3, 4, 15), }; inline for (round0a) |r| { - s[r.i] = (u32(b[r.i * 4 + 0]) << 24) | - (u32(b[r.i * 4 + 1]) << 16) | - (u32(b[r.i * 4 + 2]) << 8) | - (u32(b[r.i * 4 + 3]) << 0); + s[r.i] = (u32(b[r.i * 4 + 0]) << 24) | (u32(b[r.i * 4 + 1]) << 16) | (u32(b[r.i * 4 + 2]) << 8) | (u32(b[r.i * 4 + 3]) << 0); - v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x5A827999 +% s[r.i & 0xf] - +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d])); + v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d])); v[r.b] = math.rotl(u32, v[r.b], u32(30)); } - const round0b = comptime []RoundParam { + const round0b = comptime []RoundParam{ Rp(4, 0, 1, 2, 3, 16), Rp(3, 4, 0, 1, 2, 17), Rp(2, 3, 4, 0, 1, 18), Rp(1, 2, 3, 4, 0, 19), }; inline for (round0b) |r| { - const t = s[(r.i-3) & 0xf] ^ s[(r.i-8) & 0xf] ^ s[(r.i-14) & 0xf] ^ s[(r.i-16) & 0xf]; + const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf]; s[r.i & 0xf] = math.rotl(u32, t, u32(1)); - v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x5A827999 +% s[r.i & 0xf] - +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d])); + v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d])); v[r.b] = math.rotl(u32, v[r.b], u32(30)); } - const round1 = comptime []RoundParam { + const round1 = comptime []RoundParam{ Rp(0, 1, 2, 3, 4, 20), Rp(4, 0, 1, 2, 3, 21), Rp(3, 4, 0, 1, 2, 22), @@ -179,15 +190,14 @@ pub const Sha1 = struct { Rp(1, 2, 3, 4, 0, 39), }; inline for (round1) |r| { - const t = s[(r.i-3) & 0xf] ^ s[(r.i-8) & 0xf] ^ s[(r.i-14) & 0xf] ^ s[(r.i-16) & 0xf]; + const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf]; s[r.i & 0xf] = math.rotl(u32, t, u32(1)); - v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x6ED9EBA1 +% s[r.i & 0xf] - +% (v[r.b] ^ v[r.c] ^ v[r.d]); + v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x6ED9EBA1 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]); v[r.b] = math.rotl(u32, v[r.b], u32(30)); } - const round2 = comptime []RoundParam { + const round2 = comptime []RoundParam{ Rp(0, 1, 2, 3, 4, 40), Rp(4, 0, 1, 2, 3, 41), Rp(3, 4, 0, 1, 2, 42), @@ -210,15 +220,14 @@ pub const Sha1 = struct { Rp(1, 2, 3, 4, 0, 59), }; inline for (round2) |r| { - const t = s[(r.i-3) & 0xf] ^ s[(r.i-8) & 0xf] ^ s[(r.i-14) & 0xf] ^ s[(r.i-16) & 0xf]; + const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf]; s[r.i & 0xf] = math.rotl(u32, t, u32(1)); - v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x8F1BBCDC +% s[r.i & 0xf] - +% ((v[r.b] & v[r.c]) ^ (v[r.b] & v[r.d]) ^ (v[r.c] & v[r.d])); + v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x8F1BBCDC +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) ^ (v[r.b] & v[r.d]) ^ (v[r.c] & v[r.d])); v[r.b] = math.rotl(u32, v[r.b], u32(30)); } - const round3 = comptime []RoundParam { + const round3 = comptime []RoundParam{ Rp(0, 1, 2, 3, 4, 60), Rp(4, 0, 1, 2, 3, 61), Rp(3, 4, 0, 1, 2, 62), @@ -241,11 +250,10 @@ pub const Sha1 = struct { Rp(1, 2, 3, 4, 0, 79), }; inline for (round3) |r| { - const t = s[(r.i-3) & 0xf] ^ s[(r.i-8) & 0xf] ^ s[(r.i-14) & 0xf] ^ s[(r.i-16) & 0xf]; + const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf]; s[r.i & 0xf] = math.rotl(u32, t, u32(1)); - v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0xCA62C1D6 +% s[r.i & 0xf] - +% (v[r.b] ^ v[r.c] ^ v[r.d]); + v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0xCA62C1D6 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]); v[r.b] = math.rotl(u32, v[r.b], u32(30)); } @@ -286,7 +294,7 @@ test "sha1 streaming" { } test "sha1 aligned final" { - var block = []u8 {0} ** Sha1.block_size; + var block = []u8{0} ** Sha1.block_size; var out: [Sha1.digest_size]u8 = undefined; var h = Sha1.init(); diff --git a/std/crypto/sha2.zig b/std/crypto/sha2.zig index b70450c0ad..a55182aacd 100644 --- a/std/crypto/sha2.zig +++ b/std/crypto/sha2.zig @@ -9,12 +9,31 @@ const htest = @import("test.zig"); // Sha224 + Sha256 const RoundParam256 = struct { - a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, - i: usize, k: u32, + a: usize, + b: usize, + c: usize, + d: usize, + e: usize, + f: usize, + g: usize, + h: usize, + i: usize, + k: u32, }; fn Rp256(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, i: usize, k: u32) RoundParam256 { - return RoundParam256 { .a = a, .b = b, .c = c, .d = d, .e = e, .f = f, .g = g, .h = h, .i = i, .k = k }; + return RoundParam256{ + .a = a, + .b = b, + .c = c, + .d = d, + .e = e, + .f = f, + .g = g, + .h = h, + .i = i, + .k = k, + }; } const Sha2Params32 = struct { @@ -29,7 +48,7 @@ const Sha2Params32 = struct { out_len: usize, }; -const Sha224Params = Sha2Params32 { +const Sha224Params = Sha2Params32{ .iv0 = 0xC1059ED8, .iv1 = 0x367CD507, .iv2 = 0x3070DD17, @@ -41,7 +60,7 @@ const Sha224Params = Sha2Params32 { .out_len = 224, }; -const Sha256Params = Sha2Params32 { +const Sha256Params = Sha2Params32{ .iv0 = 0x6A09E667, .iv1 = 0xBB67AE85, .iv2 = 0x3C6EF372, @@ -56,216 +75,215 @@ const Sha256Params = Sha2Params32 { pub const Sha224 = Sha2_32(Sha224Params); pub const Sha256 = Sha2_32(Sha256Params); -fn Sha2_32(comptime params: Sha2Params32) type { return struct { - const Self = this; - const block_size = 64; - const digest_size = params.out_len / 8; +fn Sha2_32(comptime params: Sha2Params32) type { + return struct { + const Self = this; + const block_size = 64; + const digest_size = params.out_len / 8; - s: [8]u32, - // Streaming Cache - buf: [64]u8, - buf_len: u8, - total_len: u64, + s: [8]u32, + // Streaming Cache + buf: [64]u8, + buf_len: u8, + total_len: u64, - pub fn init() Self { - var d: Self = undefined; - d.reset(); - return d; - } + pub fn init() Self { + var d: Self = undefined; + d.reset(); + return d; + } - pub fn reset(d: &Self) void { - d.s[0] = params.iv0; - d.s[1] = params.iv1; - d.s[2] = params.iv2; - d.s[3] = params.iv3; - d.s[4] = params.iv4; - d.s[5] = params.iv5; - d.s[6] = params.iv6; - d.s[7] = params.iv7; - d.buf_len = 0; - d.total_len = 0; - } - - pub fn hash(b: []const u8, out: []u8) void { - var d = Self.init(); - d.update(b); - d.final(out); - } - - pub fn update(d: &Self, b: []const u8) void { - var off: usize = 0; - - // Partial buffer exists from previous update. Copy into buffer then hash. - if (d.buf_len != 0 and d.buf_len + b.len > 64) { - off += 64 - d.buf_len; - mem.copy(u8, d.buf[d.buf_len..], b[0..off]); - - d.round(d.buf[0..]); + pub fn reset(d: &Self) void { + d.s[0] = params.iv0; + d.s[1] = params.iv1; + d.s[2] = params.iv2; + d.s[3] = params.iv3; + d.s[4] = params.iv4; + d.s[5] = params.iv5; + d.s[6] = params.iv6; + d.s[7] = params.iv7; d.buf_len = 0; + d.total_len = 0; } - // Full middle blocks. - while (off + 64 <= b.len) : (off += 64) { - d.round(b[off..off + 64]); + pub fn hash(b: []const u8, out: []u8) void { + var d = Self.init(); + d.update(b); + d.final(out); } - // Copy any remainder for next pass. - mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + pub fn update(d: &Self, b: []const u8) void { + var off: usize = 0; - d.total_len += b.len; - } + // Partial buffer exists from previous update. Copy into buffer then hash. + if (d.buf_len != 0 and d.buf_len + b.len > 64) { + off += 64 - d.buf_len; + mem.copy(u8, d.buf[d.buf_len..], b[0..off]); - pub fn final(d: &Self, out: []u8) void { - debug.assert(out.len >= params.out_len / 8); + d.round(d.buf[0..]); + d.buf_len = 0; + } - // The buffer here will never be completely full. - mem.set(u8, d.buf[d.buf_len..], 0); + // Full middle blocks. + while (off + 64 <= b.len) : (off += 64) { + d.round(b[off..off + 64]); + } - // Append padding bits. - d.buf[d.buf_len] = 0x80; - d.buf_len += 1; + // Copy any remainder for next pass. + mem.copy(u8, d.buf[d.buf_len..], b[off..]); + d.buf_len += u8(b[off..].len); + + d.total_len += b.len; + } + + pub fn final(d: &Self, out: []u8) void { + debug.assert(out.len >= params.out_len / 8); + + // The buffer here will never be completely full. + mem.set(u8, d.buf[d.buf_len..], 0); + + // Append padding bits. + d.buf[d.buf_len] = 0x80; + d.buf_len += 1; + + // > 448 mod 512 so need to add an extra round to wrap around. + if (64 - d.buf_len < 8) { + d.round(d.buf[0..]); + mem.set(u8, d.buf[0..], 0); + } + + // Append message length. + var i: usize = 1; + var len = d.total_len >> 5; + d.buf[63] = u8(d.total_len & 0x1f) << 3; + while (i < 8) : (i += 1) { + d.buf[63 - i] = u8(len & 0xff); + len >>= 8; + } - // > 448 mod 512 so need to add an extra round to wrap around. - if (64 - d.buf_len < 8) { d.round(d.buf[0..]); - mem.set(u8, d.buf[0..], 0); + + // May truncate for possible 224 output + const rr = d.s[0..params.out_len / 32]; + + for (rr) |s, j| { + mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Big); + } } - // Append message length. - var i: usize = 1; - var len = d.total_len >> 5; - d.buf[63] = u8(d.total_len & 0x1f) << 3; - while (i < 8) : (i += 1) { - d.buf[63 - i] = u8(len & 0xff); - len >>= 8; + fn round(d: &Self, b: []const u8) void { + debug.assert(b.len == 64); + + var s: [64]u32 = undefined; + + var i: usize = 0; + while (i < 16) : (i += 1) { + s[i] = 0; + s[i] |= u32(b[i * 4 + 0]) << 24; + s[i] |= u32(b[i * 4 + 1]) << 16; + s[i] |= u32(b[i * 4 + 2]) << 8; + s[i] |= u32(b[i * 4 + 3]) << 0; + } + while (i < 64) : (i += 1) { + s[i] = s[i - 16] +% s[i - 7] +% (math.rotr(u32, s[i - 15], u32(7)) ^ math.rotr(u32, s[i - 15], u32(18)) ^ (s[i - 15] >> 3)) +% (math.rotr(u32, s[i - 2], u32(17)) ^ math.rotr(u32, s[i - 2], u32(19)) ^ (s[i - 2] >> 10)); + } + + var v: [8]u32 = []u32{ + d.s[0], + d.s[1], + d.s[2], + d.s[3], + d.s[4], + d.s[5], + d.s[6], + d.s[7], + }; + + const round0 = comptime []RoundParam256{ + Rp256(0, 1, 2, 3, 4, 5, 6, 7, 0, 0x428A2F98), + Rp256(7, 0, 1, 2, 3, 4, 5, 6, 1, 0x71374491), + Rp256(6, 7, 0, 1, 2, 3, 4, 5, 2, 0xB5C0FBCF), + Rp256(5, 6, 7, 0, 1, 2, 3, 4, 3, 0xE9B5DBA5), + Rp256(4, 5, 6, 7, 0, 1, 2, 3, 4, 0x3956C25B), + Rp256(3, 4, 5, 6, 7, 0, 1, 2, 5, 0x59F111F1), + Rp256(2, 3, 4, 5, 6, 7, 0, 1, 6, 0x923F82A4), + Rp256(1, 2, 3, 4, 5, 6, 7, 0, 7, 0xAB1C5ED5), + Rp256(0, 1, 2, 3, 4, 5, 6, 7, 8, 0xD807AA98), + Rp256(7, 0, 1, 2, 3, 4, 5, 6, 9, 0x12835B01), + Rp256(6, 7, 0, 1, 2, 3, 4, 5, 10, 0x243185BE), + Rp256(5, 6, 7, 0, 1, 2, 3, 4, 11, 0x550C7DC3), + Rp256(4, 5, 6, 7, 0, 1, 2, 3, 12, 0x72BE5D74), + Rp256(3, 4, 5, 6, 7, 0, 1, 2, 13, 0x80DEB1FE), + Rp256(2, 3, 4, 5, 6, 7, 0, 1, 14, 0x9BDC06A7), + Rp256(1, 2, 3, 4, 5, 6, 7, 0, 15, 0xC19BF174), + Rp256(0, 1, 2, 3, 4, 5, 6, 7, 16, 0xE49B69C1), + Rp256(7, 0, 1, 2, 3, 4, 5, 6, 17, 0xEFBE4786), + Rp256(6, 7, 0, 1, 2, 3, 4, 5, 18, 0x0FC19DC6), + Rp256(5, 6, 7, 0, 1, 2, 3, 4, 19, 0x240CA1CC), + Rp256(4, 5, 6, 7, 0, 1, 2, 3, 20, 0x2DE92C6F), + Rp256(3, 4, 5, 6, 7, 0, 1, 2, 21, 0x4A7484AA), + Rp256(2, 3, 4, 5, 6, 7, 0, 1, 22, 0x5CB0A9DC), + Rp256(1, 2, 3, 4, 5, 6, 7, 0, 23, 0x76F988DA), + Rp256(0, 1, 2, 3, 4, 5, 6, 7, 24, 0x983E5152), + Rp256(7, 0, 1, 2, 3, 4, 5, 6, 25, 0xA831C66D), + Rp256(6, 7, 0, 1, 2, 3, 4, 5, 26, 0xB00327C8), + Rp256(5, 6, 7, 0, 1, 2, 3, 4, 27, 0xBF597FC7), + Rp256(4, 5, 6, 7, 0, 1, 2, 3, 28, 0xC6E00BF3), + Rp256(3, 4, 5, 6, 7, 0, 1, 2, 29, 0xD5A79147), + Rp256(2, 3, 4, 5, 6, 7, 0, 1, 30, 0x06CA6351), + Rp256(1, 2, 3, 4, 5, 6, 7, 0, 31, 0x14292967), + Rp256(0, 1, 2, 3, 4, 5, 6, 7, 32, 0x27B70A85), + Rp256(7, 0, 1, 2, 3, 4, 5, 6, 33, 0x2E1B2138), + Rp256(6, 7, 0, 1, 2, 3, 4, 5, 34, 0x4D2C6DFC), + Rp256(5, 6, 7, 0, 1, 2, 3, 4, 35, 0x53380D13), + Rp256(4, 5, 6, 7, 0, 1, 2, 3, 36, 0x650A7354), + Rp256(3, 4, 5, 6, 7, 0, 1, 2, 37, 0x766A0ABB), + Rp256(2, 3, 4, 5, 6, 7, 0, 1, 38, 0x81C2C92E), + Rp256(1, 2, 3, 4, 5, 6, 7, 0, 39, 0x92722C85), + Rp256(0, 1, 2, 3, 4, 5, 6, 7, 40, 0xA2BFE8A1), + Rp256(7, 0, 1, 2, 3, 4, 5, 6, 41, 0xA81A664B), + Rp256(6, 7, 0, 1, 2, 3, 4, 5, 42, 0xC24B8B70), + Rp256(5, 6, 7, 0, 1, 2, 3, 4, 43, 0xC76C51A3), + Rp256(4, 5, 6, 7, 0, 1, 2, 3, 44, 0xD192E819), + Rp256(3, 4, 5, 6, 7, 0, 1, 2, 45, 0xD6990624), + Rp256(2, 3, 4, 5, 6, 7, 0, 1, 46, 0xF40E3585), + Rp256(1, 2, 3, 4, 5, 6, 7, 0, 47, 0x106AA070), + Rp256(0, 1, 2, 3, 4, 5, 6, 7, 48, 0x19A4C116), + Rp256(7, 0, 1, 2, 3, 4, 5, 6, 49, 0x1E376C08), + Rp256(6, 7, 0, 1, 2, 3, 4, 5, 50, 0x2748774C), + Rp256(5, 6, 7, 0, 1, 2, 3, 4, 51, 0x34B0BCB5), + Rp256(4, 5, 6, 7, 0, 1, 2, 3, 52, 0x391C0CB3), + Rp256(3, 4, 5, 6, 7, 0, 1, 2, 53, 0x4ED8AA4A), + Rp256(2, 3, 4, 5, 6, 7, 0, 1, 54, 0x5B9CCA4F), + Rp256(1, 2, 3, 4, 5, 6, 7, 0, 55, 0x682E6FF3), + Rp256(0, 1, 2, 3, 4, 5, 6, 7, 56, 0x748F82EE), + Rp256(7, 0, 1, 2, 3, 4, 5, 6, 57, 0x78A5636F), + Rp256(6, 7, 0, 1, 2, 3, 4, 5, 58, 0x84C87814), + Rp256(5, 6, 7, 0, 1, 2, 3, 4, 59, 0x8CC70208), + Rp256(4, 5, 6, 7, 0, 1, 2, 3, 60, 0x90BEFFFA), + Rp256(3, 4, 5, 6, 7, 0, 1, 2, 61, 0xA4506CEB), + Rp256(2, 3, 4, 5, 6, 7, 0, 1, 62, 0xBEF9A3F7), + Rp256(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2), + }; + inline for (round0) |r| { + v[r.h] = v[r.h] +% (math.rotr(u32, v[r.e], u32(6)) ^ math.rotr(u32, v[r.e], u32(11)) ^ math.rotr(u32, v[r.e], u32(25))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i]; + + v[r.d] = v[r.d] +% v[r.h]; + + v[r.h] = v[r.h] +% (math.rotr(u32, v[r.a], u32(2)) ^ math.rotr(u32, v[r.a], u32(13)) ^ math.rotr(u32, v[r.a], u32(22))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c])); + } + + d.s[0] +%= v[0]; + d.s[1] +%= v[1]; + d.s[2] +%= v[2]; + d.s[3] +%= v[3]; + d.s[4] +%= v[4]; + d.s[5] +%= v[5]; + d.s[6] +%= v[6]; + d.s[7] +%= v[7]; } - - d.round(d.buf[0..]); - - // May truncate for possible 224 output - const rr = d.s[0 .. params.out_len / 32]; - - for (rr) |s, j| { - mem.writeInt(out[4*j .. 4*j + 4], s, builtin.Endian.Big); - } - } - - fn round(d: &Self, b: []const u8) void { - debug.assert(b.len == 64); - - var s: [64]u32 = undefined; - - var i: usize = 0; - while (i < 16) : (i += 1) { - s[i] = 0; - s[i] |= u32(b[i*4+0]) << 24; - s[i] |= u32(b[i*4+1]) << 16; - s[i] |= u32(b[i*4+2]) << 8; - s[i] |= u32(b[i*4+3]) << 0; - } - while (i < 64) : (i += 1) { - s[i] = - s[i-16] +% s[i-7] +% - (math.rotr(u32, s[i-15], u32(7)) ^ math.rotr(u32, s[i-15], u32(18)) ^ (s[i-15] >> 3)) +% - (math.rotr(u32, s[i-2], u32(17)) ^ math.rotr(u32, s[i-2], u32(19)) ^ (s[i-2] >> 10)); - } - - var v: [8]u32 = []u32 { - d.s[0], d.s[1], d.s[2], d.s[3], d.s[4], d.s[5], d.s[6], d.s[7], - }; - - const round0 = comptime []RoundParam256 { - Rp256(0, 1, 2, 3, 4, 5, 6, 7, 0, 0x428A2F98), - Rp256(7, 0, 1, 2, 3, 4, 5, 6, 1, 0x71374491), - Rp256(6, 7, 0, 1, 2, 3, 4, 5, 2, 0xB5C0FBCF), - Rp256(5, 6, 7, 0, 1, 2, 3, 4, 3, 0xE9B5DBA5), - Rp256(4, 5, 6, 7, 0, 1, 2, 3, 4, 0x3956C25B), - Rp256(3, 4, 5, 6, 7, 0, 1, 2, 5, 0x59F111F1), - Rp256(2, 3, 4, 5, 6, 7, 0, 1, 6, 0x923F82A4), - Rp256(1, 2, 3, 4, 5, 6, 7, 0, 7, 0xAB1C5ED5), - Rp256(0, 1, 2, 3, 4, 5, 6, 7, 8, 0xD807AA98), - Rp256(7, 0, 1, 2, 3, 4, 5, 6, 9, 0x12835B01), - Rp256(6, 7, 0, 1, 2, 3, 4, 5, 10, 0x243185BE), - Rp256(5, 6, 7, 0, 1, 2, 3, 4, 11, 0x550C7DC3), - Rp256(4, 5, 6, 7, 0, 1, 2, 3, 12, 0x72BE5D74), - Rp256(3, 4, 5, 6, 7, 0, 1, 2, 13, 0x80DEB1FE), - Rp256(2, 3, 4, 5, 6, 7, 0, 1, 14, 0x9BDC06A7), - Rp256(1, 2, 3, 4, 5, 6, 7, 0, 15, 0xC19BF174), - Rp256(0, 1, 2, 3, 4, 5, 6, 7, 16, 0xE49B69C1), - Rp256(7, 0, 1, 2, 3, 4, 5, 6, 17, 0xEFBE4786), - Rp256(6, 7, 0, 1, 2, 3, 4, 5, 18, 0x0FC19DC6), - Rp256(5, 6, 7, 0, 1, 2, 3, 4, 19, 0x240CA1CC), - Rp256(4, 5, 6, 7, 0, 1, 2, 3, 20, 0x2DE92C6F), - Rp256(3, 4, 5, 6, 7, 0, 1, 2, 21, 0x4A7484AA), - Rp256(2, 3, 4, 5, 6, 7, 0, 1, 22, 0x5CB0A9DC), - Rp256(1, 2, 3, 4, 5, 6, 7, 0, 23, 0x76F988DA), - Rp256(0, 1, 2, 3, 4, 5, 6, 7, 24, 0x983E5152), - Rp256(7, 0, 1, 2, 3, 4, 5, 6, 25, 0xA831C66D), - Rp256(6, 7, 0, 1, 2, 3, 4, 5, 26, 0xB00327C8), - Rp256(5, 6, 7, 0, 1, 2, 3, 4, 27, 0xBF597FC7), - Rp256(4, 5, 6, 7, 0, 1, 2, 3, 28, 0xC6E00BF3), - Rp256(3, 4, 5, 6, 7, 0, 1, 2, 29, 0xD5A79147), - Rp256(2, 3, 4, 5, 6, 7, 0, 1, 30, 0x06CA6351), - Rp256(1, 2, 3, 4, 5, 6, 7, 0, 31, 0x14292967), - Rp256(0, 1, 2, 3, 4, 5, 6, 7, 32, 0x27B70A85), - Rp256(7, 0, 1, 2, 3, 4, 5, 6, 33, 0x2E1B2138), - Rp256(6, 7, 0, 1, 2, 3, 4, 5, 34, 0x4D2C6DFC), - Rp256(5, 6, 7, 0, 1, 2, 3, 4, 35, 0x53380D13), - Rp256(4, 5, 6, 7, 0, 1, 2, 3, 36, 0x650A7354), - Rp256(3, 4, 5, 6, 7, 0, 1, 2, 37, 0x766A0ABB), - Rp256(2, 3, 4, 5, 6, 7, 0, 1, 38, 0x81C2C92E), - Rp256(1, 2, 3, 4, 5, 6, 7, 0, 39, 0x92722C85), - Rp256(0, 1, 2, 3, 4, 5, 6, 7, 40, 0xA2BFE8A1), - Rp256(7, 0, 1, 2, 3, 4, 5, 6, 41, 0xA81A664B), - Rp256(6, 7, 0, 1, 2, 3, 4, 5, 42, 0xC24B8B70), - Rp256(5, 6, 7, 0, 1, 2, 3, 4, 43, 0xC76C51A3), - Rp256(4, 5, 6, 7, 0, 1, 2, 3, 44, 0xD192E819), - Rp256(3, 4, 5, 6, 7, 0, 1, 2, 45, 0xD6990624), - Rp256(2, 3, 4, 5, 6, 7, 0, 1, 46, 0xF40E3585), - Rp256(1, 2, 3, 4, 5, 6, 7, 0, 47, 0x106AA070), - Rp256(0, 1, 2, 3, 4, 5, 6, 7, 48, 0x19A4C116), - Rp256(7, 0, 1, 2, 3, 4, 5, 6, 49, 0x1E376C08), - Rp256(6, 7, 0, 1, 2, 3, 4, 5, 50, 0x2748774C), - Rp256(5, 6, 7, 0, 1, 2, 3, 4, 51, 0x34B0BCB5), - Rp256(4, 5, 6, 7, 0, 1, 2, 3, 52, 0x391C0CB3), - Rp256(3, 4, 5, 6, 7, 0, 1, 2, 53, 0x4ED8AA4A), - Rp256(2, 3, 4, 5, 6, 7, 0, 1, 54, 0x5B9CCA4F), - Rp256(1, 2, 3, 4, 5, 6, 7, 0, 55, 0x682E6FF3), - Rp256(0, 1, 2, 3, 4, 5, 6, 7, 56, 0x748F82EE), - Rp256(7, 0, 1, 2, 3, 4, 5, 6, 57, 0x78A5636F), - Rp256(6, 7, 0, 1, 2, 3, 4, 5, 58, 0x84C87814), - Rp256(5, 6, 7, 0, 1, 2, 3, 4, 59, 0x8CC70208), - Rp256(4, 5, 6, 7, 0, 1, 2, 3, 60, 0x90BEFFFA), - Rp256(3, 4, 5, 6, 7, 0, 1, 2, 61, 0xA4506CEB), - Rp256(2, 3, 4, 5, 6, 7, 0, 1, 62, 0xBEF9A3F7), - Rp256(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2), - }; - inline for (round0) |r| { - v[r.h] = - v[r.h] +% - (math.rotr(u32, v[r.e], u32(6)) ^ math.rotr(u32, v[r.e], u32(11)) ^ math.rotr(u32, v[r.e], u32(25))) +% - (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% - r.k +% s[r.i]; - - v[r.d] = v[r.d] +% v[r.h]; - - v[r.h] = - v[r.h] +% - (math.rotr(u32, v[r.a], u32(2)) ^ math.rotr(u32, v[r.a], u32(13)) ^ math.rotr(u32, v[r.a], u32(22))) +% - ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c])); - } - - d.s[0] +%= v[0]; - d.s[1] +%= v[1]; - d.s[2] +%= v[2]; - d.s[3] +%= v[3]; - d.s[4] +%= v[4]; - d.s[5] +%= v[5]; - d.s[6] +%= v[6]; - d.s[7] +%= v[7]; - } -};} + }; +} test "sha224 single" { htest.assertEqualHash(Sha224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", ""); @@ -320,7 +338,7 @@ test "sha256 streaming" { } test "sha256 aligned final" { - var block = []u8 {0} ** Sha256.block_size; + var block = []u8{0} ** Sha256.block_size; var out: [Sha256.digest_size]u8 = undefined; var h = Sha256.init(); @@ -328,17 +346,35 @@ test "sha256 aligned final" { h.final(out[0..]); } - ///////////////////// // Sha384 + Sha512 const RoundParam512 = struct { - a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, - i: usize, k: u64, + a: usize, + b: usize, + c: usize, + d: usize, + e: usize, + f: usize, + g: usize, + h: usize, + i: usize, + k: u64, }; fn Rp512(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, i: usize, k: u64) RoundParam512 { - return RoundParam512 { .a = a, .b = b, .c = c, .d = d, .e = e, .f = f, .g = g, .h = h, .i = i, .k = k }; + return RoundParam512{ + .a = a, + .b = b, + .c = c, + .d = d, + .e = e, + .f = f, + .g = g, + .h = h, + .i = i, + .k = k, + }; } const Sha2Params64 = struct { @@ -353,7 +389,7 @@ const Sha2Params64 = struct { out_len: usize, }; -const Sha384Params = Sha2Params64 { +const Sha384Params = Sha2Params64{ .iv0 = 0xCBBB9D5DC1059ED8, .iv1 = 0x629A292A367CD507, .iv2 = 0x9159015A3070DD17, @@ -365,7 +401,7 @@ const Sha384Params = Sha2Params64 { .out_len = 384, }; -const Sha512Params = Sha2Params64 { +const Sha512Params = Sha2Params64{ .iv0 = 0x6A09E667F3BCC908, .iv1 = 0xBB67AE8584CAA73B, .iv2 = 0x3C6EF372FE94F82B, @@ -374,242 +410,241 @@ const Sha512Params = Sha2Params64 { .iv5 = 0x9B05688C2B3E6C1F, .iv6 = 0x1F83D9ABFB41BD6B, .iv7 = 0x5BE0CD19137E2179, - .out_len = 512 + .out_len = 512, }; pub const Sha384 = Sha2_64(Sha384Params); pub const Sha512 = Sha2_64(Sha512Params); -fn Sha2_64(comptime params: Sha2Params64) type { return struct { - const Self = this; - const block_size = 128; - const digest_size = params.out_len / 8; +fn Sha2_64(comptime params: Sha2Params64) type { + return struct { + const Self = this; + const block_size = 128; + const digest_size = params.out_len / 8; - s: [8]u64, - // Streaming Cache - buf: [128]u8, - buf_len: u8, - total_len: u128, + s: [8]u64, + // Streaming Cache + buf: [128]u8, + buf_len: u8, + total_len: u128, - pub fn init() Self { - var d: Self = undefined; - d.reset(); - return d; - } + pub fn init() Self { + var d: Self = undefined; + d.reset(); + return d; + } - pub fn reset(d: &Self) void { - d.s[0] = params.iv0; - d.s[1] = params.iv1; - d.s[2] = params.iv2; - d.s[3] = params.iv3; - d.s[4] = params.iv4; - d.s[5] = params.iv5; - d.s[6] = params.iv6; - d.s[7] = params.iv7; - d.buf_len = 0; - d.total_len = 0; - } - - pub fn hash(b: []const u8, out: []u8) void { - var d = Self.init(); - d.update(b); - d.final(out); - } - - pub fn update(d: &Self, b: []const u8) void { - var off: usize = 0; - - // Partial buffer exists from previous update. Copy into buffer then hash. - if (d.buf_len != 0 and d.buf_len + b.len > 128) { - off += 128 - d.buf_len; - mem.copy(u8, d.buf[d.buf_len..], b[0..off]); - - d.round(d.buf[0..]); + pub fn reset(d: &Self) void { + d.s[0] = params.iv0; + d.s[1] = params.iv1; + d.s[2] = params.iv2; + d.s[3] = params.iv3; + d.s[4] = params.iv4; + d.s[5] = params.iv5; + d.s[6] = params.iv6; + d.s[7] = params.iv7; d.buf_len = 0; + d.total_len = 0; } - // Full middle blocks. - while (off + 128 <= b.len) : (off += 128) { - d.round(b[off..off + 128]); + pub fn hash(b: []const u8, out: []u8) void { + var d = Self.init(); + d.update(b); + d.final(out); } - // Copy any remainder for next pass. - mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + pub fn update(d: &Self, b: []const u8) void { + var off: usize = 0; - d.total_len += b.len; - } + // Partial buffer exists from previous update. Copy into buffer then hash. + if (d.buf_len != 0 and d.buf_len + b.len > 128) { + off += 128 - d.buf_len; + mem.copy(u8, d.buf[d.buf_len..], b[0..off]); - pub fn final(d: &Self, out: []u8) void { - debug.assert(out.len >= params.out_len / 8); + d.round(d.buf[0..]); + d.buf_len = 0; + } - // The buffer here will never be completely full. - mem.set(u8, d.buf[d.buf_len..], 0); + // Full middle blocks. + while (off + 128 <= b.len) : (off += 128) { + d.round(b[off..off + 128]); + } - // Append padding bits. - d.buf[d.buf_len] = 0x80; - d.buf_len += 1; + // Copy any remainder for next pass. + mem.copy(u8, d.buf[d.buf_len..], b[off..]); + d.buf_len += u8(b[off..].len); + + d.total_len += b.len; + } + + pub fn final(d: &Self, out: []u8) void { + debug.assert(out.len >= params.out_len / 8); + + // The buffer here will never be completely full. + mem.set(u8, d.buf[d.buf_len..], 0); + + // Append padding bits. + d.buf[d.buf_len] = 0x80; + d.buf_len += 1; + + // > 896 mod 1024 so need to add an extra round to wrap around. + if (128 - d.buf_len < 16) { + d.round(d.buf[0..]); + mem.set(u8, d.buf[0..], 0); + } + + // Append message length. + var i: usize = 1; + var len = d.total_len >> 5; + d.buf[127] = u8(d.total_len & 0x1f) << 3; + while (i < 16) : (i += 1) { + d.buf[127 - i] = u8(len & 0xff); + len >>= 8; + } - // > 896 mod 1024 so need to add an extra round to wrap around. - if (128 - d.buf_len < 16) { d.round(d.buf[0..]); - mem.set(u8, d.buf[0..], 0); + + // May truncate for possible 384 output + const rr = d.s[0..params.out_len / 64]; + + for (rr) |s, j| { + mem.writeInt(out[8 * j..8 * j + 8], s, builtin.Endian.Big); + } } - // Append message length. - var i: usize = 1; - var len = d.total_len >> 5; - d.buf[127] = u8(d.total_len & 0x1f) << 3; - while (i < 16) : (i += 1) { - d.buf[127 - i] = u8(len & 0xff); - len >>= 8; + fn round(d: &Self, b: []const u8) void { + debug.assert(b.len == 128); + + var s: [80]u64 = undefined; + + var i: usize = 0; + while (i < 16) : (i += 1) { + s[i] = 0; + s[i] |= u64(b[i * 8 + 0]) << 56; + s[i] |= u64(b[i * 8 + 1]) << 48; + s[i] |= u64(b[i * 8 + 2]) << 40; + s[i] |= u64(b[i * 8 + 3]) << 32; + s[i] |= u64(b[i * 8 + 4]) << 24; + s[i] |= u64(b[i * 8 + 5]) << 16; + s[i] |= u64(b[i * 8 + 6]) << 8; + s[i] |= u64(b[i * 8 + 7]) << 0; + } + while (i < 80) : (i += 1) { + s[i] = s[i - 16] +% s[i - 7] +% (math.rotr(u64, s[i - 15], u64(1)) ^ math.rotr(u64, s[i - 15], u64(8)) ^ (s[i - 15] >> 7)) +% (math.rotr(u64, s[i - 2], u64(19)) ^ math.rotr(u64, s[i - 2], u64(61)) ^ (s[i - 2] >> 6)); + } + + var v: [8]u64 = []u64{ + d.s[0], + d.s[1], + d.s[2], + d.s[3], + d.s[4], + d.s[5], + d.s[6], + d.s[7], + }; + + const round0 = comptime []RoundParam512{ + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 0, 0x428A2F98D728AE22), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 1, 0x7137449123EF65CD), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 2, 0xB5C0FBCFEC4D3B2F), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 3, 0xE9B5DBA58189DBBC), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 4, 0x3956C25BF348B538), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 5, 0x59F111F1B605D019), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 6, 0x923F82A4AF194F9B), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 7, 0xAB1C5ED5DA6D8118), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 8, 0xD807AA98A3030242), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 9, 0x12835B0145706FBE), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 10, 0x243185BE4EE4B28C), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 11, 0x550C7DC3D5FFB4E2), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 12, 0x72BE5D74F27B896F), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 13, 0x80DEB1FE3B1696B1), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 14, 0x9BDC06A725C71235), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 15, 0xC19BF174CF692694), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 16, 0xE49B69C19EF14AD2), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 17, 0xEFBE4786384F25E3), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 18, 0x0FC19DC68B8CD5B5), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 19, 0x240CA1CC77AC9C65), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 20, 0x2DE92C6F592B0275), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 21, 0x4A7484AA6EA6E483), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 22, 0x5CB0A9DCBD41FBD4), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 23, 0x76F988DA831153B5), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 24, 0x983E5152EE66DFAB), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 25, 0xA831C66D2DB43210), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 26, 0xB00327C898FB213F), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 27, 0xBF597FC7BEEF0EE4), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 28, 0xC6E00BF33DA88FC2), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 29, 0xD5A79147930AA725), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 30, 0x06CA6351E003826F), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 31, 0x142929670A0E6E70), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 32, 0x27B70A8546D22FFC), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 33, 0x2E1B21385C26C926), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 34, 0x4D2C6DFC5AC42AED), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 35, 0x53380D139D95B3DF), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 36, 0x650A73548BAF63DE), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 37, 0x766A0ABB3C77B2A8), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 38, 0x81C2C92E47EDAEE6), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 39, 0x92722C851482353B), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 40, 0xA2BFE8A14CF10364), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 41, 0xA81A664BBC423001), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 42, 0xC24B8B70D0F89791), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 43, 0xC76C51A30654BE30), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 44, 0xD192E819D6EF5218), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 45, 0xD69906245565A910), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 46, 0xF40E35855771202A), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 47, 0x106AA07032BBD1B8), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 48, 0x19A4C116B8D2D0C8), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 49, 0x1E376C085141AB53), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 50, 0x2748774CDF8EEB99), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 51, 0x34B0BCB5E19B48A8), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 52, 0x391C0CB3C5C95A63), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 53, 0x4ED8AA4AE3418ACB), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 54, 0x5B9CCA4F7763E373), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 55, 0x682E6FF3D6B2B8A3), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 56, 0x748F82EE5DEFB2FC), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 57, 0x78A5636F43172F60), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 58, 0x84C87814A1F0AB72), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 59, 0x8CC702081A6439EC), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 60, 0x90BEFFFA23631E28), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 61, 0xA4506CEBDE82BDE9), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 62, 0xBEF9A3F7B2C67915), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2E372532B), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 64, 0xCA273ECEEA26619C), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 65, 0xD186B8C721C0C207), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 66, 0xEADA7DD6CDE0EB1E), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 67, 0xF57D4F7FEE6ED178), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 68, 0x06F067AA72176FBA), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 69, 0x0A637DC5A2C898A6), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 70, 0x113F9804BEF90DAE), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 71, 0x1B710B35131C471B), + Rp512(0, 1, 2, 3, 4, 5, 6, 7, 72, 0x28DB77F523047D84), + Rp512(7, 0, 1, 2, 3, 4, 5, 6, 73, 0x32CAAB7B40C72493), + Rp512(6, 7, 0, 1, 2, 3, 4, 5, 74, 0x3C9EBE0A15C9BEBC), + Rp512(5, 6, 7, 0, 1, 2, 3, 4, 75, 0x431D67C49C100D4C), + Rp512(4, 5, 6, 7, 0, 1, 2, 3, 76, 0x4CC5D4BECB3E42B6), + Rp512(3, 4, 5, 6, 7, 0, 1, 2, 77, 0x597F299CFC657E2A), + Rp512(2, 3, 4, 5, 6, 7, 0, 1, 78, 0x5FCB6FAB3AD6FAEC), + Rp512(1, 2, 3, 4, 5, 6, 7, 0, 79, 0x6C44198C4A475817), + }; + inline for (round0) |r| { + v[r.h] = v[r.h] +% (math.rotr(u64, v[r.e], u64(14)) ^ math.rotr(u64, v[r.e], u64(18)) ^ math.rotr(u64, v[r.e], u64(41))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i]; + + v[r.d] = v[r.d] +% v[r.h]; + + v[r.h] = v[r.h] +% (math.rotr(u64, v[r.a], u64(28)) ^ math.rotr(u64, v[r.a], u64(34)) ^ math.rotr(u64, v[r.a], u64(39))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c])); + } + + d.s[0] +%= v[0]; + d.s[1] +%= v[1]; + d.s[2] +%= v[2]; + d.s[3] +%= v[3]; + d.s[4] +%= v[4]; + d.s[5] +%= v[5]; + d.s[6] +%= v[6]; + d.s[7] +%= v[7]; } - - d.round(d.buf[0..]); - - // May truncate for possible 384 output - const rr = d.s[0 .. params.out_len / 64]; - - for (rr) |s, j| { - mem.writeInt(out[8*j .. 8*j + 8], s, builtin.Endian.Big); - } - } - - fn round(d: &Self, b: []const u8) void { - debug.assert(b.len == 128); - - var s: [80]u64 = undefined; - - var i: usize = 0; - while (i < 16) : (i += 1) { - s[i] = 0; - s[i] |= u64(b[i*8+0]) << 56; - s[i] |= u64(b[i*8+1]) << 48; - s[i] |= u64(b[i*8+2]) << 40; - s[i] |= u64(b[i*8+3]) << 32; - s[i] |= u64(b[i*8+4]) << 24; - s[i] |= u64(b[i*8+5]) << 16; - s[i] |= u64(b[i*8+6]) << 8; - s[i] |= u64(b[i*8+7]) << 0; - } - while (i < 80) : (i += 1) { - s[i] = - s[i-16] +% s[i-7] +% - (math.rotr(u64, s[i-15], u64(1)) ^ math.rotr(u64, s[i-15], u64(8)) ^ (s[i-15] >> 7)) +% - (math.rotr(u64, s[i-2], u64(19)) ^ math.rotr(u64, s[i-2], u64(61)) ^ (s[i-2] >> 6)); - } - - var v: [8]u64 = []u64 { - d.s[0], d.s[1], d.s[2], d.s[3], d.s[4], d.s[5], d.s[6], d.s[7], - }; - - const round0 = comptime []RoundParam512 { - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 0, 0x428A2F98D728AE22), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 1, 0x7137449123EF65CD), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 2, 0xB5C0FBCFEC4D3B2F), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 3, 0xE9B5DBA58189DBBC), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 4, 0x3956C25BF348B538), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 5, 0x59F111F1B605D019), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 6, 0x923F82A4AF194F9B), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 7, 0xAB1C5ED5DA6D8118), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 8, 0xD807AA98A3030242), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 9, 0x12835B0145706FBE), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 10, 0x243185BE4EE4B28C), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 11, 0x550C7DC3D5FFB4E2), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 12, 0x72BE5D74F27B896F), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 13, 0x80DEB1FE3B1696B1), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 14, 0x9BDC06A725C71235), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 15, 0xC19BF174CF692694), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 16, 0xE49B69C19EF14AD2), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 17, 0xEFBE4786384F25E3), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 18, 0x0FC19DC68B8CD5B5), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 19, 0x240CA1CC77AC9C65), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 20, 0x2DE92C6F592B0275), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 21, 0x4A7484AA6EA6E483), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 22, 0x5CB0A9DCBD41FBD4), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 23, 0x76F988DA831153B5), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 24, 0x983E5152EE66DFAB), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 25, 0xA831C66D2DB43210), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 26, 0xB00327C898FB213F), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 27, 0xBF597FC7BEEF0EE4), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 28, 0xC6E00BF33DA88FC2), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 29, 0xD5A79147930AA725), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 30, 0x06CA6351E003826F), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 31, 0x142929670A0E6E70), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 32, 0x27B70A8546D22FFC), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 33, 0x2E1B21385C26C926), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 34, 0x4D2C6DFC5AC42AED), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 35, 0x53380D139D95B3DF), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 36, 0x650A73548BAF63DE), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 37, 0x766A0ABB3C77B2A8), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 38, 0x81C2C92E47EDAEE6), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 39, 0x92722C851482353B), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 40, 0xA2BFE8A14CF10364), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 41, 0xA81A664BBC423001), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 42, 0xC24B8B70D0F89791), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 43, 0xC76C51A30654BE30), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 44, 0xD192E819D6EF5218), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 45, 0xD69906245565A910), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 46, 0xF40E35855771202A), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 47, 0x106AA07032BBD1B8), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 48, 0x19A4C116B8D2D0C8), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 49, 0x1E376C085141AB53), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 50, 0x2748774CDF8EEB99), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 51, 0x34B0BCB5E19B48A8), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 52, 0x391C0CB3C5C95A63), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 53, 0x4ED8AA4AE3418ACB), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 54, 0x5B9CCA4F7763E373), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 55, 0x682E6FF3D6B2B8A3), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 56, 0x748F82EE5DEFB2FC), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 57, 0x78A5636F43172F60), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 58, 0x84C87814A1F0AB72), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 59, 0x8CC702081A6439EC), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 60, 0x90BEFFFA23631E28), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 61, 0xA4506CEBDE82BDE9), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 62, 0xBEF9A3F7B2C67915), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2E372532B), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 64, 0xCA273ECEEA26619C), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 65, 0xD186B8C721C0C207), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 66, 0xEADA7DD6CDE0EB1E), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 67, 0xF57D4F7FEE6ED178), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 68, 0x06F067AA72176FBA), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 69, 0x0A637DC5A2C898A6), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 70, 0x113F9804BEF90DAE), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 71, 0x1B710B35131C471B), - Rp512(0, 1, 2, 3, 4, 5, 6, 7, 72, 0x28DB77F523047D84), - Rp512(7, 0, 1, 2, 3, 4, 5, 6, 73, 0x32CAAB7B40C72493), - Rp512(6, 7, 0, 1, 2, 3, 4, 5, 74, 0x3C9EBE0A15C9BEBC), - Rp512(5, 6, 7, 0, 1, 2, 3, 4, 75, 0x431D67C49C100D4C), - Rp512(4, 5, 6, 7, 0, 1, 2, 3, 76, 0x4CC5D4BECB3E42B6), - Rp512(3, 4, 5, 6, 7, 0, 1, 2, 77, 0x597F299CFC657E2A), - Rp512(2, 3, 4, 5, 6, 7, 0, 1, 78, 0x5FCB6FAB3AD6FAEC), - Rp512(1, 2, 3, 4, 5, 6, 7, 0, 79, 0x6C44198C4A475817), - }; - inline for (round0) |r| { - v[r.h] = - v[r.h] +% - (math.rotr(u64, v[r.e], u64(14)) ^ math.rotr(u64, v[r.e], u64(18)) ^ math.rotr(u64, v[r.e], u64(41))) +% - (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% - r.k +% s[r.i]; - - v[r.d] = v[r.d] +% v[r.h]; - - v[r.h] = - v[r.h] +% - (math.rotr(u64, v[r.a], u64(28)) ^ math.rotr(u64, v[r.a], u64(34)) ^ math.rotr(u64, v[r.a], u64(39))) +% - ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c])); - } - - d.s[0] +%= v[0]; - d.s[1] +%= v[1]; - d.s[2] +%= v[2]; - d.s[3] +%= v[3]; - d.s[4] +%= v[4]; - d.s[5] +%= v[5]; - d.s[6] +%= v[6]; - d.s[7] +%= v[7]; - } -};} + }; +} test "sha384 single" { const h1 = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"; @@ -680,7 +715,7 @@ test "sha512 streaming" { } test "sha512 aligned final" { - var block = []u8 {0} ** Sha512.block_size; + var block = []u8{0} ** Sha512.block_size; var out: [Sha512.digest_size]u8 = undefined; var h = Sha512.init(); diff --git a/std/crypto/test.zig b/std/crypto/test.zig index 3fa24272e5..c0a96a98de 100644 --- a/std/crypto/test.zig +++ b/std/crypto/test.zig @@ -14,7 +14,7 @@ pub fn assertEqualHash(comptime Hasher: var, comptime expected: []const u8, inpu pub fn assertEqual(comptime expected: []const u8, input: []const u8) void { var expected_bytes: [expected.len / 2]u8 = undefined; for (expected_bytes) |*r, i| { - r.* = fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable; + r.* = fmt.parseInt(u8, expected[2 * i..2 * i + 2], 16) catch unreachable; } debug.assert(mem.eql(u8, expected_bytes, input)); diff --git a/std/crypto/throughput_test.zig b/std/crypto/throughput_test.zig index 0756f9a4eb..c5c4f9fe10 100644 --- a/std/crypto/throughput_test.zig +++ b/std/crypto/throughput_test.zig @@ -11,7 +11,7 @@ const Timer = time.Timer; const HashFunction = @import("md5.zig").Md5; const MiB = 1024 * 1024; -const BytesToHash = 1024 * MiB; +const BytesToHash = 1024 * MiB; pub fn main() !void { var stdout_file = try std.io.getStdOut(); diff --git a/std/cstr.zig b/std/cstr.zig index d396dcbce3..c9f3026064 100644 --- a/std/cstr.zig +++ b/std/cstr.zig @@ -9,7 +9,6 @@ pub const line_sep = switch (builtin.os) { else => "\n", }; - pub fn len(ptr: &const u8) usize { var count: usize = 0; while (ptr[count] != 0) : (count += 1) {} @@ -95,7 +94,7 @@ pub const NullTerminated2DArray = struct { } index_buf[i] = null; - return NullTerminated2DArray { + return NullTerminated2DArray{ .allocator = allocator, .byte_count = byte_count, .ptr = @ptrCast(?&?&u8, buf.ptr), @@ -107,4 +106,3 @@ pub const NullTerminated2DArray = struct { self.allocator.free(buf[0..self.byte_count]); } }; - diff --git a/std/debug/failing_allocator.zig b/std/debug/failing_allocator.zig index f876b7902d..6b5edff5bf 100644 --- a/std/debug/failing_allocator.zig +++ b/std/debug/failing_allocator.zig @@ -13,14 +13,14 @@ pub const FailingAllocator = struct { deallocations: usize, pub fn init(allocator: &mem.Allocator, fail_index: usize) FailingAllocator { - return FailingAllocator { + return FailingAllocator{ .internal_allocator = allocator, .fail_index = fail_index, .index = 0, .allocated_bytes = 0, .freed_bytes = 0, .deallocations = 0, - .allocator = mem.Allocator { + .allocator = mem.Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, diff --git a/std/debug/index.zig b/std/debug/index.zig index 36ac2e8a3f..92e565b391 100644 --- a/std/debug/index.zig +++ b/std/debug/index.zig @@ -227,8 +227,7 @@ fn printSourceAtAddress(debug_info: &ElfStackTrace, out_stream: var, address: us else => return err, } } else |err| switch (err) { - error.MissingDebugInfo, - error.InvalidDebugInfo => { + error.MissingDebugInfo, error.InvalidDebugInfo => { try out_stream.print(ptr_hex ++ " in ??? ({})\n", address, compile_unit_name); }, else => return err, @@ -597,10 +596,12 @@ fn parseFormValueBlock(allocator: &mem.Allocator, in_stream: var, size: usize) ! } fn parseFormValueConstant(allocator: &mem.Allocator, in_stream: var, signed: bool, size: usize) !FormValue { - return FormValue{ .Const = Constant{ - .signed = signed, - .payload = try readAllocBytes(allocator, in_stream, size), - } }; + return FormValue{ + .Const = Constant{ + .signed = signed, + .payload = try readAllocBytes(allocator, in_stream, size), + }, + }; } fn parseFormValueDwarfOffsetSize(in_stream: var, is_64: bool) !u64 { @@ -621,7 +622,7 @@ fn parseFormValueRef(allocator: &mem.Allocator, in_stream: var, comptime T: type return parseFormValueRefLen(allocator, in_stream, block_len); } -const ParseFormValueError = error { +const ParseFormValueError = error{ EndOfStream, Io, BadFd, @@ -645,8 +646,7 @@ fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64 DW.FORM_data2 => parseFormValueConstant(allocator, in_stream, false, 2), DW.FORM_data4 => parseFormValueConstant(allocator, in_stream, false, 4), DW.FORM_data8 => parseFormValueConstant(allocator, in_stream, false, 8), - DW.FORM_udata, - DW.FORM_sdata => { + DW.FORM_udata, DW.FORM_sdata => { const block_len = try readULeb128(in_stream); const signed = form_id == DW.FORM_sdata; return parseFormValueConstant(allocator, in_stream, signed, block_len); diff --git a/std/dwarf.zig b/std/dwarf.zig index 04456d9e5c..76ed122447 100644 --- a/std/dwarf.zig +++ b/std/dwarf.zig @@ -337,7 +337,6 @@ pub const AT_PGI_lbase = 0x3a00; pub const AT_PGI_soffset = 0x3a01; pub const AT_PGI_lstride = 0x3a02; - pub const OP_addr = 0x03; pub const OP_deref = 0x06; pub const OP_const1u = 0x08; @@ -577,7 +576,6 @@ pub const ATE_HP_unsigned_fixed = 0x8e; // Cobol. pub const ATE_HP_VAX_complex_float = 0x8f; // F or G floating complex. pub const ATE_HP_VAX_complex_float_d = 0x90; // D floating complex. - pub const CFA_advance_loc = 0x40; pub const CFA_offset = 0x80; pub const CFA_restore = 0xc0; diff --git a/std/elf.zig b/std/elf.zig index 1764829bc8..29b9473f98 100644 --- a/std/elf.zig +++ b/std/elf.zig @@ -123,13 +123,11 @@ pub const DT_SYMINFO = 0x6ffffeff; pub const DT_ADDRRNGHI = 0x6ffffeff; pub const DT_ADDRNUM = 11; - pub const DT_VERSYM = 0x6ffffff0; pub const DT_RELACOUNT = 0x6ffffff9; pub const DT_RELCOUNT = 0x6ffffffa; - pub const DT_FLAGS_1 = 0x6ffffffb; pub const DT_VERDEF = 0x6ffffffc; @@ -139,13 +137,10 @@ pub const DT_VERNEED = 0x6ffffffe; pub const DT_VERNEEDNUM = 0x6fffffff; pub const DT_VERSIONTAGNUM = 16; - - pub const DT_AUXILIARY = 0x7ffffffd; pub const DT_FILTER = 0x7fffffff; pub const DT_EXTRANUM = 3; - pub const DT_SPARC_REGISTER = 0x70000001; pub const DT_SPARC_NUM = 2; @@ -434,9 +429,7 @@ pub const Elf = struct { try elf.in_file.seekForward(4); const header_size = try in.readInt(elf.endian, u16); - if ((elf.is_64 and header_size != 64) or - (!elf.is_64 and header_size != 52)) - { + if ((elf.is_64 and header_size != 64) or (!elf.is_64 and header_size != 52)) { return error.InvalidFormat; } @@ -467,16 +460,16 @@ pub const Elf = struct { if (sh_entry_size != 64) return error.InvalidFormat; for (elf.section_headers) |*elf_section| { - elf_section.name = try in.readInt(elf.endian, u32); - elf_section.sh_type = try in.readInt(elf.endian, u32); - elf_section.flags = try in.readInt(elf.endian, u64); - elf_section.addr = try in.readInt(elf.endian, u64); - elf_section.offset = try in.readInt(elf.endian, u64); - elf_section.size = try in.readInt(elf.endian, u64); - elf_section.link = try in.readInt(elf.endian, u32); - elf_section.info = try in.readInt(elf.endian, u32); - elf_section.addr_align = try in.readInt(elf.endian, u64); - elf_section.ent_size = try in.readInt(elf.endian, u64); + elf_section.name = try in.readInt(elf.endian, u32); + elf_section.sh_type = try in.readInt(elf.endian, u32); + elf_section.flags = try in.readInt(elf.endian, u64); + elf_section.addr = try in.readInt(elf.endian, u64); + elf_section.offset = try in.readInt(elf.endian, u64); + elf_section.size = try in.readInt(elf.endian, u64); + elf_section.link = try in.readInt(elf.endian, u32); + elf_section.info = try in.readInt(elf.endian, u32); + elf_section.addr_align = try in.readInt(elf.endian, u64); + elf_section.ent_size = try in.readInt(elf.endian, u64); } } else { if (sh_entry_size != 40) return error.InvalidFormat; @@ -513,8 +506,7 @@ pub const Elf = struct { pub fn close(elf: &Elf) void { elf.allocator.free(elf.section_headers); - if (elf.auto_close_stream) - elf.in_file.close(); + if (elf.auto_close_stream) elf.in_file.close(); } pub fn findSection(elf: &Elf, name: []const u8) !?&SectionHeader { @@ -852,27 +844,27 @@ pub const Elf_MIPS_ABIFlags_v0 = extern struct { flags2: Elf32_Word, }; -pub const Ehdr = switch(@sizeOf(usize)) { +pub const Ehdr = switch (@sizeOf(usize)) { 4 => Elf32_Ehdr, 8 => Elf64_Ehdr, else => @compileError("expected pointer size of 32 or 64"), }; -pub const Phdr = switch(@sizeOf(usize)) { +pub const Phdr = switch (@sizeOf(usize)) { 4 => Elf32_Phdr, 8 => Elf64_Phdr, else => @compileError("expected pointer size of 32 or 64"), }; -pub const Sym = switch(@sizeOf(usize)) { +pub const Sym = switch (@sizeOf(usize)) { 4 => Elf32_Sym, 8 => Elf64_Sym, else => @compileError("expected pointer size of 32 or 64"), }; -pub const Verdef = switch(@sizeOf(usize)) { +pub const Verdef = switch (@sizeOf(usize)) { 4 => Elf32_Verdef, 8 => Elf64_Verdef, else => @compileError("expected pointer size of 32 or 64"), }; -pub const Verdaux = switch(@sizeOf(usize)) { +pub const Verdaux = switch (@sizeOf(usize)) { 4 => Elf32_Verdaux, 8 => Elf64_Verdaux, else => @compileError("expected pointer size of 32 or 64"), diff --git a/std/event.zig b/std/event.zig index 558bd2a188..6ee8ab35f1 100644 --- a/std/event.zig +++ b/std/event.zig @@ -76,19 +76,14 @@ pub const TcpServer = struct { } continue; }, - error.ConnectionAborted, - error.FileDescriptorClosed => continue, + error.ConnectionAborted, error.FileDescriptorClosed => continue, error.PageFault => unreachable, error.InvalidSyscall => unreachable, error.FileDescriptorNotASocket => unreachable, error.OperationNotSupported => unreachable, - error.SystemFdQuotaExceeded, - error.SystemResources, - error.ProtocolFailure, - error.BlockedByFirewall, - error.Unexpected => { + error.SystemFdQuotaExceeded, error.SystemResources, error.ProtocolFailure, error.BlockedByFirewall, error.Unexpected => { @panic("TODO handle this error"); }, } @@ -121,7 +116,6 @@ pub const Loop = struct { pub fn removeFd(self: &Loop, fd: i32) void { std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_DEL, fd, undefined) catch {}; } - async fn waitFd(self: &Loop, fd: i32) !void { defer self.removeFd(fd); suspend |p| { @@ -169,7 +163,6 @@ test "listen on a port, send bytes, receive bytes" { tcp_server: TcpServer, const Self = this; - async<&mem.Allocator> fn handler(tcp_server: &TcpServer, _addr: &const std.net.Address, _socket: &const std.os.File) void { const self = @fieldParentPtr(Self, "tcp_server", tcp_server); var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733 @@ -184,7 +177,6 @@ test "listen on a port, send bytes, receive bytes" { cancel p; } } - async fn errorableHandler(self: &Self, _addr: &const std.net.Address, _socket: &const std.os.File) !void { const addr = _addr.*; // TODO https://github.com/ziglang/zig/issues/733 var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733 @@ -207,7 +199,6 @@ test "listen on a port, send bytes, receive bytes" { defer cancel p; loop.run(); } - async fn doAsyncTest(loop: &Loop, address: &const std.net.Address) void { errdefer @panic("test failure"); diff --git a/std/fmt/errol/enum3.zig b/std/fmt/errol/enum3.zig index f8299d3c6f..7663f9b5d9 100644 --- a/std/fmt/errol/enum3.zig +++ b/std/fmt/errol/enum3.zig @@ -1,4 +1,4 @@ -pub const enum3 = []u64 { +pub const enum3 = []u64{ 0x4e2e2785c3a2a20b, 0x240a28877a09a4e1, 0x728fca36c06cf106, @@ -439,13 +439,13 @@ const Slab = struct { }; fn slab(str: []const u8, exp: i32) Slab { - return Slab { + return Slab{ .str = str, .exp = exp, }; } -pub const enum3_data = []Slab { +pub const enum3_data = []Slab{ slab("40648030339495312", 69), slab("4498645355592131", -134), slab("678321594594593", 244), @@ -879,4 +879,3 @@ pub const enum3_data = []Slab { slab("32216657306260762", 218), slab("30423431424080128", 219), }; - From afdfbc0367b261ea43d5618027e23022c01e2c93 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 26 May 2018 23:17:24 -0400 Subject: [PATCH 56/75] zig fmt: delete empty comments that do nothing --- std/zig/parser_test.zig | 16 ++++++++++++++++ std/zig/render.zig | 9 +++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 909220a6f6..a2ee77796b 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -28,6 +28,12 @@ test "zig fmt: array literal with hint" { \\ 5, \\ 6, \\ 7 }; + \\const a = []u8{ + \\ 1, 2, + \\ 3, 4, // + \\ 5, 6, // + \\ 7, 8, // + \\}; , \\const a = []u8{ \\ 1, 2, // @@ -53,6 +59,16 @@ test "zig fmt: array literal with hint" { \\ 5, 6, // \\ 7, \\}; + \\const a = []u8{ + \\ 1, + \\ 2, + \\ 3, + \\ 4, + \\ 5, + \\ 6, + \\ 7, + \\ 8, + \\}; \\ ); } diff --git a/std/zig/render.zig b/std/zig/render.zig index fa3755b719..49138e0e78 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -1583,8 +1583,13 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } } - if (space == Space.IgnoreEmptyComment and mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ").len == 2) { - return stream.writeByte(' '); + const comment_is_empty = mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ").len == 2; + if (comment_is_empty) { + switch (space) { + Space.IgnoreEmptyComment => return stream.writeByte(' '), + Space.Newline => return stream.writeByte('\n'), + else => {}, + } } var loc = tree.tokenLocationPtr(token.end, next_token); From 3fed10883bd6916147cce8060949040770532daf Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 26 May 2018 23:24:43 -0400 Subject: [PATCH 57/75] zig fmt: array literals with no trailing comma all on one line --- std/zig/parser_test.zig | 10 ++++------ std/zig/render.zig | 32 ++++++++++++++++++++++++++++---- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index a2ee77796b..e83f99c972 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -229,16 +229,14 @@ test "zig fmt: add trailing comma to array literal" { \\comptime { \\ return []u16{'m', 's', 'y', 's', '-' // hi \\ }; + \\ return []u16{'m', 's', 'y', 's', + \\ '-'}; \\} , \\comptime { - \\ return []u16{ - \\ 'm', - \\ 's', - \\ 'y', - \\ 's', - \\ '-', // hi + \\ return []u16{ 'm', 's', 'y', 's', '-' // hi \\ }; + \\ return []u16{ 'm', 's', 'y', 's', '-'}; \\} \\ ); diff --git a/std/zig/render.zig b/std/zig/render.zig index 49138e0e78..9805b7cf75 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -557,11 +557,11 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind }; - const new_indent = indent + indent_delta; - try renderToken(tree, stream, lbrace, new_indent, Space.Newline); - try stream.writeByteNTimes(' ', new_indent); - if (maybe_row_size) |row_size| { + const new_indent = indent + indent_delta; + try renderToken(tree, stream, lbrace, new_indent, Space.Newline); + try stream.writeByteNTimes(' ', new_indent); + var it = exprs.iterator(0); var i: usize = 0; while (it.next()) |expr| { @@ -597,6 +597,30 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind return; } + const src_has_trailing_comma = blk: { + const maybe_comma = tree.prevToken(suffix_op.rtoken); + break :blk tree.tokens.at(maybe_comma).id == Token.Id.Comma; + }; + if (!src_has_trailing_comma) { + try renderToken(tree, stream, lbrace, indent, Space.Space); + var it = exprs.iterator(0); + while (it.next()) |expr| { + try renderExpression(allocator, stream, tree, indent, expr.*, Space.None); + + if (it.peek()) |next_expr| { + const comma = tree.nextToken(expr.*.lastToken()); + try renderToken(tree, stream, comma, indent, Space.Space); // , + } + } + + try renderToken(tree, stream, suffix_op.rtoken, indent, space); + return; + } + + const new_indent = indent + indent_delta; + try renderToken(tree, stream, lbrace, new_indent, Space.Newline); + try stream.writeByteNTimes(' ', new_indent); + var it = exprs.iterator(0); while (it.next()) |expr| { From 122a74724cb527ae6e1997c2c77118047fb50a2c Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 16:23:33 -0400 Subject: [PATCH 58/75] zig fmt: use simple newlines rather than empty comments to hint now the first row of an array literal is the hint to zig fmt for how long each row should be. See #1003 --- std/zig/parser_test.zig | 40 ++++++++++-------- std/zig/render.zig | 91 ++++++++++++++--------------------------- 2 files changed, 55 insertions(+), 76 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index e83f99c972..550d8fa111 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -29,34 +29,36 @@ test "zig fmt: array literal with hint" { \\ 6, \\ 7 }; \\const a = []u8{ - \\ 1, 2, + \\ 1, + \\ 2, \\ 3, 4, // \\ 5, 6, // \\ 7, 8, // \\}; , \\const a = []u8{ - \\ 1, 2, // - \\ 3, 4, // - \\ 5, 6, // + \\ 1, 2, + \\ 3, 4, + \\ 5, 6, \\ 7, \\}; \\const a = []u8{ - \\ 1, 2, // - \\ 3, 4, // - \\ 5, 6, // - \\ 7, 8, // + \\ 1, 2, + \\ 3, 4, + \\ 5, 6, + \\ 7, 8, \\}; \\const a = []u8{ - \\ 1, 2, // - \\ 3, 4, // + \\ 1, 2, + \\ 3, 4, \\ 5, 6, // blah - \\ 7, 8, // + \\ 7, 8, \\}; \\const a = []u8{ - \\ 1, 2, // - \\ 3, 4, // - \\ 5, 6, // + \\ 1, 2, + \\ 3, // + \\ 4, + \\ 5, 6, \\ 7, \\}; \\const a = []u8{ @@ -231,12 +233,18 @@ test "zig fmt: add trailing comma to array literal" { \\ }; \\ return []u16{'m', 's', 'y', 's', \\ '-'}; + \\ return []u16{'m', 's', 'y', 's', '-'}; \\} , \\comptime { - \\ return []u16{ 'm', 's', 'y', 's', '-' // hi + \\ return []u16{ + \\ 'm', 's', 'y', 's', '-', // hi \\ }; - \\ return []u16{ 'm', 's', 'y', 's', '-'}; + \\ return []u16{ + \\ 'm', 's', 'y', 's', + \\ '-', + \\ }; + \\ return []u16{ 'm', 's', 'y', 's', '-' }; \\} \\ ); diff --git a/std/zig/render.zig b/std/zig/render.zig index 9805b7cf75..1528ae31aa 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -534,36 +534,42 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind // scan to find row size const maybe_row_size: ?usize = blk: { - var count: usize = 0; + var count: usize = 1; var it = exprs.iterator(0); - var prev_token = (??it.peek()).*.lastToken() + 1; - while (it.next()) |expr| { - const expr_last_token = expr.*.lastToken() + 1; - const next_token = tree.tokens.at(expr_last_token + 1); - const loc = tree.tokenLocationPtr(tree.tokens.at(prev_token).end, next_token); - if (loc.line != 0) break :blk null; - if (next_token.id == Token.Id.LineComment) { - const trimmed = mem.trimRight(u8, tree.tokenSlicePtr(next_token), " "); - if (trimmed.len == 2) { - break :blk count; - } else { - break :blk null; + while (true) { + const expr = (??it.next()).*; + if (it.peek()) |next_expr| { + const expr_last_token = expr.*.lastToken() + 1; + const loc = tree.tokenLocation(tree.tokens.at(expr_last_token).end, next_expr.*.firstToken()); + if (loc.line != 0) break :blk count; + count += 1; + } else { + const expr_last_token = expr.*.lastToken(); + const loc = tree.tokenLocation(tree.tokens.at(expr_last_token).end, suffix_op.rtoken); + if (loc.line == 0) { + // all on one line + const src_has_trailing_comma = trailblk: { + const maybe_comma = tree.prevToken(suffix_op.rtoken); + break :trailblk tree.tokens.at(maybe_comma).id == Token.Id.Comma; + }; + if (src_has_trailing_comma) { + break :blk 1; // force row size 1 + } else { + break :blk null; // no newlines + } } + break :blk count; } - prev_token = expr_last_token; - count += 1; } - break :blk null; }; - if (maybe_row_size) |row_size| { const new_indent = indent + indent_delta; try renderToken(tree, stream, lbrace, new_indent, Space.Newline); try stream.writeByteNTimes(' ', new_indent); var it = exprs.iterator(0); - var i: usize = 0; + var i: usize = 1; while (it.next()) |expr| { if (it.peek()) |next_expr| { try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.None); @@ -571,23 +577,16 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const comma = tree.nextToken(expr.*.lastToken()); if (i != row_size) { - try renderToken(tree, stream, comma, new_indent, Space.IgnoreEmptyComment); // , + try renderToken(tree, stream, comma, new_indent, Space.Space); // , i += 1; continue; } - i = 0; + i = 1; - try renderToken(tree, stream, comma, new_indent, Space.NoIndent); // , - - const next_token = tree.tokens.at(comma + 1); - if (next_token.id != Token.Id.LineComment) { - try stream.print(" //\n"); - } + try renderToken(tree, stream, comma, new_indent, Space.Newline); // , try renderExtraNewline(tree, stream, next_expr.*); try stream.writeByteNTimes(' ', new_indent); - } else if (i == row_size) { - try renderTrailingCommaAndEmptyComment(allocator, stream, tree, new_indent, expr.*); // , // } else { try renderTrailingComma(allocator, stream, tree, new_indent, expr.*, Space.Newline); // , } @@ -595,50 +594,22 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.writeByteNTimes(' ', indent); try renderToken(tree, stream, suffix_op.rtoken, indent, space); return; - } - - const src_has_trailing_comma = blk: { - const maybe_comma = tree.prevToken(suffix_op.rtoken); - break :blk tree.tokens.at(maybe_comma).id == Token.Id.Comma; - }; - if (!src_has_trailing_comma) { + } else { try renderToken(tree, stream, lbrace, indent, Space.Space); var it = exprs.iterator(0); while (it.next()) |expr| { - try renderExpression(allocator, stream, tree, indent, expr.*, Space.None); - if (it.peek()) |next_expr| { + try renderExpression(allocator, stream, tree, indent, expr.*, Space.None); const comma = tree.nextToken(expr.*.lastToken()); try renderToken(tree, stream, comma, indent, Space.Space); // , + } else { + try renderExpression(allocator, stream, tree, indent, expr.*, Space.Space); } } try renderToken(tree, stream, suffix_op.rtoken, indent, space); return; } - - const new_indent = indent + indent_delta; - try renderToken(tree, stream, lbrace, new_indent, Space.Newline); - try stream.writeByteNTimes(' ', new_indent); - - var it = exprs.iterator(0); - while (it.next()) |expr| { - - if (it.peek()) |next_expr| { - try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.None); - - const comma = tree.nextToken(expr.*.lastToken()); - try renderToken(tree, stream, comma, new_indent, Space.Newline); // , - - try renderExtraNewline(tree, stream, next_expr.*); - try stream.writeByteNTimes(' ', new_indent); - } else { - try renderTrailingComma(allocator, stream, tree, new_indent, expr.*, Space.Newline); - } - } - - try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); }, } }, From fd13a757855e185b4250c65fe89bbd72c9479a52 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 16:59:42 -0400 Subject: [PATCH 59/75] zig fmt: allow same line struct literal with no trailing comma See #1003 --- std/zig/parser_test.zig | 15 +++++++++++++++ std/zig/render.zig | 31 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 550d8fa111..72818bc074 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,18 @@ +test "zig fmt: struct literal no trailing comma" { + try testTransform( + \\const a = foo{ .x = 1, .y = 2 }; + \\const a = foo{ .x = 1, + \\ .y = 2 }; + , + \\const a = foo{ .x = 1, .y = 2 }; + \\const a = foo{ + \\ .x = 1, + \\ .y = 2, + \\}; + \\ + ); +} + test "zig fmt: array literal with hint" { try testTransform( \\const a = []u8{ diff --git a/std/zig/render.zig b/std/zig/render.zig index 1528ae31aa..86e972c173 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -486,6 +486,37 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind return; } + const src_has_trailing_comma = blk: { + const maybe_comma = tree.prevToken(suffix_op.rtoken); + break :blk tree.tokens.at(maybe_comma).id == Token.Id.Comma; + }; + + const src_same_line = blk: { + const loc = tree.tokenLocation(tree.tokens.at(lbrace).end, suffix_op.rtoken); + break :blk loc.line == 0; + }; + + if (!src_has_trailing_comma and src_same_line) { + // render all on one line, no trailing comma + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, Space.Space); + + var it = field_inits.iterator(0); + while (it.next()) |field_init| { + if (it.peek() != null) { + try renderExpression(allocator, stream, tree, indent, field_init.*, Space.None); + + const comma = tree.nextToken(field_init.*.lastToken()); + try renderToken(tree, stream, comma, indent, Space.Space); + } else { + try renderExpression(allocator, stream, tree, indent, field_init.*, Space.Space); + } + } + + try renderToken(tree, stream, suffix_op.rtoken, indent, space); + return; + } + try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); try renderToken(tree, stream, lbrace, indent, Space.Newline); From 6c1fda3f99ebef60f4cb45b6bd66e76c85483c36 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 17:09:55 -0400 Subject: [PATCH 60/75] zig fmt: fix switch body indent --- std/zig/parser_test.zig | 12 ++++++++++++ std/zig/render.zig | 6 +++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 72818bc074..dc522b3ef4 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,15 @@ +test "zig fmt: switch comment before prong" { + try testCanonical( + \\comptime { + \\ switch (a) { + \\ // hi + \\ 0 => {}, + \\ } + \\} + \\ + ); +} + test "zig fmt: struct literal no trailing comma" { try testTransform( \\const a = foo{ .x = 1, .y = 2 }; diff --git a/std/zig/render.zig b/std/zig/render.zig index 86e972c173..2f94d1cf8a 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -1050,11 +1050,11 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExpression(allocator, stream, tree, indent, switch_node.expr, Space.None); - try renderToken(tree, stream, rparen, indent, Space.Space); // ) - try renderToken(tree, stream, lbrace, indent, Space.Newline); // { - const new_indent = indent + indent_delta; + try renderToken(tree, stream, rparen, indent, Space.Space); // ) + try renderToken(tree, stream, lbrace, new_indent, Space.Newline); // { + var it = switch_node.cases.iterator(0); while (it.next()) |node| { try stream.writeByteNTimes(' ', new_indent); From 530da363521ca7c3b22e6451874cef24d49683cc Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 17:43:17 -0400 Subject: [PATCH 61/75] zig fmt: fix enum decl with no trailing comma See #1003 --- std/zig/parser_test.zig | 12 +++++++ std/zig/render.zig | 71 ++++++++++++++++++++--------------------- 2 files changed, 47 insertions(+), 36 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index dc522b3ef4..dc586e53b4 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,15 @@ +test "zig fmt: enum decl with no trailing comma" { + try testTransform( + \\const StrLitKind = enum {Normal, C}; + , + \\const StrLitKind = enum { + \\ Normal, + \\ C, + \\}; + \\ + ); +} + test "zig fmt: switch comment before prong" { try testCanonical( \\comptime { diff --git a/std/zig/render.zig b/std/zig/render.zig index 2f94d1cf8a..ed760a4b22 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -110,22 +110,29 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i try renderDocComments(tree, stream, tag, indent); - const name_space = if (tag.type_expr == null and tag.value_expr != null) Space.Space else Space.None; - try renderToken(tree, stream, tag.name_token, indent, name_space); // name + if (tag.type_expr == null and tag.value_expr == null) { + return renderTokenAndTrailingComma(tree, stream, tag.name_token, indent, Space.Newline); // name, + } + + if (tag.type_expr == null) { + try renderToken(tree, stream, tag.name_token, indent, Space.Space); // name + } else { + try renderToken(tree, stream, tag.name_token, indent, Space.None); // name + } if (tag.type_expr) |type_expr| { try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // : - const after_type_space = if (tag.value_expr == null) Space.None else Space.Space; - try renderExpression(allocator, stream, tree, indent, type_expr, after_type_space); + if (tag.value_expr == null) { + return renderTrailingComma(allocator, stream, tree, indent, type_expr, Space.Newline); // type, + } else { + try renderExpression(allocator, stream, tree, indent, type_expr, Space.Space); // type + } } - if (tag.value_expr) |value_expr| { - try renderToken(tree, stream, tree.prevToken(value_expr.firstToken()), indent, Space.Space); // = - try renderExpression(allocator, stream, tree, indent, value_expr, Space.None); - } - - try renderToken(tree, stream, tree.nextToken(decl.lastToken()), indent, Space.Newline); // , + const value_expr = ??tag.value_expr; + try renderToken(tree, stream, tree.prevToken(value_expr.firstToken()), indent, Space.Space); // = + try renderTrailingComma(allocator, stream, tree, indent, value_expr, Space.Newline); // value, }, ast.Node.Id.EnumTag => { @@ -133,15 +140,14 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i try renderDocComments(tree, stream, tag, indent); - const after_name_space = if (tag.value == null) Space.None else Space.Space; - try renderToken(tree, stream, tag.name_token, indent, after_name_space); // name - if (tag.value) |value| { - try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // = - try renderExpression(allocator, stream, tree, indent, value, Space.None); - } + try renderToken(tree, stream, tag.name_token, indent, Space.Space); // name - try renderToken(tree, stream, tree.nextToken(decl.lastToken()), indent, Space.Newline); // , + try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // = + try renderTrailingComma(allocator, stream, tree, indent, value, Space.Newline); + } else { + try renderTokenAndTrailingComma(tree, stream, tag.name_token, indent, Space.Newline); // name + } }, ast.Node.Id.Comptime => { @@ -1584,7 +1590,6 @@ const Space = enum { NoNewline, NoIndent, NoComment, - IgnoreEmptyComment, }; fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, space: Space) (@typeOf(stream).Child.Error || Error)!void { @@ -1604,7 +1609,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent return stream.write("\n"); } }, - Space.Space, Space.IgnoreEmptyComment => return stream.writeByte(' '), + Space.Space => return stream.writeByte(' '), Space.NoComment => unreachable, } } @@ -1612,7 +1617,6 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent const comment_is_empty = mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ").len == 2; if (comment_is_empty) { switch (space) { - Space.IgnoreEmptyComment => return stream.writeByte(' '), Space.Newline => return stream.writeByte('\n'), else => {}, } @@ -1644,7 +1648,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } }, Space.NoNewline => {}, - Space.NoComment, Space.IgnoreEmptyComment => unreachable, + Space.NoComment => unreachable, } return; } @@ -1681,7 +1685,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent try stream.writeByteNTimes(' ', next_line_indent); }, Space.NoNewline => {}, - Space.NoComment, Space.IgnoreEmptyComment => unreachable, + Space.NoComment => unreachable, } return; } @@ -1720,27 +1724,22 @@ fn renderTrailingComma(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, } } -fn renderTrailingCommaAndEmptyComment(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void -{ - const end_token = base.lastToken() + 1; +fn renderTokenAndTrailingComma(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, space: Space) (@typeOf(stream).Child.Error || Error)!void { + const end_token = token_index + 1; switch (tree.tokens.at(end_token).id) { Token.Id.Comma => { - try renderExpression(allocator, stream, tree, indent, base, Space.None); - try renderToken(tree, stream, end_token, indent, Space.Space); // , - - const next_token = tree.tokens.at(end_token + 1); - if (next_token.id != Token.Id.LineComment) { - try stream.print("//\n"); - } + try renderToken(tree, stream, token_index, indent, Space.None); + try renderToken(tree, stream, end_token, indent, space); // , }, Token.Id.LineComment => { - try renderExpression(allocator, stream, tree, indent, base, Space.NoComment); + try renderToken(tree, stream, token_index, indent, Space.NoComment); try stream.write(", "); - try renderToken(tree, stream, end_token, indent, Space.Newline); + try renderToken(tree, stream, end_token, indent, space); }, else => { - try renderExpression(allocator, stream, tree, indent, base, Space.None); - try stream.write(", //\n"); + try renderToken(tree, stream, token_index, indent, Space.None); + try stream.write(",\n"); + assert(space == Space.Newline); }, } } From 354ab1c5c8ec62c485fbc297817a0e70ab625a71 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 21:18:41 -0400 Subject: [PATCH 62/75] zig fmt: render fn decl with trailing comma 1 line per param --- std/zig/parser_test.zig | 15 +++- std/zig/render.zig | 158 ++++++++++++++++++++-------------------- 2 files changed, 95 insertions(+), 78 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index dc586e53b4..edf1b002b0 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,15 @@ +test "zig fmt: fn decl with trailing comma" { + try testTransform( + \\fn foo(a: i32, b: i32,) void {} + , + \\fn foo( + \\ a: i32, + \\ b: i32, + \\) void {} + \\ + ); +} + test "zig fmt: enum decl with no trailing comma" { try testTransform( \\const StrLitKind = enum {Normal, C}; @@ -247,7 +259,8 @@ test "zig fmt: switch cases trailing comma" { \\ switch (x) { \\ 1, 2, 3 => {}, \\ 4, - \\ 5, => {}, + \\ 5, + \\ => {}, \\ 6...8 => {}, \\ else => {}, \\ } diff --git a/std/zig/render.zig b/std/zig/render.zig index ed760a4b22..b8481b1348 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -102,7 +102,7 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i } try renderToken(tree, stream, field.name_token, indent, Space.None); // name try renderToken(tree, stream, tree.nextToken(field.name_token), indent, Space.Space); // : - try renderTrailingComma(allocator, stream, tree, indent, field.type_expr, Space.Newline); // type, + try renderExpression(allocator, stream, tree, indent, field.type_expr, Space.Comma); // type, }, ast.Node.Id.UnionTag => { @@ -111,7 +111,7 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i try renderDocComments(tree, stream, tag, indent); if (tag.type_expr == null and tag.value_expr == null) { - return renderTokenAndTrailingComma(tree, stream, tag.name_token, indent, Space.Newline); // name, + return renderToken(tree, stream, tag.name_token, indent, Space.Comma); // name, } if (tag.type_expr == null) { @@ -124,7 +124,7 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // : if (tag.value_expr == null) { - return renderTrailingComma(allocator, stream, tree, indent, type_expr, Space.Newline); // type, + return renderExpression(allocator, stream, tree, indent, type_expr, Space.Comma); // type, } else { try renderExpression(allocator, stream, tree, indent, type_expr, Space.Space); // type } @@ -132,7 +132,7 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i const value_expr = ??tag.value_expr; try renderToken(tree, stream, tree.prevToken(value_expr.firstToken()), indent, Space.Space); // = - try renderTrailingComma(allocator, stream, tree, indent, value_expr, Space.Newline); // value, + try renderExpression(allocator, stream, tree, indent, value_expr, Space.Comma); // value, }, ast.Node.Id.EnumTag => { @@ -144,9 +144,9 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i try renderToken(tree, stream, tag.name_token, indent, Space.Space); // name try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // = - try renderTrailingComma(allocator, stream, tree, indent, value, Space.Newline); + try renderExpression(allocator, stream, tree, indent, value, Space.Comma); } else { - try renderTokenAndTrailingComma(tree, stream, tag.name_token, indent, Space.Newline); // name + try renderToken(tree, stream, tag.name_token, indent, Space.Comma); // name } }, @@ -413,7 +413,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderToken(tree, stream, comma, new_indent, Space.Newline); // , try renderExtraNewline(tree, stream, next_node.*); } else { - try renderTrailingComma(allocator, stream, tree, param_node_new_indent, param_node.*, Space.Newline); + try renderExpression(allocator, stream, tree, param_node_new_indent, param_node.*, Space.Comma); try stream.writeByteNTimes(' ', indent); try renderToken(tree, stream, suffix_op.rtoken, indent, space); return; @@ -540,7 +540,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExtraNewline(tree, stream, next_field_init.*); } else { - try renderTrailingComma(allocator, stream, tree, new_indent, field_init.*, Space.Newline); + try renderExpression(allocator, stream, tree, new_indent, field_init.*, Space.Comma); } } @@ -625,7 +625,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExtraNewline(tree, stream, next_expr.*); try stream.writeByteNTimes(' ', new_indent); } else { - try renderTrailingComma(allocator, stream, tree, new_indent, expr.*, Space.Newline); // , + try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.Comma); // , } } try stream.writeByteNTimes(' ', indent); @@ -892,7 +892,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExtraNewline(tree, stream, next_node.*); } else { - try renderTrailingComma(allocator, stream, tree, new_indent, node.*, Space.Newline); + try renderExpression(allocator, stream, tree, new_indent, node.*, Space.Comma); } } @@ -976,29 +976,55 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExpression(allocator, stream, tree, indent, &async_attr.base, Space.Space); } - if (fn_proto.name_token) |name_token| blk: { + const lparen = if (fn_proto.name_token) |name_token| blk: { try renderToken(tree, stream, fn_proto.fn_token, indent, Space.Space); // fn try renderToken(tree, stream, name_token, indent, Space.None); // name - try renderToken(tree, stream, tree.nextToken(name_token), indent, Space.None); // ( + break :blk tree.nextToken(name_token); } else blk: { try renderToken(tree, stream, fn_proto.fn_token, indent, Space.None); // fn - try renderToken(tree, stream, tree.nextToken(fn_proto.fn_token), indent, Space.None); // ( - } - - var it = fn_proto.params.iterator(0); - while (it.next()) |param_decl_node| { - try renderParamDecl(allocator, stream, tree, indent, param_decl_node.*); - - if (it.peek() != null) { - const comma = tree.nextToken(param_decl_node.*.lastToken()); - try renderToken(tree, stream, comma, indent, Space.Space); // , - } - } + break :blk tree.nextToken(fn_proto.fn_token); + }; const rparen = tree.prevToken(switch (fn_proto.return_type) { ast.Node.FnProto.ReturnType.Explicit => |node| node.firstToken(), ast.Node.FnProto.ReturnType.InferErrorSet => |node| tree.prevToken(node.firstToken()), }); + + const src_params_trailing_comma = blk: { + const maybe_comma = tree.prevToken(rparen); + break :blk tree.tokens.at(maybe_comma).id == Token.Id.Comma; + }; + const src_params_same_line = blk: { + const loc = tree.tokenLocation(tree.tokens.at(lparen).end, rparen); + break :blk loc.line == 0; + }; + + if (!src_params_trailing_comma and src_params_same_line) { + try renderToken(tree, stream, lparen, indent, Space.None); // ( + + // render all on one line, no trailing comma + var it = fn_proto.params.iterator(0); + while (it.next()) |param_decl_node| { + try renderParamDecl(allocator, stream, tree, indent, param_decl_node.*, Space.None); + + if (it.peek() != null) { + const comma = tree.nextToken(param_decl_node.*.lastToken()); + try renderToken(tree, stream, comma, indent, Space.Space); // , + } + } + } else { + // one param per line + const new_indent = indent + indent_delta; + try renderToken(tree, stream, lparen, new_indent, Space.Newline); // ( + + var it = fn_proto.params.iterator(0); + while (it.next()) |param_decl_node| { + try stream.writeByteNTimes(' ', new_indent); + try renderParamDecl(allocator, stream, tree, indent, param_decl_node.*, Space.Comma); + } + try stream.writeByteNTimes(' ', indent); + } + try renderToken(tree, stream, rparen, indent, Space.Space); // ) if (fn_proto.align_expr) |align_expr| { @@ -1064,7 +1090,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = switch_node.cases.iterator(0); while (it.next()) |node| { try stream.writeByteNTimes(' ', new_indent); - try renderExpression(allocator, stream, tree, new_indent, node.*, Space.Newline); + try renderExpression(allocator, stream, tree, new_indent, node.*, Space.Comma); if (it.peek()) |next_node| { try renderExtraNewline(tree, stream, next_node.*); @@ -1110,7 +1136,8 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExtraNewline(tree, stream, next_node.*); try stream.writeByteNTimes(' ', indent); } else { - try renderTrailingComma(allocator, stream, tree, indent, node.*, Space.Space); + try renderExpression(allocator, stream, tree, indent, node.*, Space.Comma); + try stream.writeByteNTimes(' ', indent); break; } } @@ -1122,7 +1149,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExpression(allocator, stream, tree, indent, payload, Space.Space); } - try renderTrailingComma(allocator, stream, tree, indent, switch_case.expr, space); + try renderExpression(allocator, stream, tree, indent, switch_case.expr, space); }, ast.Node.Id.SwitchElse => { const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base); @@ -1543,7 +1570,7 @@ fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent try renderToken(tree, stream, var_decl.semicolon_token, indent, Space.Newline); } -fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { +fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node, space: Space) (@typeOf(stream).Child.Error || Error)!void { const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base); if (param_decl.comptime_token) |comptime_token| { @@ -1557,9 +1584,9 @@ fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, inde try renderToken(tree, stream, tree.nextToken(name_token), indent, Space.Space); // : } if (param_decl.var_args_token) |var_args_token| { - try renderToken(tree, stream, var_args_token, indent, Space.None); + try renderToken(tree, stream, var_args_token, indent, space); } else { - try renderExpression(allocator, stream, tree, indent, param_decl.type_node, Space.None); + try renderExpression(allocator, stream, tree, indent, param_decl.type_node, space); } } @@ -1586,6 +1613,7 @@ fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, inde const Space = enum { None, Newline, + Comma, Space, NoNewline, NoIndent, @@ -1596,9 +1624,27 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent var token = tree.tokens.at(token_index); try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(token), " ")); - if (space == Space.NoComment) return; - var next_token = tree.tokens.at(token_index + 1); + + switch (space) { + Space.NoComment => return, + Space.Comma => switch (next_token.id) { + Token.Id.Comma => return renderToken(tree, stream, token_index + 1, indent, Space.Newline), + Token.Id.LineComment => { + try stream.write(", "); + return renderToken(tree, stream, token_index + 1, indent, Space.Newline); + }, + else => { + if (tree.tokens.at(token_index + 2).id == Token.Id.MultilineStringLiteralLine) { + return stream.write(","); + } else { + return stream.write(",\n"); + } + }, + }, + else => {}, + } + if (next_token.id != Token.Id.LineComment) { switch (space) { Space.None, Space.NoNewline, Space.NoIndent => return, @@ -1610,7 +1656,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } }, Space.Space => return stream.writeByte(' '), - Space.NoComment => unreachable, + Space.NoComment, Space.Comma => unreachable, } } @@ -1648,7 +1694,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } }, Space.NoNewline => {}, - Space.NoComment => unreachable, + Space.NoComment, Space.Comma => unreachable, } return; } @@ -1685,7 +1731,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent try stream.writeByteNTimes(' ', next_line_indent); }, Space.NoNewline => {}, - Space.NoComment => unreachable, + Space.NoComment, Space.Comma => unreachable, } return; } @@ -1701,45 +1747,3 @@ fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@t try stream.writeByteNTimes(' ', indent); } } - -fn renderTrailingComma(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node, - space: Space) (@typeOf(stream).Child.Error || Error)!void -{ - const end_token = base.lastToken() + 1; - switch (tree.tokens.at(end_token).id) { - Token.Id.Comma => { - try renderExpression(allocator, stream, tree, indent, base, Space.None); - try renderToken(tree, stream, end_token, indent, space); // , - }, - Token.Id.LineComment => { - try renderExpression(allocator, stream, tree, indent, base, Space.NoComment); - try stream.write(", "); - try renderToken(tree, stream, end_token, indent, space); - }, - else => { - try renderExpression(allocator, stream, tree, indent, base, Space.None); - try stream.write(",\n"); - assert(space == Space.Newline); - }, - } -} - -fn renderTokenAndTrailingComma(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, space: Space) (@typeOf(stream).Child.Error || Error)!void { - const end_token = token_index + 1; - switch (tree.tokens.at(end_token).id) { - Token.Id.Comma => { - try renderToken(tree, stream, token_index, indent, Space.None); - try renderToken(tree, stream, end_token, indent, space); // , - }, - Token.Id.LineComment => { - try renderToken(tree, stream, token_index, indent, Space.NoComment); - try stream.write(", "); - try renderToken(tree, stream, end_token, indent, space); - }, - else => { - try renderToken(tree, stream, token_index, indent, Space.None); - try stream.write(",\n"); - assert(space == Space.Newline); - }, - } -} From 71badebd08a1e5da9326fc7126c4de0fba4ae3d0 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 21:28:32 -0400 Subject: [PATCH 63/75] zig fmt: respect line breaks after infix operators --- std/zig/parser_test.zig | 17 +++++++++++++++++ std/zig/render.zig | 12 +++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index edf1b002b0..f722c7f08f 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,20 @@ +test "zig fmt: respect line breaks after infix operators" { + try testCanonical( + \\comptime { + \\ self.crc = + \\ lookup_tables[0][p[7]] ^ + \\ lookup_tables[1][p[6]] ^ + \\ lookup_tables[2][p[5]] ^ + \\ lookup_tables[3][p[4]] ^ + \\ lookup_tables[4][@truncate(u8, self.crc >> 24)] ^ + \\ lookup_tables[5][@truncate(u8, self.crc >> 16)] ^ + \\ lookup_tables[6][@truncate(u8, self.crc >> 8)] ^ + \\ lookup_tables[7][@truncate(u8, self.crc >> 0)]; + \\} + \\ + ); +} + test "zig fmt: fn decl with trailing comma" { try testTransform( \\fn foo(a: i32, b: i32,) void {} diff --git a/std/zig/render.zig b/std/zig/render.zig index b8481b1348..56f3d24b8e 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -254,7 +254,17 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind else => Space.Space, }; try renderExpression(allocator, stream, tree, indent, infix_op_node.lhs, op_space); - try renderToken(tree, stream, infix_op_node.op_token, indent, op_space); + + const after_op_space = blk: { + const loc = tree.tokenLocation(tree.tokens.at(infix_op_node.op_token).end, + tree.nextToken(infix_op_node.op_token)); + break :blk if (loc.line == 0) op_space else Space.Newline; + }; + + try renderToken(tree, stream, infix_op_node.op_token, indent, after_op_space); + if (after_op_space == Space.Newline) { + try stream.writeByteNTimes(' ', indent + indent_delta); + } switch (infix_op_node.op) { ast.Node.InfixOp.Op.Catch => |maybe_payload| if (maybe_payload) |payload| { From 77ec81b0353eac45a66b4ed79821c8c954032345 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 22:22:01 -0400 Subject: [PATCH 64/75] zig fmt: respect line breaks in if-else --- std/zig/parser_test.zig | 19 +++++++ std/zig/render.zig | 116 ++++++++++++++++++++++++++++++---------- 2 files changed, 107 insertions(+), 28 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index f722c7f08f..30e7eb3e7c 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,22 @@ +test "zig fmt: respect line breaks in if-else" { + try testCanonical( + \\comptime { + \\ return if (cond) a else b; + \\ return if (cond) + \\ a + \\ else + \\ b; + \\ return if (cond) + \\ a + \\ else if (cond) + \\ b + \\ else + \\ c; + \\} + \\ + ); +} + test "zig fmt: respect line breaks after infix operators" { try testCanonical( \\comptime { diff --git a/std/zig/render.zig b/std/zig/render.zig index 56f3d24b8e..90bc74fd63 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -1315,49 +1315,109 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.If => { const if_node = @fieldParentPtr(ast.Node.If, "base", base); - try renderToken(tree, stream, if_node.if_token, indent, Space.Space); - try renderToken(tree, stream, tree.prevToken(if_node.condition.firstToken()), indent, Space.None); + const lparen = tree.prevToken(if_node.condition.firstToken()); + const rparen = tree.nextToken(if_node.condition.lastToken()); - try renderExpression(allocator, stream, tree, indent, if_node.condition, Space.None); - try renderToken(tree, stream, tree.nextToken(if_node.condition.lastToken()), indent, Space.Space); + try renderToken(tree, stream, if_node.if_token, indent, Space.Space); // if + try renderToken(tree, stream, lparen, indent, Space.None); // ( - if (if_node.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); - } + try renderExpression(allocator, stream, tree, indent, if_node.condition, Space.None); // condition - switch (if_node.body.id) { + const body_is_block = switch (if_node.body.id) { ast.Node.Id.Block, ast.Node.Id.If, ast.Node.Id.For, ast.Node.Id.While, - ast.Node.Id.Switch => { - if (if_node.@"else") |@"else"| { - if (if_node.body.id == ast.Node.Id.Block) { - try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Space); - } else { - try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Newline); - try stream.writeByteNTimes(' ', indent); - } + ast.Node.Id.Switch, + => true, + else => false, + }; - try renderExpression(allocator, stream, tree, indent, &@"else".base, space); - } else { - try renderExpression(allocator, stream, tree, indent, if_node.body, space); - } - }, - else => { - if (if_node.@"else") |@"else"| { - try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Space); - try renderToken(tree, stream, @"else".else_token, indent, Space.Space); + if (body_is_block) { + try renderToken(tree, stream, rparen, indent, Space.Space); // ) + + if (if_node.payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); // |x| + } + + if (if_node.@"else") |@"else"| { + try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Space); + return renderExpression(allocator, stream, tree, indent, &@"else".base, space); + } else { + return renderExpression(allocator, stream, tree, indent, if_node.body, space); + } + } + + const src_has_newline = blk: { + const loc = tree.tokenLocation(tree.tokens.at(rparen).end, if_node.body.lastToken()); + break :blk loc.line != 0; + }; + + if (src_has_newline) { + const after_rparen_space = if (if_node.payload == null) Space.Newline else Space.Space; + try renderToken(tree, stream, rparen, indent, after_rparen_space); // ) + + if (if_node.payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload, Space.Newline); + } + + const new_indent = indent + indent_delta; + try stream.writeByteNTimes(' ', new_indent); + + if (if_node.@"else") |@"else"| { + const else_is_block = switch (@"else".body.id) { + ast.Node.Id.Block, + ast.Node.Id.If, + ast.Node.Id.For, + ast.Node.Id.While, + ast.Node.Id.Switch, + => true, + else => false, + }; + try renderExpression(allocator, stream, tree, new_indent, if_node.body, Space.Newline); + try stream.writeByteNTimes(' ', indent); + + if (else_is_block) { + try renderToken(tree, stream, @"else".else_token, indent, Space.Space); // else if (@"else".payload) |payload| { try renderExpression(allocator, stream, tree, indent, payload, Space.Space); } - try renderExpression(allocator, stream, tree, indent, @"else".body, space); + return renderExpression(allocator, stream, tree, indent, @"else".body, space); } else { - try renderExpression(allocator, stream, tree, indent, if_node.body, space); + const after_else_space = if (@"else".payload == null) Space.Newline else Space.Space; + try renderToken(tree, stream, @"else".else_token, indent, after_else_space); // else + + if (@"else".payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload, Space.Newline); + } + try stream.writeByteNTimes(' ', new_indent); + + return renderExpression(allocator, stream, tree, new_indent, @"else".body, space); } - }, + } else { + return renderExpression(allocator, stream, tree, new_indent, if_node.body, space); + } + } + + try renderToken(tree, stream, rparen, indent, Space.Space); // ) + + if (if_node.payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + } + + if (if_node.@"else") |@"else"| { + try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Space); + try renderToken(tree, stream, @"else".else_token, indent, Space.Space); + + if (@"else".payload) |payload| { + try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + } + + return renderExpression(allocator, stream, tree, indent, @"else".body, space); + } else { + return renderExpression(allocator, stream, tree, indent, if_node.body, space); } }, From 0d1b47362c7623ba923a6831dab0989133caf9ab Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 22:41:05 -0400 Subject: [PATCH 65/75] zig fmt: if-else with comment before else --- std/zig/parser_test.zig | 18 ++++++++++++++++++ std/zig/render.zig | 20 ++++++++++++++------ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 30e7eb3e7c..0f8b2d798a 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,21 @@ +test "zig fmt: if-else with comment before else" { + try testCanonical( + \\comptime { + \\ // cexp(finite|nan +- i inf|nan) = nan + i nan + \\ if ((hx & 0x7fffffff) != 0x7f800000) { + \\ return Complex(f32).new(y - y, y - y); + \\ } // cexp(-inf +- i inf|nan) = 0 + i0 + \\ else if (hx & 0x80000000 != 0) { + \\ return Complex(f32).new(0, 0); + \\ } // cexp(+inf +- i inf|nan) = inf + i nan + \\ else { + \\ return Complex(f32).new(x, y - y); + \\ } + \\} + \\ + ); +} + test "zig fmt: respect line breaks in if-else" { try testCanonical( \\comptime { diff --git a/std/zig/render.zig b/std/zig/render.zig index 90bc74fd63..af8f3f385c 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -1341,7 +1341,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } if (if_node.@"else") |@"else"| { - try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Space); + try renderExpression(allocator, stream, tree, indent, if_node.body, Space.SpaceOrOutdent); return renderExpression(allocator, stream, tree, indent, &@"else".base, space); } else { return renderExpression(allocator, stream, tree, indent, if_node.body, space); @@ -1685,8 +1685,8 @@ const Space = enum { Newline, Comma, Space, + SpaceOrOutdent, NoNewline, - NoIndent, NoComment, }; @@ -1717,7 +1717,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent if (next_token.id != Token.Id.LineComment) { switch (space) { - Space.None, Space.NoNewline, Space.NoIndent => return, + Space.None, Space.NoNewline => return, Space.Newline => { if (next_token.id == Token.Id.MultilineStringLiteralLine) { return; @@ -1725,7 +1725,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent return stream.write("\n"); } }, - Space.Space => return stream.writeByte(' '), + Space.Space, Space.SpaceOrOutdent => return stream.writeByte(' '), Space.NoComment, Space.Comma => unreachable, } } @@ -1756,7 +1756,11 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent }; try stream.writeByteNTimes(' ', next_line_indent); }, - Space.Newline, Space.NoIndent => { + Space.SpaceOrOutdent => { + try stream.writeByte('\n'); + try stream.writeByteNTimes(' ', indent); + }, + Space.Newline => { if (next_token.id == Token.Id.MultilineStringLiteralLine) { return; } else { @@ -1783,7 +1787,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent next_token = tree.tokens.at(token_index + offset); if (next_token.id != Token.Id.LineComment) { switch (space) { - Space.Newline, Space.NoIndent => { + Space.Newline => { if (next_token.id == Token.Id.MultilineStringLiteralLine) { return; } else { @@ -1800,6 +1804,10 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent }; try stream.writeByteNTimes(' ', next_line_indent); }, + Space.SpaceOrOutdent => { + try stream.writeByte('\n'); + try stream.writeByteNTimes(' ', indent); + }, Space.NoNewline => {}, Space.NoComment, Space.Comma => unreachable, } From 530d17542207151f768a14a0cc8311181599b9b9 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 23:41:09 -0400 Subject: [PATCH 66/75] zig fmt: fix spacing when moving doc comment on var decls --- std/zig/parser_test.zig | 39 +++++++++++++++++++++++++-------------- std/zig/render.zig | 33 +++++++++++++++++++++++++-------- 2 files changed, 50 insertions(+), 22 deletions(-) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 0f8b2d798a..0106b990bc 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,28 @@ +test "zig fmt: same-line doc comment on variable declaration" { + try testTransform( + \\pub const MAP_ANONYMOUS = 0x1000; /// allocated from memory, swap space + \\pub const MAP_FILE = 0x0000; /// map from file (default) + \\ + \\pub const EMEDIUMTYPE = 124; /// Wrong medium type + \\ + \\// nameserver query return codes + \\pub const ENSROK = 0; /// DNS server returned answer with no data + , + \\/// allocated from memory, swap space + \\pub const MAP_ANONYMOUS = 0x1000; + \\/// map from file (default) + \\pub const MAP_FILE = 0x0000; + \\ + \\/// Wrong medium type + \\pub const EMEDIUMTYPE = 124; + \\ + \\// nameserver query return codes + \\/// DNS server returned answer with no data + \\pub const ENSROK = 0; + \\ + ); +} + test "zig fmt: if-else with comment before else" { try testCanonical( \\comptime { @@ -557,20 +582,6 @@ test "zig fmt: add comma on last switch prong" { ); } -test "zig fmt: same-line doc comment on variable declaration" { - try testTransform( - \\pub const MAP_ANONYMOUS = 0x1000; /// allocated from memory, swap space - \\pub const MAP_FILE = 0x0000; /// map from file (default) - \\ - , - \\/// allocated from memory, swap space - \\pub const MAP_ANONYMOUS = 0x1000; - \\/// map from file (default) - \\pub const MAP_FILE = 0x0000; - \\ - ); -} - test "zig fmt: same-line comment after a statement" { try testCanonical( \\test "" { diff --git a/std/zig/render.zig b/std/zig/render.zig index af8f3f385c..3248b33aa7 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -39,11 +39,12 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf( } fn renderExtraNewline(tree: &ast.Tree, stream: var, node: &ast.Node) !void { - var first_token = node.firstToken(); - while (tree.tokens.at(first_token - 1).id == Token.Id.DocComment) { - first_token -= 1; + const first_token = node.firstToken(); + var prev_token = first_token; + while (tree.tokens.at(prev_token - 1).id == Token.Id.DocComment) { + prev_token -= 1; } - const prev_token_end = tree.tokens.at(first_token - 1).end; + const prev_token_end = tree.tokens.at(prev_token - 1).end; const loc = tree.tokenLocation(prev_token_end, first_token); if (loc.line >= 2) { try stream.writeByte('\n'); @@ -1715,7 +1716,17 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent else => {}, } - if (next_token.id != Token.Id.LineComment) { + // Skip over same line doc comments + var offset: usize = 1; + if (next_token.id == Token.Id.DocComment) { + const loc = tree.tokenLocationPtr(token.end, next_token); + if (loc.line == 0) { + offset += 1; + next_token = tree.tokens.at(token_index + offset); + } + } + + if (next_token.id != Token.Id.LineComment) blk: { switch (space) { Space.None, Space.NoNewline => return, Space.Newline => { @@ -1739,7 +1750,6 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } var loc = tree.tokenLocationPtr(token.end, next_token); - var offset: usize = 1; if (loc.line == 0) { try stream.print(" {}", mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ")); offset = 2; @@ -1820,8 +1830,15 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@typeOf(stream).Child.Error || Error)!void { const comment = node.doc_comments ?? return; var it = comment.lines.iterator(0); + const first_token = node.firstToken(); while (it.next()) |line_token_index| { - try renderToken(tree, stream, line_token_index.*, indent, Space.Newline); - try stream.writeByteNTimes(' ', indent); + if (line_token_index.* < first_token) { + try renderToken(tree, stream, line_token_index.*, indent, Space.Newline); + try stream.writeByteNTimes(' ', indent); + } else { + try renderToken(tree, stream, line_token_index.*, indent, Space.NoComment); + try stream.write("\n"); + try stream.writeByteNTimes(' ', indent); + } } } From eda6898c5b253367174172db909ee23013f32733 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 29 May 2018 03:15:12 -0400 Subject: [PATCH 67/75] zig fmt: handle if and while indentation better --- std/zig/ast.zig | 24 +- std/zig/parser_test.zig | 92 ++++ std/zig/render.zig | 1077 ++++++++++++++++++++------------------- 3 files changed, 658 insertions(+), 535 deletions(-) diff --git a/std/zig/ast.zig b/std/zig/ast.zig index addd3a37e8..3b705e2ee6 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -68,6 +68,14 @@ pub const Tree = struct { return self.tokenLocationPtr(start_index, self.tokens.at(token_index)); } + pub fn tokensOnSameLine(self: &Tree, token1_index: TokenIndex, token2_index: TokenIndex) bool { + return self.tokensOnSameLinePtr(self.tokens.at(token1_index), self.tokens.at(token2_index)); + } + + pub fn tokensOnSameLinePtr(self: &Tree, token1: &const Token, token2: &const Token) bool { + return mem.indexOfScalar(u8, self.source[token1.end..token2.start], '\n') == null; + } + pub fn dump(self: &Tree) void { self.root_node.base.dump(0); } @@ -1529,14 +1537,14 @@ pub const Node = struct { switch (self.op) { Op.SliceType => |addr_of_info| { - if (addr_of_info.align_expr) |align_expr| { - if (i < 1) return align_expr; + if (addr_of_info.align_info) |align_info| { + if (i < 1) return align_info.node; i -= 1; } }, Op.AddrOf => |addr_of_info| { - if (addr_of_info.align_expr) |align_expr| { - if (i < 1) return align_expr; + if (addr_of_info.align_info) |align_info| { + if (i < 1) return align_info.node; i -= 1; } }, @@ -1553,7 +1561,9 @@ pub const Node = struct { Op.NegationWrap, Op.Try, Op.Resume, - Op.UnwrapMaybe => {}, + Op.UnwrapMaybe, + Op.PointerType, + => {}, } if (i < 1) return self.rhs; @@ -1656,6 +1666,7 @@ pub const Node = struct { if (i < fields.len) return fields.at(i).*; i -= fields.len; }, + Op.Deref => {}, } return null; @@ -2082,9 +2093,6 @@ pub const Node = struct { if (i < self.inputs.len) return &(self.inputs.at(index).*).base; i -= self.inputs.len; - if (i < self.clobbers.len) return self.clobbers.at(index).*; - i -= self.clobbers.len; - return null; } diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 0106b990bc..8ed748ed30 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,95 @@ +test "zig fmt: if condition wraps" { + try testTransform( + \\comptime { + \\ if (cond and + \\ cond) { + \\ return x; + \\ } + \\ while (cond and + \\ cond) { + \\ return x; + \\ } + \\ if (a == b and + \\ c) { + \\ a = b; + \\ } + \\ while (a == b and + \\ c) { + \\ a = b; + \\ } + \\ if ((cond and + \\ cond)) { + \\ return x; + \\ } + \\ while ((cond and + \\ cond)) { + \\ return x; + \\ } + \\ var a = if (a) |*f| x: { + \\ break :x &a.b; + \\ } else |err| err; + \\} + , + \\comptime { + \\ if (cond and + \\ cond) + \\ { + \\ return x; + \\ } + \\ while (cond and + \\ cond) + \\ { + \\ return x; + \\ } + \\ if (a == b and + \\ c) + \\ { + \\ a = b; + \\ } + \\ while (a == b and + \\ c) + \\ { + \\ a = b; + \\ } + \\ if ((cond and + \\ cond)) + \\ { + \\ return x; + \\ } + \\ while ((cond and + \\ cond)) + \\ { + \\ return x; + \\ } + \\ var a = if (a) |*f| x: { + \\ break :x &a.b; + \\ } else |err| err; + \\} + \\ + ); +} + +test "zig fmt: if condition has line break but must not wrap" { + try testCanonical( + \\comptime { + \\ if (self.user_input_options.put(name, UserInputOption{ + \\ .name = name, + \\ .used = false, + \\ }) catch unreachable) |*prev_value| { + \\ foo(); + \\ bar(); + \\ } + \\ if (put( + \\ a, + \\ b, + \\ )) { + \\ foo(); + \\ } + \\} + \\ + ); +} + test "zig fmt: same-line doc comment on variable declaration" { try testTransform( \\pub const MAP_ANONYMOUS = 0x1000; /// allocated from memory, swap space diff --git a/std/zig/render.zig b/std/zig/render.zig index 3248b33aa7..16aed808fc 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -28,17 +28,17 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf( } } - + var start_col: usize = 0; var it = tree.root_node.decls.iterator(0); while (it.next()) |decl| { - try renderTopLevelDecl(allocator, stream, tree, 0, decl.*); + try renderTopLevelDecl(allocator, stream, tree, 0, &start_col, decl.*); if (it.peek()) |next_decl| { - try renderExtraNewline(tree, stream, next_decl.*); + try renderExtraNewline(tree, stream, &start_col, next_decl.*); } } } -fn renderExtraNewline(tree: &ast.Tree, stream: var, node: &ast.Node) !void { +fn renderExtraNewline(tree: &ast.Tree, stream: var, start_col: &usize, node: &ast.Node) !void { const first_token = node.firstToken(); var prev_token = first_token; while (tree.tokens.at(prev_token - 1).id == Token.Id.DocComment) { @@ -48,22 +48,23 @@ fn renderExtraNewline(tree: &ast.Tree, stream: var, node: &ast.Node) !void { const loc = tree.tokenLocation(prev_token_end, first_token); if (loc.line >= 2) { try stream.writeByte('\n'); + start_col.* = 0; } } -fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, decl: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { +fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, decl: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { switch (decl.id) { ast.Node.Id.FnProto => { const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl); - try renderDocComments(tree, stream, fn_proto, indent); + try renderDocComments(tree, stream, fn_proto, indent, start_col); if (fn_proto.body_node) |body_node| { - try renderExpression(allocator, stream, tree, indent, decl, Space.Space); - try renderExpression(allocator, stream, tree, indent, body_node, Space.Newline); + try renderExpression(allocator, stream, tree, indent, start_col, decl, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, body_node, Space.Newline); } else { - try renderExpression(allocator, stream, tree, indent, decl, Space.None); - try renderToken(tree, stream, tree.nextToken(decl.lastToken()), indent, Space.Newline); + try renderExpression(allocator, stream, tree, indent, start_col, decl, Space.None); + try renderToken(tree, stream, tree.nextToken(decl.lastToken()), indent, start_col, Space.Newline); } }, @@ -71,153 +72,154 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i const use_decl = @fieldParentPtr(ast.Node.Use, "base", decl); if (use_decl.visib_token) |visib_token| { - try renderToken(tree, stream, visib_token, indent, Space.Space); // pub + try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub } - try renderToken(tree, stream, use_decl.use_token, indent, Space.Space); // use - try renderExpression(allocator, stream, tree, indent, use_decl.expr, Space.None); - try renderToken(tree, stream, use_decl.semicolon_token, indent, Space.Newline); // ; + try renderToken(tree, stream, use_decl.use_token, indent, start_col, Space.Space); // use + try renderExpression(allocator, stream, tree, indent, start_col, use_decl.expr, Space.None); + try renderToken(tree, stream, use_decl.semicolon_token, indent, start_col, Space.Newline); // ; }, ast.Node.Id.VarDecl => { const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", decl); - try renderDocComments(tree, stream, var_decl, indent); - try renderVarDecl(allocator, stream, tree, indent, var_decl); + try renderDocComments(tree, stream, var_decl, indent, start_col); + try renderVarDecl(allocator, stream, tree, indent, start_col, var_decl); }, ast.Node.Id.TestDecl => { const test_decl = @fieldParentPtr(ast.Node.TestDecl, "base", decl); - try renderDocComments(tree, stream, test_decl, indent); - try renderToken(tree, stream, test_decl.test_token, indent, Space.Space); - try renderExpression(allocator, stream, tree, indent, test_decl.name, Space.Space); - try renderExpression(allocator, stream, tree, indent, test_decl.body_node, Space.Newline); + try renderDocComments(tree, stream, test_decl, indent, start_col); + try renderToken(tree, stream, test_decl.test_token, indent, start_col, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, test_decl.name, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, test_decl.body_node, Space.Newline); }, ast.Node.Id.StructField => { const field = @fieldParentPtr(ast.Node.StructField, "base", decl); - try renderDocComments(tree, stream, field, indent); + try renderDocComments(tree, stream, field, indent, start_col); if (field.visib_token) |visib_token| { - try renderToken(tree, stream, visib_token, indent, Space.Space); // pub + try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub } - try renderToken(tree, stream, field.name_token, indent, Space.None); // name - try renderToken(tree, stream, tree.nextToken(field.name_token), indent, Space.Space); // : - try renderExpression(allocator, stream, tree, indent, field.type_expr, Space.Comma); // type, + try renderToken(tree, stream, field.name_token, indent, start_col, Space.None); // name + try renderToken(tree, stream, tree.nextToken(field.name_token), indent, start_col, Space.Space); // : + try renderExpression(allocator, stream, tree, indent, start_col, field.type_expr, Space.Comma); // type, }, ast.Node.Id.UnionTag => { const tag = @fieldParentPtr(ast.Node.UnionTag, "base", decl); - try renderDocComments(tree, stream, tag, indent); + try renderDocComments(tree, stream, tag, indent, start_col); if (tag.type_expr == null and tag.value_expr == null) { - return renderToken(tree, stream, tag.name_token, indent, Space.Comma); // name, + return renderToken(tree, stream, tag.name_token, indent, start_col, Space.Comma); // name, } if (tag.type_expr == null) { - try renderToken(tree, stream, tag.name_token, indent, Space.Space); // name + try renderToken(tree, stream, tag.name_token, indent, start_col, Space.Space); // name } else { - try renderToken(tree, stream, tag.name_token, indent, Space.None); // name + try renderToken(tree, stream, tag.name_token, indent, start_col, Space.None); // name } if (tag.type_expr) |type_expr| { - try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // : + try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, start_col, Space.Space); // : if (tag.value_expr == null) { - return renderExpression(allocator, stream, tree, indent, type_expr, Space.Comma); // type, + try renderExpression(allocator, stream, tree, indent, start_col, type_expr, Space.Comma); // type, + return; } else { - try renderExpression(allocator, stream, tree, indent, type_expr, Space.Space); // type + try renderExpression(allocator, stream, tree, indent, start_col, type_expr, Space.Space); // type } } const value_expr = ??tag.value_expr; - try renderToken(tree, stream, tree.prevToken(value_expr.firstToken()), indent, Space.Space); // = - try renderExpression(allocator, stream, tree, indent, value_expr, Space.Comma); // value, + try renderToken(tree, stream, tree.prevToken(value_expr.firstToken()), indent, start_col, Space.Space); // = + try renderExpression(allocator, stream, tree, indent, start_col, value_expr, Space.Comma); // value, }, ast.Node.Id.EnumTag => { const tag = @fieldParentPtr(ast.Node.EnumTag, "base", decl); - try renderDocComments(tree, stream, tag, indent); + try renderDocComments(tree, stream, tag, indent, start_col); if (tag.value) |value| { - try renderToken(tree, stream, tag.name_token, indent, Space.Space); // name + try renderToken(tree, stream, tag.name_token, indent, start_col, Space.Space); // name - try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, Space.Space); // = - try renderExpression(allocator, stream, tree, indent, value, Space.Comma); + try renderToken(tree, stream, tree.nextToken(tag.name_token), indent, start_col, Space.Space); // = + try renderExpression(allocator, stream, tree, indent, start_col, value, Space.Comma); } else { - try renderToken(tree, stream, tag.name_token, indent, Space.Comma); // name + try renderToken(tree, stream, tag.name_token, indent, start_col, Space.Comma); // name } }, ast.Node.Id.Comptime => { assert(!decl.requireSemiColon()); - try renderExpression(allocator, stream, tree, indent, decl, Space.Newline); + try renderExpression(allocator, stream, tree, indent, start_col, decl, Space.Newline); }, else => unreachable, } } -fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node, space: Space) (@typeOf(stream).Child.Error || Error)!void { +fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node, space: Space,) (@typeOf(stream).Child.Error || Error)!void { switch (base.id) { ast.Node.Id.Identifier => { const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base); - try renderToken(tree, stream, identifier.token, indent, space); + return renderToken(tree, stream, identifier.token, indent, start_col, space); }, ast.Node.Id.Block => { const block = @fieldParentPtr(ast.Node.Block, "base", base); if (block.label) |label| { - try renderToken(tree, stream, label, indent, Space.None); - try renderToken(tree, stream, tree.nextToken(label), indent, Space.Space); + try renderToken(tree, stream, label, indent, start_col, Space.None); + try renderToken(tree, stream, tree.nextToken(label), indent, start_col, Space.Space); } if (block.statements.len == 0) { - try renderToken(tree, stream, block.lbrace, indent + indent_delta, Space.None); - try renderToken(tree, stream, block.rbrace, indent, space); + try renderToken(tree, stream, block.lbrace, indent + indent_delta, start_col, Space.None); + return renderToken(tree, stream, block.rbrace, indent, start_col, space); } else { const block_indent = indent + indent_delta; - try renderToken(tree, stream, block.lbrace, block_indent, Space.Newline); + try renderToken(tree, stream, block.lbrace, block_indent, start_col, Space.Newline); var it = block.statements.iterator(0); while (it.next()) |statement| { try stream.writeByteNTimes(' ', block_indent); - try renderStatement(allocator, stream, tree, block_indent, statement.*); + try renderStatement(allocator, stream, tree, block_indent, start_col, statement.*); if (it.peek()) |next_statement| { - try renderExtraNewline(tree, stream, next_statement.*); + try renderExtraNewline(tree, stream, start_col, next_statement.*); } } try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, block.rbrace, indent, space); + return renderToken(tree, stream, block.rbrace, indent, start_col, space); } }, ast.Node.Id.Defer => { const defer_node = @fieldParentPtr(ast.Node.Defer, "base", base); - try renderToken(tree, stream, defer_node.defer_token, indent, Space.Space); - try renderExpression(allocator, stream, tree, indent, defer_node.expr, space); + try renderToken(tree, stream, defer_node.defer_token, indent, start_col, Space.Space); + return renderExpression(allocator, stream, tree, indent, start_col, defer_node.expr, space); }, ast.Node.Id.Comptime => { const comptime_node = @fieldParentPtr(ast.Node.Comptime, "base", base); - try renderToken(tree, stream, comptime_node.comptime_token, indent, Space.Space); - try renderExpression(allocator, stream, tree, indent, comptime_node.expr, space); + try renderToken(tree, stream, comptime_node.comptime_token, indent, start_col, Space.Space); + return renderExpression(allocator, stream, tree, indent, start_col, comptime_node.expr, space); }, ast.Node.Id.AsyncAttribute => { const async_attr = @fieldParentPtr(ast.Node.AsyncAttribute, "base", base); if (async_attr.allocator_type) |allocator_type| { - try renderToken(tree, stream, async_attr.async_token, indent, Space.None); + try renderToken(tree, stream, async_attr.async_token, indent, start_col, Space.None); - try renderToken(tree, stream, tree.nextToken(async_attr.async_token), indent, Space.None); - try renderExpression(allocator, stream, tree, indent, allocator_type, Space.None); - try renderToken(tree, stream, tree.nextToken(allocator_type.lastToken()), indent, space); + try renderToken(tree, stream, tree.nextToken(async_attr.async_token), indent, start_col, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, allocator_type, Space.None); + return renderToken(tree, stream, tree.nextToken(allocator_type.lastToken()), indent, start_col, space); } else { - try renderToken(tree, stream, async_attr.async_token, indent, space); + return renderToken(tree, stream, async_attr.async_token, indent, start_col, space); } }, @@ -225,24 +227,24 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base); if (suspend_node.label) |label| { - try renderToken(tree, stream, label, indent, Space.None); - try renderToken(tree, stream, tree.nextToken(label), indent, Space.Space); + try renderToken(tree, stream, label, indent, start_col, Space.None); + try renderToken(tree, stream, tree.nextToken(label), indent, start_col, Space.Space); } if (suspend_node.payload) |payload| { if (suspend_node.body) |body| { - try renderToken(tree, stream, suspend_node.suspend_token, indent, Space.Space); - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); - try renderExpression(allocator, stream, tree, indent, body, space); + try renderToken(tree, stream, suspend_node.suspend_token, indent, start_col, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.Space); + return renderExpression(allocator, stream, tree, indent, start_col, body, space); } else { - try renderToken(tree, stream, suspend_node.suspend_token, indent, Space.Space); - try renderExpression(allocator, stream, tree, indent, payload, space); + try renderToken(tree, stream, suspend_node.suspend_token, indent, start_col, Space.Space); + return renderExpression(allocator, stream, tree, indent, start_col, payload, space); } } else if (suspend_node.body) |body| { - try renderToken(tree, stream, suspend_node.suspend_token, indent, Space.Space); - try renderExpression(allocator, stream, tree, indent, body, space); + try renderToken(tree, stream, suspend_node.suspend_token, indent, start_col, Space.Space); + return renderExpression(allocator, stream, tree, indent, start_col, body, space); } else { - try renderToken(tree, stream, suspend_node.suspend_token, indent, space); + return renderToken(tree, stream, suspend_node.suspend_token, indent, start_col, space); } }, @@ -254,7 +256,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.InfixOp.Op.Period, ast.Node.InfixOp.Op.ErrorUnion, ast.Node.InfixOp.Op.Range => Space.None, else => Space.Space, }; - try renderExpression(allocator, stream, tree, indent, infix_op_node.lhs, op_space); + try renderExpression(allocator, stream, tree, indent, start_col, infix_op_node.lhs, op_space); const after_op_space = blk: { const loc = tree.tokenLocation(tree.tokens.at(infix_op_node.op_token).end, @@ -262,19 +264,20 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind break :blk if (loc.line == 0) op_space else Space.Newline; }; - try renderToken(tree, stream, infix_op_node.op_token, indent, after_op_space); + try renderToken(tree, stream, infix_op_node.op_token, indent, start_col, after_op_space); if (after_op_space == Space.Newline) { try stream.writeByteNTimes(' ', indent + indent_delta); + start_col.* = indent + indent_delta; } switch (infix_op_node.op) { ast.Node.InfixOp.Op.Catch => |maybe_payload| if (maybe_payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.Space); }, else => {}, } - try renderExpression(allocator, stream, tree, indent, infix_op_node.rhs, space); + return renderExpression(allocator, stream, tree, indent, start_col, infix_op_node.rhs, space); }, ast.Node.Id.PrefixOp => { @@ -282,81 +285,81 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind switch (prefix_op_node.op) { ast.Node.PrefixOp.Op.AddrOf => |addr_of_info| { - try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // & + try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); // & if (addr_of_info.align_info) |align_info| { const lparen_token = tree.prevToken(align_info.node.firstToken()); const align_token = tree.prevToken(lparen_token); - try renderToken(tree, stream, align_token, indent, Space.None); // align - try renderToken(tree, stream, lparen_token, indent, Space.None); // ( + try renderToken(tree, stream, align_token, indent, start_col, Space.None); // align + try renderToken(tree, stream, lparen_token, indent, start_col, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, align_info.node, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, align_info.node, Space.None); if (align_info.bit_range) |bit_range| { const colon1 = tree.prevToken(bit_range.start.firstToken()); const colon2 = tree.prevToken(bit_range.end.firstToken()); - try renderToken(tree, stream, colon1, indent, Space.None); // : - try renderExpression(allocator, stream, tree, indent, bit_range.start, Space.None); - try renderToken(tree, stream, colon2, indent, Space.None); // : - try renderExpression(allocator, stream, tree, indent, bit_range.end, Space.None); + try renderToken(tree, stream, colon1, indent, start_col, Space.None); // : + try renderExpression(allocator, stream, tree, indent, start_col, bit_range.start, Space.None); + try renderToken(tree, stream, colon2, indent, start_col, Space.None); // : + try renderExpression(allocator, stream, tree, indent, start_col, bit_range.end, Space.None); const rparen_token = tree.nextToken(bit_range.end.lastToken()); - try renderToken(tree, stream, rparen_token, indent, Space.Space); // ) + try renderToken(tree, stream, rparen_token, indent, start_col, Space.Space); // ) } else { const rparen_token = tree.nextToken(align_info.node.lastToken()); - try renderToken(tree, stream, rparen_token, indent, Space.Space); // ) + try renderToken(tree, stream, rparen_token, indent, start_col, Space.Space); // ) } } if (addr_of_info.const_token) |const_token| { - try renderToken(tree, stream, const_token, indent, Space.Space); // const + try renderToken(tree, stream, const_token, indent, start_col, Space.Space); // const } if (addr_of_info.volatile_token) |volatile_token| { - try renderToken(tree, stream, volatile_token, indent, Space.Space); // volatile + try renderToken(tree, stream, volatile_token, indent, start_col, Space.Space); // volatile } }, ast.Node.PrefixOp.Op.SliceType => |addr_of_info| { - try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // [ - try renderToken(tree, stream, tree.nextToken(prefix_op_node.op_token), indent, Space.None); // ] + try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); // [ + try renderToken(tree, stream, tree.nextToken(prefix_op_node.op_token), indent, start_col, Space.None); // ] if (addr_of_info.align_info) |align_info| { const lparen_token = tree.prevToken(align_info.node.firstToken()); const align_token = tree.prevToken(lparen_token); - try renderToken(tree, stream, align_token, indent, Space.None); // align - try renderToken(tree, stream, lparen_token, indent, Space.None); // ( + try renderToken(tree, stream, align_token, indent, start_col, Space.None); // align + try renderToken(tree, stream, lparen_token, indent, start_col, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, align_info.node, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, align_info.node, Space.None); if (align_info.bit_range) |bit_range| { const colon1 = tree.prevToken(bit_range.start.firstToken()); const colon2 = tree.prevToken(bit_range.end.firstToken()); - try renderToken(tree, stream, colon1, indent, Space.None); // : - try renderExpression(allocator, stream, tree, indent, bit_range.start, Space.None); - try renderToken(tree, stream, colon2, indent, Space.None); // : - try renderExpression(allocator, stream, tree, indent, bit_range.end, Space.None); + try renderToken(tree, stream, colon1, indent, start_col, Space.None); // : + try renderExpression(allocator, stream, tree, indent, start_col, bit_range.start, Space.None); + try renderToken(tree, stream, colon2, indent, start_col, Space.None); // : + try renderExpression(allocator, stream, tree, indent, start_col, bit_range.end, Space.None); const rparen_token = tree.nextToken(bit_range.end.lastToken()); - try renderToken(tree, stream, rparen_token, indent, Space.Space); // ) + try renderToken(tree, stream, rparen_token, indent, start_col, Space.Space); // ) } else { const rparen_token = tree.nextToken(align_info.node.lastToken()); - try renderToken(tree, stream, rparen_token, indent, Space.Space); // ) + try renderToken(tree, stream, rparen_token, indent, start_col, Space.Space); // ) } } if (addr_of_info.const_token) |const_token| { - try renderToken(tree, stream, const_token, indent, Space.Space); + try renderToken(tree, stream, const_token, indent, start_col, Space.Space); } if (addr_of_info.volatile_token) |volatile_token| { - try renderToken(tree, stream, volatile_token, indent, Space.Space); + try renderToken(tree, stream, volatile_token, indent, start_col, Space.Space); } }, ast.Node.PrefixOp.Op.ArrayType => |array_index| { - try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); // [ - try renderExpression(allocator, stream, tree, indent, array_index, Space.None); - try renderToken(tree, stream, tree.nextToken(array_index.lastToken()), indent, Space.None); // ] + try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); // [ + try renderExpression(allocator, stream, tree, indent, start_col, array_index, Space.None); + try renderToken(tree, stream, tree.nextToken(array_index.lastToken()), indent, start_col, Space.None); // ] }, ast.Node.PrefixOp.Op.BitNot, ast.Node.PrefixOp.Op.BoolNot, @@ -365,18 +368,18 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.PrefixOp.Op.UnwrapMaybe, ast.Node.PrefixOp.Op.MaybeType, ast.Node.PrefixOp.Op.PointerType => { - try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.None); + try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); }, ast.Node.PrefixOp.Op.Try, ast.Node.PrefixOp.Op.Await, ast.Node.PrefixOp.Op.Cancel, ast.Node.PrefixOp.Op.Resume => { - try renderToken(tree, stream, prefix_op_node.op_token, indent, Space.Space); + try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.Space); }, } - try renderExpression(allocator, stream, tree, indent, prefix_op_node.rhs, space); + return renderExpression(allocator, stream, tree, indent, start_col, prefix_op_node.rhs, space); }, ast.Node.Id.SuffixOp => { @@ -385,17 +388,16 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind switch (suffix_op.op) { @TagType(ast.Node.SuffixOp.Op).Call => |*call_info| { if (call_info.async_attr) |async_attr| { - try renderExpression(allocator, stream, tree, indent, &async_attr.base, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, &async_attr.base, Space.Space); } - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); const lparen = tree.nextToken(suffix_op.lhs.lastToken()); if (call_info.params.len == 0) { - try renderToken(tree, stream, lparen, indent, Space.None); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + try renderToken(tree, stream, lparen, indent, start_col, Space.None); + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } const src_has_trailing_comma = blk: { @@ -405,7 +407,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind if (src_has_trailing_comma) { const new_indent = indent + indent_delta; - try renderToken(tree, stream, lparen, new_indent, Space.Newline); + try renderToken(tree, stream, lparen, new_indent, start_col, Space.Newline); var it = call_info.params.iterator(0); while (true) { @@ -419,72 +421,70 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind }; if (it.peek()) |next_node| { - try renderExpression(allocator, stream, tree, param_node_new_indent, param_node.*, Space.None); + try renderExpression(allocator, stream, tree, param_node_new_indent, start_col, param_node.*, Space.None); const comma = tree.nextToken(param_node.*.lastToken()); - try renderToken(tree, stream, comma, new_indent, Space.Newline); // , - try renderExtraNewline(tree, stream, next_node.*); + try renderToken(tree, stream, comma, new_indent, start_col, Space.Newline); // , + try renderExtraNewline(tree, stream, start_col, next_node.*); } else { - try renderExpression(allocator, stream, tree, param_node_new_indent, param_node.*, Space.Comma); + try renderExpression(allocator, stream, tree, param_node_new_indent, start_col, param_node.*, Space.Comma); try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } } } - try renderToken(tree, stream, lparen, indent, Space.None); // ( + try renderToken(tree, stream, lparen, indent, start_col, Space.None); // ( var it = call_info.params.iterator(0); while (it.next()) |param_node| { - try renderExpression(allocator, stream, tree, indent, param_node.*, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, param_node.*, Space.None); if (it.peek() != null) { const comma = tree.nextToken(param_node.*.lastToken()); - try renderToken(tree, stream, comma, indent, Space.Space); + try renderToken(tree, stream, comma, indent, start_col, Space.Space); } } - try renderToken(tree, stream, suffix_op.rtoken, indent, space); + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); }, ast.Node.SuffixOp.Op.ArrayAccess => |index_expr| { const lbracket = tree.prevToken(index_expr.firstToken()); const rbracket = tree.nextToken(index_expr.lastToken()); - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); - try renderToken(tree, stream, lbracket, indent, Space.None); // [ - try renderExpression(allocator, stream, tree, indent, index_expr, Space.None); - try renderToken(tree, stream, rbracket, indent, space); // ] + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbracket, indent, start_col, Space.None); // [ + try renderExpression(allocator, stream, tree, indent, start_col, index_expr, Space.None); + return renderToken(tree, stream, rbracket, indent, start_col, space); // ] }, ast.Node.SuffixOp.Op.Deref => { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); - try renderToken(tree, stream, tree.prevToken(suffix_op.rtoken), indent, Space.None); // . - try renderToken(tree, stream, suffix_op.rtoken, indent, space); // * + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); + try renderToken(tree, stream, tree.prevToken(suffix_op.rtoken), indent, start_col, Space.None); // . + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); // * }, @TagType(ast.Node.SuffixOp.Op).Slice => |range| { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); const lbracket = tree.prevToken(range.start.firstToken()); const dotdot = tree.nextToken(range.start.lastToken()); - try renderToken(tree, stream, lbracket, indent, Space.None); // [ - try renderExpression(allocator, stream, tree, indent, range.start, Space.None); - try renderToken(tree, stream, dotdot, indent, Space.None); // .. + try renderToken(tree, stream, lbracket, indent, start_col, Space.None); // [ + try renderExpression(allocator, stream, tree, indent, start_col, range.start, Space.None); + try renderToken(tree, stream, dotdot, indent, start_col, Space.None); // .. if (range.end) |end| { - try renderExpression(allocator, stream, tree, indent, end, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, end, Space.None); } - try renderToken(tree, stream, suffix_op.rtoken, indent, space); // ] + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); // ] }, ast.Node.SuffixOp.Op.StructInitializer => |*field_inits| { const lbrace = tree.nextToken(suffix_op.lhs.lastToken()); if (field_inits.len == 0) { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); - try renderToken(tree, stream, lbrace, indent, Space.None); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, start_col, Space.None); + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } if (field_inits.len == 1) blk: { @@ -496,11 +496,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } } - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); - try renderToken(tree, stream, lbrace, indent, Space.Space); - try renderExpression(allocator, stream, tree, indent, &field_init.base, Space.Space); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, start_col, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, &field_init.base, Space.Space); + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } const src_has_trailing_comma = blk: { @@ -515,27 +514,26 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind if (!src_has_trailing_comma and src_same_line) { // render all on one line, no trailing comma - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); - try renderToken(tree, stream, lbrace, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, start_col, Space.Space); var it = field_inits.iterator(0); while (it.next()) |field_init| { if (it.peek() != null) { - try renderExpression(allocator, stream, tree, indent, field_init.*, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, field_init.*, Space.None); const comma = tree.nextToken(field_init.*.lastToken()); - try renderToken(tree, stream, comma, indent, Space.Space); + try renderToken(tree, stream, comma, indent, start_col, Space.Space); } else { - try renderExpression(allocator, stream, tree, indent, field_init.*, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, field_init.*, Space.Space); } } - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); - try renderToken(tree, stream, lbrace, indent, Space.Newline); + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, start_col, Space.Newline); const new_indent = indent + indent_delta; @@ -544,41 +542,39 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.writeByteNTimes(' ', new_indent); if (it.peek()) |next_field_init| { - try renderExpression(allocator, stream, tree, new_indent, field_init.*, Space.None); + try renderExpression(allocator, stream, tree, new_indent, start_col, field_init.*, Space.None); const comma = tree.nextToken(field_init.*.lastToken()); - try renderToken(tree, stream, comma, new_indent, Space.Newline); + try renderToken(tree, stream, comma, new_indent, start_col, Space.Newline); - try renderExtraNewline(tree, stream, next_field_init.*); + try renderExtraNewline(tree, stream, start_col, next_field_init.*); } else { - try renderExpression(allocator, stream, tree, new_indent, field_init.*, Space.Comma); + try renderExpression(allocator, stream, tree, new_indent, start_col, field_init.*, Space.Comma); } } try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); }, ast.Node.SuffixOp.Op.ArrayInitializer => |*exprs| { const lbrace = tree.nextToken(suffix_op.lhs.lastToken()); if (exprs.len == 0) { - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); - try renderToken(tree, stream, lbrace, indent, Space.None); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, start_col, Space.None); + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } if (exprs.len == 1) { const expr = exprs.at(0).*; - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); - try renderToken(tree, stream, lbrace, indent, Space.None); - try renderExpression(allocator, stream, tree, indent, expr, Space.None); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); + try renderToken(tree, stream, lbrace, indent, start_col, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, expr, Space.None); + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } - try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); // scan to find row size const maybe_row_size: ?usize = blk: { @@ -613,50 +609,48 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind if (maybe_row_size) |row_size| { const new_indent = indent + indent_delta; - try renderToken(tree, stream, lbrace, new_indent, Space.Newline); + try renderToken(tree, stream, lbrace, new_indent, start_col, Space.Newline); try stream.writeByteNTimes(' ', new_indent); var it = exprs.iterator(0); var i: usize = 1; while (it.next()) |expr| { if (it.peek()) |next_expr| { - try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.None); + try renderExpression(allocator, stream, tree, new_indent, start_col, expr.*, Space.None); const comma = tree.nextToken(expr.*.lastToken()); if (i != row_size) { - try renderToken(tree, stream, comma, new_indent, Space.Space); // , + try renderToken(tree, stream, comma, new_indent, start_col, Space.Space); // , i += 1; continue; } i = 1; - try renderToken(tree, stream, comma, new_indent, Space.Newline); // , + try renderToken(tree, stream, comma, new_indent, start_col, Space.Newline); // , - try renderExtraNewline(tree, stream, next_expr.*); + try renderExtraNewline(tree, stream, start_col, next_expr.*); try stream.writeByteNTimes(' ', new_indent); } else { - try renderExpression(allocator, stream, tree, new_indent, expr.*, Space.Comma); // , + try renderExpression(allocator, stream, tree, new_indent, start_col, expr.*, Space.Comma); // , } } try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } else { - try renderToken(tree, stream, lbrace, indent, Space.Space); + try renderToken(tree, stream, lbrace, indent, start_col, Space.Space); var it = exprs.iterator(0); while (it.next()) |expr| { if (it.peek()) |next_expr| { - try renderExpression(allocator, stream, tree, indent, expr.*, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, expr.*, Space.None); const comma = tree.nextToken(expr.*.lastToken()); - try renderToken(tree, stream, comma, indent, Space.Space); // , + try renderToken(tree, stream, comma, indent, start_col, Space.Space); // , } else { - try renderExpression(allocator, stream, tree, indent, expr.*, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, expr.*, Space.Space); } } - try renderToken(tree, stream, suffix_op.rtoken, indent, space); - return; + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); } }, } @@ -667,195 +661,204 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind switch (flow_expr.kind) { ast.Node.ControlFlowExpression.Kind.Break => |maybe_label| { - const kw_space = if (maybe_label != null or flow_expr.rhs != null) Space.Space else space; - try renderToken(tree, stream, flow_expr.ltoken, indent, kw_space); + if (maybe_label == null and flow_expr.rhs == null) { + return renderToken(tree, stream, flow_expr.ltoken, indent, start_col, space); // break + } + + try renderToken(tree, stream, flow_expr.ltoken, indent, start_col, Space.Space); // break if (maybe_label) |label| { const colon = tree.nextToken(flow_expr.ltoken); - try renderToken(tree, stream, colon, indent, Space.None); + try renderToken(tree, stream, colon, indent, start_col, Space.None); // : - const expr_space = if (flow_expr.rhs != null) Space.Space else space; - try renderExpression(allocator, stream, tree, indent, label, expr_space); + if (flow_expr.rhs == null) { + return renderExpression(allocator, stream, tree, indent, start_col, label, space); // label + } + try renderExpression(allocator, stream, tree, indent, start_col, label, Space.Space); // label } }, ast.Node.ControlFlowExpression.Kind.Continue => |maybe_label| { - const kw_space = if (maybe_label != null or flow_expr.rhs != null) Space.Space else space; - try renderToken(tree, stream, flow_expr.ltoken, indent, kw_space); + assert(flow_expr.rhs == null); + + if (maybe_label == null and flow_expr.rhs == null) { + return renderToken(tree, stream, flow_expr.ltoken, indent, start_col, space); // continue + } + + try renderToken(tree, stream, flow_expr.ltoken, indent, start_col, Space.Space); // continue if (maybe_label) |label| { const colon = tree.nextToken(flow_expr.ltoken); - try renderToken(tree, stream, colon, indent, Space.None); + try renderToken(tree, stream, colon, indent, start_col, Space.None); // : - const expr_space = if (flow_expr.rhs != null) Space.Space else space; - try renderExpression(allocator, stream, tree, indent, label, space); + return renderExpression(allocator, stream, tree, indent, start_col, label, space); } }, ast.Node.ControlFlowExpression.Kind.Return => { - const kw_space = if (flow_expr.rhs != null) Space.Space else space; - try renderToken(tree, stream, flow_expr.ltoken, indent, kw_space); + if (flow_expr.rhs == null) { + return renderToken(tree, stream, flow_expr.ltoken, indent, start_col, space); + } + try renderToken(tree, stream, flow_expr.ltoken, indent, start_col, Space.Space); }, } - if (flow_expr.rhs) |rhs| { - try renderExpression(allocator, stream, tree, indent, rhs, space); - } + return renderExpression(allocator, stream, tree, indent, start_col, ??flow_expr.rhs, space); }, ast.Node.Id.Payload => { const payload = @fieldParentPtr(ast.Node.Payload, "base", base); - try renderToken(tree, stream, payload.lpipe, indent, Space.None); - try renderExpression(allocator, stream, tree, indent, payload.error_symbol, Space.None); - try renderToken(tree, stream, payload.rpipe, indent, space); + try renderToken(tree, stream, payload.lpipe, indent, start_col, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, payload.error_symbol, Space.None); + return renderToken(tree, stream, payload.rpipe, indent, start_col, space); }, ast.Node.Id.PointerPayload => { const payload = @fieldParentPtr(ast.Node.PointerPayload, "base", base); - try renderToken(tree, stream, payload.lpipe, indent, Space.None); + try renderToken(tree, stream, payload.lpipe, indent, start_col, Space.None); if (payload.ptr_token) |ptr_token| { - try renderToken(tree, stream, ptr_token, indent, Space.None); + try renderToken(tree, stream, ptr_token, indent, start_col, Space.None); } - try renderExpression(allocator, stream, tree, indent, payload.value_symbol, Space.None); - try renderToken(tree, stream, payload.rpipe, indent, space); + try renderExpression(allocator, stream, tree, indent, start_col, payload.value_symbol, Space.None); + return renderToken(tree, stream, payload.rpipe, indent, start_col, space); }, ast.Node.Id.PointerIndexPayload => { const payload = @fieldParentPtr(ast.Node.PointerIndexPayload, "base", base); - try renderToken(tree, stream, payload.lpipe, indent, Space.None); + try renderToken(tree, stream, payload.lpipe, indent, start_col, Space.None); if (payload.ptr_token) |ptr_token| { - try renderToken(tree, stream, ptr_token, indent, Space.None); + try renderToken(tree, stream, ptr_token, indent, start_col, Space.None); } - try renderExpression(allocator, stream, tree, indent, payload.value_symbol, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, payload.value_symbol, Space.None); if (payload.index_symbol) |index_symbol| { const comma = tree.nextToken(payload.value_symbol.lastToken()); - try renderToken(tree, stream, comma, indent, Space.Space); - try renderExpression(allocator, stream, tree, indent, index_symbol, Space.None); + try renderToken(tree, stream, comma, indent, start_col, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, index_symbol, Space.None); } - try renderToken(tree, stream, payload.rpipe, indent, space); + return renderToken(tree, stream, payload.rpipe, indent, start_col, space); }, ast.Node.Id.GroupedExpression => { const grouped_expr = @fieldParentPtr(ast.Node.GroupedExpression, "base", base); - try renderToken(tree, stream, grouped_expr.lparen, indent, Space.None); - try renderExpression(allocator, stream, tree, indent, grouped_expr.expr, Space.None); - try renderToken(tree, stream, grouped_expr.rparen, indent, space); + try renderToken(tree, stream, grouped_expr.lparen, indent, start_col, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, grouped_expr.expr, Space.None); + return renderToken(tree, stream, grouped_expr.rparen, indent, start_col, space); }, ast.Node.Id.FieldInitializer => { const field_init = @fieldParentPtr(ast.Node.FieldInitializer, "base", base); - try renderToken(tree, stream, field_init.period_token, indent, Space.None); // . - try renderToken(tree, stream, field_init.name_token, indent, Space.Space); // name - try renderToken(tree, stream, tree.nextToken(field_init.name_token), indent, Space.Space); // = - try renderExpression(allocator, stream, tree, indent, field_init.expr, space); + try renderToken(tree, stream, field_init.period_token, indent, start_col, Space.None); // . + try renderToken(tree, stream, field_init.name_token, indent, start_col, Space.Space); // name + try renderToken(tree, stream, tree.nextToken(field_init.name_token), indent, start_col, Space.Space); // = + return renderExpression(allocator, stream, tree, indent, start_col, field_init.expr, space); }, ast.Node.Id.IntegerLiteral => { const integer_literal = @fieldParentPtr(ast.Node.IntegerLiteral, "base", base); - try renderToken(tree, stream, integer_literal.token, indent, space); + return renderToken(tree, stream, integer_literal.token, indent, start_col, space); }, ast.Node.Id.FloatLiteral => { const float_literal = @fieldParentPtr(ast.Node.FloatLiteral, "base", base); - try renderToken(tree, stream, float_literal.token, indent, space); + return renderToken(tree, stream, float_literal.token, indent, start_col, space); }, ast.Node.Id.StringLiteral => { const string_literal = @fieldParentPtr(ast.Node.StringLiteral, "base", base); - try renderToken(tree, stream, string_literal.token, indent, space); + return renderToken(tree, stream, string_literal.token, indent, start_col, space); }, ast.Node.Id.CharLiteral => { const char_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); - try renderToken(tree, stream, char_literal.token, indent, space); + return renderToken(tree, stream, char_literal.token, indent, start_col, space); }, ast.Node.Id.BoolLiteral => { const bool_literal = @fieldParentPtr(ast.Node.CharLiteral, "base", base); - try renderToken(tree, stream, bool_literal.token, indent, space); + return renderToken(tree, stream, bool_literal.token, indent, start_col, space); }, ast.Node.Id.NullLiteral => { const null_literal = @fieldParentPtr(ast.Node.NullLiteral, "base", base); - try renderToken(tree, stream, null_literal.token, indent, space); + return renderToken(tree, stream, null_literal.token, indent, start_col, space); }, ast.Node.Id.ThisLiteral => { const this_literal = @fieldParentPtr(ast.Node.ThisLiteral, "base", base); - try renderToken(tree, stream, this_literal.token, indent, space); + return renderToken(tree, stream, this_literal.token, indent, start_col, space); }, ast.Node.Id.Unreachable => { const unreachable_node = @fieldParentPtr(ast.Node.Unreachable, "base", base); - try renderToken(tree, stream, unreachable_node.token, indent, space); + return renderToken(tree, stream, unreachable_node.token, indent, start_col, space); }, ast.Node.Id.ErrorType => { const error_type = @fieldParentPtr(ast.Node.ErrorType, "base", base); - try renderToken(tree, stream, error_type.token, indent, space); + return renderToken(tree, stream, error_type.token, indent, start_col, space); }, ast.Node.Id.VarType => { const var_type = @fieldParentPtr(ast.Node.VarType, "base", base); - try renderToken(tree, stream, var_type.token, indent, space); + return renderToken(tree, stream, var_type.token, indent, start_col, space); }, ast.Node.Id.ContainerDecl => { const container_decl = @fieldParentPtr(ast.Node.ContainerDecl, "base", base); if (container_decl.layout_token) |layout_token| { - try renderToken(tree, stream, layout_token, indent, Space.Space); + try renderToken(tree, stream, layout_token, indent, start_col, Space.Space); } switch (container_decl.init_arg_expr) { ast.Node.ContainerDecl.InitArg.None => { - try renderToken(tree, stream, container_decl.kind_token, indent, Space.Space); // union + try renderToken(tree, stream, container_decl.kind_token, indent, start_col, Space.Space); // union }, ast.Node.ContainerDecl.InitArg.Enum => |enum_tag_type| { - try renderToken(tree, stream, container_decl.kind_token, indent, Space.None); // union + try renderToken(tree, stream, container_decl.kind_token, indent, start_col, Space.None); // union const lparen = tree.nextToken(container_decl.kind_token); const enum_token = tree.nextToken(lparen); - try renderToken(tree, stream, lparen, indent, Space.None); // ( - try renderToken(tree, stream, enum_token, indent, Space.None); // enum + try renderToken(tree, stream, lparen, indent, start_col, Space.None); // ( + try renderToken(tree, stream, enum_token, indent, start_col, Space.None); // enum if (enum_tag_type) |expr| { - try renderToken(tree, stream, tree.nextToken(enum_token), indent, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, expr, Space.None); + try renderToken(tree, stream, tree.nextToken(enum_token), indent, start_col, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, start_col, expr, Space.None); const rparen = tree.nextToken(expr.lastToken()); - try renderToken(tree, stream, rparen, indent, Space.None); // ) - try renderToken(tree, stream, tree.nextToken(rparen), indent, Space.Space); // ) + try renderToken(tree, stream, rparen, indent, start_col, Space.None); // ) + try renderToken(tree, stream, tree.nextToken(rparen), indent, start_col, Space.Space); // ) } else { - try renderToken(tree, stream, tree.nextToken(enum_token), indent, Space.Space); // ) + try renderToken(tree, stream, tree.nextToken(enum_token), indent, start_col, Space.Space); // ) } }, ast.Node.ContainerDecl.InitArg.Type => |type_expr| { - try renderToken(tree, stream, container_decl.kind_token, indent, Space.None); // union + try renderToken(tree, stream, container_decl.kind_token, indent, start_col, Space.None); // union const lparen = tree.nextToken(container_decl.kind_token); const rparen = tree.nextToken(type_expr.lastToken()); - try renderToken(tree, stream, lparen, indent, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, type_expr, Space.None); - try renderToken(tree, stream, rparen, indent, Space.Space); // ) + try renderToken(tree, stream, lparen, indent, start_col, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, start_col, type_expr, Space.None); + try renderToken(tree, stream, rparen, indent, start_col, Space.Space); // ) }, } if (container_decl.fields_and_decls.len == 0) { - try renderToken(tree, stream, container_decl.lbrace_token, indent + indent_delta, Space.None); // { - try renderToken(tree, stream, container_decl.rbrace_token, indent, space); // } + try renderToken(tree, stream, container_decl.lbrace_token, indent + indent_delta, start_col, Space.None); // { + return renderToken(tree, stream, container_decl.rbrace_token, indent, start_col, space); // } } else { const new_indent = indent + indent_delta; - try renderToken(tree, stream, container_decl.lbrace_token, new_indent, Space.Newline); // { + try renderToken(tree, stream, container_decl.lbrace_token, new_indent, start_col, Space.Newline); // { var it = container_decl.fields_and_decls.iterator(0); while (it.next()) |decl| { try stream.writeByteNTimes(' ', new_indent); - try renderTopLevelDecl(allocator, stream, tree, new_indent, decl.*); + try renderTopLevelDecl(allocator, stream, tree, new_indent, start_col, decl.*); if (it.peek()) |next_decl| { - try renderExtraNewline(tree, stream, next_decl.*); + try renderExtraNewline(tree, stream, start_col, next_decl.*); } } try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, container_decl.rbrace_token, indent, space); // } + return renderToken(tree, stream, container_decl.rbrace_token, indent, start_col, space); // } } }, @@ -865,10 +868,9 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const lbrace = tree.nextToken(err_set_decl.error_token); if (err_set_decl.decls.len == 0) { - try renderToken(tree, stream, err_set_decl.error_token, indent, Space.None); - try renderToken(tree, stream, lbrace, indent, Space.None); - try renderToken(tree, stream, err_set_decl.rbrace_token, indent, space); - return; + try renderToken(tree, stream, err_set_decl.error_token, indent, start_col, Space.None); + try renderToken(tree, stream, lbrace, indent, start_col, Space.None); + return renderToken(tree, stream, err_set_decl.rbrace_token, indent, start_col, space); } if (err_set_decl.decls.len == 1) blk: { @@ -882,15 +884,14 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind break :blk; } - try renderToken(tree, stream, err_set_decl.error_token, indent, Space.None); // error - try renderToken(tree, stream, lbrace, indent, Space.None); // { - try renderExpression(allocator, stream, tree, indent, node, Space.None); - try renderToken(tree, stream, err_set_decl.rbrace_token, indent, space); // } - return; + try renderToken(tree, stream, err_set_decl.error_token, indent, start_col, Space.None); // error + try renderToken(tree, stream, lbrace, indent, start_col, Space.None); // { + try renderExpression(allocator, stream, tree, indent, start_col, node, Space.None); + return renderToken(tree, stream, err_set_decl.rbrace_token, indent, start_col, space); // } } - try renderToken(tree, stream, err_set_decl.error_token, indent, Space.None); // error - try renderToken(tree, stream, lbrace, indent, Space.Newline); // { + try renderToken(tree, stream, err_set_decl.error_token, indent, start_col, Space.None); // error + try renderToken(tree, stream, lbrace, indent, start_col, Space.Newline); // { const new_indent = indent + indent_delta; var it = err_set_decl.decls.iterator(0); @@ -898,24 +899,24 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.writeByteNTimes(' ', new_indent); if (it.peek()) |next_node| { - try renderExpression(allocator, stream, tree, new_indent, node.*, Space.None); - try renderToken(tree, stream, tree.nextToken(node.*.lastToken()), new_indent, Space.Newline); // , + try renderExpression(allocator, stream, tree, new_indent, start_col, node.*, Space.None); + try renderToken(tree, stream, tree.nextToken(node.*.lastToken()), new_indent, start_col, Space.Newline); // , - try renderExtraNewline(tree, stream, next_node.*); + try renderExtraNewline(tree, stream, start_col, next_node.*); } else { - try renderExpression(allocator, stream, tree, new_indent, node.*, Space.Comma); + try renderExpression(allocator, stream, tree, new_indent, start_col, node.*, Space.Comma); } } try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, err_set_decl.rbrace_token, indent, space); // } + return renderToken(tree, stream, err_set_decl.rbrace_token, indent, start_col, space); // } }, ast.Node.Id.ErrorTag => { const tag = @fieldParentPtr(ast.Node.ErrorTag, "base", base); - try renderDocComments(tree, stream, tag, indent); - try renderToken(tree, stream, tag.name_token, indent, space); // name + try renderDocComments(tree, stream, tag, indent, start_col); + return renderToken(tree, stream, tag.name_token, indent, start_col, space); // name }, ast.Node.Id.MultilineStringLiteral => { @@ -933,32 +934,32 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind if (!skip_first_indent) { try stream.writeByteNTimes(' ', indent + indent_delta); } - try renderToken(tree, stream, t, indent, Space.None); + try renderToken(tree, stream, t, indent, start_col, Space.None); skip_first_indent = false; } try stream.writeByteNTimes(' ', indent); }, ast.Node.Id.UndefinedLiteral => { const undefined_literal = @fieldParentPtr(ast.Node.UndefinedLiteral, "base", base); - try renderToken(tree, stream, undefined_literal.token, indent, space); + return renderToken(tree, stream, undefined_literal.token, indent, start_col, space); }, ast.Node.Id.BuiltinCall => { const builtin_call = @fieldParentPtr(ast.Node.BuiltinCall, "base", base); - try renderToken(tree, stream, builtin_call.builtin_token, indent, Space.None); // @name - try renderToken(tree, stream, tree.nextToken(builtin_call.builtin_token), indent, Space.None); // ( + try renderToken(tree, stream, builtin_call.builtin_token, indent, start_col, Space.None); // @name + try renderToken(tree, stream, tree.nextToken(builtin_call.builtin_token), indent, start_col, Space.None); // ( var it = builtin_call.params.iterator(0); while (it.next()) |param_node| { - try renderExpression(allocator, stream, tree, indent, param_node.*, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, param_node.*, Space.None); if (it.peek() != null) { const comma_token = tree.nextToken(param_node.*.lastToken()); - try renderToken(tree, stream, comma_token, indent, Space.Space); // , + try renderToken(tree, stream, comma_token, indent, start_col, Space.Space); // , } } - try renderToken(tree, stream, builtin_call.rparen_token, indent, space); // ) + return renderToken(tree, stream, builtin_call.rparen_token, indent, start_col, space); // ) }, ast.Node.Id.FnProto => { @@ -968,31 +969,31 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const visib_token = tree.tokens.at(visib_token_index); assert(visib_token.id == Token.Id.Keyword_pub or visib_token.id == Token.Id.Keyword_export); - try renderToken(tree, stream, visib_token_index, indent, Space.Space); // pub + try renderToken(tree, stream, visib_token_index, indent, start_col, Space.Space); // pub } if (fn_proto.extern_export_inline_token) |extern_export_inline_token| { - try renderToken(tree, stream, extern_export_inline_token, indent, Space.Space); // extern/export + try renderToken(tree, stream, extern_export_inline_token, indent, start_col, Space.Space); // extern/export } if (fn_proto.lib_name) |lib_name| { - try renderExpression(allocator, stream, tree, indent, lib_name, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, lib_name, Space.Space); } if (fn_proto.cc_token) |cc_token| { - try renderToken(tree, stream, cc_token, indent, Space.Space); // stdcallcc + try renderToken(tree, stream, cc_token, indent, start_col, Space.Space); // stdcallcc } if (fn_proto.async_attr) |async_attr| { - try renderExpression(allocator, stream, tree, indent, &async_attr.base, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, &async_attr.base, Space.Space); } const lparen = if (fn_proto.name_token) |name_token| blk: { - try renderToken(tree, stream, fn_proto.fn_token, indent, Space.Space); // fn - try renderToken(tree, stream, name_token, indent, Space.None); // name + try renderToken(tree, stream, fn_proto.fn_token, indent, start_col, Space.Space); // fn + try renderToken(tree, stream, name_token, indent, start_col, Space.None); // name break :blk tree.nextToken(name_token); } else blk: { - try renderToken(tree, stream, fn_proto.fn_token, indent, Space.None); // fn + try renderToken(tree, stream, fn_proto.fn_token, indent, start_col, Space.None); // fn break :blk tree.nextToken(fn_proto.fn_token); }; @@ -1011,51 +1012,51 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind }; if (!src_params_trailing_comma and src_params_same_line) { - try renderToken(tree, stream, lparen, indent, Space.None); // ( + try renderToken(tree, stream, lparen, indent, start_col, Space.None); // ( // render all on one line, no trailing comma var it = fn_proto.params.iterator(0); while (it.next()) |param_decl_node| { - try renderParamDecl(allocator, stream, tree, indent, param_decl_node.*, Space.None); + try renderParamDecl(allocator, stream, tree, indent, start_col, param_decl_node.*, Space.None); if (it.peek() != null) { const comma = tree.nextToken(param_decl_node.*.lastToken()); - try renderToken(tree, stream, comma, indent, Space.Space); // , + try renderToken(tree, stream, comma, indent, start_col, Space.Space); // , } } } else { // one param per line const new_indent = indent + indent_delta; - try renderToken(tree, stream, lparen, new_indent, Space.Newline); // ( + try renderToken(tree, stream, lparen, new_indent, start_col, Space.Newline); // ( var it = fn_proto.params.iterator(0); while (it.next()) |param_decl_node| { try stream.writeByteNTimes(' ', new_indent); - try renderParamDecl(allocator, stream, tree, indent, param_decl_node.*, Space.Comma); + try renderParamDecl(allocator, stream, tree, indent, start_col, param_decl_node.*, Space.Comma); } try stream.writeByteNTimes(' ', indent); } - try renderToken(tree, stream, rparen, indent, Space.Space); // ) + try renderToken(tree, stream, rparen, indent, start_col, Space.Space); // ) if (fn_proto.align_expr) |align_expr| { const align_rparen = tree.nextToken(align_expr.lastToken()); const align_lparen = tree.prevToken(align_expr.firstToken()); const align_kw = tree.prevToken(align_lparen); - try renderToken(tree, stream, align_kw, indent, Space.None); // align - try renderToken(tree, stream, align_lparen, indent, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, align_expr, Space.None); - try renderToken(tree, stream, align_rparen, indent, Space.Space); // ) + try renderToken(tree, stream, align_kw, indent, start_col, Space.None); // align + try renderToken(tree, stream, align_lparen, indent, start_col, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, start_col, align_expr, Space.None); + try renderToken(tree, stream, align_rparen, indent, start_col, Space.Space); // ) } switch (fn_proto.return_type) { ast.Node.FnProto.ReturnType.Explicit => |node| { - try renderExpression(allocator, stream, tree, indent, node, space); + return renderExpression(allocator, stream, tree, indent, start_col, node, space); }, ast.Node.FnProto.ReturnType.InferErrorSet => |node| { - try renderToken(tree, stream, tree.prevToken(node.firstToken()), indent, Space.None); // ! - try renderExpression(allocator, stream, tree, indent, node, space); + try renderToken(tree, stream, tree.prevToken(node.firstToken()), indent, start_col, Space.None); // ! + return renderExpression(allocator, stream, tree, indent, start_col, node, space); }, } }, @@ -1064,11 +1065,11 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const promise_type = @fieldParentPtr(ast.Node.PromiseType, "base", base); if (promise_type.result) |result| { - try renderToken(tree, stream, promise_type.promise_token, indent, Space.None); // promise - try renderToken(tree, stream, result.arrow_token, indent, Space.None); // -> - try renderExpression(allocator, stream, tree, indent, result.return_type, space); + try renderToken(tree, stream, promise_type.promise_token, indent, start_col, Space.None); // promise + try renderToken(tree, stream, result.arrow_token, indent, start_col, Space.None); // -> + return renderExpression(allocator, stream, tree, indent, start_col, result.return_type, space); } else { - try renderToken(tree, stream, promise_type.promise_token, indent, space); // promise + return renderToken(tree, stream, promise_type.promise_token, indent, start_col, space); // promise } }, @@ -1077,39 +1078,38 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.Switch => { const switch_node = @fieldParentPtr(ast.Node.Switch, "base", base); - try renderToken(tree, stream, switch_node.switch_token, indent, Space.Space); // switch - try renderToken(tree, stream, tree.nextToken(switch_node.switch_token), indent, Space.None); // ( + try renderToken(tree, stream, switch_node.switch_token, indent, start_col, Space.Space); // switch + try renderToken(tree, stream, tree.nextToken(switch_node.switch_token), indent, start_col, Space.None); // ( const rparen = tree.nextToken(switch_node.expr.lastToken()); const lbrace = tree.nextToken(rparen); if (switch_node.cases.len == 0) { - try renderExpression(allocator, stream, tree, indent, switch_node.expr, Space.None); - try renderToken(tree, stream, rparen, indent, Space.Space); // ) - try renderToken(tree, stream, lbrace, indent, Space.None); // { - try renderToken(tree, stream, switch_node.rbrace, indent, space); // } - return; + try renderExpression(allocator, stream, tree, indent, start_col, switch_node.expr, Space.None); + try renderToken(tree, stream, rparen, indent, start_col, Space.Space); // ) + try renderToken(tree, stream, lbrace, indent, start_col, Space.None); // { + return renderToken(tree, stream, switch_node.rbrace, indent, start_col, space); // } } - try renderExpression(allocator, stream, tree, indent, switch_node.expr, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, switch_node.expr, Space.None); const new_indent = indent + indent_delta; - try renderToken(tree, stream, rparen, indent, Space.Space); // ) - try renderToken(tree, stream, lbrace, new_indent, Space.Newline); // { + try renderToken(tree, stream, rparen, indent, start_col, Space.Space); // ) + try renderToken(tree, stream, lbrace, new_indent, start_col, Space.Newline); // { var it = switch_node.cases.iterator(0); while (it.next()) |node| { try stream.writeByteNTimes(' ', new_indent); - try renderExpression(allocator, stream, tree, new_indent, node.*, Space.Comma); + try renderExpression(allocator, stream, tree, new_indent, start_col, node.*, Space.Comma); if (it.peek()) |next_node| { - try renderExtraNewline(tree, stream, next_node.*); + try renderExtraNewline(tree, stream, start_col, next_node.*); } } try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, switch_node.rbrace, indent, space); // } + return renderToken(tree, stream, switch_node.rbrace, indent, start_col, space); // } }, ast.Node.Id.SwitchCase => { @@ -1126,13 +1126,13 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind var it = switch_case.items.iterator(0); while (it.next()) |node| { if (it.peek()) |next_node| { - try renderExpression(allocator, stream, tree, indent, node.*, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, node.*, Space.None); const comma_token = tree.nextToken(node.*.lastToken()); - try renderToken(tree, stream, comma_token, indent, Space.Space); // , - try renderExtraNewline(tree, stream, next_node.*); + try renderToken(tree, stream, comma_token, indent, start_col, Space.Space); // , + try renderExtraNewline(tree, stream, start_col, next_node.*); } else { - try renderExpression(allocator, stream, tree, indent, node.*, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, node.*, Space.Space); } } } else { @@ -1140,85 +1140,97 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind while (true) { const node = ??it.next(); if (it.peek()) |next_node| { - try renderExpression(allocator, stream, tree, indent, node.*, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, node.*, Space.None); const comma_token = tree.nextToken(node.*.lastToken()); - try renderToken(tree, stream, comma_token, indent, Space.Newline); // , - try renderExtraNewline(tree, stream, next_node.*); + try renderToken(tree, stream, comma_token, indent, start_col, Space.Newline); // , + try renderExtraNewline(tree, stream, start_col, next_node.*); try stream.writeByteNTimes(' ', indent); } else { - try renderExpression(allocator, stream, tree, indent, node.*, Space.Comma); + try renderExpression(allocator, stream, tree, indent, start_col, node.*, Space.Comma); try stream.writeByteNTimes(' ', indent); break; } } } - try renderToken(tree, stream, switch_case.arrow_token, indent, Space.Space); // => + try renderToken(tree, stream, switch_case.arrow_token, indent, start_col, Space.Space); // => if (switch_case.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.Space); } - try renderExpression(allocator, stream, tree, indent, switch_case.expr, space); + return renderExpression(allocator, stream, tree, indent, start_col, switch_case.expr, space); }, ast.Node.Id.SwitchElse => { const switch_else = @fieldParentPtr(ast.Node.SwitchElse, "base", base); - try renderToken(tree, stream, switch_else.token, indent, space); + return renderToken(tree, stream, switch_else.token, indent, start_col, space); }, ast.Node.Id.Else => { const else_node = @fieldParentPtr(ast.Node.Else, "base", base); - const block_body = switch (else_node.body.id) { - ast.Node.Id.Block, - ast.Node.Id.If, - ast.Node.Id.For, - ast.Node.Id.While, - ast.Node.Id.Switch => true, - else => false, - }; + const body_is_block = nodeIsBlock(else_node.body); + const same_line = body_is_block or tree.tokensOnSameLine(else_node.else_token, else_node.body.lastToken()); - const after_else_space = if (block_body or else_node.payload != null) Space.Space else Space.Newline; - try renderToken(tree, stream, else_node.else_token, indent, after_else_space); + const after_else_space = if (same_line or else_node.payload != null) Space.Space else Space.Newline; + try renderToken(tree, stream, else_node.else_token, indent, start_col, after_else_space); if (else_node.payload) |payload| { - const payload_space = if (block_body) Space.Space else Space.Newline; - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + const payload_space = if (same_line) Space.Space else Space.Newline; + try renderExpression(allocator, stream, tree, indent, start_col, payload, payload_space); } - if (block_body) { - try renderExpression(allocator, stream, tree, indent, else_node.body, space); - } else { - try stream.writeByteNTimes(' ', indent + indent_delta); - try renderExpression(allocator, stream, tree, indent, else_node.body, space); + if (same_line) { + return renderExpression(allocator, stream, tree, indent, start_col, else_node.body, space); } + + try stream.writeByteNTimes(' ', indent + indent_delta); + start_col.* = indent + indent_delta; + return renderExpression(allocator, stream, tree, indent, start_col, else_node.body, space); }, ast.Node.Id.While => { const while_node = @fieldParentPtr(ast.Node.While, "base", base); if (while_node.label) |label| { - try renderToken(tree, stream, label, indent, Space.None); // label - try renderToken(tree, stream, tree.nextToken(label), indent, Space.Space); // : + try renderToken(tree, stream, label, indent, start_col, Space.None); // label + try renderToken(tree, stream, tree.nextToken(label), indent, start_col, Space.Space); // : } if (while_node.inline_token) |inline_token| { - try renderToken(tree, stream, inline_token, indent, Space.Space); // inline + try renderToken(tree, stream, inline_token, indent, start_col, Space.Space); // inline } - try renderToken(tree, stream, while_node.while_token, indent, Space.Space); // while - try renderToken(tree, stream, tree.nextToken(while_node.while_token), indent, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, while_node.condition, Space.None); + try renderToken(tree, stream, while_node.while_token, indent, start_col, Space.Space); // while + try renderToken(tree, stream, tree.nextToken(while_node.while_token), indent, start_col, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, start_col, while_node.condition, Space.None); + + const cond_rparen = tree.nextToken(while_node.condition.lastToken()); + + const body_is_block = nodeIsBlock(while_node.body); + + var block_start_space: Space = undefined; + var after_body_space: Space = undefined; + + if (body_is_block) { + block_start_space = Space.BlockStart; + after_body_space = if (while_node.@"else" == null) space else Space.SpaceOrOutdent; + } else if (tree.tokensOnSameLine(cond_rparen, while_node.body.lastToken())) { + block_start_space = Space.Space; + after_body_space = if (while_node.@"else" == null) space else Space.Space; + } else { + block_start_space = Space.Newline; + after_body_space = if (while_node.@"else" == null) space else Space.Newline; + } { - const rparen = tree.nextToken(while_node.condition.lastToken()); - const rparen_space = if (while_node.payload != null or while_node.continue_expr != null or - while_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; - try renderToken(tree, stream, rparen, indent, rparen_space); // ) + const rparen_space = if (while_node.payload != null or while_node.continue_expr != null) Space.Space else block_start_space; + try renderToken(tree, stream, cond_rparen, indent, start_col, rparen_space); // ) } if (while_node.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + const payload_space = if (while_node.continue_expr != null) Space.Space else block_start_space; + try renderExpression(allocator, stream, tree, indent, start_col, payload, payload_space); } if (while_node.continue_expr) |continue_expr| { @@ -1226,37 +1238,29 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const lparen = tree.prevToken(continue_expr.firstToken()); const colon = tree.prevToken(lparen); - try renderToken(tree, stream, colon, indent, Space.Space); // : - try renderToken(tree, stream, lparen, indent, Space.None); // ( + try renderToken(tree, stream, colon, indent, start_col, Space.Space); // : + try renderToken(tree, stream, lparen, indent, start_col, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, continue_expr, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, continue_expr, Space.None); - const rparen_space = if (while_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; - try renderToken(tree, stream, rparen, indent, rparen_space); // ) + try renderToken(tree, stream, rparen, indent, start_col, block_start_space); // ) } - const body_space = blk: { - if (while_node.@"else" != null) { - break :blk if (while_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; - } else { - break :blk space; - } - }; - - if (while_node.body.id == ast.Node.Id.Block) { - try renderExpression(allocator, stream, tree, indent, while_node.body, body_space); - } else { - try stream.writeByteNTimes(' ', indent + indent_delta); - try renderExpression(allocator, stream, tree, indent, while_node.body, body_space); + var new_indent = indent; + if (block_start_space == Space.Newline) { + new_indent += indent_delta; + try stream.writeByteNTimes(' ', new_indent); + start_col.* = new_indent; } + try renderExpression(allocator, stream, tree, indent, start_col, while_node.body, after_body_space); + if (while_node.@"else") |@"else"| { - if (while_node.body.id == ast.Node.Id.Block) { - } else { + if (after_body_space == Space.Newline) { try stream.writeByteNTimes(' ', indent); + start_col.* = indent; } - - try renderExpression(allocator, stream, tree, indent, &@"else".base, space); + return renderExpression(allocator, stream, tree, indent, start_col, &@"else".base, space); } }, @@ -1264,26 +1268,26 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const for_node = @fieldParentPtr(ast.Node.For, "base", base); if (for_node.label) |label| { - try renderToken(tree, stream, label, indent, Space.None); // label - try renderToken(tree, stream, tree.nextToken(label), indent, Space.Space); // : + try renderToken(tree, stream, label, indent, start_col, Space.None); // label + try renderToken(tree, stream, tree.nextToken(label), indent, start_col, Space.Space); // : } if (for_node.inline_token) |inline_token| { - try renderToken(tree, stream, inline_token, indent, Space.Space); // inline + try renderToken(tree, stream, inline_token, indent, start_col, Space.Space); // inline } - try renderToken(tree, stream, for_node.for_token, indent, Space.Space); // for - try renderToken(tree, stream, tree.nextToken(for_node.for_token), indent, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, for_node.array_expr, Space.None); + try renderToken(tree, stream, for_node.for_token, indent, start_col, Space.Space); // for + try renderToken(tree, stream, tree.nextToken(for_node.for_token), indent, start_col, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, start_col, for_node.array_expr, Space.None); const rparen = tree.nextToken(for_node.array_expr.lastToken()); const rparen_space = if (for_node.payload != null or for_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; - try renderToken(tree, stream, rparen, indent, rparen_space); // ) + try renderToken(tree, stream, rparen, indent, start_col, rparen_space); // ) if (for_node.payload) |payload| { const payload_space = if (for_node.body.id == ast.Node.Id.Block) Space.Space else Space.Newline; - try renderExpression(allocator, stream, tree, indent, payload, payload_space); + try renderExpression(allocator, stream, tree, indent, start_col, payload, payload_space); } const body_space = blk: { @@ -1298,10 +1302,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } }; if (for_node.body.id == ast.Node.Id.Block) { - try renderExpression(allocator, stream, tree, indent, for_node.body, body_space); + try renderExpression(allocator, stream, tree, indent, start_col, for_node.body, body_space); } else { try stream.writeByteNTimes(' ', indent + indent_delta); - try renderExpression(allocator, stream, tree, indent, for_node.body, body_space); + try renderExpression(allocator, stream, tree, indent, start_col, for_node.body, body_space); } if (for_node.@"else") |@"else"| { @@ -1309,7 +1313,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try stream.writeByteNTimes(' ', indent); } - try renderExpression(allocator, stream, tree, indent, &@"else".base, space); + return renderExpression(allocator, stream, tree, indent, start_col, &@"else".base, space); } }, @@ -1319,128 +1323,109 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const lparen = tree.prevToken(if_node.condition.firstToken()); const rparen = tree.nextToken(if_node.condition.lastToken()); - try renderToken(tree, stream, if_node.if_token, indent, Space.Space); // if - try renderToken(tree, stream, lparen, indent, Space.None); // ( + try renderToken(tree, stream, if_node.if_token, indent, start_col, Space.Space); // if + try renderToken(tree, stream, lparen, indent, start_col, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, if_node.condition, Space.None); // condition + try renderExpression(allocator, stream, tree, indent, start_col, if_node.condition, Space.None); // condition - const body_is_block = switch (if_node.body.id) { - ast.Node.Id.Block, - ast.Node.Id.If, - ast.Node.Id.For, - ast.Node.Id.While, - ast.Node.Id.Switch, - => true, - else => false, - }; + const body_is_block = nodeIsBlock(if_node.body); if (body_is_block) { - try renderToken(tree, stream, rparen, indent, Space.Space); // ) + const after_rparen_space = if (if_node.payload == null) Space.BlockStart else Space.Space; + try renderToken(tree, stream, rparen, indent, start_col, after_rparen_space); // ) if (if_node.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); // |x| + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.BlockStart); // |x| } if (if_node.@"else") |@"else"| { - try renderExpression(allocator, stream, tree, indent, if_node.body, Space.SpaceOrOutdent); - return renderExpression(allocator, stream, tree, indent, &@"else".base, space); + try renderExpression(allocator, stream, tree, indent, start_col, if_node.body, Space.SpaceOrOutdent); + return renderExpression(allocator, stream, tree, indent, start_col, &@"else".base, space); } else { - return renderExpression(allocator, stream, tree, indent, if_node.body, space); + return renderExpression(allocator, stream, tree, indent, start_col, if_node.body, space); } } - const src_has_newline = blk: { - const loc = tree.tokenLocation(tree.tokens.at(rparen).end, if_node.body.lastToken()); - break :blk loc.line != 0; - }; + const src_has_newline = !tree.tokensOnSameLine(rparen, if_node.body.lastToken()); if (src_has_newline) { const after_rparen_space = if (if_node.payload == null) Space.Newline else Space.Space; - try renderToken(tree, stream, rparen, indent, after_rparen_space); // ) + try renderToken(tree, stream, rparen, indent, start_col, after_rparen_space); // ) if (if_node.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Newline); + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.Newline); } const new_indent = indent + indent_delta; try stream.writeByteNTimes(' ', new_indent); if (if_node.@"else") |@"else"| { - const else_is_block = switch (@"else".body.id) { - ast.Node.Id.Block, - ast.Node.Id.If, - ast.Node.Id.For, - ast.Node.Id.While, - ast.Node.Id.Switch, - => true, - else => false, - }; - try renderExpression(allocator, stream, tree, new_indent, if_node.body, Space.Newline); + const else_is_block = nodeIsBlock(@"else".body); + try renderExpression(allocator, stream, tree, new_indent, start_col, if_node.body, Space.Newline); try stream.writeByteNTimes(' ', indent); if (else_is_block) { - try renderToken(tree, stream, @"else".else_token, indent, Space.Space); // else + try renderToken(tree, stream, @"else".else_token, indent, start_col, Space.Space); // else if (@"else".payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.Space); } - return renderExpression(allocator, stream, tree, indent, @"else".body, space); + return renderExpression(allocator, stream, tree, indent, start_col, @"else".body, space); } else { const after_else_space = if (@"else".payload == null) Space.Newline else Space.Space; - try renderToken(tree, stream, @"else".else_token, indent, after_else_space); // else + try renderToken(tree, stream, @"else".else_token, indent, start_col, after_else_space); // else if (@"else".payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Newline); + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.Newline); } try stream.writeByteNTimes(' ', new_indent); - return renderExpression(allocator, stream, tree, new_indent, @"else".body, space); + return renderExpression(allocator, stream, tree, new_indent, start_col, @"else".body, space); } } else { - return renderExpression(allocator, stream, tree, new_indent, if_node.body, space); + return renderExpression(allocator, stream, tree, new_indent, start_col, if_node.body, space); } } - try renderToken(tree, stream, rparen, indent, Space.Space); // ) + try renderToken(tree, stream, rparen, indent, start_col, Space.Space); // ) if (if_node.payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.Space); } if (if_node.@"else") |@"else"| { - try renderExpression(allocator, stream, tree, indent, if_node.body, Space.Space); - try renderToken(tree, stream, @"else".else_token, indent, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, if_node.body, Space.Space); + try renderToken(tree, stream, @"else".else_token, indent, start_col, Space.Space); if (@"else".payload) |payload| { - try renderExpression(allocator, stream, tree, indent, payload, Space.Space); + try renderExpression(allocator, stream, tree, indent, start_col, payload, Space.Space); } - return renderExpression(allocator, stream, tree, indent, @"else".body, space); + return renderExpression(allocator, stream, tree, indent, start_col, @"else".body, space); } else { - return renderExpression(allocator, stream, tree, indent, if_node.body, space); + return renderExpression(allocator, stream, tree, indent, start_col, if_node.body, space); } }, ast.Node.Id.Asm => { const asm_node = @fieldParentPtr(ast.Node.Asm, "base", base); - try renderToken(tree, stream, asm_node.asm_token, indent, Space.Space); // asm + try renderToken(tree, stream, asm_node.asm_token, indent, start_col, Space.Space); // asm if (asm_node.volatile_token) |volatile_token| { - try renderToken(tree, stream, volatile_token, indent, Space.Space); // volatile - try renderToken(tree, stream, tree.nextToken(volatile_token), indent, Space.None); // ( + try renderToken(tree, stream, volatile_token, indent, start_col, Space.Space); // volatile + try renderToken(tree, stream, tree.nextToken(volatile_token), indent, start_col, Space.None); // ( } else { - try renderToken(tree, stream, tree.nextToken(asm_node.asm_token), indent, Space.None); // ( + try renderToken(tree, stream, tree.nextToken(asm_node.asm_token), indent, start_col, Space.None); // ( } if (asm_node.outputs.len == 0 and asm_node.inputs.len == 0 and asm_node.clobbers.len == 0) { - try renderExpression(allocator, stream, tree, indent, asm_node.template, Space.None); - try renderToken(tree, stream, asm_node.rparen, indent, space); - return; + try renderExpression(allocator, stream, tree, indent, start_col, asm_node.template, Space.None); + return renderToken(tree, stream, asm_node.rparen, indent, start_col, space); } - try renderExpression(allocator, stream, tree, indent, asm_node.template, Space.Newline); + try renderExpression(allocator, stream, tree, indent, start_col, asm_node.template, Space.Newline); const indent_once = indent + indent_delta; try stream.writeByteNTimes(' ', indent_once); @@ -1449,12 +1434,12 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const indent_extra = indent_once + 2; const colon2 = if (asm_node.outputs.len == 0) blk: { - try renderToken(tree, stream, colon1, indent, Space.Newline); // : + try renderToken(tree, stream, colon1, indent, start_col, Space.Newline); // : try stream.writeByteNTimes(' ', indent_once); break :blk tree.nextToken(colon1); } else blk: { - try renderToken(tree, stream, colon1, indent, Space.Space); // : + try renderToken(tree, stream, colon1, indent, start_col, Space.Space); // : var it = asm_node.outputs.iterator(0); while (true) { @@ -1462,21 +1447,20 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const node = &(asm_output.*).base; if (it.peek()) |next_asm_output| { - try renderExpression(allocator, stream, tree, indent_extra, node, Space.None); + try renderExpression(allocator, stream, tree, indent_extra, start_col, node, Space.None); const next_node = &(next_asm_output.*).base; const comma = tree.prevToken(next_asm_output.*.firstToken()); - try renderToken(tree, stream, comma, indent_extra, Space.Newline); // , - try renderExtraNewline(tree, stream, next_node); + try renderToken(tree, stream, comma, indent_extra, start_col, Space.Newline); // , + try renderExtraNewline(tree, stream, start_col, next_node); try stream.writeByteNTimes(' ', indent_extra); } else if (asm_node.inputs.len == 0 and asm_node.clobbers.len == 0) { - try renderExpression(allocator, stream, tree, indent_extra, node, Space.Newline); + try renderExpression(allocator, stream, tree, indent_extra, start_col, node, Space.Newline); try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, asm_node.rparen, indent, space); - return; + return renderToken(tree, stream, asm_node.rparen, indent, start_col, space); } else { - try renderExpression(allocator, stream, tree, indent_extra, node, Space.Newline); + try renderExpression(allocator, stream, tree, indent_extra, start_col, node, Space.Newline); try stream.writeByteNTimes(' ', indent_once); const comma_or_colon = tree.nextToken(node.lastToken()); break :blk switch (tree.tokens.at(comma_or_colon).id) { @@ -1488,12 +1472,12 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind }; const colon3 = if (asm_node.inputs.len == 0) blk: { - try renderToken(tree, stream, colon2, indent, Space.Newline); // : + try renderToken(tree, stream, colon2, indent, start_col, Space.Newline); // : try stream.writeByteNTimes(' ', indent_once); break :blk tree.nextToken(colon2); } else blk: { - try renderToken(tree, stream, colon2, indent, Space.Space); // : + try renderToken(tree, stream, colon2, indent, start_col, Space.Space); // : var it = asm_node.inputs.iterator(0); while (true) { @@ -1501,21 +1485,20 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const node = &(asm_input.*).base; if (it.peek()) |next_asm_input| { - try renderExpression(allocator, stream, tree, indent_extra, node, Space.None); + try renderExpression(allocator, stream, tree, indent_extra, start_col, node, Space.None); const next_node = &(next_asm_input.*).base; const comma = tree.prevToken(next_asm_input.*.firstToken()); - try renderToken(tree, stream, comma, indent_extra, Space.Newline); // , - try renderExtraNewline(tree, stream, next_node); + try renderToken(tree, stream, comma, indent_extra, start_col, Space.Newline); // , + try renderExtraNewline(tree, stream, start_col, next_node); try stream.writeByteNTimes(' ', indent_extra); } else if (asm_node.clobbers.len == 0) { - try renderExpression(allocator, stream, tree, indent_extra, node, Space.Newline); + try renderExpression(allocator, stream, tree, indent_extra, start_col, node, Space.Newline); try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, asm_node.rparen, indent, space); // ) - return; + return renderToken(tree, stream, asm_node.rparen, indent, start_col, space); // ) } else { - try renderExpression(allocator, stream, tree, indent_extra, node, Space.Newline); + try renderExpression(allocator, stream, tree, indent_extra, start_col, node, Space.Newline); try stream.writeByteNTimes(' ', indent_once); const comma_or_colon = tree.nextToken(node.lastToken()); break :blk switch (tree.tokens.at(comma_or_colon).id) { @@ -1526,21 +1509,20 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } }; - try renderToken(tree, stream, colon3, indent, Space.Space); // : + try renderToken(tree, stream, colon3, indent, start_col, Space.Space); // : var it = asm_node.clobbers.iterator(0); while (true) { const clobber_token = ??it.next(); if (it.peek() == null) { - try renderToken(tree, stream, clobber_token.*, indent_once, Space.Newline); + try renderToken(tree, stream, clobber_token.*, indent_once, start_col, Space.Newline); try stream.writeByteNTimes(' ', indent); - try renderToken(tree, stream, asm_node.rparen, indent, space); - return; + return renderToken(tree, stream, asm_node.rparen, indent, start_col, space); } else { - try renderToken(tree, stream, clobber_token.*, indent_once, Space.None); + try renderToken(tree, stream, clobber_token.*, indent_once, start_col, Space.None); const comma = tree.nextToken(clobber_token.*); - try renderToken(tree, stream, comma, indent_once, Space.Space); // , + try renderToken(tree, stream, comma, indent_once, start_col, Space.Space); // , } } }, @@ -1549,34 +1531,34 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const asm_input = @fieldParentPtr(ast.Node.AsmInput, "base", base); try stream.write("["); - try renderExpression(allocator, stream, tree, indent, asm_input.symbolic_name, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, asm_input.symbolic_name, Space.None); try stream.write("] "); - try renderExpression(allocator, stream, tree, indent, asm_input.constraint, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, asm_input.constraint, Space.None); try stream.write(" ("); - try renderExpression(allocator, stream, tree, indent, asm_input.expr, Space.None); - try renderToken(tree, stream, asm_input.lastToken(), indent, space); // ) + try renderExpression(allocator, stream, tree, indent, start_col, asm_input.expr, Space.None); + return renderToken(tree, stream, asm_input.lastToken(), indent, start_col, space); // ) }, ast.Node.Id.AsmOutput => { const asm_output = @fieldParentPtr(ast.Node.AsmOutput, "base", base); try stream.write("["); - try renderExpression(allocator, stream, tree, indent, asm_output.symbolic_name, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, asm_output.symbolic_name, Space.None); try stream.write("] "); - try renderExpression(allocator, stream, tree, indent, asm_output.constraint, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, asm_output.constraint, Space.None); try stream.write(" ("); switch (asm_output.kind) { ast.Node.AsmOutput.Kind.Variable => |variable_name| { - try renderExpression(allocator, stream, tree, indent, &variable_name.base, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, &variable_name.base, Space.None); }, ast.Node.AsmOutput.Kind.Return => |return_type| { try stream.write("-> "); - try renderExpression(allocator, stream, tree, indent, return_type, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, return_type, Space.None); }, } - try renderToken(tree, stream, asm_output.lastToken(), indent, space); // ) + return renderToken(tree, stream, asm_output.lastToken(), indent, start_col, space); // ) }, ast.Node.Id.StructField, @@ -1590,92 +1572,92 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind } } -fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, - var_decl: &ast.Node.VarDecl) (@typeOf(stream).Child.Error || Error)!void +fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, + var_decl: &ast.Node.VarDecl,) (@typeOf(stream).Child.Error || Error)!void { if (var_decl.visib_token) |visib_token| { - try renderToken(tree, stream, visib_token, indent, Space.Space); // pub + try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub } if (var_decl.extern_export_token) |extern_export_token| { - try renderToken(tree, stream, extern_export_token, indent, Space.Space); // extern + try renderToken(tree, stream, extern_export_token, indent, start_col, Space.Space); // extern if (var_decl.lib_name) |lib_name| { - try renderExpression(allocator, stream, tree, indent, lib_name, Space.Space); // "lib" + try renderExpression(allocator, stream, tree, indent, start_col, lib_name, Space.Space); // "lib" } } if (var_decl.comptime_token) |comptime_token| { - try renderToken(tree, stream, comptime_token, indent, Space.Space); // comptime + try renderToken(tree, stream, comptime_token, indent, start_col, Space.Space); // comptime } - try renderToken(tree, stream, var_decl.mut_token, indent, Space.Space); // var + try renderToken(tree, stream, var_decl.mut_token, indent, start_col, Space.Space); // var const name_space = if (var_decl.type_node == null and (var_decl.align_node != null or var_decl.init_node != null)) Space.Space else Space.None; - try renderToken(tree, stream, var_decl.name_token, indent, name_space); + try renderToken(tree, stream, var_decl.name_token, indent, start_col, name_space); if (var_decl.type_node) |type_node| { - try renderToken(tree, stream, tree.nextToken(var_decl.name_token), indent, Space.Space); + try renderToken(tree, stream, tree.nextToken(var_decl.name_token), indent, start_col, Space.Space); const s = if (var_decl.align_node != null or var_decl.init_node != null) Space.Space else Space.None; - try renderExpression(allocator, stream, tree, indent, type_node, s); + try renderExpression(allocator, stream, tree, indent, start_col, type_node, s); } if (var_decl.align_node) |align_node| { const lparen = tree.prevToken(align_node.firstToken()); const align_kw = tree.prevToken(lparen); const rparen = tree.nextToken(align_node.lastToken()); - try renderToken(tree, stream, align_kw, indent, Space.None); // align - try renderToken(tree, stream, lparen, indent, Space.None); // ( - try renderExpression(allocator, stream, tree, indent, align_node, Space.None); + try renderToken(tree, stream, align_kw, indent, start_col, Space.None); // align + try renderToken(tree, stream, lparen, indent, start_col, Space.None); // ( + try renderExpression(allocator, stream, tree, indent, start_col, align_node, Space.None); const s = if (var_decl.init_node != null) Space.Space else Space.None; - try renderToken(tree, stream, rparen, indent, s); // ) + try renderToken(tree, stream, rparen, indent, start_col, s); // ) } if (var_decl.init_node) |init_node| { const s = if (init_node.id == ast.Node.Id.MultilineStringLiteral) Space.None else Space.Space; - try renderToken(tree, stream, var_decl.eq_token, indent, s); // = - try renderExpression(allocator, stream, tree, indent, init_node, Space.None); + try renderToken(tree, stream, var_decl.eq_token, indent, start_col, s); // = + try renderExpression(allocator, stream, tree, indent, start_col, init_node, Space.None); } - try renderToken(tree, stream, var_decl.semicolon_token, indent, Space.Newline); + try renderToken(tree, stream, var_decl.semicolon_token, indent, start_col, Space.Newline); } -fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node, space: Space) (@typeOf(stream).Child.Error || Error)!void { +fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node, space: Space,) (@typeOf(stream).Child.Error || Error)!void { const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base); if (param_decl.comptime_token) |comptime_token| { - try renderToken(tree, stream, comptime_token, indent, Space.Space); + try renderToken(tree, stream, comptime_token, indent, start_col, Space.Space); } if (param_decl.noalias_token) |noalias_token| { - try renderToken(tree, stream, noalias_token, indent, Space.Space); + try renderToken(tree, stream, noalias_token, indent, start_col, Space.Space); } if (param_decl.name_token) |name_token| { - try renderToken(tree, stream, name_token, indent, Space.None); - try renderToken(tree, stream, tree.nextToken(name_token), indent, Space.Space); // : + try renderToken(tree, stream, name_token, indent, start_col, Space.None); + try renderToken(tree, stream, tree.nextToken(name_token), indent, start_col, Space.Space); // : } if (param_decl.var_args_token) |var_args_token| { - try renderToken(tree, stream, var_args_token, indent, space); + try renderToken(tree, stream, var_args_token, indent, start_col, space); } else { - try renderExpression(allocator, stream, tree, indent, param_decl.type_node, space); + try renderExpression(allocator, stream, tree, indent, start_col, param_decl.type_node, space); } } -fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, base: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { +fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node,) (@typeOf(stream).Child.Error || Error)!void { switch (base.id) { ast.Node.Id.VarDecl => { const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base); - try renderVarDecl(allocator, stream, tree, indent, var_decl); + try renderVarDecl(allocator, stream, tree, indent, start_col, var_decl); }, else => { if (base.requireSemiColon()) { - try renderExpression(allocator, stream, tree, indent, base, Space.None); + try renderExpression(allocator, stream, tree, indent, start_col, base, Space.None); const semicolon_index = tree.nextToken(base.lastToken()); assert(tree.tokens.at(semicolon_index).id == Token.Id.Semicolon); - try renderToken(tree, stream, semicolon_index, indent, Space.Newline); + try renderToken(tree, stream, semicolon_index, indent, start_col, Space.Newline); } else { - try renderExpression(allocator, stream, tree, indent, base, Space.Newline); + try renderExpression(allocator, stream, tree, indent, start_col, base, Space.Newline); } }, } @@ -1689,32 +1671,44 @@ const Space = enum { SpaceOrOutdent, NoNewline, NoComment, + BlockStart, }; -fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, space: Space) (@typeOf(stream).Child.Error || Error)!void { +fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, start_col: &usize, space: Space) (@typeOf(stream).Child.Error || Error)!void { + if (space == Space.BlockStart) { + if (start_col.* < indent + indent_delta) + return renderToken(tree, stream, token_index, indent, start_col, Space.Space); + try renderToken(tree, stream, token_index, indent, start_col, Space.Newline); + try stream.writeByteNTimes(' ', indent); + start_col.* = indent; + return; + } + var token = tree.tokens.at(token_index); try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(token), " ")); + if (space == Space.NoComment) + return; + var next_token = tree.tokens.at(token_index + 1); - switch (space) { - Space.NoComment => return, - Space.Comma => switch (next_token.id) { - Token.Id.Comma => return renderToken(tree, stream, token_index + 1, indent, Space.Newline), - Token.Id.LineComment => { - try stream.write(", "); - return renderToken(tree, stream, token_index + 1, indent, Space.Newline); - }, - else => { - if (tree.tokens.at(token_index + 2).id == Token.Id.MultilineStringLiteralLine) { - return stream.write(","); - } else { - return stream.write(",\n"); - } - }, + if (space == Space.Comma) switch (next_token.id) { + Token.Id.Comma => return renderToken(tree, stream, token_index + 1, indent, start_col, Space.Newline), + Token.Id.LineComment => { + try stream.write(", "); + return renderToken(tree, stream, token_index + 1, indent, start_col, Space.Newline); }, - else => {}, - } + else => { + if (tree.tokens.at(token_index + 2).id == Token.Id.MultilineStringLiteralLine) { + try stream.write(","); + return; + } else { + try stream.write(",\n"); + start_col.* = 0; + return; + } + }, + }; // Skip over same line doc comments var offset: usize = 1; @@ -1733,18 +1727,27 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent if (next_token.id == Token.Id.MultilineStringLiteralLine) { return; } else { - return stream.write("\n"); + try stream.write("\n"); + start_col.* = 0; + return; } }, - Space.Space, Space.SpaceOrOutdent => return stream.writeByte(' '), - Space.NoComment, Space.Comma => unreachable, + Space.Space, Space.SpaceOrOutdent => { + try stream.writeByte(' '); + return; + }, + Space.NoComment, Space.Comma, Space.BlockStart => unreachable, } } const comment_is_empty = mem.trimRight(u8, tree.tokenSlicePtr(next_token), " ").len == 2; if (comment_is_empty) { switch (space) { - Space.Newline => return stream.writeByte('\n'), + Space.Newline => { + try stream.writeByte('\n'); + start_col.* = 0; + return; + }, else => {}, } } @@ -1765,20 +1768,24 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent else => indent + indent_delta, }; try stream.writeByteNTimes(' ', next_line_indent); + start_col.* = next_line_indent; }, Space.SpaceOrOutdent => { try stream.writeByte('\n'); try stream.writeByteNTimes(' ', indent); + start_col.* = indent; }, Space.Newline => { if (next_token.id == Token.Id.MultilineStringLiteralLine) { return; } else { - return stream.write("\n"); + try stream.write("\n"); + start_col.* = 0; + return; } }, Space.NoNewline => {}, - Space.NoComment, Space.Comma => unreachable, + Space.NoComment, Space.Comma, Space.BlockStart => unreachable, } return; } @@ -1801,7 +1808,9 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent if (next_token.id == Token.Id.MultilineStringLiteralLine) { return; } else { - return stream.write("\n"); + try stream.write("\n"); + start_col.* = 0; + return; } }, Space.None, Space.Space => { @@ -1813,13 +1822,15 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent else => indent, }; try stream.writeByteNTimes(' ', next_line_indent); + start_col.* = next_line_indent; }, Space.SpaceOrOutdent => { try stream.writeByte('\n'); try stream.writeByteNTimes(' ', indent); + start_col.* = indent; }, Space.NoNewline => {}, - Space.NoComment, Space.Comma => unreachable, + Space.NoComment, Space.Comma, Space.BlockStart => unreachable, } return; } @@ -1827,18 +1838,30 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } } -fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@typeOf(stream).Child.Error || Error)!void { +fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize, start_col: &usize,) (@typeOf(stream).Child.Error || Error)!void { const comment = node.doc_comments ?? return; var it = comment.lines.iterator(0); const first_token = node.firstToken(); while (it.next()) |line_token_index| { if (line_token_index.* < first_token) { - try renderToken(tree, stream, line_token_index.*, indent, Space.Newline); + try renderToken(tree, stream, line_token_index.*, indent, start_col, Space.Newline); try stream.writeByteNTimes(' ', indent); } else { - try renderToken(tree, stream, line_token_index.*, indent, Space.NoComment); + try renderToken(tree, stream, line_token_index.*, indent, start_col, Space.NoComment); try stream.write("\n"); try stream.writeByteNTimes(' ', indent); } } } + +fn nodeIsBlock(base: &const ast.Node) bool { + return switch (base.id) { + ast.Node.Id.Block, + ast.Node.Id.If, + ast.Node.Id.For, + ast.Node.Id.While, + ast.Node.Id.Switch, + => true, + else => false, + }; +} From cd325e408e2d23734ba84e412b6f1706cf442434 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 29 May 2018 03:25:03 -0400 Subject: [PATCH 68/75] zig fmt: fix extra space after comma before multi line string --- std/zig/parser_test.zig | 11 +++++++++++ std/zig/render.zig | 2 ++ 2 files changed, 13 insertions(+) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 8ed748ed30..c72888a984 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,14 @@ +test "zig fmt: 2nd arg multiline string" { + try testCanonical( + \\comptime { + \\ cases.addAsm("hello world linux x86_64", + \\ \\.text + \\ , "Hello, world!\n"); + \\} + \\ + ); +} + test "zig fmt: if condition wraps" { try testTransform( \\comptime { diff --git a/std/zig/render.zig b/std/zig/render.zig index 16aed808fc..c8efce63c5 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -1733,6 +1733,8 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } }, Space.Space, Space.SpaceOrOutdent => { + if (next_token.id == Token.Id.MultilineStringLiteralLine) + return; try stream.writeByte(' '); return; }, From cdf30c31ea36365859dd81c207aede3c45c4e022 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 29 May 2018 03:47:27 -0400 Subject: [PATCH 69/75] zig fmt: fix implementation of firstToken() for fn call --- std/zig/ast.zig | 4 ++++ std/zig/parser_test.zig | 11 +++++++++++ std/zig/render.zig | 10 +++++----- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/std/zig/ast.zig b/std/zig/ast.zig index 3b705e2ee6..e86c40e310 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -1673,6 +1673,10 @@ pub const Node = struct { } pub fn firstToken(self: &SuffixOp) TokenIndex { + switch (self.op) { + @TagType(Op).Call => |*call_info| if (call_info.async_attr) |async_attr| return async_attr.firstToken(), + else => {}, + } return self.lhs.firstToken(); } diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index c72888a984..1f60fae270 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,14 @@ +test "zig fmt: async call in if condition" { + try testCanonical( + \\comptime { + \\ if (async b()) { + \\ a(); + \\ } + \\} + \\ + ); +} + test "zig fmt: 2nd arg multiline string" { try testCanonical( \\comptime { diff --git a/std/zig/render.zig b/std/zig/render.zig index c8efce63c5..dce659f1ef 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -213,13 +213,13 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind const async_attr = @fieldParentPtr(ast.Node.AsyncAttribute, "base", base); if (async_attr.allocator_type) |allocator_type| { - try renderToken(tree, stream, async_attr.async_token, indent, start_col, Space.None); + try renderToken(tree, stream, async_attr.async_token, indent, start_col, Space.None); // async - try renderToken(tree, stream, tree.nextToken(async_attr.async_token), indent, start_col, Space.None); - try renderExpression(allocator, stream, tree, indent, start_col, allocator_type, Space.None); - return renderToken(tree, stream, tree.nextToken(allocator_type.lastToken()), indent, start_col, space); + try renderToken(tree, stream, tree.nextToken(async_attr.async_token), indent, start_col, Space.None); // < + try renderExpression(allocator, stream, tree, indent, start_col, allocator_type, Space.None); // allocator + return renderToken(tree, stream, tree.nextToken(allocator_type.lastToken()), indent, start_col, space); // > } else { - return renderToken(tree, stream, async_attr.async_token, indent, start_col, space); + return renderToken(tree, stream, async_attr.async_token, indent, start_col, space); // async } }, From 0c16cd2d0ed78be2d160f9c865cd0a8703348232 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 20:23:55 -0400 Subject: [PATCH 70/75] run zig fmt on the codebase See #1003 --- std/base64.zig | 1 + std/crypto/blake2.zig | 248 +- std/fmt/errol/index.zig | 3 +- std/fmt/errol/lookup.zig | 1200 ++++----- std/fmt/index.zig | 70 +- std/hash/adler.zig | 17 +- std/hash/crc.zig | 5 +- std/hash/fnv.zig | 6 +- std/hash/siphash.zig | 6 +- std/heap.zig | 14 +- std/io_test.zig | 2 +- std/json.zig | 106 +- std/macho.zig | 20 +- std/math/atan.zig | 32 +- std/math/atan2.zig | 6 +- std/math/complex/index.zig | 22 +- std/math/complex/tanh.zig | 4 +- std/math/exp.zig | 30 +- std/math/exp2.zig | 280 +-- std/math/expm1.zig | 24 +- std/math/index.zig | 2 +- std/math/log1p.zig | 3 +- std/math/pow.zig | 1 - std/net.zig | 32 +- std/os/child_process.zig | 11 +- std/os/darwin.zig | 66 + std/os/darwin_errno.zig | 400 ++- std/os/epoch.zig | 46 +- std/os/file.zig | 59 +- std/os/get_user_id.zig | 6 +- std/os/index.zig | 168 +- std/os/linux/errno.zig | 565 +++-- std/os/linux/index.zig | 3 +- std/os/linux/test.zig | 12 +- std/os/linux/vdso.zig | 20 +- std/os/linux/x86_64.zig | 114 +- std/os/path.zig | 93 +- std/os/time.zig | 69 +- std/os/windows/error.zig | 1188 +++++++++ std/os/windows/index.zig | 166 +- std/os/windows/util.zig | 37 +- std/os/zen.zig | 138 +- std/rand/index.zig | 92 +- std/rand/ziggurat.zig | 30 +- std/segmented_list.zig | 6 +- std/sort.zig | 1 - std/special/bootstrap.zig | 8 +- std/special/bootstrap_lib.zig | 8 +- std/special/build_runner.zig | 6 +- std/special/builtin.zig | 60 +- std/special/compiler_rt/comparetf2.zig | 57 +- std/special/compiler_rt/fixunsdfti_test.zig | 1 - std/special/compiler_rt/index.zig | 14 +- std/unicode.zig | 22 +- std/zig/ast.zig | 9 +- std/zig/parse.zig | 923 ++++--- std/zig/parser_test.zig | 22 +- std/zig/render.zig | 60 +- std/zig/tokenizer.zig | 202 +- test/cases/align.zig | 12 +- test/cases/array.zig | 12 +- test/cases/bugs/394.zig | 6 +- test/cases/bugs/656.zig | 6 +- test/cases/bugs/828.zig | 8 +- test/cases/cast.zig | 31 +- test/cases/const_slice_child.zig | 2 +- test/cases/coroutines.zig | 23 +- test/cases/enum.zig | 22 +- test/cases/enum_with_members.zig | 8 +- test/cases/error.zig | 22 +- test/cases/eval.zig | 52 +- test/cases/field_parent_ptr.zig | 2 +- test/cases/fn.zig | 2 +- test/cases/fn_in_struct_in_comptime.zig | 2 +- test/cases/for.zig | 6 +- test/cases/generics.zig | 10 +- test/cases/incomplete_struct_param_tld.zig | 8 +- test/cases/math.zig | 2 +- test/cases/misc.zig | 42 +- test/cases/null.zig | 6 +- test/cases/reflection.zig | 2 +- test/cases/slice.zig | 2 +- test/cases/struct.zig | 40 +- .../cases/struct_contains_slice_of_itself.zig | 16 +- test/cases/switch.zig | 54 +- test/cases/switch_prong_err_enum.zig | 4 +- test/cases/switch_prong_implicit_cast.zig | 8 +- test/cases/this.zig | 2 +- test/cases/try.zig | 3 +- test/cases/type_info.zig | 4 +- test/cases/union.zig | 5 +- test/cases/var_args.zig | 2 +- test/cases/void.zig | 2 +- test/cases/while.zig | 4 +- test/compare_output.zig | 4 +- test/compile_errors.zig | 2218 +++++++++++------ test/gen_h.zig | 1 - test/standalone/brace_expansion/main.zig | 13 +- test/standalone/issue_339/test.zig | 5 +- test/standalone/pkg_import/pkg.zig | 4 +- test/standalone/use_alias/main.zig | 2 +- test/translate_c.zig | 49 +- 102 files changed, 5957 insertions(+), 3587 deletions(-) diff --git a/std/base64.zig b/std/base64.zig index 515738a99e..b714250992 100644 --- a/std/base64.zig +++ b/std/base64.zig @@ -81,6 +81,7 @@ pub const Base64Decoder = struct { /// e.g. 'A' => 0. /// undefined for any value not in the 64 alphabet chars. char_to_index: [256]u8, + /// true only for the 64 chars in the alphabet, not the pad char. char_in_alphabet: [256]bool, pad_char: u8, diff --git a/std/crypto/blake2.zig b/std/crypto/blake2.zig index 18025d08eb..b48e2fb4ba 100644 --- a/std/crypto/blake2.zig +++ b/std/crypto/blake2.zig @@ -49,16 +49,16 @@ fn Blake2s(comptime out_len: usize) type { }; const sigma = [10][16]u8{ - []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, - []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, - []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, - []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, - []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, - []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, - []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, - []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + []const u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + []const u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + []const u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + []const u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + []const u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + []const u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + []const u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + []const u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, }; h: [8]u32, @@ -282,222 +282,18 @@ fn Blake2b(comptime out_len: usize) type { }; const sigma = [12][16]u8{ - []const u8{ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - }, - []const u8{ - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3, - }, - []const u8{ - 11, - 8, - 12, - 0, - 5, - 2, - 15, - 13, - 10, - 14, - 3, - 6, - 7, - 1, - 9, - 4, - }, - []const u8{ - 7, - 9, - 3, - 1, - 13, - 12, - 11, - 14, - 2, - 6, - 5, - 10, - 4, - 0, - 15, - 8, - }, - []const u8{ - 9, - 0, - 5, - 7, - 2, - 4, - 10, - 15, - 14, - 1, - 11, - 12, - 6, - 8, - 3, - 13, - }, - []const u8{ - 2, - 12, - 6, - 10, - 0, - 11, - 8, - 3, - 4, - 13, - 7, - 5, - 15, - 14, - 1, - 9, - }, - []const u8{ - 12, - 5, - 1, - 15, - 14, - 13, - 4, - 10, - 0, - 7, - 6, - 3, - 9, - 2, - 8, - 11, - }, - []const u8{ - 13, - 11, - 7, - 14, - 12, - 1, - 3, - 9, - 5, - 0, - 15, - 4, - 8, - 6, - 2, - 10, - }, - []const u8{ - 6, - 15, - 14, - 9, - 11, - 3, - 0, - 8, - 12, - 2, - 13, - 7, - 1, - 4, - 10, - 5, - }, - []const u8{ - 10, - 2, - 8, - 4, - 7, - 6, - 1, - 5, - 15, - 11, - 9, - 14, - 3, - 12, - 13, - 0, - }, - []const u8{ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - }, - []const u8{ - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3, - }, + []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + []const u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + []const u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + []const u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + []const u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + []const u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + []const u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + []const u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + []const u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, }; h: [8]u64, diff --git a/std/fmt/errol/index.zig b/std/fmt/errol/index.zig index f4ec251b77..9c8fe343b5 100644 --- a/std/fmt/errol/index.zig +++ b/std/fmt/errol/index.zig @@ -98,7 +98,6 @@ pub fn errol3(value: f64, buffer: []u8) FloatDecimal { /// Uncorrected Errol3 double to ASCII conversion. fn errol3u(val: f64, buffer: []u8) FloatDecimal { // check if in integer or fixed range - if (val > 9.007199254740992e15 and val < 3.40282366920938e+38) { return errolInt(val, buffer); } else if (val >= 16.0 and val < 9.007199254740992e15) { @@ -420,7 +419,7 @@ fn fpprev(val: f64) f64 { return @bitCast(f64, @bitCast(u64, val) -% 1); } -pub const c_digits_lut = []u8 { +pub const c_digits_lut = []u8{ '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0', diff --git a/std/fmt/errol/lookup.zig b/std/fmt/errol/lookup.zig index b7b89ba732..bd0a4ac8d1 100644 --- a/std/fmt/errol/lookup.zig +++ b/std/fmt/errol/lookup.zig @@ -3,604 +3,604 @@ pub const HP = struct { off: f64, }; pub const lookup_table = []HP{ - HP{.val=1.000000e+308, .off= -1.097906362944045488e+291 }, - HP{.val=1.000000e+307, .off= 1.396894023974354241e+290 }, - HP{.val=1.000000e+306, .off= -1.721606459673645508e+289 }, - HP{.val=1.000000e+305, .off= 6.074644749446353973e+288 }, - HP{.val=1.000000e+304, .off= 6.074644749446353567e+287 }, - HP{.val=1.000000e+303, .off= -1.617650767864564452e+284 }, - HP{.val=1.000000e+302, .off= -7.629703079084895055e+285 }, - HP{.val=1.000000e+301, .off= -5.250476025520442286e+284 }, - HP{.val=1.000000e+300, .off= -5.250476025520441956e+283 }, - HP{.val=1.000000e+299, .off= -5.250476025520441750e+282 }, - HP{.val=1.000000e+298, .off= 4.043379652465702264e+281 }, - HP{.val=1.000000e+297, .off= -1.765280146275637946e+280 }, - HP{.val=1.000000e+296, .off= 1.865132227937699609e+279 }, - HP{.val=1.000000e+295, .off= 1.865132227937699609e+278 }, - HP{.val=1.000000e+294, .off= -6.643646774124810287e+277 }, - HP{.val=1.000000e+293, .off= 7.537651562646039934e+276 }, - HP{.val=1.000000e+292, .off= -1.325659897835741608e+275 }, - HP{.val=1.000000e+291, .off= 4.213909764965371606e+274 }, - HP{.val=1.000000e+290, .off= -6.172783352786715670e+273 }, - HP{.val=1.000000e+289, .off= -6.172783352786715670e+272 }, - HP{.val=1.000000e+288, .off= -7.630473539575035471e+270 }, - HP{.val=1.000000e+287, .off= -7.525217352494018700e+270 }, - HP{.val=1.000000e+286, .off= -3.298861103408696612e+269 }, - HP{.val=1.000000e+285, .off= 1.984084207947955778e+268 }, - HP{.val=1.000000e+284, .off= -7.921438250845767591e+267 }, - HP{.val=1.000000e+283, .off= 4.460464822646386735e+266 }, - HP{.val=1.000000e+282, .off= -3.278224598286209647e+265 }, - HP{.val=1.000000e+281, .off= -3.278224598286209737e+264 }, - HP{.val=1.000000e+280, .off= -3.278224598286209961e+263 }, - HP{.val=1.000000e+279, .off= -5.797329227496039232e+262 }, - HP{.val=1.000000e+278, .off= 3.649313132040821498e+261 }, - HP{.val=1.000000e+277, .off= -2.867878510995372374e+259 }, - HP{.val=1.000000e+276, .off= -5.206914080024985409e+259 }, - HP{.val=1.000000e+275, .off= 4.018322599210230404e+258 }, - HP{.val=1.000000e+274, .off= 7.862171215558236495e+257 }, - HP{.val=1.000000e+273, .off= 5.459765830340732821e+256 }, - HP{.val=1.000000e+272, .off= -6.552261095746788047e+255 }, - HP{.val=1.000000e+271, .off= 4.709014147460262298e+254 }, - HP{.val=1.000000e+270, .off= -4.675381888545612729e+253 }, - HP{.val=1.000000e+269, .off= -4.675381888545612892e+252 }, - HP{.val=1.000000e+268, .off= 2.656177514583977380e+251 }, - HP{.val=1.000000e+267, .off= 2.656177514583977190e+250 }, - HP{.val=1.000000e+266, .off= -3.071603269111014892e+249 }, - HP{.val=1.000000e+265, .off= -6.651466258920385440e+248 }, - HP{.val=1.000000e+264, .off= -4.414051890289528972e+247 }, - HP{.val=1.000000e+263, .off= -1.617283929500958387e+246 }, - HP{.val=1.000000e+262, .off= -1.617283929500958241e+245 }, - HP{.val=1.000000e+261, .off= 7.122615947963323868e+244 }, - HP{.val=1.000000e+260, .off= -6.533477610574617382e+243 }, - HP{.val=1.000000e+259, .off= 7.122615947963323982e+242 }, - HP{.val=1.000000e+258, .off= -5.679971763165996225e+241 }, - HP{.val=1.000000e+257, .off= -3.012765990014054219e+240 }, - HP{.val=1.000000e+256, .off= -3.012765990014054219e+239 }, - HP{.val=1.000000e+255, .off= 1.154743030535854616e+238 }, - HP{.val=1.000000e+254, .off= 6.364129306223240767e+237 }, - HP{.val=1.000000e+253, .off= 6.364129306223241129e+236 }, - HP{.val=1.000000e+252, .off= -9.915202805299840595e+235 }, - HP{.val=1.000000e+251, .off= -4.827911520448877980e+234 }, - HP{.val=1.000000e+250, .off= 7.890316691678530146e+233 }, - HP{.val=1.000000e+249, .off= 7.890316691678529484e+232 }, - HP{.val=1.000000e+248, .off= -4.529828046727141859e+231 }, - HP{.val=1.000000e+247, .off= 4.785280507077111924e+230 }, - HP{.val=1.000000e+246, .off= -6.858605185178205305e+229 }, - HP{.val=1.000000e+245, .off= -4.432795665958347728e+228 }, - HP{.val=1.000000e+244, .off= -7.465057564983169531e+227 }, - HP{.val=1.000000e+243, .off= -7.465057564983169741e+226 }, - HP{.val=1.000000e+242, .off= -5.096102956370027445e+225 }, - HP{.val=1.000000e+241, .off= -5.096102956370026952e+224 }, - HP{.val=1.000000e+240, .off= -1.394611380411992474e+223 }, - HP{.val=1.000000e+239, .off= 9.188208545617793960e+221 }, - HP{.val=1.000000e+238, .off= -4.864759732872650359e+221 }, - HP{.val=1.000000e+237, .off= 5.979453868566904629e+220 }, - HP{.val=1.000000e+236, .off= -5.316601966265964857e+219 }, - HP{.val=1.000000e+235, .off= -5.316601966265964701e+218 }, - HP{.val=1.000000e+234, .off= -1.786584517880693123e+217 }, - HP{.val=1.000000e+233, .off= 2.625937292600896716e+216 }, - HP{.val=1.000000e+232, .off= -5.647541102052084079e+215 }, - HP{.val=1.000000e+231, .off= -5.647541102052083888e+214 }, - HP{.val=1.000000e+230, .off= -9.956644432600511943e+213 }, - HP{.val=1.000000e+229, .off= 8.161138937705571862e+211 }, - HP{.val=1.000000e+228, .off= 7.549087847752475275e+211 }, - HP{.val=1.000000e+227, .off= -9.283347037202319948e+210 }, - HP{.val=1.000000e+226, .off= 3.866992716668613820e+209 }, - HP{.val=1.000000e+225, .off= 7.154577655136347262e+208 }, - HP{.val=1.000000e+224, .off= 3.045096482051680688e+207 }, - HP{.val=1.000000e+223, .off= -4.660180717482069567e+206 }, - HP{.val=1.000000e+222, .off= -4.660180717482070101e+205 }, - HP{.val=1.000000e+221, .off= -4.660180717482069544e+204 }, - HP{.val=1.000000e+220, .off= 3.562757926310489022e+202 }, - HP{.val=1.000000e+219, .off= 3.491561111451748149e+202 }, - HP{.val=1.000000e+218, .off= -8.265758834125874135e+201 }, - HP{.val=1.000000e+217, .off= 3.981449442517482365e+200 }, - HP{.val=1.000000e+216, .off= -2.142154695804195936e+199 }, - HP{.val=1.000000e+215, .off= 9.339603063548950188e+198 }, - HP{.val=1.000000e+214, .off= 4.555537330485139746e+197 }, - HP{.val=1.000000e+213, .off= 1.565496247320257804e+196 }, - HP{.val=1.000000e+212, .off= 9.040598955232462036e+195 }, - HP{.val=1.000000e+211, .off= 4.368659762787334780e+194 }, - HP{.val=1.000000e+210, .off= 7.288621758065539072e+193 }, - HP{.val=1.000000e+209, .off= -7.311188218325485628e+192 }, - HP{.val=1.000000e+208, .off= 1.813693016918905189e+191 }, - HP{.val=1.000000e+207, .off= -3.889357755108838992e+190 }, - HP{.val=1.000000e+206, .off= -3.889357755108838992e+189 }, - HP{.val=1.000000e+205, .off= -1.661603547285501360e+188 }, - HP{.val=1.000000e+204, .off= 1.123089212493670643e+187 }, - HP{.val=1.000000e+203, .off= 1.123089212493670643e+186 }, - HP{.val=1.000000e+202, .off= 9.825254086803583029e+185 }, - HP{.val=1.000000e+201, .off= -3.771878529305654999e+184 }, - HP{.val=1.000000e+200, .off= 3.026687778748963675e+183 }, - HP{.val=1.000000e+199, .off= -9.720624048853446693e+182 }, - HP{.val=1.000000e+198, .off= -1.753554156601940139e+181 }, - HP{.val=1.000000e+197, .off= 4.885670753607648963e+180 }, - HP{.val=1.000000e+196, .off= 4.885670753607648963e+179 }, - HP{.val=1.000000e+195, .off= 2.292223523057028076e+178 }, - HP{.val=1.000000e+194, .off= 5.534032561245303825e+177 }, - HP{.val=1.000000e+193, .off= -6.622751331960730683e+176 }, - HP{.val=1.000000e+192, .off= -4.090088020876139692e+175 }, - HP{.val=1.000000e+191, .off= -7.255917159731877552e+174 }, - HP{.val=1.000000e+190, .off= -7.255917159731877992e+173 }, - HP{.val=1.000000e+189, .off= -2.309309130269787104e+172 }, - HP{.val=1.000000e+188, .off= -2.309309130269787019e+171 }, - HP{.val=1.000000e+187, .off= 9.284303438781988230e+170 }, - HP{.val=1.000000e+186, .off= 2.038295583124628364e+169 }, - HP{.val=1.000000e+185, .off= 2.038295583124628532e+168 }, - HP{.val=1.000000e+184, .off= -1.735666841696912925e+167 }, - HP{.val=1.000000e+183, .off= 5.340512704843477241e+166 }, - HP{.val=1.000000e+182, .off= -6.453119872723839321e+165 }, - HP{.val=1.000000e+181, .off= 8.288920849235306587e+164 }, - HP{.val=1.000000e+180, .off= -9.248546019891598293e+162 }, - HP{.val=1.000000e+179, .off= 1.954450226518486016e+162 }, - HP{.val=1.000000e+178, .off= -5.243811844750628197e+161 }, - HP{.val=1.000000e+177, .off= -7.448980502074320639e+159 }, - HP{.val=1.000000e+176, .off= -7.448980502074319858e+158 }, - HP{.val=1.000000e+175, .off= 6.284654753766312753e+158 }, - HP{.val=1.000000e+174, .off= -6.895756753684458388e+157 }, - HP{.val=1.000000e+173, .off= -1.403918625579970616e+156 }, - HP{.val=1.000000e+172, .off= -8.268716285710580522e+155 }, - HP{.val=1.000000e+171, .off= 4.602779327034313170e+154 }, - HP{.val=1.000000e+170, .off= -3.441905430931244940e+153 }, - HP{.val=1.000000e+169, .off= 6.613950516525702884e+152 }, - HP{.val=1.000000e+168, .off= 6.613950516525702652e+151 }, - HP{.val=1.000000e+167, .off= -3.860899428741951187e+150 }, - HP{.val=1.000000e+166, .off= 5.959272394946474605e+149 }, - HP{.val=1.000000e+165, .off= 1.005101065481665103e+149 }, - HP{.val=1.000000e+164, .off= -1.783349948587918355e+146 }, - HP{.val=1.000000e+163, .off= 6.215006036188360099e+146 }, - HP{.val=1.000000e+162, .off= 6.215006036188360099e+145 }, - HP{.val=1.000000e+161, .off= -3.774589324822814903e+144 }, - HP{.val=1.000000e+160, .off= -6.528407745068226929e+142 }, - HP{.val=1.000000e+159, .off= 7.151530601283157561e+142 }, - HP{.val=1.000000e+158, .off= 4.712664546348788765e+141 }, - HP{.val=1.000000e+157, .off= 1.664081977680827856e+140 }, - HP{.val=1.000000e+156, .off= 1.664081977680827750e+139 }, - HP{.val=1.000000e+155, .off= -7.176231540910168265e+137 }, - HP{.val=1.000000e+154, .off= -3.694754568805822650e+137 }, - HP{.val=1.000000e+153, .off= 2.665969958768462622e+134 }, - HP{.val=1.000000e+152, .off= -4.625108135904199522e+135 }, - HP{.val=1.000000e+151, .off= -1.717753238721771919e+134 }, - HP{.val=1.000000e+150, .off= 1.916440382756262433e+133 }, - HP{.val=1.000000e+149, .off= -4.897672657515052040e+132 }, - HP{.val=1.000000e+148, .off= -4.897672657515052198e+131 }, - HP{.val=1.000000e+147, .off= 2.200361759434233991e+130 }, - HP{.val=1.000000e+146, .off= 6.636633270027537273e+129 }, - HP{.val=1.000000e+145, .off= 1.091293881785907977e+128 }, - HP{.val=1.000000e+144, .off= -2.374543235865110597e+127 }, - HP{.val=1.000000e+143, .off= -2.374543235865110537e+126 }, - HP{.val=1.000000e+142, .off= -5.082228484029969099e+125 }, - HP{.val=1.000000e+141, .off= -1.697621923823895943e+124 }, - HP{.val=1.000000e+140, .off= -5.928380124081487212e+123 }, - HP{.val=1.000000e+139, .off= -3.284156248920492522e+122 }, - HP{.val=1.000000e+138, .off= -3.284156248920492706e+121 }, - HP{.val=1.000000e+137, .off= -3.284156248920492476e+120 }, - HP{.val=1.000000e+136, .off= -5.866406127007401066e+119 }, - HP{.val=1.000000e+135, .off= 3.817030915818506056e+118 }, - HP{.val=1.000000e+134, .off= 7.851796350329300951e+117 }, - HP{.val=1.000000e+133, .off= -2.235117235947686077e+116 }, - HP{.val=1.000000e+132, .off= 9.170432597638723691e+114 }, - HP{.val=1.000000e+131, .off= 8.797444499042767883e+114 }, - HP{.val=1.000000e+130, .off= -5.978307824605161274e+113 }, - HP{.val=1.000000e+129, .off= 1.782556435814758516e+111 }, - HP{.val=1.000000e+128, .off= -7.517448691651820362e+111 }, - HP{.val=1.000000e+127, .off= 4.507089332150205498e+110 }, - HP{.val=1.000000e+126, .off= 7.513223838100711695e+109 }, - HP{.val=1.000000e+125, .off= 7.513223838100712113e+108 }, - HP{.val=1.000000e+124, .off= 5.164681255326878494e+107 }, - HP{.val=1.000000e+123, .off= 2.229003026859587122e+106 }, - HP{.val=1.000000e+122, .off= -1.440594758724527399e+105 }, - HP{.val=1.000000e+121, .off= -3.734093374714598783e+104 }, - HP{.val=1.000000e+120, .off= 1.999653165260579757e+103 }, - HP{.val=1.000000e+119, .off= 5.583244752745066693e+102 }, - HP{.val=1.000000e+118, .off= 3.343500010567262234e+101 }, - HP{.val=1.000000e+117, .off= -5.055542772599503556e+100 }, - HP{.val=1.000000e+116, .off= -1.555941612946684331e+99 }, - HP{.val=1.000000e+115, .off= -1.555941612946684331e+98 }, - HP{.val=1.000000e+114, .off= -1.555941612946684293e+97 }, - HP{.val=1.000000e+113, .off= -1.555941612946684246e+96 }, - HP{.val=1.000000e+112, .off= 6.988006530736955847e+95 }, - HP{.val=1.000000e+111, .off= 4.318022735835818244e+94 }, - HP{.val=1.000000e+110, .off= -2.356936751417025578e+93 }, - HP{.val=1.000000e+109, .off= 1.814912928116001926e+92 }, - HP{.val=1.000000e+108, .off= -3.399899171300282744e+91 }, - HP{.val=1.000000e+107, .off= 3.118615952970072913e+90 }, - HP{.val=1.000000e+106, .off= -9.103599905036843605e+89 }, - HP{.val=1.000000e+105, .off= 6.174169917471802325e+88 }, - HP{.val=1.000000e+104, .off= -1.915675085734668657e+86 }, - HP{.val=1.000000e+103, .off= -1.915675085734668864e+85 }, - HP{.val=1.000000e+102, .off= 2.295048673475466221e+85 }, - HP{.val=1.000000e+101, .off= 2.295048673475466135e+84 }, - HP{.val=1.000000e+100, .off= -1.590289110975991792e+83 }, - HP{.val=1.000000e+99, .off= 3.266383119588331155e+82 }, - HP{.val=1.000000e+98, .off= 2.309629754856292029e+80 }, - HP{.val=1.000000e+97, .off= -7.357587384771124533e+80 }, - HP{.val=1.000000e+96, .off= -4.986165397190889509e+79 }, - HP{.val=1.000000e+95, .off= -2.021887912715594741e+78 }, - HP{.val=1.000000e+94, .off= -2.021887912715594638e+77 }, - HP{.val=1.000000e+93, .off= -4.337729697461918675e+76 }, - HP{.val=1.000000e+92, .off= -4.337729697461918997e+75 }, - HP{.val=1.000000e+91, .off= -7.956232486128049702e+74 }, - HP{.val=1.000000e+90, .off= 3.351588728453609882e+73 }, - HP{.val=1.000000e+89, .off= 5.246334248081951113e+71 }, - HP{.val=1.000000e+88, .off= 4.058327554364963672e+71 }, - HP{.val=1.000000e+87, .off= 4.058327554364963918e+70 }, - HP{.val=1.000000e+86, .off= -1.463069523067487266e+69 }, - HP{.val=1.000000e+85, .off= -1.463069523067487314e+68 }, - HP{.val=1.000000e+84, .off= -5.776660989811589441e+67 }, - HP{.val=1.000000e+83, .off= -3.080666323096525761e+66 }, - HP{.val=1.000000e+82, .off= 3.659320343691134468e+65 }, - HP{.val=1.000000e+81, .off= 7.871812010433421235e+64 }, - HP{.val=1.000000e+80, .off= -2.660986470836727449e+61 }, - HP{.val=1.000000e+79, .off= 3.264399249934044627e+62 }, - HP{.val=1.000000e+78, .off= -8.493621433689703070e+60 }, - HP{.val=1.000000e+77, .off= 1.721738727445414063e+60 }, - HP{.val=1.000000e+76, .off= -4.706013449590547218e+59 }, - HP{.val=1.000000e+75, .off= 7.346021882351880518e+58 }, - HP{.val=1.000000e+74, .off= 4.835181188197207515e+57 }, - HP{.val=1.000000e+73, .off= 1.696630320503867482e+56 }, - HP{.val=1.000000e+72, .off= 5.619818905120542959e+55 }, - HP{.val=1.000000e+71, .off= -4.188152556421145598e+54 }, - HP{.val=1.000000e+70, .off= -7.253143638152923145e+53 }, - HP{.val=1.000000e+69, .off= -7.253143638152923145e+52 }, - HP{.val=1.000000e+68, .off= 4.719477774861832896e+51 }, - HP{.val=1.000000e+67, .off= 1.726322421608144052e+50 }, - HP{.val=1.000000e+66, .off= 5.467766613175255107e+49 }, - HP{.val=1.000000e+65, .off= 7.909613737163661911e+47 }, - HP{.val=1.000000e+64, .off= -2.132041900945439564e+47 }, - HP{.val=1.000000e+63, .off= -5.785795994272697265e+46 }, - HP{.val=1.000000e+62, .off= -3.502199685943161329e+45 }, - HP{.val=1.000000e+61, .off= 5.061286470292598274e+44 }, - HP{.val=1.000000e+60, .off= 5.061286470292598472e+43 }, - HP{.val=1.000000e+59, .off= 2.831211950439536034e+42 }, - HP{.val=1.000000e+58, .off= 5.618805100255863927e+41 }, - HP{.val=1.000000e+57, .off= -4.834669211555366251e+40 }, - HP{.val=1.000000e+56, .off= -9.190283508143378583e+39 }, - HP{.val=1.000000e+55, .off= -1.023506702040855158e+38 }, - HP{.val=1.000000e+54, .off= -7.829154040459624616e+37 }, - HP{.val=1.000000e+53, .off= 6.779051325638372659e+35 }, - HP{.val=1.000000e+52, .off= 6.779051325638372290e+34 }, - HP{.val=1.000000e+51, .off= 6.779051325638371598e+33 }, - HP{.val=1.000000e+50, .off= -7.629769841091887392e+33 }, - HP{.val=1.000000e+49, .off= 5.350972305245182400e+32 }, - HP{.val=1.000000e+48, .off= -4.384584304507619764e+31 }, - HP{.val=1.000000e+47, .off= -4.384584304507619876e+30 }, - HP{.val=1.000000e+46, .off= 6.860180964052978705e+28 }, - HP{.val=1.000000e+45, .off= 7.024271097546444878e+28 }, - HP{.val=1.000000e+44, .off= -8.821361405306422641e+27 }, - HP{.val=1.000000e+43, .off= -1.393721169594140991e+26 }, - HP{.val=1.000000e+42, .off= -4.488571267807591679e+25 }, - HP{.val=1.000000e+41, .off= -6.200086450407783195e+23 }, - HP{.val=1.000000e+40, .off= -3.037860284270036669e+23 }, - HP{.val=1.000000e+39, .off= 6.029083362839682141e+22 }, - HP{.val=1.000000e+38, .off= 2.251190176543965970e+21 }, - HP{.val=1.000000e+37, .off= 4.612373417978788577e+20 }, - HP{.val=1.000000e+36, .off= -4.242063737401796198e+19 }, - HP{.val=1.000000e+35, .off= 3.136633892082024448e+18 }, - HP{.val=1.000000e+34, .off= 5.442476901295718400e+17 }, - HP{.val=1.000000e+33, .off= 5.442476901295718400e+16 }, - HP{.val=1.000000e+32, .off= -5.366162204393472000e+15 }, - HP{.val=1.000000e+31, .off= 3.641037050347520000e+14 }, - HP{.val=1.000000e+30, .off= -1.988462483865600000e+13 }, - HP{.val=1.000000e+29, .off= 8.566849142784000000e+12 }, - HP{.val=1.000000e+28, .off= 4.168802631680000000e+11 }, - HP{.val=1.000000e+27, .off= -1.328755507200000000e+10 }, - HP{.val=1.000000e+26, .off= -4.764729344000000000e+09 }, - HP{.val=1.000000e+25, .off= -9.059696640000000000e+08 }, - HP{.val=1.000000e+24, .off= 1.677721600000000000e+07 }, - HP{.val=1.000000e+23, .off= 8.388608000000000000e+06 }, - HP{.val=1.000000e+22, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+21, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+20, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+19, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+18, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+17, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+16, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+15, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+14, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+13, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+12, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+11, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+10, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+09, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+08, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+07, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+06, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+05, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+04, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+03, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+02, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+01, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+00, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e-01, .off= -5.551115123125783010e-18 }, - HP{.val=1.000000e-02, .off= -2.081668171172168436e-19 }, - HP{.val=1.000000e-03, .off= -2.081668171172168557e-20 }, - HP{.val=1.000000e-04, .off= -4.792173602385929943e-21 }, - HP{.val=1.000000e-05, .off= -8.180305391403130547e-22 }, - HP{.val=1.000000e-06, .off= 4.525188817411374069e-23 }, - HP{.val=1.000000e-07, .off= 4.525188817411373922e-24 }, - HP{.val=1.000000e-08, .off= -2.092256083012847109e-25 }, - HP{.val=1.000000e-09, .off= -6.228159145777985254e-26 }, - HP{.val=1.000000e-10, .off= -3.643219731549774344e-27 }, - HP{.val=1.000000e-11, .off= 6.050303071806019080e-28 }, - HP{.val=1.000000e-12, .off= 2.011335237074438524e-29 }, - HP{.val=1.000000e-13, .off= -3.037374556340037101e-30 }, - HP{.val=1.000000e-14, .off= 1.180690645440101289e-32 }, - HP{.val=1.000000e-15, .off= -7.770539987666107583e-32 }, - HP{.val=1.000000e-16, .off= 2.090221327596539779e-33 }, - HP{.val=1.000000e-17, .off= -7.154242405462192144e-34 }, - HP{.val=1.000000e-18, .off= -7.154242405462192572e-35 }, - HP{.val=1.000000e-19, .off= 2.475407316473986894e-36 }, - HP{.val=1.000000e-20, .off= 5.484672854579042914e-37 }, - HP{.val=1.000000e-21, .off= 9.246254777210362522e-38 }, - HP{.val=1.000000e-22, .off= -4.859677432657087182e-39 }, - HP{.val=1.000000e-23, .off= 3.956530198510069291e-40 }, - HP{.val=1.000000e-24, .off= 7.629950044829717753e-41 }, - HP{.val=1.000000e-25, .off= -3.849486974919183692e-42 }, - HP{.val=1.000000e-26, .off= -3.849486974919184170e-43 }, - HP{.val=1.000000e-27, .off= -3.849486974919184070e-44 }, - HP{.val=1.000000e-28, .off= 2.876745653839937870e-45 }, - HP{.val=1.000000e-29, .off= 5.679342582489572168e-46 }, - HP{.val=1.000000e-30, .off= -8.333642060758598930e-47 }, - HP{.val=1.000000e-31, .off= -8.333642060758597958e-48 }, - HP{.val=1.000000e-32, .off= -5.596730997624190224e-49 }, - HP{.val=1.000000e-33, .off= -5.596730997624190604e-50 }, - HP{.val=1.000000e-34, .off= 7.232539610818348498e-51 }, - HP{.val=1.000000e-35, .off= -7.857545194582380514e-53 }, - HP{.val=1.000000e-36, .off= 5.896157255772251528e-53 }, - HP{.val=1.000000e-37, .off= -6.632427322784915796e-54 }, - HP{.val=1.000000e-38, .off= 3.808059826012723592e-55 }, - HP{.val=1.000000e-39, .off= 7.070712060011985131e-56 }, - HP{.val=1.000000e-40, .off= 7.070712060011985584e-57 }, - HP{.val=1.000000e-41, .off= -5.761291134237854167e-59 }, - HP{.val=1.000000e-42, .off= -3.762312935688689794e-59 }, - HP{.val=1.000000e-43, .off= -7.745042713519821150e-60 }, - HP{.val=1.000000e-44, .off= 4.700987842202462817e-61 }, - HP{.val=1.000000e-45, .off= 1.589480203271891964e-62 }, - HP{.val=1.000000e-46, .off= -2.299904345391321765e-63 }, - HP{.val=1.000000e-47, .off= 2.561826340437695261e-64 }, - HP{.val=1.000000e-48, .off= 2.561826340437695345e-65 }, - HP{.val=1.000000e-49, .off= 6.360053438741614633e-66 }, - HP{.val=1.000000e-50, .off= -7.616223705782342295e-68 }, - HP{.val=1.000000e-51, .off= -7.616223705782343324e-69 }, - HP{.val=1.000000e-52, .off= -7.616223705782342295e-70 }, - HP{.val=1.000000e-53, .off= -3.079876214757872338e-70 }, - HP{.val=1.000000e-54, .off= -3.079876214757872821e-71 }, - HP{.val=1.000000e-55, .off= 5.423954167728123147e-73 }, - HP{.val=1.000000e-56, .off= -3.985444122640543680e-73 }, - HP{.val=1.000000e-57, .off= 4.504255013759498850e-74 }, - HP{.val=1.000000e-58, .off= -2.570494266573869991e-75 }, - HP{.val=1.000000e-59, .off= -2.570494266573869930e-76 }, - HP{.val=1.000000e-60, .off= 2.956653608686574324e-77 }, - HP{.val=1.000000e-61, .off= -3.952281235388981376e-78 }, - HP{.val=1.000000e-62, .off= -3.952281235388981376e-79 }, - HP{.val=1.000000e-63, .off= -6.651083908855995172e-80 }, - HP{.val=1.000000e-64, .off= 3.469426116645307030e-81 }, - HP{.val=1.000000e-65, .off= 7.686305293937516319e-82 }, - HP{.val=1.000000e-66, .off= 2.415206322322254927e-83 }, - HP{.val=1.000000e-67, .off= 5.709643179581793251e-84 }, - HP{.val=1.000000e-68, .off= -6.644495035141475923e-85 }, - HP{.val=1.000000e-69, .off= 3.650620143794581913e-86 }, - HP{.val=1.000000e-70, .off= 4.333966503770636492e-88 }, - HP{.val=1.000000e-71, .off= 8.476455383920859113e-88 }, - HP{.val=1.000000e-72, .off= 3.449543675455986564e-89 }, - HP{.val=1.000000e-73, .off= 3.077238576654418974e-91 }, - HP{.val=1.000000e-74, .off= 4.234998629903623140e-91 }, - HP{.val=1.000000e-75, .off= 4.234998629903623412e-92 }, - HP{.val=1.000000e-76, .off= 7.303182045714702338e-93 }, - HP{.val=1.000000e-77, .off= 7.303182045714701699e-94 }, - HP{.val=1.000000e-78, .off= 1.121271649074855759e-96 }, - HP{.val=1.000000e-79, .off= 1.121271649074855863e-97 }, - HP{.val=1.000000e-80, .off= 3.857468248661243988e-97 }, - HP{.val=1.000000e-81, .off= 3.857468248661244248e-98 }, - HP{.val=1.000000e-82, .off= 3.857468248661244410e-99 }, - HP{.val=1.000000e-83, .off= -3.457651055545315679e-100 }, - HP{.val=1.000000e-84, .off= -3.457651055545315933e-101 }, - HP{.val=1.000000e-85, .off= 2.257285900866059216e-102 }, - HP{.val=1.000000e-86, .off= -8.458220892405268345e-103 }, - HP{.val=1.000000e-87, .off= -1.761029146610688867e-104 }, - HP{.val=1.000000e-88, .off= 6.610460535632536565e-105 }, - HP{.val=1.000000e-89, .off= -3.853901567171494935e-106 }, - HP{.val=1.000000e-90, .off= 5.062493089968513723e-108 }, - HP{.val=1.000000e-91, .off= -2.218844988608365240e-108 }, - HP{.val=1.000000e-92, .off= 1.187522883398155383e-109 }, - HP{.val=1.000000e-93, .off= 9.703442563414457296e-110 }, - HP{.val=1.000000e-94, .off= 4.380992763404268896e-111 }, - HP{.val=1.000000e-95, .off= 1.054461638397900823e-112 }, - HP{.val=1.000000e-96, .off= 9.370789450913819736e-113 }, - HP{.val=1.000000e-97, .off= -3.623472756142303998e-114 }, - HP{.val=1.000000e-98, .off= 6.122223899149788839e-115 }, - HP{.val=1.000000e-99, .off= -1.999189980260288281e-116 }, - HP{.val=1.000000e-100, .off= -1.999189980260288281e-117 }, - HP{.val=1.000000e-101, .off= -5.171617276904849634e-118 }, - HP{.val=1.000000e-102, .off= 6.724985085512256320e-119 }, - HP{.val=1.000000e-103, .off= 4.246526260008692213e-120 }, - HP{.val=1.000000e-104, .off= 7.344599791888147003e-121 }, - HP{.val=1.000000e-105, .off= 3.472007877038828407e-122 }, - HP{.val=1.000000e-106, .off= 5.892377823819652194e-123 }, - HP{.val=1.000000e-107, .off= -1.585470431324073925e-125 }, - HP{.val=1.000000e-108, .off= -3.940375084977444795e-125 }, - HP{.val=1.000000e-109, .off= 7.869099673288519908e-127 }, - HP{.val=1.000000e-110, .off= -5.122196348054018581e-127 }, - HP{.val=1.000000e-111, .off= -8.815387795168313713e-128 }, - HP{.val=1.000000e-112, .off= 5.034080131510290214e-129 }, - HP{.val=1.000000e-113, .off= 2.148774313452247863e-130 }, - HP{.val=1.000000e-114, .off= -5.064490231692858416e-131 }, - HP{.val=1.000000e-115, .off= -5.064490231692858166e-132 }, - HP{.val=1.000000e-116, .off= 5.708726942017560559e-134 }, - HP{.val=1.000000e-117, .off= -2.951229134482377772e-134 }, - HP{.val=1.000000e-118, .off= 1.451398151372789513e-135 }, - HP{.val=1.000000e-119, .off= -1.300243902286690040e-136 }, - HP{.val=1.000000e-120, .off= 2.139308664787659449e-137 }, - HP{.val=1.000000e-121, .off= 2.139308664787659329e-138 }, - HP{.val=1.000000e-122, .off= -5.922142664292847471e-139 }, - HP{.val=1.000000e-123, .off= -5.922142664292846912e-140 }, - HP{.val=1.000000e-124, .off= 6.673875037395443799e-141 }, - HP{.val=1.000000e-125, .off= -1.198636026159737932e-142 }, - HP{.val=1.000000e-126, .off= 5.361789860136246995e-143 }, - HP{.val=1.000000e-127, .off= -2.838742497733733936e-144 }, - HP{.val=1.000000e-128, .off= -5.401408859568103261e-145 }, - HP{.val=1.000000e-129, .off= 7.411922949603743011e-146 }, - HP{.val=1.000000e-130, .off= -8.604741811861064385e-147 }, - HP{.val=1.000000e-131, .off= 1.405673664054439890e-148 }, - HP{.val=1.000000e-132, .off= 1.405673664054439933e-149 }, - HP{.val=1.000000e-133, .off= -6.414963426504548053e-150 }, - HP{.val=1.000000e-134, .off= -3.971014335704864578e-151 }, - HP{.val=1.000000e-135, .off= -3.971014335704864748e-152 }, - HP{.val=1.000000e-136, .off= -1.523438813303585576e-154 }, - HP{.val=1.000000e-137, .off= 2.234325152653707766e-154 }, - HP{.val=1.000000e-138, .off= -6.715683724786540160e-155 }, - HP{.val=1.000000e-139, .off= -2.986513359186437306e-156 }, - HP{.val=1.000000e-140, .off= 1.674949597813692102e-157 }, - HP{.val=1.000000e-141, .off= -4.151879098436469092e-158 }, - HP{.val=1.000000e-142, .off= -4.151879098436469295e-159 }, - HP{.val=1.000000e-143, .off= 4.952540739454407825e-160 }, - HP{.val=1.000000e-144, .off= 4.952540739454407667e-161 }, - HP{.val=1.000000e-145, .off= 8.508954738630531443e-162 }, - HP{.val=1.000000e-146, .off= -2.604839008794855481e-163 }, - HP{.val=1.000000e-147, .off= 2.952057864917838382e-164 }, - HP{.val=1.000000e-148, .off= 6.425118410988271757e-165 }, - HP{.val=1.000000e-149, .off= 2.083792728400229858e-166 }, - HP{.val=1.000000e-150, .off= -6.295358232172964237e-168 }, - HP{.val=1.000000e-151, .off= 6.153785555826519421e-168 }, - HP{.val=1.000000e-152, .off= -6.564942029880634994e-169 }, - HP{.val=1.000000e-153, .off= -3.915207116191644540e-170 }, - HP{.val=1.000000e-154, .off= 2.709130168030831503e-171 }, - HP{.val=1.000000e-155, .off= -1.431080634608215966e-172 }, - HP{.val=1.000000e-156, .off= -4.018712386257620994e-173 }, - HP{.val=1.000000e-157, .off= 5.684906682427646782e-174 }, - HP{.val=1.000000e-158, .off= -6.444617153428937489e-175 }, - HP{.val=1.000000e-159, .off= 1.136335243981427681e-176 }, - HP{.val=1.000000e-160, .off= 1.136335243981427725e-177 }, - HP{.val=1.000000e-161, .off= -2.812077463003137395e-178 }, - HP{.val=1.000000e-162, .off= 4.591196362592922204e-179 }, - HP{.val=1.000000e-163, .off= 7.675893789924613703e-180 }, - HP{.val=1.000000e-164, .off= 3.820022005759999543e-181 }, - HP{.val=1.000000e-165, .off= -9.998177244457686588e-183 }, - HP{.val=1.000000e-166, .off= -4.012217555824373639e-183 }, - HP{.val=1.000000e-167, .off= -2.467177666011174334e-185 }, - HP{.val=1.000000e-168, .off= -4.953592503130188139e-185 }, - HP{.val=1.000000e-169, .off= -2.011795792799518887e-186 }, - HP{.val=1.000000e-170, .off= 1.665450095113817423e-187 }, - HP{.val=1.000000e-171, .off= 1.665450095113817487e-188 }, - HP{.val=1.000000e-172, .off= -4.080246604750770577e-189 }, - HP{.val=1.000000e-173, .off= -4.080246604750770677e-190 }, - HP{.val=1.000000e-174, .off= 4.085789420184387951e-192 }, - HP{.val=1.000000e-175, .off= 4.085789420184388146e-193 }, - HP{.val=1.000000e-176, .off= 4.085789420184388146e-194 }, - HP{.val=1.000000e-177, .off= 4.792197640035244894e-194 }, - HP{.val=1.000000e-178, .off= 4.792197640035244742e-195 }, - HP{.val=1.000000e-179, .off= -2.057206575616014662e-196 }, - HP{.val=1.000000e-180, .off= -2.057206575616014662e-197 }, - HP{.val=1.000000e-181, .off= -4.732755097354788053e-198 }, - HP{.val=1.000000e-182, .off= -4.732755097354787867e-199 }, - HP{.val=1.000000e-183, .off= -5.522105321379546765e-201 }, - HP{.val=1.000000e-184, .off= -5.777891238658996019e-201 }, - HP{.val=1.000000e-185, .off= 7.542096444923057046e-203 }, - HP{.val=1.000000e-186, .off= 8.919335748431433483e-203 }, - HP{.val=1.000000e-187, .off= -1.287071881492476028e-204 }, - HP{.val=1.000000e-188, .off= 5.091932887209967018e-205 }, - HP{.val=1.000000e-189, .off= -6.868701054107114024e-206 }, - HP{.val=1.000000e-190, .off= -1.885103578558330118e-207 }, - HP{.val=1.000000e-191, .off= -1.885103578558330205e-208 }, - HP{.val=1.000000e-192, .off= -9.671974634103305058e-209 }, - HP{.val=1.000000e-193, .off= -4.805180224387695640e-210 }, - HP{.val=1.000000e-194, .off= -1.763433718315439838e-211 }, - HP{.val=1.000000e-195, .off= -9.367799983496079132e-212 }, - HP{.val=1.000000e-196, .off= -4.615071067758179837e-213 }, - HP{.val=1.000000e-197, .off= 1.325840076914194777e-214 }, - HP{.val=1.000000e-198, .off= 8.751979007754662425e-215 }, - HP{.val=1.000000e-199, .off= 1.789973760091724198e-216 }, - HP{.val=1.000000e-200, .off= 1.789973760091724077e-217 }, - HP{.val=1.000000e-201, .off= 5.416018159916171171e-218 }, - HP{.val=1.000000e-202, .off= -3.649092839644947067e-219 }, - HP{.val=1.000000e-203, .off= -3.649092839644947067e-220 }, - HP{.val=1.000000e-204, .off= -1.080338554413850956e-222 }, - HP{.val=1.000000e-205, .off= -1.080338554413850841e-223 }, - HP{.val=1.000000e-206, .off= -2.874486186850417807e-223 }, - HP{.val=1.000000e-207, .off= 7.499710055933455072e-224 }, - HP{.val=1.000000e-208, .off= -9.790617015372999087e-225 }, - HP{.val=1.000000e-209, .off= -4.387389805589732612e-226 }, - HP{.val=1.000000e-210, .off= -4.387389805589732612e-227 }, - HP{.val=1.000000e-211, .off= -8.608661063232909897e-228 }, - HP{.val=1.000000e-212, .off= 4.582811616902018972e-229 }, - HP{.val=1.000000e-213, .off= 4.582811616902019155e-230 }, - HP{.val=1.000000e-214, .off= 8.705146829444184930e-231 }, - HP{.val=1.000000e-215, .off= -4.177150709750081830e-232 }, - HP{.val=1.000000e-216, .off= -4.177150709750082366e-233 }, - HP{.val=1.000000e-217, .off= -8.202868690748290237e-234 }, - HP{.val=1.000000e-218, .off= -3.170721214500530119e-235 }, - HP{.val=1.000000e-219, .off= -3.170721214500529857e-236 }, - HP{.val=1.000000e-220, .off= 7.606440013180328441e-238 }, - HP{.val=1.000000e-221, .off= -1.696459258568569049e-238 }, - HP{.val=1.000000e-222, .off= -4.767838333426821244e-239 }, - HP{.val=1.000000e-223, .off= 2.910609353718809138e-240 }, - HP{.val=1.000000e-224, .off= -1.888420450747209784e-241 }, - HP{.val=1.000000e-225, .off= 4.110366804835314035e-242 }, - HP{.val=1.000000e-226, .off= 7.859608839574391006e-243 }, - HP{.val=1.000000e-227, .off= 5.516332567862468419e-244 }, - HP{.val=1.000000e-228, .off= -3.270953451057244613e-245 }, - HP{.val=1.000000e-229, .off= -6.932322625607124670e-246 }, - HP{.val=1.000000e-230, .off= -4.643966891513449762e-247 }, - HP{.val=1.000000e-231, .off= 1.076922443720738305e-248 }, - HP{.val=1.000000e-232, .off= -2.498633390800628939e-249 }, - HP{.val=1.000000e-233, .off= 4.205533798926934891e-250 }, - HP{.val=1.000000e-234, .off= 4.205533798926934891e-251 }, - HP{.val=1.000000e-235, .off= 4.205533798926934697e-252 }, - HP{.val=1.000000e-236, .off= -4.523850562697497656e-253 }, - HP{.val=1.000000e-237, .off= 9.320146633177728298e-255 }, - HP{.val=1.000000e-238, .off= 9.320146633177728062e-256 }, - HP{.val=1.000000e-239, .off= -7.592774752331086440e-256 }, - HP{.val=1.000000e-240, .off= 3.063212017229987840e-257 }, - HP{.val=1.000000e-241, .off= 3.063212017229987562e-258 }, - HP{.val=1.000000e-242, .off= 3.063212017229987562e-259 }, - HP{.val=1.000000e-243, .off= 4.616527473176159842e-261 }, - HP{.val=1.000000e-244, .off= 6.965550922098544975e-261 }, - HP{.val=1.000000e-245, .off= 6.965550922098544749e-262 }, - HP{.val=1.000000e-246, .off= 4.424965697574744679e-263 }, - HP{.val=1.000000e-247, .off= -1.926497363734756420e-264 }, - HP{.val=1.000000e-248, .off= 2.043167049583681740e-265 }, - HP{.val=1.000000e-249, .off= -5.399953725388390154e-266 }, - HP{.val=1.000000e-250, .off= -5.399953725388389982e-267 }, - HP{.val=1.000000e-251, .off= -1.523328321757102663e-268 }, - HP{.val=1.000000e-252, .off= 5.745344310051561161e-269 }, - HP{.val=1.000000e-253, .off= -6.369110076296211879e-270 }, - HP{.val=1.000000e-254, .off= 8.773957906638504842e-271 }, - HP{.val=1.000000e-255, .off= -6.904595826956931908e-273 }, - HP{.val=1.000000e-256, .off= 2.267170882721243669e-273 }, - HP{.val=1.000000e-257, .off= 2.267170882721243669e-274 }, - HP{.val=1.000000e-258, .off= 4.577819683828225398e-275 }, - HP{.val=1.000000e-259, .off= -6.975424321706684210e-276 }, - HP{.val=1.000000e-260, .off= 3.855741933482293648e-277 }, - HP{.val=1.000000e-261, .off= 1.599248963651256552e-278 }, - HP{.val=1.000000e-262, .off= -1.221367248637539543e-279 }, - HP{.val=1.000000e-263, .off= -1.221367248637539494e-280 }, - HP{.val=1.000000e-264, .off= -1.221367248637539647e-281 }, - HP{.val=1.000000e-265, .off= 1.533140771175737943e-282 }, - HP{.val=1.000000e-266, .off= 1.533140771175737895e-283 }, - HP{.val=1.000000e-267, .off= 1.533140771175738074e-284 }, - HP{.val=1.000000e-268, .off= 4.223090009274641634e-285 }, - HP{.val=1.000000e-269, .off= 4.223090009274641634e-286 }, - HP{.val=1.000000e-270, .off= -4.183001359784432924e-287 }, - HP{.val=1.000000e-271, .off= 3.697709298708449474e-288 }, - HP{.val=1.000000e-272, .off= 6.981338739747150474e-289 }, - HP{.val=1.000000e-273, .off= -9.436808465446354751e-290 }, - HP{.val=1.000000e-274, .off= 3.389869038611071740e-291 }, - HP{.val=1.000000e-275, .off= 6.596538414625427829e-292 }, - HP{.val=1.000000e-276, .off= -9.436808465446354618e-293 }, - HP{.val=1.000000e-277, .off= 3.089243784609725523e-294 }, - HP{.val=1.000000e-278, .off= 6.220756847123745836e-295 }, - HP{.val=1.000000e-279, .off= -5.522417137303829470e-296 }, - HP{.val=1.000000e-280, .off= 4.263561183052483059e-297 }, - HP{.val=1.000000e-281, .off= -1.852675267170212272e-298 }, - HP{.val=1.000000e-282, .off= -1.852675267170212378e-299 }, - HP{.val=1.000000e-283, .off= 5.314789322934508480e-300 }, - HP{.val=1.000000e-284, .off= -3.644541414696392675e-301 }, - HP{.val=1.000000e-285, .off= -7.377595888709267777e-302 }, - HP{.val=1.000000e-286, .off= -5.044436842451220838e-303 }, - HP{.val=1.000000e-287, .off= -2.127988034628661760e-304 }, - HP{.val=1.000000e-288, .off= -5.773549044406860911e-305 }, - HP{.val=1.000000e-289, .off= -1.216597782184112068e-306 }, - HP{.val=1.000000e-290, .off= -6.912786859962547924e-307 }, - HP{.val=1.000000e-291, .off= 3.767567660872018813e-308 }, + HP{ .val = 1.000000e+308, .off = -1.097906362944045488e+291 }, + HP{ .val = 1.000000e+307, .off = 1.396894023974354241e+290 }, + HP{ .val = 1.000000e+306, .off = -1.721606459673645508e+289 }, + HP{ .val = 1.000000e+305, .off = 6.074644749446353973e+288 }, + HP{ .val = 1.000000e+304, .off = 6.074644749446353567e+287 }, + HP{ .val = 1.000000e+303, .off = -1.617650767864564452e+284 }, + HP{ .val = 1.000000e+302, .off = -7.629703079084895055e+285 }, + HP{ .val = 1.000000e+301, .off = -5.250476025520442286e+284 }, + HP{ .val = 1.000000e+300, .off = -5.250476025520441956e+283 }, + HP{ .val = 1.000000e+299, .off = -5.250476025520441750e+282 }, + HP{ .val = 1.000000e+298, .off = 4.043379652465702264e+281 }, + HP{ .val = 1.000000e+297, .off = -1.765280146275637946e+280 }, + HP{ .val = 1.000000e+296, .off = 1.865132227937699609e+279 }, + HP{ .val = 1.000000e+295, .off = 1.865132227937699609e+278 }, + HP{ .val = 1.000000e+294, .off = -6.643646774124810287e+277 }, + HP{ .val = 1.000000e+293, .off = 7.537651562646039934e+276 }, + HP{ .val = 1.000000e+292, .off = -1.325659897835741608e+275 }, + HP{ .val = 1.000000e+291, .off = 4.213909764965371606e+274 }, + HP{ .val = 1.000000e+290, .off = -6.172783352786715670e+273 }, + HP{ .val = 1.000000e+289, .off = -6.172783352786715670e+272 }, + HP{ .val = 1.000000e+288, .off = -7.630473539575035471e+270 }, + HP{ .val = 1.000000e+287, .off = -7.525217352494018700e+270 }, + HP{ .val = 1.000000e+286, .off = -3.298861103408696612e+269 }, + HP{ .val = 1.000000e+285, .off = 1.984084207947955778e+268 }, + HP{ .val = 1.000000e+284, .off = -7.921438250845767591e+267 }, + HP{ .val = 1.000000e+283, .off = 4.460464822646386735e+266 }, + HP{ .val = 1.000000e+282, .off = -3.278224598286209647e+265 }, + HP{ .val = 1.000000e+281, .off = -3.278224598286209737e+264 }, + HP{ .val = 1.000000e+280, .off = -3.278224598286209961e+263 }, + HP{ .val = 1.000000e+279, .off = -5.797329227496039232e+262 }, + HP{ .val = 1.000000e+278, .off = 3.649313132040821498e+261 }, + HP{ .val = 1.000000e+277, .off = -2.867878510995372374e+259 }, + HP{ .val = 1.000000e+276, .off = -5.206914080024985409e+259 }, + HP{ .val = 1.000000e+275, .off = 4.018322599210230404e+258 }, + HP{ .val = 1.000000e+274, .off = 7.862171215558236495e+257 }, + HP{ .val = 1.000000e+273, .off = 5.459765830340732821e+256 }, + HP{ .val = 1.000000e+272, .off = -6.552261095746788047e+255 }, + HP{ .val = 1.000000e+271, .off = 4.709014147460262298e+254 }, + HP{ .val = 1.000000e+270, .off = -4.675381888545612729e+253 }, + HP{ .val = 1.000000e+269, .off = -4.675381888545612892e+252 }, + HP{ .val = 1.000000e+268, .off = 2.656177514583977380e+251 }, + HP{ .val = 1.000000e+267, .off = 2.656177514583977190e+250 }, + HP{ .val = 1.000000e+266, .off = -3.071603269111014892e+249 }, + HP{ .val = 1.000000e+265, .off = -6.651466258920385440e+248 }, + HP{ .val = 1.000000e+264, .off = -4.414051890289528972e+247 }, + HP{ .val = 1.000000e+263, .off = -1.617283929500958387e+246 }, + HP{ .val = 1.000000e+262, .off = -1.617283929500958241e+245 }, + HP{ .val = 1.000000e+261, .off = 7.122615947963323868e+244 }, + HP{ .val = 1.000000e+260, .off = -6.533477610574617382e+243 }, + HP{ .val = 1.000000e+259, .off = 7.122615947963323982e+242 }, + HP{ .val = 1.000000e+258, .off = -5.679971763165996225e+241 }, + HP{ .val = 1.000000e+257, .off = -3.012765990014054219e+240 }, + HP{ .val = 1.000000e+256, .off = -3.012765990014054219e+239 }, + HP{ .val = 1.000000e+255, .off = 1.154743030535854616e+238 }, + HP{ .val = 1.000000e+254, .off = 6.364129306223240767e+237 }, + HP{ .val = 1.000000e+253, .off = 6.364129306223241129e+236 }, + HP{ .val = 1.000000e+252, .off = -9.915202805299840595e+235 }, + HP{ .val = 1.000000e+251, .off = -4.827911520448877980e+234 }, + HP{ .val = 1.000000e+250, .off = 7.890316691678530146e+233 }, + HP{ .val = 1.000000e+249, .off = 7.890316691678529484e+232 }, + HP{ .val = 1.000000e+248, .off = -4.529828046727141859e+231 }, + HP{ .val = 1.000000e+247, .off = 4.785280507077111924e+230 }, + HP{ .val = 1.000000e+246, .off = -6.858605185178205305e+229 }, + HP{ .val = 1.000000e+245, .off = -4.432795665958347728e+228 }, + HP{ .val = 1.000000e+244, .off = -7.465057564983169531e+227 }, + HP{ .val = 1.000000e+243, .off = -7.465057564983169741e+226 }, + HP{ .val = 1.000000e+242, .off = -5.096102956370027445e+225 }, + HP{ .val = 1.000000e+241, .off = -5.096102956370026952e+224 }, + HP{ .val = 1.000000e+240, .off = -1.394611380411992474e+223 }, + HP{ .val = 1.000000e+239, .off = 9.188208545617793960e+221 }, + HP{ .val = 1.000000e+238, .off = -4.864759732872650359e+221 }, + HP{ .val = 1.000000e+237, .off = 5.979453868566904629e+220 }, + HP{ .val = 1.000000e+236, .off = -5.316601966265964857e+219 }, + HP{ .val = 1.000000e+235, .off = -5.316601966265964701e+218 }, + HP{ .val = 1.000000e+234, .off = -1.786584517880693123e+217 }, + HP{ .val = 1.000000e+233, .off = 2.625937292600896716e+216 }, + HP{ .val = 1.000000e+232, .off = -5.647541102052084079e+215 }, + HP{ .val = 1.000000e+231, .off = -5.647541102052083888e+214 }, + HP{ .val = 1.000000e+230, .off = -9.956644432600511943e+213 }, + HP{ .val = 1.000000e+229, .off = 8.161138937705571862e+211 }, + HP{ .val = 1.000000e+228, .off = 7.549087847752475275e+211 }, + HP{ .val = 1.000000e+227, .off = -9.283347037202319948e+210 }, + HP{ .val = 1.000000e+226, .off = 3.866992716668613820e+209 }, + HP{ .val = 1.000000e+225, .off = 7.154577655136347262e+208 }, + HP{ .val = 1.000000e+224, .off = 3.045096482051680688e+207 }, + HP{ .val = 1.000000e+223, .off = -4.660180717482069567e+206 }, + HP{ .val = 1.000000e+222, .off = -4.660180717482070101e+205 }, + HP{ .val = 1.000000e+221, .off = -4.660180717482069544e+204 }, + HP{ .val = 1.000000e+220, .off = 3.562757926310489022e+202 }, + HP{ .val = 1.000000e+219, .off = 3.491561111451748149e+202 }, + HP{ .val = 1.000000e+218, .off = -8.265758834125874135e+201 }, + HP{ .val = 1.000000e+217, .off = 3.981449442517482365e+200 }, + HP{ .val = 1.000000e+216, .off = -2.142154695804195936e+199 }, + HP{ .val = 1.000000e+215, .off = 9.339603063548950188e+198 }, + HP{ .val = 1.000000e+214, .off = 4.555537330485139746e+197 }, + HP{ .val = 1.000000e+213, .off = 1.565496247320257804e+196 }, + HP{ .val = 1.000000e+212, .off = 9.040598955232462036e+195 }, + HP{ .val = 1.000000e+211, .off = 4.368659762787334780e+194 }, + HP{ .val = 1.000000e+210, .off = 7.288621758065539072e+193 }, + HP{ .val = 1.000000e+209, .off = -7.311188218325485628e+192 }, + HP{ .val = 1.000000e+208, .off = 1.813693016918905189e+191 }, + HP{ .val = 1.000000e+207, .off = -3.889357755108838992e+190 }, + HP{ .val = 1.000000e+206, .off = -3.889357755108838992e+189 }, + HP{ .val = 1.000000e+205, .off = -1.661603547285501360e+188 }, + HP{ .val = 1.000000e+204, .off = 1.123089212493670643e+187 }, + HP{ .val = 1.000000e+203, .off = 1.123089212493670643e+186 }, + HP{ .val = 1.000000e+202, .off = 9.825254086803583029e+185 }, + HP{ .val = 1.000000e+201, .off = -3.771878529305654999e+184 }, + HP{ .val = 1.000000e+200, .off = 3.026687778748963675e+183 }, + HP{ .val = 1.000000e+199, .off = -9.720624048853446693e+182 }, + HP{ .val = 1.000000e+198, .off = -1.753554156601940139e+181 }, + HP{ .val = 1.000000e+197, .off = 4.885670753607648963e+180 }, + HP{ .val = 1.000000e+196, .off = 4.885670753607648963e+179 }, + HP{ .val = 1.000000e+195, .off = 2.292223523057028076e+178 }, + HP{ .val = 1.000000e+194, .off = 5.534032561245303825e+177 }, + HP{ .val = 1.000000e+193, .off = -6.622751331960730683e+176 }, + HP{ .val = 1.000000e+192, .off = -4.090088020876139692e+175 }, + HP{ .val = 1.000000e+191, .off = -7.255917159731877552e+174 }, + HP{ .val = 1.000000e+190, .off = -7.255917159731877992e+173 }, + HP{ .val = 1.000000e+189, .off = -2.309309130269787104e+172 }, + HP{ .val = 1.000000e+188, .off = -2.309309130269787019e+171 }, + HP{ .val = 1.000000e+187, .off = 9.284303438781988230e+170 }, + HP{ .val = 1.000000e+186, .off = 2.038295583124628364e+169 }, + HP{ .val = 1.000000e+185, .off = 2.038295583124628532e+168 }, + HP{ .val = 1.000000e+184, .off = -1.735666841696912925e+167 }, + HP{ .val = 1.000000e+183, .off = 5.340512704843477241e+166 }, + HP{ .val = 1.000000e+182, .off = -6.453119872723839321e+165 }, + HP{ .val = 1.000000e+181, .off = 8.288920849235306587e+164 }, + HP{ .val = 1.000000e+180, .off = -9.248546019891598293e+162 }, + HP{ .val = 1.000000e+179, .off = 1.954450226518486016e+162 }, + HP{ .val = 1.000000e+178, .off = -5.243811844750628197e+161 }, + HP{ .val = 1.000000e+177, .off = -7.448980502074320639e+159 }, + HP{ .val = 1.000000e+176, .off = -7.448980502074319858e+158 }, + HP{ .val = 1.000000e+175, .off = 6.284654753766312753e+158 }, + HP{ .val = 1.000000e+174, .off = -6.895756753684458388e+157 }, + HP{ .val = 1.000000e+173, .off = -1.403918625579970616e+156 }, + HP{ .val = 1.000000e+172, .off = -8.268716285710580522e+155 }, + HP{ .val = 1.000000e+171, .off = 4.602779327034313170e+154 }, + HP{ .val = 1.000000e+170, .off = -3.441905430931244940e+153 }, + HP{ .val = 1.000000e+169, .off = 6.613950516525702884e+152 }, + HP{ .val = 1.000000e+168, .off = 6.613950516525702652e+151 }, + HP{ .val = 1.000000e+167, .off = -3.860899428741951187e+150 }, + HP{ .val = 1.000000e+166, .off = 5.959272394946474605e+149 }, + HP{ .val = 1.000000e+165, .off = 1.005101065481665103e+149 }, + HP{ .val = 1.000000e+164, .off = -1.783349948587918355e+146 }, + HP{ .val = 1.000000e+163, .off = 6.215006036188360099e+146 }, + HP{ .val = 1.000000e+162, .off = 6.215006036188360099e+145 }, + HP{ .val = 1.000000e+161, .off = -3.774589324822814903e+144 }, + HP{ .val = 1.000000e+160, .off = -6.528407745068226929e+142 }, + HP{ .val = 1.000000e+159, .off = 7.151530601283157561e+142 }, + HP{ .val = 1.000000e+158, .off = 4.712664546348788765e+141 }, + HP{ .val = 1.000000e+157, .off = 1.664081977680827856e+140 }, + HP{ .val = 1.000000e+156, .off = 1.664081977680827750e+139 }, + HP{ .val = 1.000000e+155, .off = -7.176231540910168265e+137 }, + HP{ .val = 1.000000e+154, .off = -3.694754568805822650e+137 }, + HP{ .val = 1.000000e+153, .off = 2.665969958768462622e+134 }, + HP{ .val = 1.000000e+152, .off = -4.625108135904199522e+135 }, + HP{ .val = 1.000000e+151, .off = -1.717753238721771919e+134 }, + HP{ .val = 1.000000e+150, .off = 1.916440382756262433e+133 }, + HP{ .val = 1.000000e+149, .off = -4.897672657515052040e+132 }, + HP{ .val = 1.000000e+148, .off = -4.897672657515052198e+131 }, + HP{ .val = 1.000000e+147, .off = 2.200361759434233991e+130 }, + HP{ .val = 1.000000e+146, .off = 6.636633270027537273e+129 }, + HP{ .val = 1.000000e+145, .off = 1.091293881785907977e+128 }, + HP{ .val = 1.000000e+144, .off = -2.374543235865110597e+127 }, + HP{ .val = 1.000000e+143, .off = -2.374543235865110537e+126 }, + HP{ .val = 1.000000e+142, .off = -5.082228484029969099e+125 }, + HP{ .val = 1.000000e+141, .off = -1.697621923823895943e+124 }, + HP{ .val = 1.000000e+140, .off = -5.928380124081487212e+123 }, + HP{ .val = 1.000000e+139, .off = -3.284156248920492522e+122 }, + HP{ .val = 1.000000e+138, .off = -3.284156248920492706e+121 }, + HP{ .val = 1.000000e+137, .off = -3.284156248920492476e+120 }, + HP{ .val = 1.000000e+136, .off = -5.866406127007401066e+119 }, + HP{ .val = 1.000000e+135, .off = 3.817030915818506056e+118 }, + HP{ .val = 1.000000e+134, .off = 7.851796350329300951e+117 }, + HP{ .val = 1.000000e+133, .off = -2.235117235947686077e+116 }, + HP{ .val = 1.000000e+132, .off = 9.170432597638723691e+114 }, + HP{ .val = 1.000000e+131, .off = 8.797444499042767883e+114 }, + HP{ .val = 1.000000e+130, .off = -5.978307824605161274e+113 }, + HP{ .val = 1.000000e+129, .off = 1.782556435814758516e+111 }, + HP{ .val = 1.000000e+128, .off = -7.517448691651820362e+111 }, + HP{ .val = 1.000000e+127, .off = 4.507089332150205498e+110 }, + HP{ .val = 1.000000e+126, .off = 7.513223838100711695e+109 }, + HP{ .val = 1.000000e+125, .off = 7.513223838100712113e+108 }, + HP{ .val = 1.000000e+124, .off = 5.164681255326878494e+107 }, + HP{ .val = 1.000000e+123, .off = 2.229003026859587122e+106 }, + HP{ .val = 1.000000e+122, .off = -1.440594758724527399e+105 }, + HP{ .val = 1.000000e+121, .off = -3.734093374714598783e+104 }, + HP{ .val = 1.000000e+120, .off = 1.999653165260579757e+103 }, + HP{ .val = 1.000000e+119, .off = 5.583244752745066693e+102 }, + HP{ .val = 1.000000e+118, .off = 3.343500010567262234e+101 }, + HP{ .val = 1.000000e+117, .off = -5.055542772599503556e+100 }, + HP{ .val = 1.000000e+116, .off = -1.555941612946684331e+99 }, + HP{ .val = 1.000000e+115, .off = -1.555941612946684331e+98 }, + HP{ .val = 1.000000e+114, .off = -1.555941612946684293e+97 }, + HP{ .val = 1.000000e+113, .off = -1.555941612946684246e+96 }, + HP{ .val = 1.000000e+112, .off = 6.988006530736955847e+95 }, + HP{ .val = 1.000000e+111, .off = 4.318022735835818244e+94 }, + HP{ .val = 1.000000e+110, .off = -2.356936751417025578e+93 }, + HP{ .val = 1.000000e+109, .off = 1.814912928116001926e+92 }, + HP{ .val = 1.000000e+108, .off = -3.399899171300282744e+91 }, + HP{ .val = 1.000000e+107, .off = 3.118615952970072913e+90 }, + HP{ .val = 1.000000e+106, .off = -9.103599905036843605e+89 }, + HP{ .val = 1.000000e+105, .off = 6.174169917471802325e+88 }, + HP{ .val = 1.000000e+104, .off = -1.915675085734668657e+86 }, + HP{ .val = 1.000000e+103, .off = -1.915675085734668864e+85 }, + HP{ .val = 1.000000e+102, .off = 2.295048673475466221e+85 }, + HP{ .val = 1.000000e+101, .off = 2.295048673475466135e+84 }, + HP{ .val = 1.000000e+100, .off = -1.590289110975991792e+83 }, + HP{ .val = 1.000000e+99, .off = 3.266383119588331155e+82 }, + HP{ .val = 1.000000e+98, .off = 2.309629754856292029e+80 }, + HP{ .val = 1.000000e+97, .off = -7.357587384771124533e+80 }, + HP{ .val = 1.000000e+96, .off = -4.986165397190889509e+79 }, + HP{ .val = 1.000000e+95, .off = -2.021887912715594741e+78 }, + HP{ .val = 1.000000e+94, .off = -2.021887912715594638e+77 }, + HP{ .val = 1.000000e+93, .off = -4.337729697461918675e+76 }, + HP{ .val = 1.000000e+92, .off = -4.337729697461918997e+75 }, + HP{ .val = 1.000000e+91, .off = -7.956232486128049702e+74 }, + HP{ .val = 1.000000e+90, .off = 3.351588728453609882e+73 }, + HP{ .val = 1.000000e+89, .off = 5.246334248081951113e+71 }, + HP{ .val = 1.000000e+88, .off = 4.058327554364963672e+71 }, + HP{ .val = 1.000000e+87, .off = 4.058327554364963918e+70 }, + HP{ .val = 1.000000e+86, .off = -1.463069523067487266e+69 }, + HP{ .val = 1.000000e+85, .off = -1.463069523067487314e+68 }, + HP{ .val = 1.000000e+84, .off = -5.776660989811589441e+67 }, + HP{ .val = 1.000000e+83, .off = -3.080666323096525761e+66 }, + HP{ .val = 1.000000e+82, .off = 3.659320343691134468e+65 }, + HP{ .val = 1.000000e+81, .off = 7.871812010433421235e+64 }, + HP{ .val = 1.000000e+80, .off = -2.660986470836727449e+61 }, + HP{ .val = 1.000000e+79, .off = 3.264399249934044627e+62 }, + HP{ .val = 1.000000e+78, .off = -8.493621433689703070e+60 }, + HP{ .val = 1.000000e+77, .off = 1.721738727445414063e+60 }, + HP{ .val = 1.000000e+76, .off = -4.706013449590547218e+59 }, + HP{ .val = 1.000000e+75, .off = 7.346021882351880518e+58 }, + HP{ .val = 1.000000e+74, .off = 4.835181188197207515e+57 }, + HP{ .val = 1.000000e+73, .off = 1.696630320503867482e+56 }, + HP{ .val = 1.000000e+72, .off = 5.619818905120542959e+55 }, + HP{ .val = 1.000000e+71, .off = -4.188152556421145598e+54 }, + HP{ .val = 1.000000e+70, .off = -7.253143638152923145e+53 }, + HP{ .val = 1.000000e+69, .off = -7.253143638152923145e+52 }, + HP{ .val = 1.000000e+68, .off = 4.719477774861832896e+51 }, + HP{ .val = 1.000000e+67, .off = 1.726322421608144052e+50 }, + HP{ .val = 1.000000e+66, .off = 5.467766613175255107e+49 }, + HP{ .val = 1.000000e+65, .off = 7.909613737163661911e+47 }, + HP{ .val = 1.000000e+64, .off = -2.132041900945439564e+47 }, + HP{ .val = 1.000000e+63, .off = -5.785795994272697265e+46 }, + HP{ .val = 1.000000e+62, .off = -3.502199685943161329e+45 }, + HP{ .val = 1.000000e+61, .off = 5.061286470292598274e+44 }, + HP{ .val = 1.000000e+60, .off = 5.061286470292598472e+43 }, + HP{ .val = 1.000000e+59, .off = 2.831211950439536034e+42 }, + HP{ .val = 1.000000e+58, .off = 5.618805100255863927e+41 }, + HP{ .val = 1.000000e+57, .off = -4.834669211555366251e+40 }, + HP{ .val = 1.000000e+56, .off = -9.190283508143378583e+39 }, + HP{ .val = 1.000000e+55, .off = -1.023506702040855158e+38 }, + HP{ .val = 1.000000e+54, .off = -7.829154040459624616e+37 }, + HP{ .val = 1.000000e+53, .off = 6.779051325638372659e+35 }, + HP{ .val = 1.000000e+52, .off = 6.779051325638372290e+34 }, + HP{ .val = 1.000000e+51, .off = 6.779051325638371598e+33 }, + HP{ .val = 1.000000e+50, .off = -7.629769841091887392e+33 }, + HP{ .val = 1.000000e+49, .off = 5.350972305245182400e+32 }, + HP{ .val = 1.000000e+48, .off = -4.384584304507619764e+31 }, + HP{ .val = 1.000000e+47, .off = -4.384584304507619876e+30 }, + HP{ .val = 1.000000e+46, .off = 6.860180964052978705e+28 }, + HP{ .val = 1.000000e+45, .off = 7.024271097546444878e+28 }, + HP{ .val = 1.000000e+44, .off = -8.821361405306422641e+27 }, + HP{ .val = 1.000000e+43, .off = -1.393721169594140991e+26 }, + HP{ .val = 1.000000e+42, .off = -4.488571267807591679e+25 }, + HP{ .val = 1.000000e+41, .off = -6.200086450407783195e+23 }, + HP{ .val = 1.000000e+40, .off = -3.037860284270036669e+23 }, + HP{ .val = 1.000000e+39, .off = 6.029083362839682141e+22 }, + HP{ .val = 1.000000e+38, .off = 2.251190176543965970e+21 }, + HP{ .val = 1.000000e+37, .off = 4.612373417978788577e+20 }, + HP{ .val = 1.000000e+36, .off = -4.242063737401796198e+19 }, + HP{ .val = 1.000000e+35, .off = 3.136633892082024448e+18 }, + HP{ .val = 1.000000e+34, .off = 5.442476901295718400e+17 }, + HP{ .val = 1.000000e+33, .off = 5.442476901295718400e+16 }, + HP{ .val = 1.000000e+32, .off = -5.366162204393472000e+15 }, + HP{ .val = 1.000000e+31, .off = 3.641037050347520000e+14 }, + HP{ .val = 1.000000e+30, .off = -1.988462483865600000e+13 }, + HP{ .val = 1.000000e+29, .off = 8.566849142784000000e+12 }, + HP{ .val = 1.000000e+28, .off = 4.168802631680000000e+11 }, + HP{ .val = 1.000000e+27, .off = -1.328755507200000000e+10 }, + HP{ .val = 1.000000e+26, .off = -4.764729344000000000e+09 }, + HP{ .val = 1.000000e+25, .off = -9.059696640000000000e+08 }, + HP{ .val = 1.000000e+24, .off = 1.677721600000000000e+07 }, + HP{ .val = 1.000000e+23, .off = 8.388608000000000000e+06 }, + HP{ .val = 1.000000e+22, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+21, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+20, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+19, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+18, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+17, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+16, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+15, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+14, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+13, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+12, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+11, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+10, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+09, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+08, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+07, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+06, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+05, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+04, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+03, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+02, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+01, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+00, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e-01, .off = -5.551115123125783010e-18 }, + HP{ .val = 1.000000e-02, .off = -2.081668171172168436e-19 }, + HP{ .val = 1.000000e-03, .off = -2.081668171172168557e-20 }, + HP{ .val = 1.000000e-04, .off = -4.792173602385929943e-21 }, + HP{ .val = 1.000000e-05, .off = -8.180305391403130547e-22 }, + HP{ .val = 1.000000e-06, .off = 4.525188817411374069e-23 }, + HP{ .val = 1.000000e-07, .off = 4.525188817411373922e-24 }, + HP{ .val = 1.000000e-08, .off = -2.092256083012847109e-25 }, + HP{ .val = 1.000000e-09, .off = -6.228159145777985254e-26 }, + HP{ .val = 1.000000e-10, .off = -3.643219731549774344e-27 }, + HP{ .val = 1.000000e-11, .off = 6.050303071806019080e-28 }, + HP{ .val = 1.000000e-12, .off = 2.011335237074438524e-29 }, + HP{ .val = 1.000000e-13, .off = -3.037374556340037101e-30 }, + HP{ .val = 1.000000e-14, .off = 1.180690645440101289e-32 }, + HP{ .val = 1.000000e-15, .off = -7.770539987666107583e-32 }, + HP{ .val = 1.000000e-16, .off = 2.090221327596539779e-33 }, + HP{ .val = 1.000000e-17, .off = -7.154242405462192144e-34 }, + HP{ .val = 1.000000e-18, .off = -7.154242405462192572e-35 }, + HP{ .val = 1.000000e-19, .off = 2.475407316473986894e-36 }, + HP{ .val = 1.000000e-20, .off = 5.484672854579042914e-37 }, + HP{ .val = 1.000000e-21, .off = 9.246254777210362522e-38 }, + HP{ .val = 1.000000e-22, .off = -4.859677432657087182e-39 }, + HP{ .val = 1.000000e-23, .off = 3.956530198510069291e-40 }, + HP{ .val = 1.000000e-24, .off = 7.629950044829717753e-41 }, + HP{ .val = 1.000000e-25, .off = -3.849486974919183692e-42 }, + HP{ .val = 1.000000e-26, .off = -3.849486974919184170e-43 }, + HP{ .val = 1.000000e-27, .off = -3.849486974919184070e-44 }, + HP{ .val = 1.000000e-28, .off = 2.876745653839937870e-45 }, + HP{ .val = 1.000000e-29, .off = 5.679342582489572168e-46 }, + HP{ .val = 1.000000e-30, .off = -8.333642060758598930e-47 }, + HP{ .val = 1.000000e-31, .off = -8.333642060758597958e-48 }, + HP{ .val = 1.000000e-32, .off = -5.596730997624190224e-49 }, + HP{ .val = 1.000000e-33, .off = -5.596730997624190604e-50 }, + HP{ .val = 1.000000e-34, .off = 7.232539610818348498e-51 }, + HP{ .val = 1.000000e-35, .off = -7.857545194582380514e-53 }, + HP{ .val = 1.000000e-36, .off = 5.896157255772251528e-53 }, + HP{ .val = 1.000000e-37, .off = -6.632427322784915796e-54 }, + HP{ .val = 1.000000e-38, .off = 3.808059826012723592e-55 }, + HP{ .val = 1.000000e-39, .off = 7.070712060011985131e-56 }, + HP{ .val = 1.000000e-40, .off = 7.070712060011985584e-57 }, + HP{ .val = 1.000000e-41, .off = -5.761291134237854167e-59 }, + HP{ .val = 1.000000e-42, .off = -3.762312935688689794e-59 }, + HP{ .val = 1.000000e-43, .off = -7.745042713519821150e-60 }, + HP{ .val = 1.000000e-44, .off = 4.700987842202462817e-61 }, + HP{ .val = 1.000000e-45, .off = 1.589480203271891964e-62 }, + HP{ .val = 1.000000e-46, .off = -2.299904345391321765e-63 }, + HP{ .val = 1.000000e-47, .off = 2.561826340437695261e-64 }, + HP{ .val = 1.000000e-48, .off = 2.561826340437695345e-65 }, + HP{ .val = 1.000000e-49, .off = 6.360053438741614633e-66 }, + HP{ .val = 1.000000e-50, .off = -7.616223705782342295e-68 }, + HP{ .val = 1.000000e-51, .off = -7.616223705782343324e-69 }, + HP{ .val = 1.000000e-52, .off = -7.616223705782342295e-70 }, + HP{ .val = 1.000000e-53, .off = -3.079876214757872338e-70 }, + HP{ .val = 1.000000e-54, .off = -3.079876214757872821e-71 }, + HP{ .val = 1.000000e-55, .off = 5.423954167728123147e-73 }, + HP{ .val = 1.000000e-56, .off = -3.985444122640543680e-73 }, + HP{ .val = 1.000000e-57, .off = 4.504255013759498850e-74 }, + HP{ .val = 1.000000e-58, .off = -2.570494266573869991e-75 }, + HP{ .val = 1.000000e-59, .off = -2.570494266573869930e-76 }, + HP{ .val = 1.000000e-60, .off = 2.956653608686574324e-77 }, + HP{ .val = 1.000000e-61, .off = -3.952281235388981376e-78 }, + HP{ .val = 1.000000e-62, .off = -3.952281235388981376e-79 }, + HP{ .val = 1.000000e-63, .off = -6.651083908855995172e-80 }, + HP{ .val = 1.000000e-64, .off = 3.469426116645307030e-81 }, + HP{ .val = 1.000000e-65, .off = 7.686305293937516319e-82 }, + HP{ .val = 1.000000e-66, .off = 2.415206322322254927e-83 }, + HP{ .val = 1.000000e-67, .off = 5.709643179581793251e-84 }, + HP{ .val = 1.000000e-68, .off = -6.644495035141475923e-85 }, + HP{ .val = 1.000000e-69, .off = 3.650620143794581913e-86 }, + HP{ .val = 1.000000e-70, .off = 4.333966503770636492e-88 }, + HP{ .val = 1.000000e-71, .off = 8.476455383920859113e-88 }, + HP{ .val = 1.000000e-72, .off = 3.449543675455986564e-89 }, + HP{ .val = 1.000000e-73, .off = 3.077238576654418974e-91 }, + HP{ .val = 1.000000e-74, .off = 4.234998629903623140e-91 }, + HP{ .val = 1.000000e-75, .off = 4.234998629903623412e-92 }, + HP{ .val = 1.000000e-76, .off = 7.303182045714702338e-93 }, + HP{ .val = 1.000000e-77, .off = 7.303182045714701699e-94 }, + HP{ .val = 1.000000e-78, .off = 1.121271649074855759e-96 }, + HP{ .val = 1.000000e-79, .off = 1.121271649074855863e-97 }, + HP{ .val = 1.000000e-80, .off = 3.857468248661243988e-97 }, + HP{ .val = 1.000000e-81, .off = 3.857468248661244248e-98 }, + HP{ .val = 1.000000e-82, .off = 3.857468248661244410e-99 }, + HP{ .val = 1.000000e-83, .off = -3.457651055545315679e-100 }, + HP{ .val = 1.000000e-84, .off = -3.457651055545315933e-101 }, + HP{ .val = 1.000000e-85, .off = 2.257285900866059216e-102 }, + HP{ .val = 1.000000e-86, .off = -8.458220892405268345e-103 }, + HP{ .val = 1.000000e-87, .off = -1.761029146610688867e-104 }, + HP{ .val = 1.000000e-88, .off = 6.610460535632536565e-105 }, + HP{ .val = 1.000000e-89, .off = -3.853901567171494935e-106 }, + HP{ .val = 1.000000e-90, .off = 5.062493089968513723e-108 }, + HP{ .val = 1.000000e-91, .off = -2.218844988608365240e-108 }, + HP{ .val = 1.000000e-92, .off = 1.187522883398155383e-109 }, + HP{ .val = 1.000000e-93, .off = 9.703442563414457296e-110 }, + HP{ .val = 1.000000e-94, .off = 4.380992763404268896e-111 }, + HP{ .val = 1.000000e-95, .off = 1.054461638397900823e-112 }, + HP{ .val = 1.000000e-96, .off = 9.370789450913819736e-113 }, + HP{ .val = 1.000000e-97, .off = -3.623472756142303998e-114 }, + HP{ .val = 1.000000e-98, .off = 6.122223899149788839e-115 }, + HP{ .val = 1.000000e-99, .off = -1.999189980260288281e-116 }, + HP{ .val = 1.000000e-100, .off = -1.999189980260288281e-117 }, + HP{ .val = 1.000000e-101, .off = -5.171617276904849634e-118 }, + HP{ .val = 1.000000e-102, .off = 6.724985085512256320e-119 }, + HP{ .val = 1.000000e-103, .off = 4.246526260008692213e-120 }, + HP{ .val = 1.000000e-104, .off = 7.344599791888147003e-121 }, + HP{ .val = 1.000000e-105, .off = 3.472007877038828407e-122 }, + HP{ .val = 1.000000e-106, .off = 5.892377823819652194e-123 }, + HP{ .val = 1.000000e-107, .off = -1.585470431324073925e-125 }, + HP{ .val = 1.000000e-108, .off = -3.940375084977444795e-125 }, + HP{ .val = 1.000000e-109, .off = 7.869099673288519908e-127 }, + HP{ .val = 1.000000e-110, .off = -5.122196348054018581e-127 }, + HP{ .val = 1.000000e-111, .off = -8.815387795168313713e-128 }, + HP{ .val = 1.000000e-112, .off = 5.034080131510290214e-129 }, + HP{ .val = 1.000000e-113, .off = 2.148774313452247863e-130 }, + HP{ .val = 1.000000e-114, .off = -5.064490231692858416e-131 }, + HP{ .val = 1.000000e-115, .off = -5.064490231692858166e-132 }, + HP{ .val = 1.000000e-116, .off = 5.708726942017560559e-134 }, + HP{ .val = 1.000000e-117, .off = -2.951229134482377772e-134 }, + HP{ .val = 1.000000e-118, .off = 1.451398151372789513e-135 }, + HP{ .val = 1.000000e-119, .off = -1.300243902286690040e-136 }, + HP{ .val = 1.000000e-120, .off = 2.139308664787659449e-137 }, + HP{ .val = 1.000000e-121, .off = 2.139308664787659329e-138 }, + HP{ .val = 1.000000e-122, .off = -5.922142664292847471e-139 }, + HP{ .val = 1.000000e-123, .off = -5.922142664292846912e-140 }, + HP{ .val = 1.000000e-124, .off = 6.673875037395443799e-141 }, + HP{ .val = 1.000000e-125, .off = -1.198636026159737932e-142 }, + HP{ .val = 1.000000e-126, .off = 5.361789860136246995e-143 }, + HP{ .val = 1.000000e-127, .off = -2.838742497733733936e-144 }, + HP{ .val = 1.000000e-128, .off = -5.401408859568103261e-145 }, + HP{ .val = 1.000000e-129, .off = 7.411922949603743011e-146 }, + HP{ .val = 1.000000e-130, .off = -8.604741811861064385e-147 }, + HP{ .val = 1.000000e-131, .off = 1.405673664054439890e-148 }, + HP{ .val = 1.000000e-132, .off = 1.405673664054439933e-149 }, + HP{ .val = 1.000000e-133, .off = -6.414963426504548053e-150 }, + HP{ .val = 1.000000e-134, .off = -3.971014335704864578e-151 }, + HP{ .val = 1.000000e-135, .off = -3.971014335704864748e-152 }, + HP{ .val = 1.000000e-136, .off = -1.523438813303585576e-154 }, + HP{ .val = 1.000000e-137, .off = 2.234325152653707766e-154 }, + HP{ .val = 1.000000e-138, .off = -6.715683724786540160e-155 }, + HP{ .val = 1.000000e-139, .off = -2.986513359186437306e-156 }, + HP{ .val = 1.000000e-140, .off = 1.674949597813692102e-157 }, + HP{ .val = 1.000000e-141, .off = -4.151879098436469092e-158 }, + HP{ .val = 1.000000e-142, .off = -4.151879098436469295e-159 }, + HP{ .val = 1.000000e-143, .off = 4.952540739454407825e-160 }, + HP{ .val = 1.000000e-144, .off = 4.952540739454407667e-161 }, + HP{ .val = 1.000000e-145, .off = 8.508954738630531443e-162 }, + HP{ .val = 1.000000e-146, .off = -2.604839008794855481e-163 }, + HP{ .val = 1.000000e-147, .off = 2.952057864917838382e-164 }, + HP{ .val = 1.000000e-148, .off = 6.425118410988271757e-165 }, + HP{ .val = 1.000000e-149, .off = 2.083792728400229858e-166 }, + HP{ .val = 1.000000e-150, .off = -6.295358232172964237e-168 }, + HP{ .val = 1.000000e-151, .off = 6.153785555826519421e-168 }, + HP{ .val = 1.000000e-152, .off = -6.564942029880634994e-169 }, + HP{ .val = 1.000000e-153, .off = -3.915207116191644540e-170 }, + HP{ .val = 1.000000e-154, .off = 2.709130168030831503e-171 }, + HP{ .val = 1.000000e-155, .off = -1.431080634608215966e-172 }, + HP{ .val = 1.000000e-156, .off = -4.018712386257620994e-173 }, + HP{ .val = 1.000000e-157, .off = 5.684906682427646782e-174 }, + HP{ .val = 1.000000e-158, .off = -6.444617153428937489e-175 }, + HP{ .val = 1.000000e-159, .off = 1.136335243981427681e-176 }, + HP{ .val = 1.000000e-160, .off = 1.136335243981427725e-177 }, + HP{ .val = 1.000000e-161, .off = -2.812077463003137395e-178 }, + HP{ .val = 1.000000e-162, .off = 4.591196362592922204e-179 }, + HP{ .val = 1.000000e-163, .off = 7.675893789924613703e-180 }, + HP{ .val = 1.000000e-164, .off = 3.820022005759999543e-181 }, + HP{ .val = 1.000000e-165, .off = -9.998177244457686588e-183 }, + HP{ .val = 1.000000e-166, .off = -4.012217555824373639e-183 }, + HP{ .val = 1.000000e-167, .off = -2.467177666011174334e-185 }, + HP{ .val = 1.000000e-168, .off = -4.953592503130188139e-185 }, + HP{ .val = 1.000000e-169, .off = -2.011795792799518887e-186 }, + HP{ .val = 1.000000e-170, .off = 1.665450095113817423e-187 }, + HP{ .val = 1.000000e-171, .off = 1.665450095113817487e-188 }, + HP{ .val = 1.000000e-172, .off = -4.080246604750770577e-189 }, + HP{ .val = 1.000000e-173, .off = -4.080246604750770677e-190 }, + HP{ .val = 1.000000e-174, .off = 4.085789420184387951e-192 }, + HP{ .val = 1.000000e-175, .off = 4.085789420184388146e-193 }, + HP{ .val = 1.000000e-176, .off = 4.085789420184388146e-194 }, + HP{ .val = 1.000000e-177, .off = 4.792197640035244894e-194 }, + HP{ .val = 1.000000e-178, .off = 4.792197640035244742e-195 }, + HP{ .val = 1.000000e-179, .off = -2.057206575616014662e-196 }, + HP{ .val = 1.000000e-180, .off = -2.057206575616014662e-197 }, + HP{ .val = 1.000000e-181, .off = -4.732755097354788053e-198 }, + HP{ .val = 1.000000e-182, .off = -4.732755097354787867e-199 }, + HP{ .val = 1.000000e-183, .off = -5.522105321379546765e-201 }, + HP{ .val = 1.000000e-184, .off = -5.777891238658996019e-201 }, + HP{ .val = 1.000000e-185, .off = 7.542096444923057046e-203 }, + HP{ .val = 1.000000e-186, .off = 8.919335748431433483e-203 }, + HP{ .val = 1.000000e-187, .off = -1.287071881492476028e-204 }, + HP{ .val = 1.000000e-188, .off = 5.091932887209967018e-205 }, + HP{ .val = 1.000000e-189, .off = -6.868701054107114024e-206 }, + HP{ .val = 1.000000e-190, .off = -1.885103578558330118e-207 }, + HP{ .val = 1.000000e-191, .off = -1.885103578558330205e-208 }, + HP{ .val = 1.000000e-192, .off = -9.671974634103305058e-209 }, + HP{ .val = 1.000000e-193, .off = -4.805180224387695640e-210 }, + HP{ .val = 1.000000e-194, .off = -1.763433718315439838e-211 }, + HP{ .val = 1.000000e-195, .off = -9.367799983496079132e-212 }, + HP{ .val = 1.000000e-196, .off = -4.615071067758179837e-213 }, + HP{ .val = 1.000000e-197, .off = 1.325840076914194777e-214 }, + HP{ .val = 1.000000e-198, .off = 8.751979007754662425e-215 }, + HP{ .val = 1.000000e-199, .off = 1.789973760091724198e-216 }, + HP{ .val = 1.000000e-200, .off = 1.789973760091724077e-217 }, + HP{ .val = 1.000000e-201, .off = 5.416018159916171171e-218 }, + HP{ .val = 1.000000e-202, .off = -3.649092839644947067e-219 }, + HP{ .val = 1.000000e-203, .off = -3.649092839644947067e-220 }, + HP{ .val = 1.000000e-204, .off = -1.080338554413850956e-222 }, + HP{ .val = 1.000000e-205, .off = -1.080338554413850841e-223 }, + HP{ .val = 1.000000e-206, .off = -2.874486186850417807e-223 }, + HP{ .val = 1.000000e-207, .off = 7.499710055933455072e-224 }, + HP{ .val = 1.000000e-208, .off = -9.790617015372999087e-225 }, + HP{ .val = 1.000000e-209, .off = -4.387389805589732612e-226 }, + HP{ .val = 1.000000e-210, .off = -4.387389805589732612e-227 }, + HP{ .val = 1.000000e-211, .off = -8.608661063232909897e-228 }, + HP{ .val = 1.000000e-212, .off = 4.582811616902018972e-229 }, + HP{ .val = 1.000000e-213, .off = 4.582811616902019155e-230 }, + HP{ .val = 1.000000e-214, .off = 8.705146829444184930e-231 }, + HP{ .val = 1.000000e-215, .off = -4.177150709750081830e-232 }, + HP{ .val = 1.000000e-216, .off = -4.177150709750082366e-233 }, + HP{ .val = 1.000000e-217, .off = -8.202868690748290237e-234 }, + HP{ .val = 1.000000e-218, .off = -3.170721214500530119e-235 }, + HP{ .val = 1.000000e-219, .off = -3.170721214500529857e-236 }, + HP{ .val = 1.000000e-220, .off = 7.606440013180328441e-238 }, + HP{ .val = 1.000000e-221, .off = -1.696459258568569049e-238 }, + HP{ .val = 1.000000e-222, .off = -4.767838333426821244e-239 }, + HP{ .val = 1.000000e-223, .off = 2.910609353718809138e-240 }, + HP{ .val = 1.000000e-224, .off = -1.888420450747209784e-241 }, + HP{ .val = 1.000000e-225, .off = 4.110366804835314035e-242 }, + HP{ .val = 1.000000e-226, .off = 7.859608839574391006e-243 }, + HP{ .val = 1.000000e-227, .off = 5.516332567862468419e-244 }, + HP{ .val = 1.000000e-228, .off = -3.270953451057244613e-245 }, + HP{ .val = 1.000000e-229, .off = -6.932322625607124670e-246 }, + HP{ .val = 1.000000e-230, .off = -4.643966891513449762e-247 }, + HP{ .val = 1.000000e-231, .off = 1.076922443720738305e-248 }, + HP{ .val = 1.000000e-232, .off = -2.498633390800628939e-249 }, + HP{ .val = 1.000000e-233, .off = 4.205533798926934891e-250 }, + HP{ .val = 1.000000e-234, .off = 4.205533798926934891e-251 }, + HP{ .val = 1.000000e-235, .off = 4.205533798926934697e-252 }, + HP{ .val = 1.000000e-236, .off = -4.523850562697497656e-253 }, + HP{ .val = 1.000000e-237, .off = 9.320146633177728298e-255 }, + HP{ .val = 1.000000e-238, .off = 9.320146633177728062e-256 }, + HP{ .val = 1.000000e-239, .off = -7.592774752331086440e-256 }, + HP{ .val = 1.000000e-240, .off = 3.063212017229987840e-257 }, + HP{ .val = 1.000000e-241, .off = 3.063212017229987562e-258 }, + HP{ .val = 1.000000e-242, .off = 3.063212017229987562e-259 }, + HP{ .val = 1.000000e-243, .off = 4.616527473176159842e-261 }, + HP{ .val = 1.000000e-244, .off = 6.965550922098544975e-261 }, + HP{ .val = 1.000000e-245, .off = 6.965550922098544749e-262 }, + HP{ .val = 1.000000e-246, .off = 4.424965697574744679e-263 }, + HP{ .val = 1.000000e-247, .off = -1.926497363734756420e-264 }, + HP{ .val = 1.000000e-248, .off = 2.043167049583681740e-265 }, + HP{ .val = 1.000000e-249, .off = -5.399953725388390154e-266 }, + HP{ .val = 1.000000e-250, .off = -5.399953725388389982e-267 }, + HP{ .val = 1.000000e-251, .off = -1.523328321757102663e-268 }, + HP{ .val = 1.000000e-252, .off = 5.745344310051561161e-269 }, + HP{ .val = 1.000000e-253, .off = -6.369110076296211879e-270 }, + HP{ .val = 1.000000e-254, .off = 8.773957906638504842e-271 }, + HP{ .val = 1.000000e-255, .off = -6.904595826956931908e-273 }, + HP{ .val = 1.000000e-256, .off = 2.267170882721243669e-273 }, + HP{ .val = 1.000000e-257, .off = 2.267170882721243669e-274 }, + HP{ .val = 1.000000e-258, .off = 4.577819683828225398e-275 }, + HP{ .val = 1.000000e-259, .off = -6.975424321706684210e-276 }, + HP{ .val = 1.000000e-260, .off = 3.855741933482293648e-277 }, + HP{ .val = 1.000000e-261, .off = 1.599248963651256552e-278 }, + HP{ .val = 1.000000e-262, .off = -1.221367248637539543e-279 }, + HP{ .val = 1.000000e-263, .off = -1.221367248637539494e-280 }, + HP{ .val = 1.000000e-264, .off = -1.221367248637539647e-281 }, + HP{ .val = 1.000000e-265, .off = 1.533140771175737943e-282 }, + HP{ .val = 1.000000e-266, .off = 1.533140771175737895e-283 }, + HP{ .val = 1.000000e-267, .off = 1.533140771175738074e-284 }, + HP{ .val = 1.000000e-268, .off = 4.223090009274641634e-285 }, + HP{ .val = 1.000000e-269, .off = 4.223090009274641634e-286 }, + HP{ .val = 1.000000e-270, .off = -4.183001359784432924e-287 }, + HP{ .val = 1.000000e-271, .off = 3.697709298708449474e-288 }, + HP{ .val = 1.000000e-272, .off = 6.981338739747150474e-289 }, + HP{ .val = 1.000000e-273, .off = -9.436808465446354751e-290 }, + HP{ .val = 1.000000e-274, .off = 3.389869038611071740e-291 }, + HP{ .val = 1.000000e-275, .off = 6.596538414625427829e-292 }, + HP{ .val = 1.000000e-276, .off = -9.436808465446354618e-293 }, + HP{ .val = 1.000000e-277, .off = 3.089243784609725523e-294 }, + HP{ .val = 1.000000e-278, .off = 6.220756847123745836e-295 }, + HP{ .val = 1.000000e-279, .off = -5.522417137303829470e-296 }, + HP{ .val = 1.000000e-280, .off = 4.263561183052483059e-297 }, + HP{ .val = 1.000000e-281, .off = -1.852675267170212272e-298 }, + HP{ .val = 1.000000e-282, .off = -1.852675267170212378e-299 }, + HP{ .val = 1.000000e-283, .off = 5.314789322934508480e-300 }, + HP{ .val = 1.000000e-284, .off = -3.644541414696392675e-301 }, + HP{ .val = 1.000000e-285, .off = -7.377595888709267777e-302 }, + HP{ .val = 1.000000e-286, .off = -5.044436842451220838e-303 }, + HP{ .val = 1.000000e-287, .off = -2.127988034628661760e-304 }, + HP{ .val = 1.000000e-288, .off = -5.773549044406860911e-305 }, + HP{ .val = 1.000000e-289, .off = -1.216597782184112068e-306 }, + HP{ .val = 1.000000e-290, .off = -6.912786859962547924e-307 }, + HP{ .val = 1.000000e-291, .off = 3.767567660872018813e-308 }, }; diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 624751822a..71ac764b0b 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -107,7 +107,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), '}' => { return output(context, args[next_arg]); }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.BufWidth; }, @@ -127,7 +127,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.IntegerWidth; }, @@ -141,7 +141,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, State.FloatScientific => switch (c) { @@ -151,7 +151,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.FloatScientificWidth; }, @@ -165,7 +165,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, State.Float => switch (c) { @@ -175,7 +175,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.FloatWidth; }, @@ -189,7 +189,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, State.BufWidth => switch (c) { @@ -200,7 +200,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, State.Character => switch (c) { @@ -223,7 +223,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), radix = 1024; state = State.BytesBase; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.BytesWidth; }, @@ -236,7 +236,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.BytesWidth; }, @@ -250,7 +250,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, } @@ -562,9 +562,14 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com } } -pub fn formatBytes(value: var, width: ?usize, comptime radix: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +pub fn formatBytes( + value: var, + width: ?usize, + comptime radix: usize, + context: var, + comptime Errors: type, + output: fn(@typeOf(context), []const u8) Errors!void, +) Errors!void { if (value == 0) { return output(context, "0B"); } @@ -585,16 +590,22 @@ pub fn formatBytes(value: var, width: ?usize, comptime radix: usize, } const buf = switch (radix) { - 1000 => []u8 { suffix, 'B' }, - 1024 => []u8 { suffix, 'i', 'B' }, + 1000 => []u8{ suffix, 'B' }, + 1024 => []u8{ suffix, 'i', 'B' }, else => unreachable, }; return output(context, buf); } -pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +pub fn formatInt( + value: var, + base: u8, + uppercase: bool, + width: usize, + context: var, + comptime Errors: type, + output: fn(@typeOf(context), []const u8) Errors!void, +) Errors!void { if (@typeOf(value).is_signed) { return formatIntSigned(value, base, uppercase, width, context, Errors, output); } else { @@ -717,9 +728,9 @@ pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) ParseUnsigned pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) { const value = switch (c) { - '0' ... '9' => c - '0', - 'A' ... 'Z' => c - 'A' + 10, - 'a' ... 'z' => c - 'a' + 10, + '0'...'9' => c - '0', + 'A'...'Z' => c - 'A' + 10, + 'a'...'z' => c - 'a' + 10, else => return error.InvalidCharacter, }; @@ -730,8 +741,8 @@ pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) { fn digitToChar(digit: u8, uppercase: bool) u8 { return switch (digit) { - 0 ... 9 => digit + '0', - 10 ... 35 => digit + ((if (uppercase) u8('A') else u8('a')) - 10), + 0...9 => digit + '0', + 10...35 => digit + ((if (uppercase) u8('A') else u8('a')) - 10), else => unreachable, }; } @@ -754,8 +765,7 @@ pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) ![]u8 { pub fn allocPrint(allocator: &mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 { var size: usize = 0; - format(&size, error{}, countSize, fmt, args) catch |err| switch (err) { - }; + format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {}; const buf = try allocator.alloc(u8, size); return bufPrint(buf, fmt, args); } @@ -1043,8 +1053,7 @@ test "fmt.format" { fn testFmt(expected: []const u8, comptime template: []const u8, args: ...) !void { var buf: [100]u8 = undefined; const result = try bufPrint(buf[0..], template, args); - if (mem.eql(u8, result, expected)) - return; + if (mem.eql(u8, result, expected)) return; std.debug.warn("\n====== expected this output: =========\n"); std.debug.warn("{}", expected); @@ -1082,10 +1091,7 @@ test "fmt.trim" { pub fn isWhiteSpace(byte: u8) bool { return switch (byte) { - ' ', - '\t', - '\n', - '\r' => true, + ' ', '\t', '\n', '\r' => true, else => false, }; } diff --git a/std/hash/adler.zig b/std/hash/adler.zig index c77a5aaf50..12dab1457c 100644 --- a/std/hash/adler.zig +++ b/std/hash/adler.zig @@ -13,9 +13,7 @@ pub const Adler32 = struct { adler: u32, pub fn init() Adler32 { - return Adler32 { - .adler = 1, - }; + return Adler32{ .adler = 1 }; } // This fast variant is taken from zlib. It reduces the required modulos and unrolls longer @@ -33,8 +31,7 @@ pub const Adler32 = struct { if (s2 >= base) { s2 -= base; } - } - else if (input.len < 16) { + } else if (input.len < 16) { for (input) |b| { s1 +%= b; s2 +%= s1; @@ -44,8 +41,7 @@ pub const Adler32 = struct { } s2 %= base; - } - else { + } else { var i: usize = 0; while (i + nmax <= input.len) : (i += nmax) { const n = nmax / 16; // note: 16 | nmax @@ -98,15 +94,14 @@ test "adler32 sanity" { } test "adler32 long" { - const long1 = []u8 {1} ** 1024; + const long1 = []u8{1} ** 1024; debug.assert(Adler32.hash(long1[0..]) == 0x06780401); - const long2 = []u8 {1} ** 1025; + const long2 = []u8{1} ** 1025; debug.assert(Adler32.hash(long2[0..]) == 0x0a7a0402); } test "adler32 very long" { - const long = []u8 {1} ** 5553; + const long = []u8{1} ** 5553; debug.assert(Adler32.hash(long[0..]) == 0x707f15b2); } - diff --git a/std/hash/crc.zig b/std/hash/crc.zig index e4c1405a1c..72c4e467c2 100644 --- a/std/hash/crc.zig +++ b/std/hash/crc.zig @@ -69,7 +69,6 @@ pub fn Crc32WithPoly(comptime poly: u32) type { self.crc ^= (u32(p[2]) << 16); self.crc ^= (u32(p[3]) << 24); - self.crc = lookup_tables[0][p[7]] ^ lookup_tables[1][p[6]] ^ @@ -77,8 +76,8 @@ pub fn Crc32WithPoly(comptime poly: u32) type { lookup_tables[3][p[4]] ^ lookup_tables[4][@truncate(u8, self.crc >> 24)] ^ lookup_tables[5][@truncate(u8, self.crc >> 16)] ^ - lookup_tables[6][@truncate(u8, self.crc >> 8)] ^ - lookup_tables[7][@truncate(u8, self.crc >> 0)]; + lookup_tables[6][@truncate(u8, self.crc >> 8)] ^ + lookup_tables[7][@truncate(u8, self.crc >> 0)]; } while (i < input.len) : (i += 1) { diff --git a/std/hash/fnv.zig b/std/hash/fnv.zig index 88b965b76a..c2439e0ebc 100644 --- a/std/hash/fnv.zig +++ b/std/hash/fnv.zig @@ -7,7 +7,7 @@ const std = @import("../index.zig"); const debug = std.debug; -pub const Fnv1a_32 = Fnv1a(u32, 0x01000193 , 0x811c9dc5); +pub const Fnv1a_32 = Fnv1a(u32, 0x01000193, 0x811c9dc5); pub const Fnv1a_64 = Fnv1a(u64, 0x100000001b3, 0xcbf29ce484222325); pub const Fnv1a_128 = Fnv1a(u128, 0x1000000000000000000013b, 0x6c62272e07bb014262b821756295c58d); @@ -18,9 +18,7 @@ fn Fnv1a(comptime T: type, comptime prime: T, comptime offset: T) type { value: T, pub fn init() Self { - return Self { - .value = offset, - }; + return Self{ .value = offset }; } pub fn update(self: &Self, input: []const u8) void { diff --git a/std/hash/siphash.zig b/std/hash/siphash.zig index 301c35cf05..b75866a403 100644 --- a/std/hash/siphash.zig +++ b/std/hash/siphash.zig @@ -45,7 +45,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) const k0 = mem.readInt(key[0..8], u64, Endian.Little); const k1 = mem.readInt(key[8..16], u64, Endian.Little); - var d = Self { + var d = Self{ .v0 = k0 ^ 0x736f6d6570736575, .v1 = k1 ^ 0x646f72616e646f6d, .v2 = k0 ^ 0x6c7967656e657261, @@ -162,7 +162,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) const test_key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"; test "siphash64-2-4 sanity" { - const vectors = [][]const u8 { + const vectors = [][]const u8{ "\x31\x0e\x0e\xdd\x47\xdb\x6f\x72", // "" "\xfd\x67\xdc\x93\xc5\x39\xf8\x74", // "\x00" "\x5a\x4f\xa9\xd9\x09\x80\x6c\x0d", // "\x00\x01" ... etc @@ -241,7 +241,7 @@ test "siphash64-2-4 sanity" { } test "siphash128-2-4 sanity" { - const vectors = [][]const u8 { + const vectors = [][]const u8{ "\xa3\x81\x7f\x04\xba\x25\xa8\xe6\x6d\xf6\x72\x14\xc7\x55\x02\x93", "\xda\x87\xc1\xd8\x6b\x99\xaf\x44\x34\x76\x59\x11\x9b\x22\xfc\x45", "\x81\x77\x22\x8d\xa4\xa4\x5d\xc7\xfc\xa3\x8b\xde\xf6\x0a\xff\xe4", diff --git a/std/heap.zig b/std/heap.zig index 7b753524a6..8d4938a7c3 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -68,9 +68,7 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { const p = os.posix; const alloc_size = if (alignment <= os.page_size) n else n + alignment; const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0); @@ -121,9 +119,7 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { if (new_size <= old_mem.len) { const base_addr = @ptrToInt(old_mem.ptr); const old_addr_end = base_addr + old_mem.len; @@ -168,9 +164,7 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { _ = os.posix.munmap(@ptrToInt(bytes.ptr), bytes.len); }, Os.windows => { @@ -430,7 +424,7 @@ fn testAllocator(allocator: &mem.Allocator) !void { } fn testAllocatorLargeAlignment(allocator: &mem.Allocator) mem.Allocator.Error!void { - //Maybe a platform's page_size is actually the same as or + //Maybe a platform's page_size is actually the same as or // very near usize? if (os.page_size << 2 > @maxValue(usize)) return; diff --git a/std/io_test.zig b/std/io_test.zig index 5f53556785..ca4eeb3aaa 100644 --- a/std/io_test.zig +++ b/std/io_test.zig @@ -42,7 +42,7 @@ test "write a file, read it, then delete it" { assert(mem.eql(u8, contents[0.."begin".len], "begin")); assert(mem.eql(u8, contents["begin".len..contents.len - "end".len], data)); - assert(mem.eql(u8, contents[contents.len - "end".len ..], "end")); + assert(mem.eql(u8, contents[contents.len - "end".len..], "end")); } try os.deleteFile(allocator, tmp_file_name); } diff --git a/std/json.zig b/std/json.zig index e969899403..c88ce59139 100644 --- a/std/json.zig +++ b/std/json.zig @@ -252,7 +252,7 @@ pub const StreamingJsonParser = struct { p.after_value_state = State.TopLevelEnd; p.count = 0; }, - '1' ... '9' => { + '1'...'9' => { p.number_is_integer = true; p.state = State.NumberMaybeDigitOrDotOrExponent; p.after_value_state = State.TopLevelEnd; @@ -281,10 +281,7 @@ pub const StreamingJsonParser = struct { p.after_value_state = State.TopLevelEnd; p.count = 0; }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -293,10 +290,7 @@ pub const StreamingJsonParser = struct { }, State.TopLevelEnd => switch (c) { - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -392,7 +386,7 @@ pub const StreamingJsonParser = struct { p.state = State.NumberMaybeDotOrExponent; p.count = 0; }, - '1' ... '9' => { + '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; p.count = 0; }, @@ -412,10 +406,7 @@ pub const StreamingJsonParser = struct { p.state = State.NullLiteral1; p.count = 0; }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -461,7 +452,7 @@ pub const StreamingJsonParser = struct { p.state = State.NumberMaybeDotOrExponent; p.count = 0; }, - '1' ... '9' => { + '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; p.count = 0; }, @@ -481,10 +472,7 @@ pub const StreamingJsonParser = struct { p.state = State.NullLiteral1; p.count = 0; }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -533,10 +521,7 @@ pub const StreamingJsonParser = struct { token.* = Token.initMarker(Token.Id.ObjectEnd); }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -549,10 +534,7 @@ pub const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -561,7 +543,7 @@ pub const StreamingJsonParser = struct { }, State.String => switch (c) { - 0x00 ... 0x1F => { + 0x00...0x1F => { return error.InvalidControlCharacter; }, '"' => { @@ -576,19 +558,16 @@ pub const StreamingJsonParser = struct { '\\' => { p.state = State.StringEscapeCharacter; }, - 0x20, - 0x21, - 0x23 ... 0x5B, - 0x5D ... 0x7F => { + 0x20, 0x21, 0x23...0x5B, 0x5D...0x7F => { // non-control ascii }, - 0xC0 ... 0xDF => { + 0xC0...0xDF => { p.state = State.StringUtf8Byte1; }, - 0xE0 ... 0xEF => { + 0xE0...0xEF => { p.state = State.StringUtf8Byte2; }, - 0xF0 ... 0xFF => { + 0xF0...0xFF => { p.state = State.StringUtf8Byte3; }, else => { @@ -620,14 +599,7 @@ pub const StreamingJsonParser = struct { // The current JSONTestSuite tests rely on both of this behaviour being present // however, so we default to the status quo where both are accepted until this // is further clarified. - '"', - '\\', - '/', - 'b', - 'f', - 'n', - 'r', - 't' => { + '"', '\\', '/', 'b', 'f', 'n', 'r', 't' => { p.string_has_escape = true; p.state = State.String; }, @@ -641,36 +613,28 @@ pub const StreamingJsonParser = struct { }, State.StringEscapeHexUnicode4 => switch (c) { - '0' ... '9', - 'A' ... 'F', - 'a' ... 'f' => { + '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode3; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode3 => switch (c) { - '0' ... '9', - 'A' ... 'F', - 'a' ... 'f' => { + '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode2; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode2 => switch (c) { - '0' ... '9', - 'A' ... 'F', - 'a' ... 'f' => { + '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode1; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode1 => switch (c) { - '0' ... '9', - 'A' ... 'F', - 'a' ... 'f' => { + '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.String; }, else => return error.InvalidUnicodeHexSymbol, @@ -682,7 +646,7 @@ pub const StreamingJsonParser = struct { '0' => { p.state = State.NumberMaybeDotOrExponent; }, - '1' ... '9' => { + '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; }, else => { @@ -698,8 +662,7 @@ pub const StreamingJsonParser = struct { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, - 'e', - 'E' => { + 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, @@ -718,12 +681,11 @@ pub const StreamingJsonParser = struct { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, - 'e', - 'E' => { + 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, - '0' ... '9' => { + '0'...'9' => { // another digit }, else => { @@ -737,7 +699,7 @@ pub const StreamingJsonParser = struct { State.NumberFractionalRequired => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - '0' ... '9' => { + '0'...'9' => { p.state = State.NumberFractional; }, else => { @@ -749,11 +711,10 @@ pub const StreamingJsonParser = struct { State.NumberFractional => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - '0' ... '9' => { + '0'...'9' => { // another digit }, - 'e', - 'E' => { + 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, @@ -768,8 +729,7 @@ pub const StreamingJsonParser = struct { State.NumberMaybeExponent => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - 'e', - 'E' => { + 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, @@ -782,12 +742,11 @@ pub const StreamingJsonParser = struct { }, State.NumberExponent => switch (c) { - '-', - '+' => { + '-', '+' => { p.complete = false; p.state = State.NumberExponentDigitsRequired; }, - '0' ... '9' => { + '0'...'9' => { p.complete = p.after_value_state == State.TopLevelEnd; p.state = State.NumberExponentDigits; }, @@ -797,7 +756,7 @@ pub const StreamingJsonParser = struct { }, State.NumberExponentDigitsRequired => switch (c) { - '0' ... '9' => { + '0'...'9' => { p.complete = p.after_value_state == State.TopLevelEnd; p.state = State.NumberExponentDigits; }, @@ -809,7 +768,7 @@ pub const StreamingJsonParser = struct { State.NumberExponentDigits => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - '0' ... '9' => { + '0'...'9' => { // another digit }, else => { @@ -1257,8 +1216,7 @@ pub const JsonParser = struct { Token.Id.Null => { try p.stack.append(Value.Null); }, - Token.Id.ObjectEnd, - Token.Id.ArrayEnd => { + Token.Id.ObjectEnd, Token.Id.ArrayEnd => { unreachable; }, }, diff --git a/std/macho.zig b/std/macho.zig index 70e2c09788..615569e4b4 100644 --- a/std/macho.zig +++ b/std/macho.zig @@ -58,15 +58,15 @@ pub const SymbolTable = struct { // code, its displacement is different. pub fn deinit(self: &SymbolTable) void { self.allocator.free(self.symbols); - self.symbols = []const Symbol {}; + self.symbols = []const Symbol{}; self.allocator.free(self.strings); - self.strings = []const u8 {}; + self.strings = []const u8{}; } pub fn search(self: &const SymbolTable, address: usize) ?&const Symbol { var min: usize = 0; - var max: usize = self.symbols.len - 1; // Exclude sentinel. + var max: usize = self.symbols.len - 1; // Exclude sentinel. while (min < max) { const mid = min + (max - min) / 2; const curr = &self.symbols[mid]; @@ -118,10 +118,11 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable try in.stream.readNoEof(strings); var nsyms: usize = 0; - for (syms) |sym| if (isSymbol(sym)) nsyms += 1; + for (syms) |sym| + if (isSymbol(sym)) nsyms += 1; if (nsyms == 0) return error.MissingDebugInfo; - var symbols = try allocator.alloc(Symbol, nsyms + 1); // Room for sentinel. + var symbols = try allocator.alloc(Symbol, nsyms + 1); // Room for sentinel. errdefer allocator.free(symbols); var pie_slide: usize = 0; @@ -132,7 +133,7 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable const end = ??mem.indexOfScalarPos(u8, strings, start, 0); const name = strings[start..end]; const address = sym.n_value; - symbols[nsym] = Symbol { .name = name, .address = address }; + symbols[nsym] = Symbol{ .name = name, .address = address }; nsym += 1; if (is_pie and mem.eql(u8, name, "_SymbolTable_deinit")) { pie_slide = @ptrToInt(SymbolTable.deinit) - address; @@ -145,13 +146,14 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable // Insert the sentinel. Since we don't know where the last function ends, // we arbitrarily limit it to the start address + 4 KB. const top = symbols[nsyms - 1].address + 4096; - symbols[nsyms] = Symbol { .name = "", .address = top }; + symbols[nsyms] = Symbol{ .name = "", .address = top }; if (pie_slide != 0) { - for (symbols) |*symbol| symbol.address += pie_slide; + for (symbols) |*symbol| + symbol.address += pie_slide; } - return SymbolTable { + return SymbolTable{ .allocator = allocator, .symbols = symbols, .strings = strings, diff --git a/std/math/atan.zig b/std/math/atan.zig index c315adc42d..7eceef98e3 100644 --- a/std/math/atan.zig +++ b/std/math/atan.zig @@ -17,25 +17,25 @@ pub fn atan(x: var) @typeOf(x) { } fn atan32(x_: f32) f32 { - const atanhi = []const f32 { + const atanhi = []const f32{ 4.6364760399e-01, // atan(0.5)hi 7.8539812565e-01, // atan(1.0)hi 9.8279368877e-01, // atan(1.5)hi 1.5707962513e+00, // atan(inf)hi }; - const atanlo = []const f32 { + const atanlo = []const f32{ 5.0121582440e-09, // atan(0.5)lo 3.7748947079e-08, // atan(1.0)lo 3.4473217170e-08, // atan(1.5)lo 7.5497894159e-08, // atan(inf)lo }; - const aT = []const f32 { + const aT = []const f32{ 3.3333328366e-01, - -1.9999158382e-01, + -1.9999158382e-01, 1.4253635705e-01, - -1.0648017377e-01, + -1.0648017377e-01, 6.1687607318e-02, }; @@ -80,8 +80,7 @@ fn atan32(x_: f32) f32 { id = 1; x = (x - 1.0) / (x + 1.0); } - } - else { + } else { // |x| < 2.4375 if (ix < 0x401C0000) { id = 2; @@ -109,31 +108,31 @@ fn atan32(x_: f32) f32 { } fn atan64(x_: f64) f64 { - const atanhi = []const f64 { + const atanhi = []const f64{ 4.63647609000806093515e-01, // atan(0.5)hi 7.85398163397448278999e-01, // atan(1.0)hi 9.82793723247329054082e-01, // atan(1.5)hi 1.57079632679489655800e+00, // atan(inf)hi }; - const atanlo = []const f64 { + const atanlo = []const f64{ 2.26987774529616870924e-17, // atan(0.5)lo 3.06161699786838301793e-17, // atan(1.0)lo 1.39033110312309984516e-17, // atan(1.5)lo 6.12323399573676603587e-17, // atan(inf)lo }; - const aT = []const f64 { + const aT = []const f64{ 3.33333333333329318027e-01, - -1.99999999998764832476e-01, + -1.99999999998764832476e-01, 1.42857142725034663711e-01, - -1.11111104054623557880e-01, + -1.11111104054623557880e-01, 9.09088713343650656196e-02, - -7.69187620504482999495e-02, + -7.69187620504482999495e-02, 6.66107313738753120669e-02, - -5.83357013379057348645e-02, + -5.83357013379057348645e-02, 4.97687799461593236017e-02, - -3.65315727442169155270e-02, + -3.65315727442169155270e-02, 1.62858201153657823623e-02, }; @@ -179,8 +178,7 @@ fn atan64(x_: f64) f64 { id = 1; x = (x - 1.0) / (x + 1.0); } - } - else { + } else { // |x| < 2.4375 if (ix < 0x40038000) { id = 2; diff --git a/std/math/atan2.zig b/std/math/atan2.zig index 0892f0b438..f0a8e67c46 100644 --- a/std/math/atan2.zig +++ b/std/math/atan2.zig @@ -53,8 +53,7 @@ fn atan2_32(y: f32, x: f32) f32 { if (iy == 0) { switch (m) { - 0, - 1 => return y, // atan(+-0, +...) + 0, 1 => return y, // atan(+-0, +...) 2 => return pi, // atan(+0, -...) 3 => return -pi, // atan(-0, -...) else => unreachable, @@ -144,8 +143,7 @@ fn atan2_64(y: f64, x: f64) f64 { if (iy | ly == 0) { switch (m) { - 0, - 1 => return y, // atan(+-0, +...) + 0, 1 => return y, // atan(+-0, +...) 2 => return pi, // atan(+0, -...) 3 => return -pi, // atan(-0, -...) else => unreachable, diff --git a/std/math/complex/index.zig b/std/math/complex/index.zig index a4d493307e..5902ffaa19 100644 --- a/std/math/complex/index.zig +++ b/std/math/complex/index.zig @@ -31,28 +31,28 @@ pub fn Complex(comptime T: type) type { im: T, pub fn new(re: T, im: T) Self { - return Self { + return Self{ .re = re, .im = im, }; } pub fn add(self: &const Self, other: &const Self) Self { - return Self { + return Self{ .re = self.re + other.re, .im = self.im + other.im, }; } pub fn sub(self: &const Self, other: &const Self) Self { - return Self { + return Self{ .re = self.re - other.re, .im = self.im - other.im, }; } pub fn mul(self: &const Self, other: &const Self) Self { - return Self { + return Self{ .re = self.re * other.re - self.im * other.im, .im = self.im * other.re + self.re * other.im, }; @@ -63,14 +63,14 @@ pub fn Complex(comptime T: type) type { const im_num = self.im * other.re - self.re * other.im; const den = other.re * other.re + other.im * other.im; - return Self { + return Self{ .re = re_num / den, .im = im_num / den, }; } pub fn conjugate(self: &const Self) Self { - return Self { + return Self{ .re = self.re, .im = -self.im, }; @@ -78,7 +78,7 @@ pub fn Complex(comptime T: type) type { pub fn reciprocal(self: &const Self) Self { const m = self.re * self.re + self.im * self.im; - return Self { + return Self{ .re = self.re / m, .im = -self.im / m, }; @@ -121,8 +121,8 @@ test "complex.div" { const b = Complex(f32).new(2, 7); const c = a.div(b); - debug.assert(math.approxEq(f32, c.re, f32(31)/53, epsilon) and - math.approxEq(f32, c.im, f32(-29)/53, epsilon)); + debug.assert(math.approxEq(f32, c.re, f32(31) / 53, epsilon) and + math.approxEq(f32, c.im, f32(-29) / 53, epsilon)); } test "complex.conjugate" { @@ -136,8 +136,8 @@ test "complex.reciprocal" { const a = Complex(f32).new(5, 3); const c = a.reciprocal(); - debug.assert(math.approxEq(f32, c.re, f32(5)/34, epsilon) and - math.approxEq(f32, c.im, f32(-3)/34, epsilon)); + debug.assert(math.approxEq(f32, c.re, f32(5) / 34, epsilon) and + math.approxEq(f32, c.im, f32(-3) / 34, epsilon)); } test "complex.magnitude" { diff --git a/std/math/complex/tanh.zig b/std/math/complex/tanh.zig index 6af62f48ae..34250b1b4a 100644 --- a/std/math/complex/tanh.zig +++ b/std/math/complex/tanh.zig @@ -98,7 +98,7 @@ test "complex.ctanh32" { const a = Complex(f32).new(5, 3); const c = tanh(a); - debug.assert(math.approxEq(f32, c.re, 0.999913, epsilon)); + debug.assert(math.approxEq(f32, c.re, 0.999913, epsilon)); debug.assert(math.approxEq(f32, c.im, -0.000025, epsilon)); } @@ -106,6 +106,6 @@ test "complex.ctanh64" { const a = Complex(f64).new(5, 3); const c = tanh(a); - debug.assert(math.approxEq(f64, c.re, 0.999913, epsilon)); + debug.assert(math.approxEq(f64, c.re, 0.999913, epsilon)); debug.assert(math.approxEq(f64, c.im, -0.000025, epsilon)); } diff --git a/std/math/exp.zig b/std/math/exp.zig index 21aa558c57..76dc47d04b 100644 --- a/std/math/exp.zig +++ b/std/math/exp.zig @@ -20,10 +20,10 @@ pub fn exp(x: var) @typeOf(x) { fn exp32(x_: f32) f32 { @setFloatMode(this, builtin.FloatMode.Strict); - const half = []f32 { 0.5, -0.5 }; + const half = []f32{ 0.5, -0.5 }; const ln2hi = 6.9314575195e-1; const ln2lo = 1.4286067653e-6; - const invln2 = 1.4426950216e+0; + const invln2 = 1.4426950216e+0; const P1 = 1.6666625440e-1; const P2 = -2.7667332906e-3; @@ -47,7 +47,7 @@ fn exp32(x_: f32) f32 { return x * 0x1.0p127; } if (sign != 0) { - math.forceEval(-0x1.0p-149 / x); // overflow + math.forceEval(-0x1.0p-149 / x); // overflow // x <= -103.972084 if (hx >= 0x42CFF1B5) { return 0; @@ -64,8 +64,7 @@ fn exp32(x_: f32) f32 { // |x| > 1.5 * ln2 if (hx > 0x3F851592) { k = i32(invln2 * x + half[usize(sign)]); - } - else { + } else { k = 1 - sign - sign; } @@ -79,8 +78,7 @@ fn exp32(x_: f32) f32 { k = 0; hi = x; lo = 0; - } - else { + } else { math.forceEval(0x1.0p127 + x); // inexact return 1 + x; } @@ -99,15 +97,15 @@ fn exp32(x_: f32) f32 { fn exp64(x_: f64) f64 { @setFloatMode(this, builtin.FloatMode.Strict); - const half = []const f64 { 0.5, -0.5 }; + const half = []const f64{ 0.5, -0.5 }; const ln2hi: f64 = 6.93147180369123816490e-01; const ln2lo: f64 = 1.90821492927058770002e-10; const invln2: f64 = 1.44269504088896338700e+00; - const P1: f64 = 1.66666666666666019037e-01; - const P2: f64 = -2.77777777770155933842e-03; - const P3: f64 = 6.61375632143793436117e-05; - const P4: f64 = -1.65339022054652515390e-06; - const P5: f64 = 4.13813679705723846039e-08; + const P1: f64 = 1.66666666666666019037e-01; + const P2: f64 = -2.77777777770155933842e-03; + const P3: f64 = 6.61375632143793436117e-05; + const P4: f64 = -1.65339022054652515390e-06; + const P5: f64 = 4.13813679705723846039e-08; var x = x_; var ux = @bitCast(u64, x); @@ -151,8 +149,7 @@ fn exp64(x_: f64) f64 { // |x| >= 1.5 * ln2 if (hx > 0x3FF0A2B2) { k = i32(invln2 * x + half[usize(sign)]); - } - else { + } else { k = 1 - sign - sign; } @@ -166,8 +163,7 @@ fn exp64(x_: f64) f64 { k = 0; hi = x; lo = 0; - } - else { + } else { // inexact if x != 0 // math.forceEval(0x1.0p1023 + x); return 1 + x; diff --git a/std/math/exp2.zig b/std/math/exp2.zig index 790bd1a558..62a3eb85b6 100644 --- a/std/math/exp2.zig +++ b/std/math/exp2.zig @@ -16,7 +16,7 @@ pub fn exp2(x: var) @typeOf(x) { }; } -const exp2ft = []const f64 { +const exp2ft = []const f64{ 0x1.6a09e667f3bcdp-1, 0x1.7a11473eb0187p-1, 0x1.8ace5422aa0dbp-1, @@ -92,195 +92,195 @@ fn exp2_32(x: f32) f32 { return f32(r * uk); } -const exp2dt = []f64 { +const exp2dt = []f64{ // exp2(z + eps) eps - 0x1.6a09e667f3d5dp-1, 0x1.9880p-44, - 0x1.6b052fa751744p-1, 0x1.8000p-50, + 0x1.6a09e667f3d5dp-1, 0x1.9880p-44, + 0x1.6b052fa751744p-1, 0x1.8000p-50, 0x1.6c012750bd9fep-1, -0x1.8780p-45, - 0x1.6cfdcddd476bfp-1, 0x1.ec00p-46, + 0x1.6cfdcddd476bfp-1, 0x1.ec00p-46, 0x1.6dfb23c651a29p-1, -0x1.8000p-50, 0x1.6ef9298593ae3p-1, -0x1.c000p-52, 0x1.6ff7df9519386p-1, -0x1.fd80p-45, 0x1.70f7466f42da3p-1, -0x1.c880p-45, - 0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46, + 0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46, 0x1.72f8286eacf05p-1, -0x1.8300p-44, 0x1.73f9a48a58152p-1, -0x1.0c00p-47, - 0x1.74fbd35d7ccfcp-1, 0x1.f880p-45, - 0x1.75feb564267f1p-1, 0x1.3e00p-47, + 0x1.74fbd35d7ccfcp-1, 0x1.f880p-45, + 0x1.75feb564267f1p-1, 0x1.3e00p-47, 0x1.77024b1ab6d48p-1, -0x1.7d00p-45, 0x1.780694fde5d38p-1, -0x1.d000p-50, - 0x1.790b938ac1d00p-1, 0x1.3000p-49, + 0x1.790b938ac1d00p-1, 0x1.3000p-49, 0x1.7a11473eb0178p-1, -0x1.d000p-49, - 0x1.7b17b0976d060p-1, 0x1.0400p-45, - 0x1.7c1ed0130c133p-1, 0x1.0000p-53, + 0x1.7b17b0976d060p-1, 0x1.0400p-45, + 0x1.7c1ed0130c133p-1, 0x1.0000p-53, 0x1.7d26a62ff8636p-1, -0x1.6900p-45, 0x1.7e2f336cf4e3bp-1, -0x1.2e00p-47, 0x1.7f3878491c3e8p-1, -0x1.4580p-45, - 0x1.80427543e1b4ep-1, 0x1.3000p-44, - 0x1.814d2add1071ap-1, 0x1.f000p-47, + 0x1.80427543e1b4ep-1, 0x1.3000p-44, + 0x1.814d2add1071ap-1, 0x1.f000p-47, 0x1.82589994ccd7ep-1, -0x1.1c00p-45, - 0x1.8364c1eb942d0p-1, 0x1.9d00p-45, - 0x1.8471a4623cab5p-1, 0x1.7100p-43, - 0x1.857f4179f5bbcp-1, 0x1.2600p-45, + 0x1.8364c1eb942d0p-1, 0x1.9d00p-45, + 0x1.8471a4623cab5p-1, 0x1.7100p-43, + 0x1.857f4179f5bbcp-1, 0x1.2600p-45, 0x1.868d99b4491afp-1, -0x1.2c40p-44, 0x1.879cad931a395p-1, -0x1.3000p-45, 0x1.88ac7d98a65b8p-1, -0x1.a800p-45, 0x1.89bd0a4785800p-1, -0x1.d000p-49, - 0x1.8ace5422aa223p-1, 0x1.3280p-44, - 0x1.8be05bad619fap-1, 0x1.2b40p-43, + 0x1.8ace5422aa223p-1, 0x1.3280p-44, + 0x1.8be05bad619fap-1, 0x1.2b40p-43, 0x1.8cf3216b54383p-1, -0x1.ed00p-45, 0x1.8e06a5e08664cp-1, -0x1.0500p-45, - 0x1.8f1ae99157807p-1, 0x1.8280p-45, + 0x1.8f1ae99157807p-1, 0x1.8280p-45, 0x1.902fed0282c0ep-1, -0x1.cb00p-46, 0x1.9145b0b91ff96p-1, -0x1.5e00p-47, - 0x1.925c353aa2ff9p-1, 0x1.5400p-48, - 0x1.93737b0cdc64ap-1, 0x1.7200p-46, + 0x1.925c353aa2ff9p-1, 0x1.5400p-48, + 0x1.93737b0cdc64ap-1, 0x1.7200p-46, 0x1.948b82b5f98aep-1, -0x1.9000p-47, - 0x1.95a44cbc852cbp-1, 0x1.5680p-45, + 0x1.95a44cbc852cbp-1, 0x1.5680p-45, 0x1.96bdd9a766f21p-1, -0x1.6d00p-44, 0x1.97d829fde4e2ap-1, -0x1.1000p-47, - 0x1.98f33e47a23a3p-1, 0x1.d000p-45, + 0x1.98f33e47a23a3p-1, 0x1.d000p-45, 0x1.9a0f170ca0604p-1, -0x1.8a40p-44, - 0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44, - 0x1.9c49182a3f15bp-1, 0x1.6b80p-45, + 0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44, + 0x1.9c49182a3f15bp-1, 0x1.6b80p-45, 0x1.9d674194bb8c5p-1, -0x1.c000p-49, - 0x1.9e86319e3238ep-1, 0x1.7d00p-46, - 0x1.9fa5e8d07f302p-1, 0x1.6400p-46, + 0x1.9e86319e3238ep-1, 0x1.7d00p-46, + 0x1.9fa5e8d07f302p-1, 0x1.6400p-46, 0x1.a0c667b5de54dp-1, -0x1.5000p-48, - 0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47, - 0x1.a309bec4a2e27p-1, 0x1.ad80p-45, + 0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47, + 0x1.a309bec4a2e27p-1, 0x1.ad80p-45, 0x1.a42c980460a5dp-1, -0x1.af00p-46, - 0x1.a5503b23e259bp-1, 0x1.b600p-47, - 0x1.a674a8af46213p-1, 0x1.8880p-44, - 0x1.a799e1330b3a7p-1, 0x1.1200p-46, - 0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47, + 0x1.a5503b23e259bp-1, 0x1.b600p-47, + 0x1.a674a8af46213p-1, 0x1.8880p-44, + 0x1.a799e1330b3a7p-1, 0x1.1200p-46, + 0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47, 0x1.a9e6b5579fcd2p-1, -0x1.9b80p-45, - 0x1.ab0e521356fb8p-1, 0x1.b700p-45, - 0x1.ac36bbfd3f381p-1, 0x1.9000p-50, - 0x1.ad5ff3a3c2780p-1, 0x1.4000p-49, + 0x1.ab0e521356fb8p-1, 0x1.b700p-45, + 0x1.ac36bbfd3f381p-1, 0x1.9000p-50, + 0x1.ad5ff3a3c2780p-1, 0x1.4000p-49, 0x1.ae89f995ad2a3p-1, -0x1.c900p-45, - 0x1.afb4ce622f367p-1, 0x1.6500p-46, - 0x1.b0e07298db790p-1, 0x1.fd40p-45, - 0x1.b20ce6c9a89a9p-1, 0x1.2700p-46, - 0x1.b33a2b84f1a4bp-1, 0x1.d470p-43, + 0x1.afb4ce622f367p-1, 0x1.6500p-46, + 0x1.b0e07298db790p-1, 0x1.fd40p-45, + 0x1.b20ce6c9a89a9p-1, 0x1.2700p-46, + 0x1.b33a2b84f1a4bp-1, 0x1.d470p-43, 0x1.b468415b747e7p-1, -0x1.8380p-44, - 0x1.b59728de5593ap-1, 0x1.8000p-54, - 0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47, - 0x1.b7f76f2fb5e50p-1, 0x1.e800p-50, + 0x1.b59728de5593ap-1, 0x1.8000p-54, + 0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47, + 0x1.b7f76f2fb5e50p-1, 0x1.e800p-50, 0x1.b928cf22749b2p-1, -0x1.4c00p-47, 0x1.ba5b030a10603p-1, -0x1.d700p-47, - 0x1.bb8e0b79a6f66p-1, 0x1.d900p-47, - 0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47, + 0x1.bb8e0b79a6f66p-1, 0x1.d900p-47, + 0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47, 0x1.bdf69c3f3a16fp-1, -0x1.f780p-46, 0x1.bf2c25bd71db8p-1, -0x1.0a00p-46, 0x1.c06286141b2e9p-1, -0x1.1400p-46, - 0x1.c199bdd8552e0p-1, 0x1.be00p-47, + 0x1.c199bdd8552e0p-1, 0x1.be00p-47, 0x1.c2d1cd9fa64eep-1, -0x1.9400p-47, 0x1.c40ab5fffd02fp-1, -0x1.ed00p-47, - 0x1.c544778fafd15p-1, 0x1.9660p-44, + 0x1.c544778fafd15p-1, 0x1.9660p-44, 0x1.c67f12e57d0cbp-1, -0x1.a100p-46, 0x1.c7ba88988c1b6p-1, -0x1.8458p-42, 0x1.c8f6d9406e733p-1, -0x1.a480p-46, - 0x1.ca3405751c4dfp-1, 0x1.b000p-51, - 0x1.cb720dcef9094p-1, 0x1.1400p-47, - 0x1.ccb0f2e6d1689p-1, 0x1.0200p-48, - 0x1.cdf0b555dc412p-1, 0x1.3600p-48, + 0x1.ca3405751c4dfp-1, 0x1.b000p-51, + 0x1.cb720dcef9094p-1, 0x1.1400p-47, + 0x1.ccb0f2e6d1689p-1, 0x1.0200p-48, + 0x1.cdf0b555dc412p-1, 0x1.3600p-48, 0x1.cf3155b5bab3bp-1, -0x1.6900p-47, - 0x1.d072d4a0789bcp-1, 0x1.9a00p-47, + 0x1.d072d4a0789bcp-1, 0x1.9a00p-47, 0x1.d1b532b08c8fap-1, -0x1.5e00p-46, - 0x1.d2f87080d8a85p-1, 0x1.d280p-46, - 0x1.d43c8eacaa203p-1, 0x1.1a00p-47, - 0x1.d5818dcfba491p-1, 0x1.f000p-50, + 0x1.d2f87080d8a85p-1, 0x1.d280p-46, + 0x1.d43c8eacaa203p-1, 0x1.1a00p-47, + 0x1.d5818dcfba491p-1, 0x1.f000p-50, 0x1.d6c76e862e6a1p-1, -0x1.3a00p-47, 0x1.d80e316c9834ep-1, -0x1.cd80p-47, - 0x1.d955d71ff6090p-1, 0x1.4c00p-48, - 0x1.da9e603db32aep-1, 0x1.f900p-48, - 0x1.dbe7cd63a8325p-1, 0x1.9800p-49, + 0x1.d955d71ff6090p-1, 0x1.4c00p-48, + 0x1.da9e603db32aep-1, 0x1.f900p-48, + 0x1.dbe7cd63a8325p-1, 0x1.9800p-49, 0x1.dd321f301b445p-1, -0x1.5200p-48, 0x1.de7d5641c05bfp-1, -0x1.d700p-46, 0x1.dfc97337b9aecp-1, -0x1.6140p-46, - 0x1.e11676b197d5ep-1, 0x1.b480p-47, - 0x1.e264614f5a3e7p-1, 0x1.0ce0p-43, - 0x1.e3b333b16ee5cp-1, 0x1.c680p-47, + 0x1.e11676b197d5ep-1, 0x1.b480p-47, + 0x1.e264614f5a3e7p-1, 0x1.0ce0p-43, + 0x1.e3b333b16ee5cp-1, 0x1.c680p-47, 0x1.e502ee78b3fb4p-1, -0x1.9300p-47, 0x1.e653924676d68p-1, -0x1.5000p-49, 0x1.e7a51fbc74c44p-1, -0x1.7f80p-47, 0x1.e8f7977cdb726p-1, -0x1.3700p-48, - 0x1.ea4afa2a490e8p-1, 0x1.5d00p-49, - 0x1.eb9f4867ccae4p-1, 0x1.61a0p-46, - 0x1.ecf482d8e680dp-1, 0x1.5500p-48, - 0x1.ee4aaa2188514p-1, 0x1.6400p-51, + 0x1.ea4afa2a490e8p-1, 0x1.5d00p-49, + 0x1.eb9f4867ccae4p-1, 0x1.61a0p-46, + 0x1.ecf482d8e680dp-1, 0x1.5500p-48, + 0x1.ee4aaa2188514p-1, 0x1.6400p-51, 0x1.efa1bee615a13p-1, -0x1.e800p-49, 0x1.f0f9c1cb64106p-1, -0x1.a880p-48, 0x1.f252b376bb963p-1, -0x1.c900p-45, - 0x1.f3ac948dd7275p-1, 0x1.a000p-53, + 0x1.f3ac948dd7275p-1, 0x1.a000p-53, 0x1.f50765b6e4524p-1, -0x1.4f00p-48, - 0x1.f6632798844fdp-1, 0x1.a800p-51, - 0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48, + 0x1.f6632798844fdp-1, 0x1.a800p-51, + 0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48, 0x1.f91d802243c82p-1, -0x1.4600p-50, 0x1.fa7c1819e908ep-1, -0x1.b0c0p-47, 0x1.fbdba3692d511p-1, -0x1.0e00p-51, 0x1.fd3c22b8f7194p-1, -0x1.0de8p-46, - 0x1.fe9d96b2a23eep-1, 0x1.e430p-49, - 0x1.0000000000000p+0, 0x0.0000p+0, + 0x1.fe9d96b2a23eep-1, 0x1.e430p-49, + 0x1.0000000000000p+0, 0x0.0000p+0, 0x1.00b1afa5abcbep+0, -0x1.3400p-52, 0x1.0163da9fb3303p+0, -0x1.2170p-46, - 0x1.02168143b0282p+0, 0x1.a400p-52, - 0x1.02c9a3e77806cp+0, 0x1.f980p-49, + 0x1.02168143b0282p+0, 0x1.a400p-52, + 0x1.02c9a3e77806cp+0, 0x1.f980p-49, 0x1.037d42e11bbcap+0, -0x1.7400p-51, - 0x1.04315e86e7f89p+0, 0x1.8300p-50, + 0x1.04315e86e7f89p+0, 0x1.8300p-50, 0x1.04e5f72f65467p+0, -0x1.a3f0p-46, 0x1.059b0d315855ap+0, -0x1.2840p-47, - 0x1.0650a0e3c1f95p+0, 0x1.1600p-48, - 0x1.0706b29ddf71ap+0, 0x1.5240p-46, + 0x1.0650a0e3c1f95p+0, 0x1.1600p-48, + 0x1.0706b29ddf71ap+0, 0x1.5240p-46, 0x1.07bd42b72a82dp+0, -0x1.9a00p-49, - 0x1.0874518759bd0p+0, 0x1.6400p-49, + 0x1.0874518759bd0p+0, 0x1.6400p-49, 0x1.092bdf66607c8p+0, -0x1.0780p-47, 0x1.09e3ecac6f383p+0, -0x1.8000p-54, - 0x1.0a9c79b1f3930p+0, 0x1.fa00p-48, + 0x1.0a9c79b1f3930p+0, 0x1.fa00p-48, 0x1.0b5586cf988fcp+0, -0x1.ac80p-48, - 0x1.0c0f145e46c8ap+0, 0x1.9c00p-50, - 0x1.0cc922b724816p+0, 0x1.5200p-47, + 0x1.0c0f145e46c8ap+0, 0x1.9c00p-50, + 0x1.0cc922b724816p+0, 0x1.5200p-47, 0x1.0d83b23395dd8p+0, -0x1.ad00p-48, - 0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46, + 0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46, 0x1.0efa55fdfa9a6p+0, -0x1.4e80p-47, 0x1.0fb66affed2f0p+0, -0x1.d300p-47, - 0x1.1073028d7234bp+0, 0x1.1500p-48, - 0x1.11301d0125b5bp+0, 0x1.c000p-49, - 0x1.11edbab5e2af9p+0, 0x1.6bc0p-46, - 0x1.12abdc06c31d5p+0, 0x1.8400p-49, + 0x1.1073028d7234bp+0, 0x1.1500p-48, + 0x1.11301d0125b5bp+0, 0x1.c000p-49, + 0x1.11edbab5e2af9p+0, 0x1.6bc0p-46, + 0x1.12abdc06c31d5p+0, 0x1.8400p-49, 0x1.136a814f2047dp+0, -0x1.ed00p-47, - 0x1.1429aaea92de9p+0, 0x1.8e00p-49, - 0x1.14e95934f3138p+0, 0x1.b400p-49, - 0x1.15a98c8a58e71p+0, 0x1.5300p-47, - 0x1.166a45471c3dfp+0, 0x1.3380p-47, - 0x1.172b83c7d5211p+0, 0x1.8d40p-45, + 0x1.1429aaea92de9p+0, 0x1.8e00p-49, + 0x1.14e95934f3138p+0, 0x1.b400p-49, + 0x1.15a98c8a58e71p+0, 0x1.5300p-47, + 0x1.166a45471c3dfp+0, 0x1.3380p-47, + 0x1.172b83c7d5211p+0, 0x1.8d40p-45, 0x1.17ed48695bb9fp+0, -0x1.5d00p-47, 0x1.18af9388c8d93p+0, -0x1.c880p-46, - 0x1.1972658375d66p+0, 0x1.1f00p-46, - 0x1.1a35beb6fcba7p+0, 0x1.0480p-46, + 0x1.1972658375d66p+0, 0x1.1f00p-46, + 0x1.1a35beb6fcba7p+0, 0x1.0480p-46, 0x1.1af99f81387e3p+0, -0x1.7390p-43, - 0x1.1bbe084045d54p+0, 0x1.4e40p-45, + 0x1.1bbe084045d54p+0, 0x1.4e40p-45, 0x1.1c82f95281c43p+0, -0x1.a200p-47, - 0x1.1d4873168b9b2p+0, 0x1.3800p-49, - 0x1.1e0e75eb44031p+0, 0x1.ac00p-49, - 0x1.1ed5022fcd938p+0, 0x1.1900p-47, + 0x1.1d4873168b9b2p+0, 0x1.3800p-49, + 0x1.1e0e75eb44031p+0, 0x1.ac00p-49, + 0x1.1ed5022fcd938p+0, 0x1.1900p-47, 0x1.1f9c18438cdf7p+0, -0x1.b780p-46, - 0x1.2063b88628d8fp+0, 0x1.d940p-45, - 0x1.212be3578a81ep+0, 0x1.8000p-50, - 0x1.21f49917ddd41p+0, 0x1.b340p-45, - 0x1.22bdda2791323p+0, 0x1.9f80p-46, + 0x1.2063b88628d8fp+0, 0x1.d940p-45, + 0x1.212be3578a81ep+0, 0x1.8000p-50, + 0x1.21f49917ddd41p+0, 0x1.b340p-45, + 0x1.22bdda2791323p+0, 0x1.9f80p-46, 0x1.2387a6e7561e7p+0, -0x1.9c80p-46, - 0x1.2451ffb821427p+0, 0x1.2300p-47, + 0x1.2451ffb821427p+0, 0x1.2300p-47, 0x1.251ce4fb2a602p+0, -0x1.3480p-46, - 0x1.25e85711eceb0p+0, 0x1.2700p-46, - 0x1.26b4565e27d16p+0, 0x1.1d00p-46, - 0x1.2780e341de00fp+0, 0x1.1ee0p-44, + 0x1.25e85711eceb0p+0, 0x1.2700p-46, + 0x1.26b4565e27d16p+0, 0x1.1d00p-46, + 0x1.2780e341de00fp+0, 0x1.1ee0p-44, 0x1.284dfe1f5633ep+0, -0x1.4c00p-46, 0x1.291ba7591bb30p+0, -0x1.3d80p-46, - 0x1.29e9df51fdf09p+0, 0x1.8b00p-47, + 0x1.29e9df51fdf09p+0, 0x1.8b00p-47, 0x1.2ab8a66d10e9bp+0, -0x1.27c0p-45, - 0x1.2b87fd0dada3ap+0, 0x1.a340p-45, + 0x1.2b87fd0dada3ap+0, 0x1.a340p-45, 0x1.2c57e39771af9p+0, -0x1.0800p-46, 0x1.2d285a6e402d9p+0, -0x1.ed00p-47, 0x1.2df961f641579p+0, -0x1.4200p-48, @@ -290,78 +290,78 @@ const exp2dt = []f64 { 0x1.31432edeea50bp+0, -0x1.0df8p-40, 0x1.32170fc4cd7b8p+0, -0x1.2480p-45, 0x1.32eb83ba8e9a2p+0, -0x1.5980p-45, - 0x1.33c08b2641766p+0, 0x1.ed00p-46, + 0x1.33c08b2641766p+0, 0x1.ed00p-46, 0x1.3496266e3fa27p+0, -0x1.c000p-50, 0x1.356c55f929f0fp+0, -0x1.0d80p-44, - 0x1.36431a2de88b9p+0, 0x1.2c80p-45, - 0x1.371a7373aaa39p+0, 0x1.0600p-45, + 0x1.36431a2de88b9p+0, 0x1.2c80p-45, + 0x1.371a7373aaa39p+0, 0x1.0600p-45, 0x1.37f26231e74fep+0, -0x1.6600p-46, 0x1.38cae6d05d838p+0, -0x1.ae00p-47, 0x1.39a401b713ec3p+0, -0x1.4720p-43, - 0x1.3a7db34e5a020p+0, 0x1.8200p-47, - 0x1.3b57fbfec6e95p+0, 0x1.e800p-44, - 0x1.3c32dc313a8f2p+0, 0x1.f800p-49, + 0x1.3a7db34e5a020p+0, 0x1.8200p-47, + 0x1.3b57fbfec6e95p+0, 0x1.e800p-44, + 0x1.3c32dc313a8f2p+0, 0x1.f800p-49, 0x1.3d0e544ede122p+0, -0x1.7a00p-46, - 0x1.3dea64c1234bbp+0, 0x1.6300p-45, + 0x1.3dea64c1234bbp+0, 0x1.6300p-45, 0x1.3ec70df1c4eccp+0, -0x1.8a60p-43, 0x1.3fa4504ac7e8cp+0, -0x1.cdc0p-44, - 0x1.40822c367a0bbp+0, 0x1.5b80p-45, - 0x1.4160a21f72e95p+0, 0x1.ec00p-46, + 0x1.40822c367a0bbp+0, 0x1.5b80p-45, + 0x1.4160a21f72e95p+0, 0x1.ec00p-46, 0x1.423fb27094646p+0, -0x1.3600p-46, - 0x1.431f5d950a920p+0, 0x1.3980p-45, - 0x1.43ffa3f84b9ebp+0, 0x1.a000p-48, + 0x1.431f5d950a920p+0, 0x1.3980p-45, + 0x1.43ffa3f84b9ebp+0, 0x1.a000p-48, 0x1.44e0860618919p+0, -0x1.6c00p-48, 0x1.45c2042a7d201p+0, -0x1.bc00p-47, 0x1.46a41ed1d0016p+0, -0x1.2800p-46, - 0x1.4786d668b3326p+0, 0x1.0e00p-44, + 0x1.4786d668b3326p+0, 0x1.0e00p-44, 0x1.486a2b5c13c00p+0, -0x1.d400p-45, - 0x1.494e1e192af04p+0, 0x1.c200p-47, + 0x1.494e1e192af04p+0, 0x1.c200p-47, 0x1.4a32af0d7d372p+0, -0x1.e500p-46, - 0x1.4b17dea6db801p+0, 0x1.7800p-47, + 0x1.4b17dea6db801p+0, 0x1.7800p-47, 0x1.4bfdad53629e1p+0, -0x1.3800p-46, - 0x1.4ce41b817c132p+0, 0x1.0800p-47, - 0x1.4dcb299fddddbp+0, 0x1.c700p-45, + 0x1.4ce41b817c132p+0, 0x1.0800p-47, + 0x1.4dcb299fddddbp+0, 0x1.c700p-45, 0x1.4eb2d81d8ab96p+0, -0x1.ce00p-46, - 0x1.4f9b2769d2d02p+0, 0x1.9200p-46, + 0x1.4f9b2769d2d02p+0, 0x1.9200p-46, 0x1.508417f4531c1p+0, -0x1.8c00p-47, 0x1.516daa2cf662ap+0, -0x1.a000p-48, - 0x1.5257de83f51eap+0, 0x1.a080p-43, + 0x1.5257de83f51eap+0, 0x1.a080p-43, 0x1.5342b569d4edap+0, -0x1.6d80p-45, 0x1.542e2f4f6ac1ap+0, -0x1.2440p-44, - 0x1.551a4ca5d94dbp+0, 0x1.83c0p-43, - 0x1.56070dde9116bp+0, 0x1.4b00p-45, - 0x1.56f4736b529dep+0, 0x1.15a0p-43, + 0x1.551a4ca5d94dbp+0, 0x1.83c0p-43, + 0x1.56070dde9116bp+0, 0x1.4b00p-45, + 0x1.56f4736b529dep+0, 0x1.15a0p-43, 0x1.57e27dbe2c40ep+0, -0x1.9e00p-45, 0x1.58d12d497c76fp+0, -0x1.3080p-45, - 0x1.59c0827ff0b4cp+0, 0x1.dec0p-43, + 0x1.59c0827ff0b4cp+0, 0x1.dec0p-43, 0x1.5ab07dd485427p+0, -0x1.4000p-51, - 0x1.5ba11fba87af4p+0, 0x1.0080p-44, + 0x1.5ba11fba87af4p+0, 0x1.0080p-44, 0x1.5c9268a59460bp+0, -0x1.6c80p-45, - 0x1.5d84590998e3fp+0, 0x1.69a0p-43, + 0x1.5d84590998e3fp+0, 0x1.69a0p-43, 0x1.5e76f15ad20e1p+0, -0x1.b400p-46, - 0x1.5f6a320dcebcap+0, 0x1.7700p-46, - 0x1.605e1b976dcb8p+0, 0x1.6f80p-45, - 0x1.6152ae6cdf715p+0, 0x1.1000p-47, + 0x1.5f6a320dcebcap+0, 0x1.7700p-46, + 0x1.605e1b976dcb8p+0, 0x1.6f80p-45, + 0x1.6152ae6cdf715p+0, 0x1.1000p-47, 0x1.6247eb03a5531p+0, -0x1.5d00p-46, 0x1.633dd1d1929b5p+0, -0x1.2d00p-46, 0x1.6434634ccc313p+0, -0x1.a800p-49, 0x1.652b9febc8efap+0, -0x1.8600p-45, - 0x1.6623882553397p+0, 0x1.1fe0p-40, + 0x1.6623882553397p+0, 0x1.1fe0p-40, 0x1.671c1c708328ep+0, -0x1.7200p-44, - 0x1.68155d44ca97ep+0, 0x1.6800p-49, + 0x1.68155d44ca97ep+0, 0x1.6800p-49, 0x1.690f4b19e9471p+0, -0x1.9780p-45, }; fn exp2_64(x: f64) f64 { @setFloatMode(this, @import("builtin").FloatMode.Strict); - const tblsiz = u32(exp2dt.len / 2); + const tblsiz = u32(exp2dt.len / 2); const redux: f64 = 0x1.8p52 / f64(tblsiz); - const P1: f64 = 0x1.62e42fefa39efp-1; - const P2: f64 = 0x1.ebfbdff82c575p-3; - const P3: f64 = 0x1.c6b08d704a0a6p-5; - const P4: f64 = 0x1.3b2ab88f70400p-7; - const P5: f64 = 0x1.5d88003875c74p-10; + const P1: f64 = 0x1.62e42fefa39efp-1; + const P2: f64 = 0x1.ebfbdff82c575p-3; + const P3: f64 = 0x1.c6b08d704a0a6p-5; + const P4: f64 = 0x1.3b2ab88f70400p-7; + const P5: f64 = 0x1.5d88003875c74p-10; const ux = @bitCast(u64, x); const ix = u32(ux >> 32) & 0x7FFFFFFF; diff --git a/std/math/expm1.zig b/std/math/expm1.zig index 316f0e3e71..11af1b215f 100644 --- a/std/math/expm1.zig +++ b/std/math/expm1.zig @@ -21,11 +21,11 @@ pub fn expm1(x: var) @typeOf(x) { fn expm1_32(x_: f32) f32 { @setFloatMode(this, builtin.FloatMode.Strict); const o_threshold: f32 = 8.8721679688e+01; - const ln2_hi: f32 = 6.9313812256e-01; - const ln2_lo: f32 = 9.0580006145e-06; - const invln2: f32 = 1.4426950216e+00; + const ln2_hi: f32 = 6.9313812256e-01; + const ln2_lo: f32 = 9.0580006145e-06; + const invln2: f32 = 1.4426950216e+00; const Q1: f32 = -3.3333212137e-2; - const Q2: f32 = 1.5807170421e-3; + const Q2: f32 = 1.5807170421e-3; var x = x_; const ux = @bitCast(u32, x); @@ -93,8 +93,7 @@ fn expm1_32(x_: f32) f32 { math.forceEval(x * x); } return x; - } - else { + } else { k = 0; } @@ -148,13 +147,13 @@ fn expm1_32(x_: f32) f32 { fn expm1_64(x_: f64) f64 { @setFloatMode(this, builtin.FloatMode.Strict); const o_threshold: f64 = 7.09782712893383973096e+02; - const ln2_hi: f64 = 6.93147180369123816490e-01; - const ln2_lo: f64 = 1.90821492927058770002e-10; - const invln2: f64 = 1.44269504088896338700e+00; + const ln2_hi: f64 = 6.93147180369123816490e-01; + const ln2_lo: f64 = 1.90821492927058770002e-10; + const invln2: f64 = 1.44269504088896338700e+00; const Q1: f64 = -3.33333333333331316428e-02; - const Q2: f64 = 1.58730158725481460165e-03; + const Q2: f64 = 1.58730158725481460165e-03; const Q3: f64 = -7.93650757867487942473e-05; - const Q4: f64 = 4.00821782732936239552e-06; + const Q4: f64 = 4.00821782732936239552e-06; const Q5: f64 = -2.01099218183624371326e-07; var x = x_; @@ -223,8 +222,7 @@ fn expm1_64(x_: f64) f64 { math.forceEval(f32(x)); } return x; - } - else { + } else { k = 0; } diff --git a/std/math/index.zig b/std/math/index.zig index 8fcd05d760..847e972500 100644 --- a/std/math/index.zig +++ b/std/math/index.zig @@ -501,7 +501,7 @@ test "math.negateCast" { if (negateCast(u32(@maxValue(i32) + 10))) |_| unreachable else |err| assert(err == error.Overflow); } -/// Cast an integer to a different integer type. If the value doesn't fit, +/// Cast an integer to a different integer type. If the value doesn't fit, /// return an error. pub fn cast(comptime T: type, x: var) (error{Overflow}!T) { comptime assert(@typeId(T) == builtin.TypeId.Int); // must pass an integer diff --git a/std/math/log1p.zig b/std/math/log1p.zig index 4616a2f2ba..57efdaf51c 100644 --- a/std/math/log1p.zig +++ b/std/math/log1p.zig @@ -138,8 +138,7 @@ fn log1p_64(x: f64) f64 { c = 0; f = x; } - } - else if (hx >= 0x7FF00000) { + } else if (hx >= 0x7FF00000) { return x; } diff --git a/std/math/pow.zig b/std/math/pow.zig index 51908f30ea..dfe4fc09d6 100644 --- a/std/math/pow.zig +++ b/std/math/pow.zig @@ -28,7 +28,6 @@ const assert = std.debug.assert; // This implementation is taken from the go stlib, musl is a bit more complex. pub fn pow(comptime T: type, x: T, y: T) T { - @setFloatMode(this, @import("builtin").FloatMode.Strict); if (T != f32 and T != f64) { diff --git a/std/net.zig b/std/net.zig index b1e291ab92..3af4e0b525 100644 --- a/std/net.zig +++ b/std/net.zig @@ -19,24 +19,30 @@ pub const Address = struct { os_addr: OsAddress, pub fn initIp4(ip4: u32, port: u16) Address { - return Address{ .os_addr = posix.sockaddr{ .in = posix.sockaddr_in{ - .family = posix.AF_INET, - .port = std.mem.endianSwapIfLe(u16, port), - .addr = ip4, - .zero = []u8{0} ** 8, - } } }; + return Address{ + .os_addr = posix.sockaddr{ + .in = posix.sockaddr_in{ + .family = posix.AF_INET, + .port = std.mem.endianSwapIfLe(u16, port), + .addr = ip4, + .zero = []u8{0} ** 8, + }, + }, + }; } pub fn initIp6(ip6: &const Ip6Addr, port: u16) Address { return Address{ .family = posix.AF_INET6, - .os_addr = posix.sockaddr{ .in6 = posix.sockaddr_in6{ - .family = posix.AF_INET6, - .port = std.mem.endianSwapIfLe(u16, port), - .flowinfo = 0, - .addr = ip6.addr, - .scope_id = ip6.scope_id, - } }, + .os_addr = posix.sockaddr{ + .in6 = posix.sockaddr_in6{ + .family = posix.AF_INET6, + .port = std.mem.endianSwapIfLe(u16, port), + .flowinfo = 0, + .addr = ip6.addr, + .scope_id = ip6.scope_id, + }, + }, }; } diff --git a/std/os/child_process.zig b/std/os/child_process.zig index dc3a582707..51f1bd96e5 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -387,15 +387,12 @@ pub const ChildProcess = struct { const pid_err = posix.getErrno(pid_result); if (pid_err > 0) { return switch (pid_err) { - posix.EAGAIN, - posix.ENOMEM, - posix.ENOSYS => error.SystemResources, + posix.EAGAIN, posix.ENOMEM, posix.ENOSYS => error.SystemResources, else => os.unexpectedErrorPosix(pid_err), }; } if (pid_result == 0) { // we are the child - setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); @@ -646,8 +643,7 @@ fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ? if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?&c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) { const err = windows.GetLastError(); return switch (err) { - windows.ERROR.FILE_NOT_FOUND, - windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, + windows.ERROR.FILE_NOT_FOUND, windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, windows.ERROR.INVALID_PARAMETER => unreachable, windows.ERROR.INVALID_NAME => error.InvalidName, else => os.unexpectedErrorWindows(err), @@ -745,8 +741,7 @@ fn makePipe() ![2]i32 { const err = posix.getErrno(posix.pipe(&fds)); if (err > 0) { return switch (err) { - posix.EMFILE, - posix.ENFILE => error.SystemResources, + posix.EMFILE, posix.ENFILE => error.SystemResources, else => os.unexpectedErrorPosix(err), }; } diff --git a/std/os/darwin.zig b/std/os/darwin.zig index 45359e757d..a01755d27b 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -12,52 +12,71 @@ pub const STDERR_FILENO = 2; /// [MC2] no permissions pub const PROT_NONE = 0x00; + /// [MC2] pages can be read pub const PROT_READ = 0x01; + /// [MC2] pages can be written pub const PROT_WRITE = 0x02; + /// [MC2] pages can be executed pub const PROT_EXEC = 0x04; /// allocated from memory, swap space pub const MAP_ANONYMOUS = 0x1000; + /// map from file (default) pub const MAP_FILE = 0x0000; + /// interpret addr exactly pub const MAP_FIXED = 0x0010; + /// region may contain semaphores pub const MAP_HASSEMAPHORE = 0x0200; + /// changes are private pub const MAP_PRIVATE = 0x0002; + /// share changes pub const MAP_SHARED = 0x0001; + /// don't cache pages for this mapping pub const MAP_NOCACHE = 0x0400; + /// don't reserve needed swap area pub const MAP_NORESERVE = 0x0040; pub const MAP_FAILED = @maxValue(usize); /// [XSI] no hang in wait/no child to reap pub const WNOHANG = 0x00000001; + /// [XSI] notify on stop, untraced child pub const WUNTRACED = 0x00000002; /// take signal on signal stack pub const SA_ONSTACK = 0x0001; + /// restart system on signal return pub const SA_RESTART = 0x0002; + /// reset to SIG_DFL when taking signal pub const SA_RESETHAND = 0x0004; + /// do not generate SIGCHLD on child stop pub const SA_NOCLDSTOP = 0x0008; + /// don't mask the signal we're delivering pub const SA_NODEFER = 0x0010; + /// don't keep zombies around pub const SA_NOCLDWAIT = 0x0020; + /// signal handler with SA_SIGINFO args pub const SA_SIGINFO = 0x0040; + /// do not bounce off kernel's sigtramp pub const SA_USERTRAMP = 0x0100; + /// signal handler with SA_SIGINFO args with 64bit regs information pub const SA_64REGSET = 0x0200; @@ -71,30 +90,43 @@ pub const R_OK = 4; /// open for reading only pub const O_RDONLY = 0x0000; + /// open for writing only pub const O_WRONLY = 0x0001; + /// open for reading and writing pub const O_RDWR = 0x0002; + /// do not block on open or for data to become available pub const O_NONBLOCK = 0x0004; + /// append on each write pub const O_APPEND = 0x0008; + /// create file if it does not exist pub const O_CREAT = 0x0200; + /// truncate size to 0 pub const O_TRUNC = 0x0400; + /// error if O_CREAT and the file exists pub const O_EXCL = 0x0800; + /// atomically obtain a shared lock pub const O_SHLOCK = 0x0010; + /// atomically obtain an exclusive lock pub const O_EXLOCK = 0x0020; + /// do not follow symlinks pub const O_NOFOLLOW = 0x0100; + /// allow open of symlinks pub const O_SYMLINK = 0x200000; + /// descriptor requested for event notifications only pub const O_EVTONLY = 0x8000; + /// mark as close-on-exec pub const O_CLOEXEC = 0x1000000; @@ -126,75 +158,109 @@ pub const DT_WHT = 14; /// block specified signal set pub const SIG_BLOCK = 1; + /// unblock specified signal set pub const SIG_UNBLOCK = 2; + /// set specified signal set pub const SIG_SETMASK = 3; /// hangup pub const SIGHUP = 1; + /// interrupt pub const SIGINT = 2; + /// quit pub const SIGQUIT = 3; + /// illegal instruction (not reset when caught) pub const SIGILL = 4; + /// trace trap (not reset when caught) pub const SIGTRAP = 5; + /// abort() pub const SIGABRT = 6; + /// pollable event ([XSR] generated, not supported) pub const SIGPOLL = 7; + /// compatibility pub const SIGIOT = SIGABRT; + /// EMT instruction pub const SIGEMT = 7; + /// floating point exception pub const SIGFPE = 8; + /// kill (cannot be caught or ignored) pub const SIGKILL = 9; + /// bus error pub const SIGBUS = 10; + /// segmentation violation pub const SIGSEGV = 11; + /// bad argument to system call pub const SIGSYS = 12; + /// write on a pipe with no one to read it pub const SIGPIPE = 13; + /// alarm clock pub const SIGALRM = 14; + /// software termination signal from kill pub const SIGTERM = 15; + /// urgent condition on IO channel pub const SIGURG = 16; + /// sendable stop signal not from tty pub const SIGSTOP = 17; + /// stop signal from tty pub const SIGTSTP = 18; + /// continue a stopped process pub const SIGCONT = 19; + /// to parent on child stop or exit pub const SIGCHLD = 20; + /// to readers pgrp upon background tty read pub const SIGTTIN = 21; + /// like TTIN for output if (tp->t_local<OSTOP) pub const SIGTTOU = 22; + /// input/output possible signal pub const SIGIO = 23; + /// exceeded CPU time limit pub const SIGXCPU = 24; + /// exceeded file size limit pub const SIGXFSZ = 25; + /// virtual time alarm pub const SIGVTALRM = 26; + /// profiling time alarm pub const SIGPROF = 27; + /// window size changes pub const SIGWINCH = 28; + /// information request pub const SIGINFO = 29; + /// user defined signal 1 pub const SIGUSR1 = 30; + /// user defined signal 2 pub const SIGUSR2 = 31; diff --git a/std/os/darwin_errno.zig b/std/os/darwin_errno.zig index 6b47e5a9fa..438f3382ad 100644 --- a/std/os/darwin_errno.zig +++ b/std/os/darwin_errno.zig @@ -1,142 +1,328 @@ +/// Operation not permitted +pub const EPERM = 1; -pub const EPERM = 1; /// Operation not permitted -pub const ENOENT = 2; /// No such file or directory -pub const ESRCH = 3; /// No such process -pub const EINTR = 4; /// Interrupted system call -pub const EIO = 5; /// Input/output error -pub const ENXIO = 6; /// Device not configured -pub const E2BIG = 7; /// Argument list too long -pub const ENOEXEC = 8; /// Exec format error -pub const EBADF = 9; /// Bad file descriptor -pub const ECHILD = 10; /// No child processes -pub const EDEADLK = 11; /// Resource deadlock avoided +/// No such file or directory +pub const ENOENT = 2; -pub const ENOMEM = 12; /// Cannot allocate memory -pub const EACCES = 13; /// Permission denied -pub const EFAULT = 14; /// Bad address -pub const ENOTBLK = 15; /// Block device required -pub const EBUSY = 16; /// Device / Resource busy -pub const EEXIST = 17; /// File exists -pub const EXDEV = 18; /// Cross-device link -pub const ENODEV = 19; /// Operation not supported by device -pub const ENOTDIR = 20; /// Not a directory -pub const EISDIR = 21; /// Is a directory -pub const EINVAL = 22; /// Invalid argument -pub const ENFILE = 23; /// Too many open files in system -pub const EMFILE = 24; /// Too many open files -pub const ENOTTY = 25; /// Inappropriate ioctl for device -pub const ETXTBSY = 26; /// Text file busy -pub const EFBIG = 27; /// File too large -pub const ENOSPC = 28; /// No space left on device -pub const ESPIPE = 29; /// Illegal seek -pub const EROFS = 30; /// Read-only file system -pub const EMLINK = 31; /// Too many links -pub const EPIPE = 32; /// Broken pipe +/// No such process +pub const ESRCH = 3; + +/// Interrupted system call +pub const EINTR = 4; + +/// Input/output error +pub const EIO = 5; + +/// Device not configured +pub const ENXIO = 6; + +/// Argument list too long +pub const E2BIG = 7; + +/// Exec format error +pub const ENOEXEC = 8; + +/// Bad file descriptor +pub const EBADF = 9; + +/// No child processes +pub const ECHILD = 10; + +/// Resource deadlock avoided +pub const EDEADLK = 11; + +/// Cannot allocate memory +pub const ENOMEM = 12; + +/// Permission denied +pub const EACCES = 13; + +/// Bad address +pub const EFAULT = 14; + +/// Block device required +pub const ENOTBLK = 15; + +/// Device / Resource busy +pub const EBUSY = 16; + +/// File exists +pub const EEXIST = 17; + +/// Cross-device link +pub const EXDEV = 18; + +/// Operation not supported by device +pub const ENODEV = 19; + +/// Not a directory +pub const ENOTDIR = 20; + +/// Is a directory +pub const EISDIR = 21; + +/// Invalid argument +pub const EINVAL = 22; + +/// Too many open files in system +pub const ENFILE = 23; + +/// Too many open files +pub const EMFILE = 24; + +/// Inappropriate ioctl for device +pub const ENOTTY = 25; + +/// Text file busy +pub const ETXTBSY = 26; + +/// File too large +pub const EFBIG = 27; + +/// No space left on device +pub const ENOSPC = 28; + +/// Illegal seek +pub const ESPIPE = 29; + +/// Read-only file system +pub const EROFS = 30; + +/// Too many links +pub const EMLINK = 31; +/// Broken pipe // math software -pub const EDOM = 33; /// Numerical argument out of domain -pub const ERANGE = 34; /// Result too large +pub const EPIPE = 32; + +/// Numerical argument out of domain +pub const EDOM = 33; +/// Result too large // non-blocking and interrupt i/o -pub const EAGAIN = 35; /// Resource temporarily unavailable -pub const EWOULDBLOCK = EAGAIN; /// Operation would block -pub const EINPROGRESS = 36; /// Operation now in progress -pub const EALREADY = 37; /// Operation already in progress +pub const ERANGE = 34; + +/// Resource temporarily unavailable +pub const EAGAIN = 35; + +/// Operation would block +pub const EWOULDBLOCK = EAGAIN; + +/// Operation now in progress +pub const EINPROGRESS = 36; +/// Operation already in progress // ipc/network software -- argument errors -pub const ENOTSOCK = 38; /// Socket operation on non-socket -pub const EDESTADDRREQ = 39; /// Destination address required -pub const EMSGSIZE = 40; /// Message too long -pub const EPROTOTYPE = 41; /// Protocol wrong type for socket -pub const ENOPROTOOPT = 42; /// Protocol not available -pub const EPROTONOSUPPORT = 43; /// Protocol not supported +pub const EALREADY = 37; -pub const ESOCKTNOSUPPORT = 44; /// Socket type not supported +/// Socket operation on non-socket +pub const ENOTSOCK = 38; -pub const ENOTSUP = 45; /// Operation not supported +/// Destination address required +pub const EDESTADDRREQ = 39; -pub const EPFNOSUPPORT = 46; /// Protocol family not supported -pub const EAFNOSUPPORT = 47; /// Address family not supported by protocol family -pub const EADDRINUSE = 48; /// Address already in use -pub const EADDRNOTAVAIL = 49; /// Can't assign requested address +/// Message too long +pub const EMSGSIZE = 40; + +/// Protocol wrong type for socket +pub const EPROTOTYPE = 41; + +/// Protocol not available +pub const ENOPROTOOPT = 42; + +/// Protocol not supported +pub const EPROTONOSUPPORT = 43; + +/// Socket type not supported +pub const ESOCKTNOSUPPORT = 44; + +/// Operation not supported +pub const ENOTSUP = 45; + +/// Protocol family not supported +pub const EPFNOSUPPORT = 46; + +/// Address family not supported by protocol family +pub const EAFNOSUPPORT = 47; + +/// Address already in use +pub const EADDRINUSE = 48; +/// Can't assign requested address // ipc/network software -- operational errors -pub const ENETDOWN = 50; /// Network is down -pub const ENETUNREACH = 51; /// Network is unreachable -pub const ENETRESET = 52; /// Network dropped connection on reset -pub const ECONNABORTED = 53; /// Software caused connection abort -pub const ECONNRESET = 54; /// Connection reset by peer -pub const ENOBUFS = 55; /// No buffer space available -pub const EISCONN = 56; /// Socket is already connected -pub const ENOTCONN = 57; /// Socket is not connected +pub const EADDRNOTAVAIL = 49; -pub const ESHUTDOWN = 58; /// Can't send after socket shutdown -pub const ETOOMANYREFS = 59; /// Too many references: can't splice +/// Network is down +pub const ENETDOWN = 50; -pub const ETIMEDOUT = 60; /// Operation timed out -pub const ECONNREFUSED = 61; /// Connection refused +/// Network is unreachable +pub const ENETUNREACH = 51; -pub const ELOOP = 62; /// Too many levels of symbolic links -pub const ENAMETOOLONG = 63; /// File name too long +/// Network dropped connection on reset +pub const ENETRESET = 52; -pub const EHOSTDOWN = 64; /// Host is down -pub const EHOSTUNREACH = 65; /// No route to host -pub const ENOTEMPTY = 66; /// Directory not empty +/// Software caused connection abort +pub const ECONNABORTED = 53; + +/// Connection reset by peer +pub const ECONNRESET = 54; + +/// No buffer space available +pub const ENOBUFS = 55; + +/// Socket is already connected +pub const EISCONN = 56; + +/// Socket is not connected +pub const ENOTCONN = 57; + +/// Can't send after socket shutdown +pub const ESHUTDOWN = 58; + +/// Too many references: can't splice +pub const ETOOMANYREFS = 59; + +/// Operation timed out +pub const ETIMEDOUT = 60; + +/// Connection refused +pub const ECONNREFUSED = 61; + +/// Too many levels of symbolic links +pub const ELOOP = 62; + +/// File name too long +pub const ENAMETOOLONG = 63; + +/// Host is down +pub const EHOSTDOWN = 64; + +/// No route to host +pub const EHOSTUNREACH = 65; +/// Directory not empty // quotas & mush -pub const EPROCLIM = 67; /// Too many processes -pub const EUSERS = 68; /// Too many users -pub const EDQUOT = 69; /// Disc quota exceeded +pub const ENOTEMPTY = 66; + +/// Too many processes +pub const EPROCLIM = 67; + +/// Too many users +pub const EUSERS = 68; +/// Disc quota exceeded // Network File System -pub const ESTALE = 70; /// Stale NFS file handle -pub const EREMOTE = 71; /// Too many levels of remote in path -pub const EBADRPC = 72; /// RPC struct is bad -pub const ERPCMISMATCH = 73; /// RPC version wrong -pub const EPROGUNAVAIL = 74; /// RPC prog. not avail -pub const EPROGMISMATCH = 75; /// Program version wrong -pub const EPROCUNAVAIL = 76; /// Bad procedure for program +pub const EDQUOT = 69; -pub const ENOLCK = 77; /// No locks available -pub const ENOSYS = 78; /// Function not implemented +/// Stale NFS file handle +pub const ESTALE = 70; -pub const EFTYPE = 79; /// Inappropriate file type or format -pub const EAUTH = 80; /// Authentication error -pub const ENEEDAUTH = 81; /// Need authenticator +/// Too many levels of remote in path +pub const EREMOTE = 71; + +/// RPC struct is bad +pub const EBADRPC = 72; + +/// RPC version wrong +pub const ERPCMISMATCH = 73; + +/// RPC prog. not avail +pub const EPROGUNAVAIL = 74; + +/// Program version wrong +pub const EPROGMISMATCH = 75; + +/// Bad procedure for program +pub const EPROCUNAVAIL = 76; + +/// No locks available +pub const ENOLCK = 77; + +/// Function not implemented +pub const ENOSYS = 78; + +/// Inappropriate file type or format +pub const EFTYPE = 79; + +/// Authentication error +pub const EAUTH = 80; +/// Need authenticator // Intelligent device errors -pub const EPWROFF = 82; /// Device power is off -pub const EDEVERR = 83; /// Device error, e.g. paper out +pub const ENEEDAUTH = 81; -pub const EOVERFLOW = 84; /// Value too large to be stored in data type +/// Device power is off +pub const EPWROFF = 82; + +/// Device error, e.g. paper out +pub const EDEVERR = 83; +/// Value too large to be stored in data type // Program loading errors -pub const EBADEXEC = 85; /// Bad executable -pub const EBADARCH = 86; /// Bad CPU type in executable -pub const ESHLIBVERS = 87; /// Shared library version mismatch -pub const EBADMACHO = 88; /// Malformed Macho file +pub const EOVERFLOW = 84; -pub const ECANCELED = 89; /// Operation canceled +/// Bad executable +pub const EBADEXEC = 85; -pub const EIDRM = 90; /// Identifier removed -pub const ENOMSG = 91; /// No message of desired type -pub const EILSEQ = 92; /// Illegal byte sequence -pub const ENOATTR = 93; /// Attribute not found +/// Bad CPU type in executable +pub const EBADARCH = 86; -pub const EBADMSG = 94; /// Bad message -pub const EMULTIHOP = 95; /// Reserved -pub const ENODATA = 96; /// No message available on STREAM -pub const ENOLINK = 97; /// Reserved -pub const ENOSR = 98; /// No STREAM resources -pub const ENOSTR = 99; /// Not a STREAM -pub const EPROTO = 100; /// Protocol error -pub const ETIME = 101; /// STREAM ioctl timeout +/// Shared library version mismatch +pub const ESHLIBVERS = 87; -pub const ENOPOLICY = 103; /// No such policy registered +/// Malformed Macho file +pub const EBADMACHO = 88; -pub const ENOTRECOVERABLE = 104; /// State not recoverable -pub const EOWNERDEAD = 105; /// Previous owner died +/// Operation canceled +pub const ECANCELED = 89; -pub const EQFULL = 106; /// Interface output queue is full -pub const ELAST = 106; /// Must be equal largest errno +/// Identifier removed +pub const EIDRM = 90; +/// No message of desired type +pub const ENOMSG = 91; + +/// Illegal byte sequence +pub const EILSEQ = 92; + +/// Attribute not found +pub const ENOATTR = 93; + +/// Bad message +pub const EBADMSG = 94; + +/// Reserved +pub const EMULTIHOP = 95; + +/// No message available on STREAM +pub const ENODATA = 96; + +/// Reserved +pub const ENOLINK = 97; + +/// No STREAM resources +pub const ENOSR = 98; + +/// Not a STREAM +pub const ENOSTR = 99; + +/// Protocol error +pub const EPROTO = 100; + +/// STREAM ioctl timeout +pub const ETIME = 101; + +/// No such policy registered +pub const ENOPOLICY = 103; + +/// State not recoverable +pub const ENOTRECOVERABLE = 104; + +/// Previous owner died +pub const EOWNERDEAD = 105; + +/// Interface output queue is full +pub const EQFULL = 106; + +/// Must be equal largest errno +pub const ELAST = 106; diff --git a/std/os/epoch.zig b/std/os/epoch.zig index e1256c1374..fc031521a5 100644 --- a/std/os/epoch.zig +++ b/std/os/epoch.zig @@ -1,26 +1,26 @@ /// Epoch reference times in terms of their difference from /// posix epoch in seconds. -pub const posix = 0; //Jan 01, 1970 AD -pub const dos = 315532800; //Jan 01, 1980 AD -pub const ios = 978307200; //Jan 01, 2001 AD -pub const openvms = -3506716800; //Nov 17, 1858 AD -pub const zos = -2208988800; //Jan 01, 1900 AD -pub const windows = -11644473600; //Jan 01, 1601 AD -pub const amiga = 252460800; //Jan 01, 1978 AD -pub const pickos = -63244800; //Dec 31, 1967 AD -pub const gps = 315964800; //Jan 06, 1980 AD -pub const clr = -62135769600; //Jan 01, 0001 AD +pub const posix = 0; //Jan 01, 1970 AD +pub const dos = 315532800; //Jan 01, 1980 AD +pub const ios = 978307200; //Jan 01, 2001 AD +pub const openvms = -3506716800; //Nov 17, 1858 AD +pub const zos = -2208988800; //Jan 01, 1900 AD +pub const windows = -11644473600; //Jan 01, 1601 AD +pub const amiga = 252460800; //Jan 01, 1978 AD +pub const pickos = -63244800; //Dec 31, 1967 AD +pub const gps = 315964800; //Jan 06, 1980 AD +pub const clr = -62135769600; //Jan 01, 0001 AD -pub const unix = posix; -pub const android = posix; -pub const os2 = dos; -pub const bios = dos; -pub const vfat = dos; -pub const ntfs = windows; -pub const ntp = zos; -pub const jbase = pickos; -pub const aros = amiga; -pub const morphos = amiga; -pub const brew = gps; -pub const atsc = gps; -pub const go = clr; \ No newline at end of file +pub const unix = posix; +pub const android = posix; +pub const os2 = dos; +pub const bios = dos; +pub const vfat = dos; +pub const ntfs = windows; +pub const ntp = zos; +pub const jbase = pickos; +pub const aros = amiga; +pub const morphos = amiga; +pub const brew = gps; +pub const atsc = gps; +pub const go = clr; diff --git a/std/os/file.zig b/std/os/file.zig index 61fc2b1455..c07e2c5c8b 100644 --- a/std/os/file.zig +++ b/std/os/file.zig @@ -21,12 +21,18 @@ pub const File = struct { /// Call close to clean up. pub fn openRead(allocator: &mem.Allocator, path: []const u8) OpenError!File { if (is_posix) { - const flags = posix.O_LARGEFILE|posix.O_RDONLY; + const flags = posix.O_LARGEFILE | posix.O_RDONLY; const fd = try os.posixOpen(allocator, path, flags, 0); return openHandle(fd); } else if (is_windows) { - const handle = try os.windowsOpen(allocator, path, windows.GENERIC_READ, windows.FILE_SHARE_READ, - windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL); + const handle = try os.windowsOpen( + allocator, + path, + windows.GENERIC_READ, + windows.FILE_SHARE_READ, + windows.OPEN_EXISTING, + windows.FILE_ATTRIBUTE_NORMAL, + ); return openHandle(handle); } else { @compileError("TODO implement openRead for this OS"); @@ -36,7 +42,6 @@ pub const File = struct { /// Calls `openWriteMode` with os.default_file_mode for the mode. pub fn openWrite(allocator: &mem.Allocator, path: []const u8) OpenError!File { return openWriteMode(allocator, path, os.default_file_mode); - } /// If the path does not exist it will be created. @@ -45,18 +50,22 @@ pub const File = struct { /// Call close to clean up. pub fn openWriteMode(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File { if (is_posix) { - const flags = posix.O_LARGEFILE|posix.O_WRONLY|posix.O_CREAT|posix.O_CLOEXEC|posix.O_TRUNC; + const flags = posix.O_LARGEFILE | posix.O_WRONLY | posix.O_CREAT | posix.O_CLOEXEC | posix.O_TRUNC; const fd = try os.posixOpen(allocator, path, flags, file_mode); return openHandle(fd); } else if (is_windows) { - const handle = try os.windowsOpen(allocator, path, windows.GENERIC_WRITE, - windows.FILE_SHARE_WRITE|windows.FILE_SHARE_READ|windows.FILE_SHARE_DELETE, - windows.CREATE_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL); + const handle = try os.windowsOpen( + allocator, + path, + windows.GENERIC_WRITE, + windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE, + windows.CREATE_ALWAYS, + windows.FILE_ATTRIBUTE_NORMAL, + ); return openHandle(handle); } else { @compileError("TODO implement openWriteMode for this OS"); } - } /// If the path does not exist it will be created. @@ -65,24 +74,26 @@ pub const File = struct { /// Call close to clean up. pub fn openWriteNoClobber(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File { if (is_posix) { - const flags = posix.O_LARGEFILE|posix.O_WRONLY|posix.O_CREAT|posix.O_CLOEXEC|posix.O_EXCL; + const flags = posix.O_LARGEFILE | posix.O_WRONLY | posix.O_CREAT | posix.O_CLOEXEC | posix.O_EXCL; const fd = try os.posixOpen(allocator, path, flags, file_mode); return openHandle(fd); } else if (is_windows) { - const handle = try os.windowsOpen(allocator, path, windows.GENERIC_WRITE, - windows.FILE_SHARE_WRITE|windows.FILE_SHARE_READ|windows.FILE_SHARE_DELETE, - windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL); + const handle = try os.windowsOpen( + allocator, + path, + windows.GENERIC_WRITE, + windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE, + windows.CREATE_NEW, + windows.FILE_ATTRIBUTE_NORMAL, + ); return openHandle(handle); } else { @compileError("TODO implement openWriteMode for this OS"); } - } pub fn openHandle(handle: os.FileHandle) File { - return File { - .handle = handle, - }; + return File{ .handle = handle }; } pub fn access(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) !bool { @@ -217,7 +228,7 @@ pub const File = struct { return result; }, Os.windows => { - var pos : windows.LARGE_INTEGER = undefined; + var pos: windows.LARGE_INTEGER = undefined; if (windows.SetFilePointerEx(self.handle, 0, &pos, windows.FILE_CURRENT) == 0) { const err = windows.GetLastError(); return switch (err) { @@ -268,7 +279,7 @@ pub const File = struct { } } - pub const ModeError = error { + pub const ModeError = error{ BadFd, SystemResources, Unexpected, @@ -296,7 +307,7 @@ pub const File = struct { } } - pub const ReadError = error {}; + pub const ReadError = error{}; pub fn read(self: &File, buffer: []u8) !usize { if (is_posix) { @@ -306,12 +317,12 @@ pub const File = struct { const read_err = posix.getErrno(amt_read); if (read_err > 0) { switch (read_err) { - posix.EINTR => continue, + posix.EINTR => continue, posix.EINVAL => unreachable, posix.EFAULT => unreachable, - posix.EBADF => return error.BadFd, - posix.EIO => return error.Io, - else => return os.unexpectedErrorPosix(read_err), + posix.EBADF => return error.BadFd, + posix.EIO => return error.Io, + else => return os.unexpectedErrorPosix(read_err), } } if (amt_read == 0) return index; diff --git a/std/os/get_user_id.zig b/std/os/get_user_id.zig index 11410ffa64..2a15e1d495 100644 --- a/std/os/get_user_id.zig +++ b/std/os/get_user_id.zig @@ -74,7 +74,7 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo { '\n' => return error.CorruptPasswordFile, else => { const digit = switch (byte) { - '0' ... '9' => byte - '0', + '0'...'9' => byte - '0', else => return error.CorruptPasswordFile, }; if (@mulWithOverflow(u32, uid, 10, &uid)) return error.CorruptPasswordFile; @@ -83,14 +83,14 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo { }, State.ReadGroupId => switch (byte) { '\n', ':' => { - return UserInfo { + return UserInfo{ .uid = uid, .gid = gid, }; }, else => { const digit = switch (byte) { - '0' ... '9' => byte - '0', + '0'...'9' => byte - '0', else => return error.CorruptPasswordFile, }; if (@mulWithOverflow(u32, gid, 10, &gid)) return error.CorruptPasswordFile; diff --git a/std/os/index.zig b/std/os/index.zig index 01e2092e1c..db182ed669 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -3,8 +3,7 @@ const builtin = @import("builtin"); const Os = builtin.Os; const is_windows = builtin.os == Os.windows; const is_posix = switch (builtin.os) { - builtin.Os.linux, - builtin.Os.macosx => true, + builtin.Os.linux, builtin.Os.macosx => true, else => false, }; const os = this; @@ -27,8 +26,7 @@ pub const linux = @import("linux/index.zig"); pub const zen = @import("zen.zig"); pub const posix = switch (builtin.os) { Os.linux => linux, - Os.macosx, - Os.ios => darwin, + Os.macosx, Os.ios => darwin, Os.zen => zen, else => @compileError("Unsupported OS"), }; @@ -112,8 +110,7 @@ pub fn getRandomBytes(buf: []u8) !void { } return; }, - Os.macosx, - Os.ios => { + Os.macosx, Os.ios => { const fd = try posixOpenC(c"/dev/urandom", posix.O_RDONLY | posix.O_CLOEXEC, 0); defer close(fd); @@ -175,9 +172,7 @@ pub fn abort() noreturn { c.abort(); } switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { _ = posix.raise(posix.SIGABRT); _ = posix.raise(posix.SIGKILL); while (true) {} @@ -199,9 +194,7 @@ pub fn exit(status: u8) noreturn { c.exit(status); } switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { posix.exit(status); }, Os.windows => { @@ -250,14 +243,12 @@ pub fn posixRead(fd: i32, buf: []u8) !void { if (err > 0) { return switch (err) { posix.EINTR => continue, - posix.EINVAL, - posix.EFAULT => unreachable, + posix.EINVAL, posix.EFAULT => unreachable, posix.EAGAIN => error.WouldBlock, posix.EBADF => error.FileClosed, posix.EIO => error.InputOutput, posix.EISDIR => error.IsDir, - posix.ENOBUFS, - posix.ENOMEM => error.SystemResources, + posix.ENOBUFS, posix.ENOMEM => error.SystemResources, else => unexpectedErrorPosix(err), }; } @@ -292,8 +283,7 @@ pub fn posixWrite(fd: i32, bytes: []const u8) !void { if (write_err > 0) { return switch (write_err) { posix.EINTR => continue, - posix.EINVAL, - posix.EFAULT => unreachable, + posix.EINVAL, posix.EFAULT => unreachable, posix.EAGAIN => PosixWriteError.WouldBlock, posix.EBADF => PosixWriteError.FileClosed, posix.EDESTADDRREQ => PosixWriteError.DestinationAddressRequired, @@ -349,8 +339,7 @@ pub fn posixOpenC(file_path: &const u8, flags: u32, perm: usize) !i32 { posix.EFAULT => unreachable, posix.EINVAL => unreachable, posix.EACCES => return PosixOpenError.AccessDenied, - posix.EFBIG, - posix.EOVERFLOW => return PosixOpenError.FileTooBig, + posix.EFBIG, posix.EOVERFLOW => return PosixOpenError.FileTooBig, posix.EISDIR => return PosixOpenError.IsDir, posix.ELOOP => return PosixOpenError.SymLinkLoop, posix.EMFILE => return PosixOpenError.ProcessFdQuotaExceeded, @@ -375,8 +364,7 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) !void { const err = posix.getErrno(posix.dup2(old_fd, new_fd)); if (err > 0) { return switch (err) { - posix.EBUSY, - posix.EINTR => continue, + posix.EBUSY, posix.EINTR => continue, posix.EMFILE => error.ProcessFdQuotaExceeded, posix.EINVAL => unreachable, else => unexpectedErrorPosix(err), @@ -493,17 +481,10 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError { assert(err > 0); return switch (err) { posix.EFAULT => unreachable, - posix.E2BIG, - posix.EMFILE, - posix.ENAMETOOLONG, - posix.ENFILE, - posix.ENOMEM => error.SystemResources, - posix.EACCES, - posix.EPERM => error.AccessDenied, - posix.EINVAL, - posix.ENOEXEC => error.InvalidExe, - posix.EIO, - posix.ELOOP => error.FileSystem, + posix.E2BIG, posix.EMFILE, posix.ENAMETOOLONG, posix.ENFILE, posix.ENOMEM => error.SystemResources, + posix.EACCES, posix.EPERM => error.AccessDenied, + posix.EINVAL, posix.ENOEXEC => error.InvalidExe, + posix.EIO, posix.ELOOP => error.FileSystem, posix.EISDIR => error.IsDir, posix.ENOENT => error.FileNotFound, posix.ENOTDIR => error.NotDir, @@ -717,10 +698,8 @@ pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path: const err = posix.getErrno(posix.symlink(existing_buf.ptr, new_buf.ptr)); if (err > 0) { return switch (err) { - posix.EFAULT, - posix.EINVAL => unreachable, - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EFAULT, posix.EINVAL => unreachable, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EDQUOT => error.DiskQuota, posix.EEXIST => error.PathAlreadyExists, posix.EIO => error.FileSystem, @@ -787,8 +766,7 @@ pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) !void { return switch (err) { windows.ERROR.FILE_NOT_FOUND => error.FileNotFound, windows.ERROR.ACCESS_DENIED => error.AccessDenied, - windows.ERROR.FILENAME_EXCED_RANGE, - windows.ERROR.INVALID_PARAMETER => error.NameTooLong, + windows.ERROR.FILENAME_EXCED_RANGE, windows.ERROR.INVALID_PARAMETER => error.NameTooLong, else => unexpectedErrorWindows(err), }; } @@ -804,11 +782,9 @@ pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void { const err = posix.getErrno(posix.unlink(buf.ptr)); if (err > 0) { return switch (err) { - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EBUSY => error.FileBusy, - posix.EFAULT, - posix.EINVAL => unreachable, + posix.EFAULT, posix.EINVAL => unreachable, posix.EIO => error.FileSystem, posix.EISDIR => error.IsDir, posix.ELOOP => error.SymLinkLoop, @@ -948,12 +924,10 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) const err = posix.getErrno(posix.rename(old_buf.ptr, new_buf.ptr)); if (err > 0) { return switch (err) { - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EBUSY => error.FileBusy, posix.EDQUOT => error.DiskQuota, - posix.EFAULT, - posix.EINVAL => unreachable, + posix.EFAULT, posix.EINVAL => unreachable, posix.EISDIR => error.IsDir, posix.ELOOP => error.SymLinkLoop, posix.EMLINK => error.LinkQuotaExceeded, @@ -962,8 +936,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) posix.ENOTDIR => error.NotDir, posix.ENOMEM => error.SystemResources, posix.ENOSPC => error.NoSpaceLeft, - posix.EEXIST, - posix.ENOTEMPTY => error.PathAlreadyExists, + posix.EEXIST, posix.ENOTEMPTY => error.PathAlreadyExists, posix.EROFS => error.ReadOnlyFileSystem, posix.EXDEV => error.RenameAcrossMountPoints, else => unexpectedErrorPosix(err), @@ -1001,8 +974,7 @@ pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) !void { const err = posix.getErrno(posix.mkdir(path_buf.ptr, 0o755)); if (err > 0) { return switch (err) { - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EDQUOT => error.DiskQuota, posix.EEXIST => error.PathAlreadyExists, posix.EFAULT => unreachable, @@ -1065,18 +1037,15 @@ pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) !void { const err = posix.getErrno(posix.rmdir(path_buf.ptr)); if (err > 0) { return switch (err) { - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EBUSY => error.FileBusy, - posix.EFAULT, - posix.EINVAL => unreachable, + posix.EFAULT, posix.EINVAL => unreachable, posix.ELOOP => error.SymLinkLoop, posix.ENAMETOOLONG => error.NameTooLong, posix.ENOENT => error.FileNotFound, posix.ENOMEM => error.SystemResources, posix.ENOTDIR => error.NotDir, - posix.EEXIST, - posix.ENOTEMPTY => error.DirNotEmpty, + posix.EEXIST, posix.ENOTEMPTY => error.DirNotEmpty, posix.EROFS => error.ReadOnlyFileSystem, else => unexpectedErrorPosix(err), }; @@ -1128,7 +1097,8 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError! error.NotDir, error.FileSystem, error.FileBusy, - error.Unexpected => return err, + error.Unexpected, + => return err, } { var dir = Dir.open(allocator, full_path) catch |err| switch (err) { @@ -1152,7 +1122,8 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError! error.SystemResources, error.NoSpaceLeft, error.PathAlreadyExists, - error.Unexpected => return err, + error.Unexpected, + => return err, }; defer dir.close(); @@ -1182,8 +1153,7 @@ pub const Dir = struct { end_index: usize, const darwin_seek_t = switch (builtin.os) { - Os.macosx, - Os.ios => i64, + Os.macosx, Os.ios => i64, else => void, }; @@ -1208,13 +1178,16 @@ pub const Dir = struct { const fd = switch (builtin.os) { Os.windows => @compileError("TODO support Dir.open for windows"), Os.linux => try posixOpen(allocator, dir_path, posix.O_RDONLY | posix.O_DIRECTORY | posix.O_CLOEXEC, 0), - Os.macosx, - Os.ios => try posixOpen(allocator, dir_path, posix.O_RDONLY | posix.O_NONBLOCK | posix.O_DIRECTORY | posix.O_CLOEXEC, 0), + Os.macosx, Os.ios => try posixOpen( + allocator, + dir_path, + posix.O_RDONLY | posix.O_NONBLOCK | posix.O_DIRECTORY | posix.O_CLOEXEC, + 0, + ), else => @compileError("Dir.open is not supported for this platform"), }; const darwin_seek_init = switch (builtin.os) { - Os.macosx, - Os.ios => 0, + Os.macosx, Os.ios => 0, else => {}, }; return Dir{ @@ -1237,8 +1210,7 @@ pub const Dir = struct { pub fn next(self: &Dir) !?Entry { switch (builtin.os) { Os.linux => return self.nextLinux(), - Os.macosx, - Os.ios => return self.nextDarwin(), + Os.macosx, Os.ios => return self.nextDarwin(), Os.windows => return self.nextWindows(), else => @compileError("Dir.next not supported on " ++ @tagName(builtin.os)), } @@ -1256,9 +1228,7 @@ pub const Dir = struct { const err = posix.getErrno(result); if (err > 0) { switch (err) { - posix.EBADF, - posix.EFAULT, - posix.ENOTDIR => unreachable, + posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable, posix.EINVAL => { self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2); continue; @@ -1317,9 +1287,7 @@ pub const Dir = struct { const err = posix.getErrno(result); if (err > 0) { switch (err) { - posix.EBADF, - posix.EFAULT, - posix.ENOTDIR => unreachable, + posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable, posix.EINVAL => { self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2); continue; @@ -1402,8 +1370,7 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 { if (err > 0) { return switch (err) { posix.EACCES => error.AccessDenied, - posix.EFAULT, - posix.EINVAL => unreachable, + posix.EFAULT, posix.EINVAL => unreachable, posix.EIO => error.FileSystem, posix.ELOOP => error.SymLinkLoop, posix.ENAMETOOLONG => error.NameTooLong, @@ -1545,8 +1512,7 @@ pub const ArgIteratorWindows = struct { const byte = self.cmd_line[self.index]; switch (byte) { 0 => return null, - ' ', - '\t' => continue, + ' ', '\t' => continue, else => break, } } @@ -1560,8 +1526,7 @@ pub const ArgIteratorWindows = struct { const byte = self.cmd_line[self.index]; switch (byte) { 0 => return false, - ' ', - '\t' => continue, + ' ', '\t' => continue, else => break, } } @@ -1580,8 +1545,7 @@ pub const ArgIteratorWindows = struct { '\\' => { backslash_count += 1; }, - ' ', - '\t' => { + ' ', '\t' => { if (self.seen_quote_count % 2 == 0 or self.seen_quote_count == self.quote_count) { return true; } @@ -1621,8 +1585,7 @@ pub const ArgIteratorWindows = struct { '\\' => { backslash_count += 1; }, - ' ', - '\t' => { + ' ', '\t' => { try self.emitBackslashes(&buf, backslash_count); backslash_count = 0; if (self.seen_quote_count % 2 == 1 and self.seen_quote_count != self.quote_count) { @@ -1840,8 +1803,7 @@ pub fn openSelfExe() !os.File { var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]); return os.File.openRead(&fixed_allocator.allocator, proc_file_path); }, - Os.macosx, - Os.ios => { + Os.macosx, Os.ios => { var fixed_buffer_mem: [darwin.PATH_MAX * 2]u8 = undefined; var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]); const self_exe_path = try selfExePath(&fixed_allocator.allocator); @@ -1853,9 +1815,7 @@ pub fn openSelfExe() !os.File { test "openSelfExe" { switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => (try openSelfExe()).close(), + Os.linux, Os.macosx, Os.ios => (try openSelfExe()).close(), else => return, // Unsupported OS. } } @@ -1893,8 +1853,7 @@ pub fn selfExePath(allocator: &mem.Allocator) ![]u8 { try out_path.resize(new_len); } }, - Os.macosx, - Os.ios => { + Os.macosx, Os.ios => { var u32_len: u32 = 0; const ret1 = c._NSGetExecutablePath(undefined, &u32_len); assert(ret1 != 0); @@ -1922,9 +1881,7 @@ pub fn selfExeDirPath(allocator: &mem.Allocator) ![]u8 { const dir = path.dirname(full_exe_path); return allocator.shrink(u8, full_exe_path, dir.len); }, - Os.windows, - Os.macosx, - Os.ios => { + Os.windows, Os.macosx, Os.ios => { const self_exe_path = try selfExePath(allocator); errdefer allocator.free(self_exe_path); const dirname = os.path.dirname(self_exe_path); @@ -1981,8 +1938,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 { posix.EINVAL => return PosixSocketError.ProtocolFamilyNotAvailable, posix.EMFILE => return PosixSocketError.ProcessFdQuotaExceeded, posix.ENFILE => return PosixSocketError.SystemFdQuotaExceeded, - posix.ENOBUFS, - posix.ENOMEM => return PosixSocketError.SystemResources, + posix.ENOBUFS, posix.ENOMEM => return PosixSocketError.SystemResources, posix.EPROTONOSUPPORT => return PosixSocketError.ProtocolNotSupported, else => return unexpectedErrorPosix(err), } @@ -1990,7 +1946,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 { pub const PosixBindError = error{ /// The address is protected, and the user is not the superuser. - /// For UNIX domain sockets: Search permission is denied on a component + /// For UNIX domain sockets: Search permission is denied on a component /// of the path prefix. AccessDenied, @@ -2151,8 +2107,7 @@ pub fn posixAccept(fd: i32, addr: &posix.sockaddr, flags: u32) PosixAcceptError! posix.EINVAL => return PosixAcceptError.InvalidSyscall, posix.EMFILE => return PosixAcceptError.ProcessFdQuotaExceeded, posix.ENFILE => return PosixAcceptError.SystemFdQuotaExceeded, - posix.ENOBUFS, - posix.ENOMEM => return PosixAcceptError.SystemResources, + posix.ENOBUFS, posix.ENOMEM => return PosixAcceptError.SystemResources, posix.ENOTSOCK => return PosixAcceptError.FileDescriptorNotASocket, posix.EOPNOTSUPP => return PosixAcceptError.OperationNotSupported, posix.EPROTO => return PosixAcceptError.ProtocolFailure, @@ -2363,8 +2318,7 @@ pub fn posixConnectAsync(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConn const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr)); const err = posix.getErrno(rc); switch (err) { - 0, - posix.EINPROGRESS => return, + 0, posix.EINPROGRESS => return, else => return unexpectedErrorPosix(err), posix.EACCES => return PosixConnectError.PermissionDenied, @@ -2416,7 +2370,7 @@ pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void { }, else => return unexpectedErrorPosix(err), posix.EBADF => unreachable, // The argument sockfd is not a valid file descriptor. - posix.EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space. + posix.EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space. posix.EINVAL => unreachable, posix.ENOPROTOOPT => unreachable, // The option is unknown at the level indicated. posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket. @@ -2427,11 +2381,13 @@ pub const Thread = struct { data: Data, pub const use_pthreads = is_posix and builtin.link_libc; - const Data = if (use_pthreads) struct { - handle: c.pthread_t, - stack_addr: usize, - stack_len: usize, - } else switch (builtin.os) { + const Data = if (use_pthreads) + struct { + handle: c.pthread_t, + stack_addr: usize, + stack_len: usize, + } + else switch (builtin.os) { builtin.Os.linux => struct { pid: i32, stack_addr: usize, diff --git a/std/os/linux/errno.zig b/std/os/linux/errno.zig index 39f4e37a10..5ad8777f92 100644 --- a/std/os/linux/errno.zig +++ b/std/os/linux/errno.zig @@ -1,146 +1,427 @@ -pub const EPERM = 1; /// Operation not permitted -pub const ENOENT = 2; /// No such file or directory -pub const ESRCH = 3; /// No such process -pub const EINTR = 4; /// Interrupted system call -pub const EIO = 5; /// I/O error -pub const ENXIO = 6; /// No such device or address -pub const E2BIG = 7; /// Arg list too long -pub const ENOEXEC = 8; /// Exec format error -pub const EBADF = 9; /// Bad file number -pub const ECHILD = 10; /// No child processes -pub const EAGAIN = 11; /// Try again -pub const ENOMEM = 12; /// Out of memory -pub const EACCES = 13; /// Permission denied -pub const EFAULT = 14; /// Bad address -pub const ENOTBLK = 15; /// Block device required -pub const EBUSY = 16; /// Device or resource busy -pub const EEXIST = 17; /// File exists -pub const EXDEV = 18; /// Cross-device link -pub const ENODEV = 19; /// No such device -pub const ENOTDIR = 20; /// Not a directory -pub const EISDIR = 21; /// Is a directory -pub const EINVAL = 22; /// Invalid argument -pub const ENFILE = 23; /// File table overflow -pub const EMFILE = 24; /// Too many open files -pub const ENOTTY = 25; /// Not a typewriter -pub const ETXTBSY = 26; /// Text file busy -pub const EFBIG = 27; /// File too large -pub const ENOSPC = 28; /// No space left on device -pub const ESPIPE = 29; /// Illegal seek -pub const EROFS = 30; /// Read-only file system -pub const EMLINK = 31; /// Too many links -pub const EPIPE = 32; /// Broken pipe -pub const EDOM = 33; /// Math argument out of domain of func -pub const ERANGE = 34; /// Math result not representable -pub const EDEADLK = 35; /// Resource deadlock would occur -pub const ENAMETOOLONG = 36; /// File name too long -pub const ENOLCK = 37; /// No record locks available -pub const ENOSYS = 38; /// Function not implemented -pub const ENOTEMPTY = 39; /// Directory not empty -pub const ELOOP = 40; /// Too many symbolic links encountered -pub const EWOULDBLOCK = EAGAIN; /// Operation would block -pub const ENOMSG = 42; /// No message of desired type -pub const EIDRM = 43; /// Identifier removed -pub const ECHRNG = 44; /// Channel number out of range -pub const EL2NSYNC = 45; /// Level 2 not synchronized -pub const EL3HLT = 46; /// Level 3 halted -pub const EL3RST = 47; /// Level 3 reset -pub const ELNRNG = 48; /// Link number out of range -pub const EUNATCH = 49; /// Protocol driver not attached -pub const ENOCSI = 50; /// No CSI structure available -pub const EL2HLT = 51; /// Level 2 halted -pub const EBADE = 52; /// Invalid exchange -pub const EBADR = 53; /// Invalid request descriptor -pub const EXFULL = 54; /// Exchange full -pub const ENOANO = 55; /// No anode -pub const EBADRQC = 56; /// Invalid request code -pub const EBADSLT = 57; /// Invalid slot +/// Operation not permitted +pub const EPERM = 1; -pub const EBFONT = 59; /// Bad font file format -pub const ENOSTR = 60; /// Device not a stream -pub const ENODATA = 61; /// No data available -pub const ETIME = 62; /// Timer expired -pub const ENOSR = 63; /// Out of streams resources -pub const ENONET = 64; /// Machine is not on the network -pub const ENOPKG = 65; /// Package not installed -pub const EREMOTE = 66; /// Object is remote -pub const ENOLINK = 67; /// Link has been severed -pub const EADV = 68; /// Advertise error -pub const ESRMNT = 69; /// Srmount error -pub const ECOMM = 70; /// Communication error on send -pub const EPROTO = 71; /// Protocol error -pub const EMULTIHOP = 72; /// Multihop attempted -pub const EDOTDOT = 73; /// RFS specific error -pub const EBADMSG = 74; /// Not a data message -pub const EOVERFLOW = 75; /// Value too large for defined data type -pub const ENOTUNIQ = 76; /// Name not unique on network -pub const EBADFD = 77; /// File descriptor in bad state -pub const EREMCHG = 78; /// Remote address changed -pub const ELIBACC = 79; /// Can not access a needed shared library -pub const ELIBBAD = 80; /// Accessing a corrupted shared library -pub const ELIBSCN = 81; /// .lib section in a.out corrupted -pub const ELIBMAX = 82; /// Attempting to link in too many shared libraries -pub const ELIBEXEC = 83; /// Cannot exec a shared library directly -pub const EILSEQ = 84; /// Illegal byte sequence -pub const ERESTART = 85; /// Interrupted system call should be restarted -pub const ESTRPIPE = 86; /// Streams pipe error -pub const EUSERS = 87; /// Too many users -pub const ENOTSOCK = 88; /// Socket operation on non-socket -pub const EDESTADDRREQ = 89; /// Destination address required -pub const EMSGSIZE = 90; /// Message too long -pub const EPROTOTYPE = 91; /// Protocol wrong type for socket -pub const ENOPROTOOPT = 92; /// Protocol not available -pub const EPROTONOSUPPORT = 93; /// Protocol not supported -pub const ESOCKTNOSUPPORT = 94; /// Socket type not supported -pub const EOPNOTSUPP = 95; /// Operation not supported on transport endpoint -pub const EPFNOSUPPORT = 96; /// Protocol family not supported -pub const EAFNOSUPPORT = 97; /// Address family not supported by protocol -pub const EADDRINUSE = 98; /// Address already in use -pub const EADDRNOTAVAIL = 99; /// Cannot assign requested address -pub const ENETDOWN = 100; /// Network is down -pub const ENETUNREACH = 101; /// Network is unreachable -pub const ENETRESET = 102; /// Network dropped connection because of reset -pub const ECONNABORTED = 103; /// Software caused connection abort -pub const ECONNRESET = 104; /// Connection reset by peer -pub const ENOBUFS = 105; /// No buffer space available -pub const EISCONN = 106; /// Transport endpoint is already connected -pub const ENOTCONN = 107; /// Transport endpoint is not connected -pub const ESHUTDOWN = 108; /// Cannot send after transport endpoint shutdown -pub const ETOOMANYREFS = 109; /// Too many references: cannot splice -pub const ETIMEDOUT = 110; /// Connection timed out -pub const ECONNREFUSED = 111; /// Connection refused -pub const EHOSTDOWN = 112; /// Host is down -pub const EHOSTUNREACH = 113; /// No route to host -pub const EALREADY = 114; /// Operation already in progress -pub const EINPROGRESS = 115; /// Operation now in progress -pub const ESTALE = 116; /// Stale NFS file handle -pub const EUCLEAN = 117; /// Structure needs cleaning -pub const ENOTNAM = 118; /// Not a XENIX named type file -pub const ENAVAIL = 119; /// No XENIX semaphores available -pub const EISNAM = 120; /// Is a named type file -pub const EREMOTEIO = 121; /// Remote I/O error -pub const EDQUOT = 122; /// Quota exceeded +/// No such file or directory +pub const ENOENT = 2; -pub const ENOMEDIUM = 123; /// No medium found -pub const EMEDIUMTYPE = 124; /// Wrong medium type +/// No such process +pub const ESRCH = 3; + +/// Interrupted system call +pub const EINTR = 4; + +/// I/O error +pub const EIO = 5; + +/// No such device or address +pub const ENXIO = 6; + +/// Arg list too long +pub const E2BIG = 7; + +/// Exec format error +pub const ENOEXEC = 8; + +/// Bad file number +pub const EBADF = 9; + +/// No child processes +pub const ECHILD = 10; + +/// Try again +pub const EAGAIN = 11; + +/// Out of memory +pub const ENOMEM = 12; + +/// Permission denied +pub const EACCES = 13; + +/// Bad address +pub const EFAULT = 14; + +/// Block device required +pub const ENOTBLK = 15; + +/// Device or resource busy +pub const EBUSY = 16; + +/// File exists +pub const EEXIST = 17; + +/// Cross-device link +pub const EXDEV = 18; + +/// No such device +pub const ENODEV = 19; + +/// Not a directory +pub const ENOTDIR = 20; + +/// Is a directory +pub const EISDIR = 21; + +/// Invalid argument +pub const EINVAL = 22; + +/// File table overflow +pub const ENFILE = 23; + +/// Too many open files +pub const EMFILE = 24; + +/// Not a typewriter +pub const ENOTTY = 25; + +/// Text file busy +pub const ETXTBSY = 26; + +/// File too large +pub const EFBIG = 27; + +/// No space left on device +pub const ENOSPC = 28; + +/// Illegal seek +pub const ESPIPE = 29; + +/// Read-only file system +pub const EROFS = 30; + +/// Too many links +pub const EMLINK = 31; + +/// Broken pipe +pub const EPIPE = 32; + +/// Math argument out of domain of func +pub const EDOM = 33; + +/// Math result not representable +pub const ERANGE = 34; + +/// Resource deadlock would occur +pub const EDEADLK = 35; + +/// File name too long +pub const ENAMETOOLONG = 36; + +/// No record locks available +pub const ENOLCK = 37; + +/// Function not implemented +pub const ENOSYS = 38; + +/// Directory not empty +pub const ENOTEMPTY = 39; + +/// Too many symbolic links encountered +pub const ELOOP = 40; + +/// Operation would block +pub const EWOULDBLOCK = EAGAIN; + +/// No message of desired type +pub const ENOMSG = 42; + +/// Identifier removed +pub const EIDRM = 43; + +/// Channel number out of range +pub const ECHRNG = 44; + +/// Level 2 not synchronized +pub const EL2NSYNC = 45; + +/// Level 3 halted +pub const EL3HLT = 46; + +/// Level 3 reset +pub const EL3RST = 47; + +/// Link number out of range +pub const ELNRNG = 48; + +/// Protocol driver not attached +pub const EUNATCH = 49; + +/// No CSI structure available +pub const ENOCSI = 50; + +/// Level 2 halted +pub const EL2HLT = 51; + +/// Invalid exchange +pub const EBADE = 52; + +/// Invalid request descriptor +pub const EBADR = 53; + +/// Exchange full +pub const EXFULL = 54; + +/// No anode +pub const ENOANO = 55; + +/// Invalid request code +pub const EBADRQC = 56; + +/// Invalid slot +pub const EBADSLT = 57; + +/// Bad font file format +pub const EBFONT = 59; + +/// Device not a stream +pub const ENOSTR = 60; + +/// No data available +pub const ENODATA = 61; + +/// Timer expired +pub const ETIME = 62; + +/// Out of streams resources +pub const ENOSR = 63; + +/// Machine is not on the network +pub const ENONET = 64; + +/// Package not installed +pub const ENOPKG = 65; + +/// Object is remote +pub const EREMOTE = 66; + +/// Link has been severed +pub const ENOLINK = 67; + +/// Advertise error +pub const EADV = 68; + +/// Srmount error +pub const ESRMNT = 69; + +/// Communication error on send +pub const ECOMM = 70; + +/// Protocol error +pub const EPROTO = 71; + +/// Multihop attempted +pub const EMULTIHOP = 72; + +/// RFS specific error +pub const EDOTDOT = 73; + +/// Not a data message +pub const EBADMSG = 74; + +/// Value too large for defined data type +pub const EOVERFLOW = 75; + +/// Name not unique on network +pub const ENOTUNIQ = 76; + +/// File descriptor in bad state +pub const EBADFD = 77; + +/// Remote address changed +pub const EREMCHG = 78; + +/// Can not access a needed shared library +pub const ELIBACC = 79; + +/// Accessing a corrupted shared library +pub const ELIBBAD = 80; + +/// .lib section in a.out corrupted +pub const ELIBSCN = 81; + +/// Attempting to link in too many shared libraries +pub const ELIBMAX = 82; + +/// Cannot exec a shared library directly +pub const ELIBEXEC = 83; + +/// Illegal byte sequence +pub const EILSEQ = 84; + +/// Interrupted system call should be restarted +pub const ERESTART = 85; + +/// Streams pipe error +pub const ESTRPIPE = 86; + +/// Too many users +pub const EUSERS = 87; + +/// Socket operation on non-socket +pub const ENOTSOCK = 88; + +/// Destination address required +pub const EDESTADDRREQ = 89; + +/// Message too long +pub const EMSGSIZE = 90; + +/// Protocol wrong type for socket +pub const EPROTOTYPE = 91; + +/// Protocol not available +pub const ENOPROTOOPT = 92; + +/// Protocol not supported +pub const EPROTONOSUPPORT = 93; + +/// Socket type not supported +pub const ESOCKTNOSUPPORT = 94; + +/// Operation not supported on transport endpoint +pub const EOPNOTSUPP = 95; + +/// Protocol family not supported +pub const EPFNOSUPPORT = 96; + +/// Address family not supported by protocol +pub const EAFNOSUPPORT = 97; + +/// Address already in use +pub const EADDRINUSE = 98; + +/// Cannot assign requested address +pub const EADDRNOTAVAIL = 99; + +/// Network is down +pub const ENETDOWN = 100; + +/// Network is unreachable +pub const ENETUNREACH = 101; + +/// Network dropped connection because of reset +pub const ENETRESET = 102; + +/// Software caused connection abort +pub const ECONNABORTED = 103; + +/// Connection reset by peer +pub const ECONNRESET = 104; + +/// No buffer space available +pub const ENOBUFS = 105; + +/// Transport endpoint is already connected +pub const EISCONN = 106; + +/// Transport endpoint is not connected +pub const ENOTCONN = 107; + +/// Cannot send after transport endpoint shutdown +pub const ESHUTDOWN = 108; + +/// Too many references: cannot splice +pub const ETOOMANYREFS = 109; + +/// Connection timed out +pub const ETIMEDOUT = 110; + +/// Connection refused +pub const ECONNREFUSED = 111; + +/// Host is down +pub const EHOSTDOWN = 112; + +/// No route to host +pub const EHOSTUNREACH = 113; + +/// Operation already in progress +pub const EALREADY = 114; + +/// Operation now in progress +pub const EINPROGRESS = 115; + +/// Stale NFS file handle +pub const ESTALE = 116; + +/// Structure needs cleaning +pub const EUCLEAN = 117; + +/// Not a XENIX named type file +pub const ENOTNAM = 118; + +/// No XENIX semaphores available +pub const ENAVAIL = 119; + +/// Is a named type file +pub const EISNAM = 120; + +/// Remote I/O error +pub const EREMOTEIO = 121; + +/// Quota exceeded +pub const EDQUOT = 122; + +/// No medium found +pub const ENOMEDIUM = 123; + +/// Wrong medium type +pub const EMEDIUMTYPE = 124; // nameserver query return codes -pub const ENSROK = 0; /// DNS server returned answer with no data -pub const ENSRNODATA = 160; /// DNS server returned answer with no data -pub const ENSRFORMERR = 161; /// DNS server claims query was misformatted -pub const ENSRSERVFAIL = 162; /// DNS server returned general failure -pub const ENSRNOTFOUND = 163; /// Domain name not found -pub const ENSRNOTIMP = 164; /// DNS server does not implement requested operation -pub const ENSRREFUSED = 165; /// DNS server refused query -pub const ENSRBADQUERY = 166; /// Misformatted DNS query -pub const ENSRBADNAME = 167; /// Misformatted domain name -pub const ENSRBADFAMILY = 168; /// Unsupported address family -pub const ENSRBADRESP = 169; /// Misformatted DNS reply -pub const ENSRCONNREFUSED = 170; /// Could not contact DNS servers -pub const ENSRTIMEOUT = 171; /// Timeout while contacting DNS servers -pub const ENSROF = 172; /// End of file -pub const ENSRFILE = 173; /// Error reading file -pub const ENSRNOMEM = 174; /// Out of memory -pub const ENSRDESTRUCTION = 175; /// Application terminated lookup -pub const ENSRQUERYDOMAINTOOLONG = 176; /// Domain name is too long -pub const ENSRCNAMELOOP = 177; /// Domain name is too long + +/// DNS server returned answer with no data +pub const ENSROK = 0; + +/// DNS server returned answer with no data +pub const ENSRNODATA = 160; + +/// DNS server claims query was misformatted +pub const ENSRFORMERR = 161; + +/// DNS server returned general failure +pub const ENSRSERVFAIL = 162; + +/// Domain name not found +pub const ENSRNOTFOUND = 163; + +/// DNS server does not implement requested operation +pub const ENSRNOTIMP = 164; + +/// DNS server refused query +pub const ENSRREFUSED = 165; + +/// Misformatted DNS query +pub const ENSRBADQUERY = 166; + +/// Misformatted domain name +pub const ENSRBADNAME = 167; + +/// Unsupported address family +pub const ENSRBADFAMILY = 168; + +/// Misformatted DNS reply +pub const ENSRBADRESP = 169; + +/// Could not contact DNS servers +pub const ENSRCONNREFUSED = 170; + +/// Timeout while contacting DNS servers +pub const ENSRTIMEOUT = 171; + +/// End of file +pub const ENSROF = 172; + +/// Error reading file +pub const ENSRFILE = 173; + +/// Out of memory +pub const ENSRNOMEM = 174; + +/// Application terminated lookup +pub const ENSRDESTRUCTION = 175; + +/// Domain name is too long +pub const ENSRQUERYDOMAINTOOLONG = 176; + +/// Domain name is too long +pub const ENSRCNAMELOOP = 177; diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 4e0e9ee5d5..1cf5bbd432 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -823,8 +823,7 @@ pub fn clock_gettime(clk_id: i32, tp: ×pec) usize { if (@ptrToInt(f) != 0) { const rc = f(clk_id, tp); switch (rc) { - 0, - @bitCast(usize, isize(-EINVAL)) => return rc, + 0, @bitCast(usize, isize(-EINVAL)) => return rc, else => {}, } } diff --git a/std/os/linux/test.zig b/std/os/linux/test.zig index 18a6e5f19f..06aae1968f 100644 --- a/std/os/linux/test.zig +++ b/std/os/linux/test.zig @@ -11,22 +11,22 @@ test "timer" { const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0); assert(linux.getErrno(timer_fd) == 0); - const time_interval = linux.timespec { + const time_interval = linux.timespec{ .tv_sec = 0, - .tv_nsec = 2000000 + .tv_nsec = 2000000, }; - const new_time = linux.itimerspec { + const new_time = linux.itimerspec{ .it_interval = time_interval, - .it_value = time_interval + .it_value = time_interval, }; err = linux.timerfd_settime(i32(timer_fd), 0, &new_time, null); assert(err == 0); - var event = linux.epoll_event { + var event = linux.epoll_event{ .events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET, - .data = linux.epoll_data { .ptr = 0 }, + .data = linux.epoll_data{ .ptr = 0 }, }; err = linux.epoll_ctl(i32(epoll_fd), linux.EPOLL_CTL_ADD, i32(timer_fd), &event); diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig index f4fb513af9..8e0a285841 100644 --- a/std/os/linux/vdso.zig +++ b/std/os/linux/vdso.zig @@ -16,7 +16,10 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { var base: usize = @maxValue(usize); { var i: usize = 0; - while (i < eh.e_phnum) : ({i += 1; ph_addr += eh.e_phentsize;}) { + while (i < eh.e_phnum) : ({ + i += 1; + ph_addr += eh.e_phentsize; + }) { const this_ph = @intToPtr(&elf.Phdr, ph_addr); switch (this_ph.p_type) { elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr, @@ -54,15 +57,14 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { const hashtab = maybe_hashtab ?? return 0; if (maybe_verdef == null) maybe_versym = null; - - const OK_TYPES = (1<>4) & OK_BINDS)) continue; - if (0==syms[i].st_shndx) continue; + if (0 == (u32(1) << u5(syms[i].st_info & 0xf) & OK_TYPES)) continue; + if (0 == (u32(1) << u5(syms[i].st_info >> 4) & OK_BINDS)) continue; + if (0 == syms[i].st_shndx) continue; if (!mem.eql(u8, name, cstr.toSliceConst(&strings[syms[i].st_name]))) continue; if (maybe_versym) |versym| { if (!checkver(??maybe_verdef, versym[i], vername, strings)) @@ -78,12 +80,12 @@ fn checkver(def_arg: &elf.Verdef, vsym_arg: i32, vername: []const u8, strings: & var def = def_arg; const vsym = @bitCast(u32, vsym_arg) & 0x7fff; while (true) { - if (0==(def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym) + if (0 == (def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym) break; if (def.vd_next == 0) return false; def = @intToPtr(&elf.Verdef, @ptrToInt(def) + def.vd_next); } - const aux = @intToPtr(&elf.Verdaux, @ptrToInt(def ) + def.vd_aux); + const aux = @intToPtr(&elf.Verdaux, @ptrToInt(def) + def.vd_aux); return mem.eql(u8, vername, cstr.toSliceConst(&strings[aux.vda_name])); } diff --git a/std/os/linux/x86_64.zig b/std/os/linux/x86_64.zig index 544b2365ce..ed32d59688 100644 --- a/std/os/linux/x86_64.zig +++ b/std/os/linux/x86_64.zig @@ -330,26 +330,26 @@ pub const SYS_userfaultfd = 323; pub const SYS_membarrier = 324; pub const SYS_mlock2 = 325; -pub const O_CREAT = 0o100; -pub const O_EXCL = 0o200; -pub const O_NOCTTY = 0o400; -pub const O_TRUNC = 0o1000; -pub const O_APPEND = 0o2000; -pub const O_NONBLOCK = 0o4000; -pub const O_DSYNC = 0o10000; -pub const O_SYNC = 0o4010000; -pub const O_RSYNC = 0o4010000; +pub const O_CREAT = 0o100; +pub const O_EXCL = 0o200; +pub const O_NOCTTY = 0o400; +pub const O_TRUNC = 0o1000; +pub const O_APPEND = 0o2000; +pub const O_NONBLOCK = 0o4000; +pub const O_DSYNC = 0o10000; +pub const O_SYNC = 0o4010000; +pub const O_RSYNC = 0o4010000; pub const O_DIRECTORY = 0o200000; -pub const O_NOFOLLOW = 0o400000; -pub const O_CLOEXEC = 0o2000000; +pub const O_NOFOLLOW = 0o400000; +pub const O_CLOEXEC = 0o2000000; -pub const O_ASYNC = 0o20000; -pub const O_DIRECT = 0o40000; -pub const O_LARGEFILE = 0; -pub const O_NOATIME = 0o1000000; -pub const O_PATH = 0o10000000; +pub const O_ASYNC = 0o20000; +pub const O_DIRECT = 0o40000; +pub const O_LARGEFILE = 0; +pub const O_NOATIME = 0o1000000; +pub const O_PATH = 0o10000000; pub const O_TMPFILE = 0o20200000; -pub const O_NDELAY = O_NONBLOCK; +pub const O_NDELAY = O_NONBLOCK; pub const F_DUPFD = 0; pub const F_GETFD = 1; @@ -371,7 +371,6 @@ pub const F_GETOWN_EX = 16; pub const F_GETOWNER_UIDS = 17; - pub const VDSO_USEFUL = true; pub const VDSO_CGT_SYM = "__vdso_clock_gettime"; pub const VDSO_CGT_VER = "LINUX_2.6"; @@ -382,72 +381,85 @@ pub fn syscall0(number: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number) - : "rcx", "r11"); + : "rcx", "r11" + ); } pub fn syscall1(number: usize, arg1: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1) + : "rcx", "r11" + ); } pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2) + : "rcx", "r11" + ); } pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2), + [arg3] "{rdx}" (arg3) + : "rcx", "r11" + ); } pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3), - [arg4] "{r10}" (arg4) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2), + [arg3] "{rdx}" (arg3), + [arg4] "{r10}" (arg4) + : "rcx", "r11" + ); } pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3), - [arg4] "{r10}" (arg4), - [arg5] "{r8}" (arg5) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2), + [arg3] "{rdx}" (arg3), + [arg4] "{r10}" (arg4), + [arg5] "{r8}" (arg5) + : "rcx", "r11" + ); } -pub fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, - arg5: usize, arg6: usize) usize -{ +pub fn syscall6( + number: usize, + arg1: usize, + arg2: usize, + arg3: usize, + arg4: usize, + arg5: usize, + arg6: usize, +) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3), - [arg4] "{r10}" (arg4), - [arg5] "{r8}" (arg5), - [arg6] "{r9}" (arg6) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2), + [arg3] "{rdx}" (arg3), + [arg4] "{r10}" (arg4), + [arg5] "{r8}" (arg5), + [arg6] "{r9}" (arg6) + : "rcx", "r11" + ); } /// This matches the libc clone function. @@ -457,10 +469,10 @@ pub nakedcc fn restore_rt() void { return asm volatile ("syscall" : : [number] "{rax}" (usize(SYS_rt_sigreturn)) - : "rcx", "r11"); + : "rcx", "r11" + ); } - pub const msghdr = extern struct { msg_name: &u8, msg_namelen: socklen_t, diff --git a/std/os/path.zig b/std/os/path.zig index 0ea5d5a753..5b2b031aab 100644 --- a/std/os/path.zig +++ b/std/os/path.zig @@ -55,9 +55,7 @@ test "os.path.join" { assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\", "a", "b\\", "c"), "c:\\a\\b\\c")); assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\a\\", "b\\", "c"), "c:\\a\\b\\c")); - assert(mem.eql(u8, try joinWindows(debug.global_allocator, - "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "io.zig"), - "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\io.zig")); + assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "io.zig"), "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\io.zig")); assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b", "c"), "/a/b/c")); assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b/", "c"), "/a/b/c")); @@ -65,8 +63,7 @@ test "os.path.join" { assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/", "a", "b/", "c"), "/a/b/c")); assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/", "b/", "c"), "/a/b/c")); - assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/home/andy/dev/zig/build/lib/zig/std", "io.zig"), - "/home/andy/dev/zig/build/lib/zig/std/io.zig")); + assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/home/andy/dev/zig/build/lib/zig/std", "io.zig"), "/home/andy/dev/zig/build/lib/zig/std/io.zig")); } pub fn isAbsolute(path: []const u8) bool { @@ -151,22 +148,22 @@ pub const WindowsPath = struct { pub fn windowsParsePath(path: []const u8) WindowsPath { if (path.len >= 2 and path[1] == ':') { - return WindowsPath { + return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.Drive, .disk_designator = path[0..2], }; } if (path.len >= 1 and (path[0] == '/' or path[0] == '\\') and - (path.len == 1 or (path[1] != '/' and path[1] != '\\'))) + (path.len == 1 or (path[1] != '/' and path[1] != '\\'))) { - return WindowsPath { + return WindowsPath{ .is_abs = true, .kind = WindowsPath.Kind.None, .disk_designator = path[0..0], }; } - const relative_path = WindowsPath { + const relative_path = WindowsPath{ .kind = WindowsPath.Kind.None, .disk_designator = []u8{}, .is_abs = false, @@ -178,7 +175,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { // TODO when I combined these together with `inline for` the compiler crashed { const this_sep = '/'; - const two_sep = []u8{this_sep, this_sep}; + const two_sep = []u8{ this_sep, this_sep }; if (mem.startsWith(u8, path, two_sep)) { if (path[2] == this_sep) { return relative_path; @@ -187,7 +184,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { var it = mem.split(path, []u8{this_sep}); _ = (it.next() ?? return relative_path); _ = (it.next() ?? return relative_path); - return WindowsPath { + return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.NetworkShare, .disk_designator = path[0..it.index], @@ -196,7 +193,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { } { const this_sep = '\\'; - const two_sep = []u8{this_sep, this_sep}; + const two_sep = []u8{ this_sep, this_sep }; if (mem.startsWith(u8, path, two_sep)) { if (path[2] == this_sep) { return relative_path; @@ -205,7 +202,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { var it = mem.split(path, []u8{this_sep}); _ = (it.next() ?? return relative_path); _ = (it.next() ?? return relative_path); - return WindowsPath { + return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.NetworkShare, .disk_designator = path[0..it.index], @@ -296,7 +293,7 @@ fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8 fn asciiUpper(byte: u8) u8 { return switch (byte) { - 'a' ... 'z' => 'A' + (byte - 'a'), + 'a'...'z' => 'A' + (byte - 'a'), else => byte, }; } @@ -372,7 +369,6 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { max_size += p.len + 1; } - // if we will result with a disk designator, loop again to determine // which is the last time the disk designator is absolutely specified, if any // and count up the max bytes for paths related to this disk designator @@ -386,8 +382,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { const parsed = windowsParsePath(p); if (parsed.kind != WindowsPath.Kind.None) { if (parsed.kind == have_drive_kind) { - correct_disk_designator = compareDiskDesignators(have_drive_kind, - result_disk_designator, parsed.disk_designator); + correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator); } else { continue; } @@ -404,7 +399,6 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { } } - // Allocate result and fill in the disk designator, calling getCwd if we have to. var result: []u8 = undefined; var result_index: usize = 0; @@ -433,7 +427,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { result_index += 1; mem.copy(u8, result[result_index..], other_name); result_index += other_name.len; - + result_disk_designator = result[0..result_index]; }, WindowsPath.Kind.None => { @@ -478,8 +472,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { if (parsed.kind != WindowsPath.Kind.None) { if (parsed.kind == have_drive_kind) { - correct_disk_designator = compareDiskDesignators(have_drive_kind, - result_disk_designator, parsed.disk_designator); + correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator); } else { continue; } @@ -591,7 +584,7 @@ test "os.path.resolve" { } assert(mem.eql(u8, testResolveWindows([][]const u8{"."}), cwd)); } else { - assert(mem.eql(u8, testResolvePosix([][]const u8{"a/b/c/", "../../.."}), cwd)); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "a/b/c/", "../../.." }), cwd)); assert(mem.eql(u8, testResolvePosix([][]const u8{"."}), cwd)); } } @@ -601,16 +594,15 @@ test "os.path.resolveWindows" { const cwd = try os.getCwd(debug.global_allocator); const parsed_cwd = windowsParsePath(cwd); { - const result = testResolveWindows([][]const u8{"/usr/local", "lib\\zig\\std\\array_list.zig"}); - const expected = try join(debug.global_allocator, - parsed_cwd.disk_designator, "usr\\local\\lib\\zig\\std\\array_list.zig"); + const result = testResolveWindows([][]const u8{ "/usr/local", "lib\\zig\\std\\array_list.zig" }); + const expected = try join(debug.global_allocator, parsed_cwd.disk_designator, "usr\\local\\lib\\zig\\std\\array_list.zig"); if (parsed_cwd.kind == WindowsPath.Kind.Drive) { expected[0] = asciiUpper(parsed_cwd.disk_designator[0]); } assert(mem.eql(u8, result, expected)); } { - const result = testResolveWindows([][]const u8{"usr/local", "lib\\zig"}); + const result = testResolveWindows([][]const u8{ "usr/local", "lib\\zig" }); const expected = try join(debug.global_allocator, cwd, "usr\\local\\lib\\zig"); if (parsed_cwd.kind == WindowsPath.Kind.Drive) { expected[0] = asciiUpper(parsed_cwd.disk_designator[0]); @@ -619,33 +611,32 @@ test "os.path.resolveWindows" { } } - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:\\a\\b\\c", "/hi", "ok"}), "C:\\hi\\ok")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/blah\\blah", "d:/games", "c:../a"}), "C:\\blah\\a")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/blah\\blah", "d:/games", "C:../a"}), "C:\\blah\\a")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/ignore", "d:\\a/b\\c/d", "\\e.exe"}), "D:\\e.exe")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/ignore", "c:/some/file"}), "C:\\some\\file")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"d:/ignore", "d:some/dir//"}), "D:\\ignore\\some\\dir")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"//server/share", "..", "relative\\"}), "\\\\server\\share\\relative")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//"}), "C:\\")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//dir"}), "C:\\dir")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//server/share"}), "\\\\server\\share\\")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//server//share"}), "\\\\server\\share\\")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "///some//dir"}), "C:\\some\\dir")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js"}), - "C:\\foo\\tmp.3\\cycles\\root.js")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:\\a\\b\\c", "/hi", "ok" }), "C:\\hi\\ok")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/blah\\blah", "d:/games", "c:../a" }), "C:\\blah\\a")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/blah\\blah", "d:/games", "C:../a" }), "C:\\blah\\a")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/ignore", "d:\\a/b\\c/d", "\\e.exe" }), "D:\\e.exe")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/ignore", "c:/some/file" }), "C:\\some\\file")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "d:/ignore", "d:some/dir//" }), "D:\\ignore\\some\\dir")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "//server/share", "..", "relative\\" }), "\\\\server\\share\\relative")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//" }), "C:\\")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//dir" }), "C:\\dir")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//server/share" }), "\\\\server\\share\\")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//server//share" }), "\\\\server\\share\\")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "///some//dir" }), "C:\\some\\dir")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js" }), "C:\\foo\\tmp.3\\cycles\\root.js")); } test "os.path.resolvePosix" { - assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b", "c"}), "/a/b/c")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b", "c", "//d", "e///"}), "/d/e")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b/c", "..", "../"}), "/a")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/", "..", ".."}), "/")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b", "c" }), "/a/b/c")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b", "c", "//d", "e///" }), "/d/e")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b/c", "..", "../" }), "/a")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/", "..", ".." }), "/")); assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b/c/"}), "/a/b/c")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/var/lib", "../", "file/"}), "/var/file")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/var/lib", "/../", "file/"}), "/file")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/some/dir", ".", "/absolute/"}), "/absolute")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/foo/tmp.3/", "../tmp.3/cycles/root.js"}), "/foo/tmp.3/cycles/root.js")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/var/lib", "../", "file/" }), "/var/file")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/var/lib", "/../", "file/" }), "/file")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/some/dir", ".", "/absolute/" }), "/absolute")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/foo/tmp.3/", "../tmp.3/cycles/root.js" }), "/foo/tmp.3/cycles/root.js")); } fn testResolveWindows(paths: []const []const u8) []u8 { @@ -1079,9 +1070,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 { mem.copy(u8, pathname_buf, pathname); pathname_buf[pathname.len] = 0; - const h_file = windows.CreateFileA(pathname_buf.ptr, - windows.GENERIC_READ, windows.FILE_SHARE_READ, null, windows.OPEN_EXISTING, - windows.FILE_ATTRIBUTE_NORMAL, null); + const h_file = windows.CreateFileA(pathname_buf.ptr, windows.GENERIC_READ, windows.FILE_SHARE_READ, null, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, null); if (h_file == windows.INVALID_HANDLE_VALUE) { const err = windows.GetLastError(); return switch (err) { @@ -1161,7 +1150,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 { return allocator.shrink(u8, result_buf, cstr.len(result_buf.ptr)); }, Os.linux => { - const fd = try os.posixOpen(allocator, pathname, posix.O_PATH|posix.O_NONBLOCK|posix.O_CLOEXEC, 0); + const fd = try os.posixOpen(allocator, pathname, posix.O_PATH | posix.O_NONBLOCK | posix.O_CLOEXEC, 0); defer os.close(fd); var buf: ["/proc/self/fd/-2147483648".len]u8 = undefined; diff --git a/std/os/time.zig b/std/os/time.zig index 3af150ab6a..9a7c682483 100644 --- a/std/os/time.zig +++ b/std/os/time.zig @@ -27,7 +27,7 @@ pub fn sleep(seconds: usize, nanoseconds: usize) void { const u63 = @IntType(false, 63); pub fn posixSleep(seconds: u63, nanoseconds: u63) void { - var req = posix.timespec { + var req = posix.timespec{ .tv_sec = seconds, .tv_nsec = nanoseconds, }; @@ -71,7 +71,7 @@ fn milliTimestampWindows() u64 { var ft: i64 = undefined; windows.GetSystemTimeAsFileTime(&ft); const hns_per_ms = (ns_per_s / 100) / ms_per_s; - const epoch_adj = epoch.windows * ms_per_s; + const epoch_adj = epoch.windows * ms_per_s; return u64(@divFloor(ft, hns_per_ms) + epoch_adj); } @@ -83,7 +83,7 @@ fn milliTimestampDarwin() u64 { debug.assert(err == 0); const sec_ms = u64(tv.tv_sec) * ms_per_s; const usec_ms = @divFloor(u64(tv.tv_usec), us_per_s / ms_per_s); - return u64(sec_ms) + u64(usec_ms); + return u64(sec_ms) + u64(usec_ms); } fn milliTimestampPosix() u64 { @@ -110,17 +110,16 @@ pub const s_per_hour = s_per_min * 60; pub const s_per_day = s_per_hour * 24; pub const s_per_week = s_per_day * 7; - /// A monotonic high-performance timer. /// Timer.start() must be called to initialize the struct, which captures /// the counter frequency on windows and darwin, records the resolution, /// and gives the user an oportunity to check for the existnece of /// monotonic clocks without forcing them to check for error on each read. -/// .resolution is in nanoseconds on all platforms but .start_time's meaning -/// depends on the OS. On Windows and Darwin it is a hardware counter +/// .resolution is in nanoseconds on all platforms but .start_time's meaning +/// depends on the OS. On Windows and Darwin it is a hardware counter /// value that requires calculation to convert to a meaninful unit. pub const Timer = struct { - + //if we used resolution's value when performing the // performance counter calc on windows/darwin, it would // be less precise @@ -131,10 +130,9 @@ pub const Timer = struct { }, resolution: u64, start_time: u64, - - + //At some point we may change our minds on RAW, but for now we're - // sticking with posix standard MONOTONIC. For more information, see: + // sticking with posix standard MONOTONIC. For more information, see: // https://github.com/ziglang/zig/pull/933 // //const monotonic_clock_id = switch(builtin.os) { @@ -142,20 +140,21 @@ pub const Timer = struct { // else => posix.CLOCK_MONOTONIC, //}; const monotonic_clock_id = posix.CLOCK_MONOTONIC; - - /// Initialize the timer structure. //This gives us an oportunity to grab the counter frequency in windows. //On Windows: QueryPerformanceCounter will succeed on anything >= XP/2000. - //On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not - // supported, or if the timespec pointer is out of bounds, which should be + //On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not + // supported, or if the timespec pointer is out of bounds, which should be // impossible here barring cosmic rays or other such occurances of // incredibly bad luck. //On Darwin: This cannot fail, as far as I am able to tell. - const TimerError = error{TimerUnsupported, Unexpected}; + const TimerError = error{ + TimerUnsupported, + Unexpected, + }; pub fn start() TimerError!Timer { var self: Timer = undefined; - + switch (builtin.os) { Os.windows => { var freq: i64 = undefined; @@ -163,7 +162,7 @@ pub const Timer = struct { if (err == windows.FALSE) return error.TimerUnsupported; self.frequency = u64(freq); self.resolution = @divFloor(ns_per_s, self.frequency); - + var start_time: i64 = undefined; err = windows.QueryPerformanceCounter(&start_time); debug.assert(err != windows.FALSE); @@ -171,9 +170,9 @@ pub const Timer = struct { }, Os.linux => { //On Linux, seccomp can do arbitrary things to our ability to call - // syscalls, including return any errno value it wants and + // syscalls, including return any errno value it wants and // inconsistently throwing errors. Since we can't account for - // abuses of seccomp in a reasonable way, we'll assume that if + // abuses of seccomp in a reasonable way, we'll assume that if // seccomp is going to block us it will at least do so consistently var ts: posix.timespec = undefined; var result = posix.clock_getres(monotonic_clock_id, &ts); @@ -184,7 +183,7 @@ pub const Timer = struct { else => return std.os.unexpectedErrorPosix(errno), } self.resolution = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec); - + result = posix.clock_gettime(monotonic_clock_id, &ts); errno = posix.getErrno(result); if (errno != 0) return std.os.unexpectedErrorPosix(errno); @@ -199,7 +198,7 @@ pub const Timer = struct { } return self; } - + /// Reads the timer value since start or the last reset in nanoseconds pub fn read(self: &Timer) u64 { var clock = clockNative() - self.start_time; @@ -210,13 +209,12 @@ pub const Timer = struct { else => @compileError("Unsupported OS"), }; } - + /// Resets the timer value to 0/now. - pub fn reset(self: &Timer) void - { + pub fn reset(self: &Timer) void { self.start_time = clockNative(); } - + /// Returns the current value of the timer in nanoseconds, then resets it pub fn lap(self: &Timer) u64 { var now = clockNative(); @@ -224,26 +222,25 @@ pub const Timer = struct { self.start_time = now; return lap_time; } - - + const clockNative = switch (builtin.os) { Os.windows => clockWindows, Os.linux => clockLinux, Os.macosx, Os.ios => clockDarwin, else => @compileError("Unsupported OS"), }; - + fn clockWindows() u64 { var result: i64 = undefined; var err = windows.QueryPerformanceCounter(&result); debug.assert(err != windows.FALSE); return u64(result); } - + fn clockDarwin() u64 { return darwin.mach_absolute_time(); } - + fn clockLinux() u64 { var ts: posix.timespec = undefined; var result = posix.clock_gettime(monotonic_clock_id, &ts); @@ -252,10 +249,6 @@ pub const Timer = struct { } }; - - - - test "os.time.sleep" { sleep(0, 1); } @@ -263,7 +256,7 @@ test "os.time.sleep" { test "os.time.timestamp" { const ns_per_ms = (ns_per_s / ms_per_s); const margin = 50; - + const time_0 = milliTimestamp(); sleep(0, ns_per_ms); const time_1 = milliTimestamp(); @@ -274,15 +267,15 @@ test "os.time.timestamp" { test "os.time.Timer" { const ns_per_ms = (ns_per_s / ms_per_s); const margin = ns_per_ms * 50; - + var timer = try Timer.start(); sleep(0, 10 * ns_per_ms); const time_0 = timer.read(); debug.assert(time_0 > 0 and time_0 < margin); - + const time_1 = timer.lap(); debug.assert(time_1 >= time_0); - + timer.reset(); debug.assert(timer.read() < time_1); } diff --git a/std/os/windows/error.zig b/std/os/windows/error.zig index 6a4087ab97..f90945d00e 100644 --- a/std/os/windows/error.zig +++ b/std/os/windows/error.zig @@ -1,2379 +1,3567 @@ /// The operation completed successfully. pub const SUCCESS = 0; + /// Incorrect function. pub const INVALID_FUNCTION = 1; + /// The system cannot find the file specified. pub const FILE_NOT_FOUND = 2; + /// The system cannot find the path specified. pub const PATH_NOT_FOUND = 3; + /// The system cannot open the file. pub const TOO_MANY_OPEN_FILES = 4; + /// Access is denied. pub const ACCESS_DENIED = 5; + /// The handle is invalid. pub const INVALID_HANDLE = 6; + /// The storage control blocks were destroyed. pub const ARENA_TRASHED = 7; + /// Not enough storage is available to process this command. pub const NOT_ENOUGH_MEMORY = 8; + /// The storage control block address is invalid. pub const INVALID_BLOCK = 9; + /// The environment is incorrect. pub const BAD_ENVIRONMENT = 10; + /// An attempt was made to load a program with an incorrect format. pub const BAD_FORMAT = 11; + /// The access code is invalid. pub const INVALID_ACCESS = 12; + /// The data is invalid. pub const INVALID_DATA = 13; + /// Not enough storage is available to complete this operation. pub const OUTOFMEMORY = 14; + /// The system cannot find the drive specified. pub const INVALID_DRIVE = 15; + /// The directory cannot be removed. pub const CURRENT_DIRECTORY = 16; + /// The system cannot move the file to a different disk drive. pub const NOT_SAME_DEVICE = 17; + /// There are no more files. pub const NO_MORE_FILES = 18; + /// The media is write protected. pub const WRITE_PROTECT = 19; + /// The system cannot find the device specified. pub const BAD_UNIT = 20; + /// The device is not ready. pub const NOT_READY = 21; + /// The device does not recognize the command. pub const BAD_COMMAND = 22; + /// Data error (cyclic redundancy check). pub const CRC = 23; + /// The program issued a command but the command length is incorrect. pub const BAD_LENGTH = 24; + /// The drive cannot locate a specific area or track on the disk. pub const SEEK = 25; + /// The specified disk or diskette cannot be accessed. pub const NOT_DOS_DISK = 26; + /// The drive cannot find the sector requested. pub const SECTOR_NOT_FOUND = 27; + /// The printer is out of paper. pub const OUT_OF_PAPER = 28; + /// The system cannot write to the specified device. pub const WRITE_FAULT = 29; + /// The system cannot read from the specified device. pub const READ_FAULT = 30; + /// A device attached to the system is not functioning. pub const GEN_FAILURE = 31; + /// The process cannot access the file because it is being used by another process. pub const SHARING_VIOLATION = 32; + /// The process cannot access the file because another process has locked a portion of the file. pub const LOCK_VIOLATION = 33; + /// The wrong diskette is in the drive. Insert %2 (Volume Serial Number: %3) into drive %1. pub const WRONG_DISK = 34; + /// Too many files opened for sharing. pub const SHARING_BUFFER_EXCEEDED = 36; + /// Reached the end of the file. pub const HANDLE_EOF = 38; + /// The disk is full. pub const HANDLE_DISK_FULL = 39; + /// The request is not supported. pub const NOT_SUPPORTED = 50; + /// Windows cannot find the network path. Verify that the network path is correct and the destination computer is not busy or turned off. If Windows still cannot find the network path, contact your network administrator. pub const REM_NOT_LIST = 51; + /// You were not connected because a duplicate name exists on the network. If joining a domain, go to System in Control Panel to change the computer name and try again. If joining a workgroup, choose another workgroup name. pub const DUP_NAME = 52; + /// The network path was not found. pub const BAD_NETPATH = 53; + /// The network is busy. pub const NETWORK_BUSY = 54; + /// The specified network resource or device is no longer available. pub const DEV_NOT_EXIST = 55; + /// The network BIOS command limit has been reached. pub const TOO_MANY_CMDS = 56; + /// A network adapter hardware error occurred. pub const ADAP_HDW_ERR = 57; + /// The specified server cannot perform the requested operation. pub const BAD_NET_RESP = 58; + /// An unexpected network error occurred. pub const UNEXP_NET_ERR = 59; + /// The remote adapter is not compatible. pub const BAD_REM_ADAP = 60; + /// The printer queue is full. pub const PRINTQ_FULL = 61; + /// Space to store the file waiting to be printed is not available on the server. pub const NO_SPOOL_SPACE = 62; + /// Your file waiting to be printed was deleted. pub const PRINT_CANCELLED = 63; + /// The specified network name is no longer available. pub const NETNAME_DELETED = 64; + /// Network access is denied. pub const NETWORK_ACCESS_DENIED = 65; + /// The network resource type is not correct. pub const BAD_DEV_TYPE = 66; + /// The network name cannot be found. pub const BAD_NET_NAME = 67; + /// The name limit for the local computer network adapter card was exceeded. pub const TOO_MANY_NAMES = 68; + /// The network BIOS session limit was exceeded. pub const TOO_MANY_SESS = 69; + /// The remote server has been paused or is in the process of being started. pub const SHARING_PAUSED = 70; + /// No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept. pub const REQ_NOT_ACCEP = 71; + /// The specified printer or disk device has been paused. pub const REDIR_PAUSED = 72; + /// The file exists. pub const FILE_EXISTS = 80; + /// The directory or file cannot be created. pub const CANNOT_MAKE = 82; + /// Fail on INT 24. pub const FAIL_I24 = 83; + /// Storage to process this request is not available. pub const OUT_OF_STRUCTURES = 84; + /// The local device name is already in use. pub const ALREADY_ASSIGNED = 85; + /// The specified network password is not correct. pub const INVALID_PASSWORD = 86; + /// The parameter is incorrect. pub const INVALID_PARAMETER = 87; + /// A write fault occurred on the network. pub const NET_WRITE_FAULT = 88; + /// The system cannot start another process at this time. pub const NO_PROC_SLOTS = 89; + /// Cannot create another system semaphore. pub const TOO_MANY_SEMAPHORES = 100; + /// The exclusive semaphore is owned by another process. pub const EXCL_SEM_ALREADY_OWNED = 101; + /// The semaphore is set and cannot be closed. pub const SEM_IS_SET = 102; + /// The semaphore cannot be set again. pub const TOO_MANY_SEM_REQUESTS = 103; + /// Cannot request exclusive semaphores at interrupt time. pub const INVALID_AT_INTERRUPT_TIME = 104; + /// The previous ownership of this semaphore has ended. pub const SEM_OWNER_DIED = 105; + /// Insert the diskette for drive %1. pub const SEM_USER_LIMIT = 106; + /// The program stopped because an alternate diskette was not inserted. pub const DISK_CHANGE = 107; + /// The disk is in use or locked by another process. pub const DRIVE_LOCKED = 108; + /// The pipe has been ended. pub const BROKEN_PIPE = 109; + /// The system cannot open the device or file specified. pub const OPEN_FAILED = 110; + /// The file name is too long. pub const BUFFER_OVERFLOW = 111; + /// There is not enough space on the disk. pub const DISK_FULL = 112; + /// No more internal file identifiers available. pub const NO_MORE_SEARCH_HANDLES = 113; + /// The target internal file identifier is incorrect. pub const INVALID_TARGET_HANDLE = 114; + /// The IOCTL call made by the application program is not correct. pub const INVALID_CATEGORY = 117; + /// The verify-on-write switch parameter value is not correct. pub const INVALID_VERIFY_SWITCH = 118; + /// The system does not support the command requested. pub const BAD_DRIVER_LEVEL = 119; + /// This function is not supported on this system. pub const CALL_NOT_IMPLEMENTED = 120; + /// The semaphore timeout period has expired. pub const SEM_TIMEOUT = 121; + /// The data area passed to a system call is too small. pub const INSUFFICIENT_BUFFER = 122; + /// The filename, directory name, or volume label syntax is incorrect. pub const INVALID_NAME = 123; + /// The system call level is not correct. pub const INVALID_LEVEL = 124; + /// The disk has no volume label. pub const NO_VOLUME_LABEL = 125; + /// The specified module could not be found. pub const MOD_NOT_FOUND = 126; + /// The specified procedure could not be found. pub const PROC_NOT_FOUND = 127; + /// There are no child processes to wait for. pub const WAIT_NO_CHILDREN = 128; + /// The %1 application cannot be run in Win32 mode. pub const CHILD_NOT_COMPLETE = 129; + /// Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O. pub const DIRECT_ACCESS_HANDLE = 130; + /// An attempt was made to move the file pointer before the beginning of the file. pub const NEGATIVE_SEEK = 131; + /// The file pointer cannot be set on the specified device or file. pub const SEEK_ON_DEVICE = 132; + /// A JOIN or SUBST command cannot be used for a drive that contains previously joined drives. pub const IS_JOIN_TARGET = 133; + /// An attempt was made to use a JOIN or SUBST command on a drive that has already been joined. pub const IS_JOINED = 134; + /// An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted. pub const IS_SUBSTED = 135; + /// The system tried to delete the JOIN of a drive that is not joined. pub const NOT_JOINED = 136; + /// The system tried to delete the substitution of a drive that is not substituted. pub const NOT_SUBSTED = 137; + /// The system tried to join a drive to a directory on a joined drive. pub const JOIN_TO_JOIN = 138; + /// The system tried to substitute a drive to a directory on a substituted drive. pub const SUBST_TO_SUBST = 139; + /// The system tried to join a drive to a directory on a substituted drive. pub const JOIN_TO_SUBST = 140; + /// The system tried to SUBST a drive to a directory on a joined drive. pub const SUBST_TO_JOIN = 141; + /// The system cannot perform a JOIN or SUBST at this time. pub const BUSY_DRIVE = 142; + /// The system cannot join or substitute a drive to or for a directory on the same drive. pub const SAME_DRIVE = 143; + /// The directory is not a subdirectory of the root directory. pub const DIR_NOT_ROOT = 144; + /// The directory is not empty. pub const DIR_NOT_EMPTY = 145; + /// The path specified is being used in a substitute. pub const IS_SUBST_PATH = 146; + /// Not enough resources are available to process this command. pub const IS_JOIN_PATH = 147; + /// The path specified cannot be used at this time. pub const PATH_BUSY = 148; + /// An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute. pub const IS_SUBST_TARGET = 149; + /// System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed. pub const SYSTEM_TRACE = 150; + /// The number of specified semaphore events for DosMuxSemWait is not correct. pub const INVALID_EVENT_COUNT = 151; + /// DosMuxSemWait did not execute; too many semaphores are already set. pub const TOO_MANY_MUXWAITERS = 152; + /// The DosMuxSemWait list is not correct. pub const INVALID_LIST_FORMAT = 153; + /// The volume label you entered exceeds the label character limit of the target file system. pub const LABEL_TOO_LONG = 154; + /// Cannot create another thread. pub const TOO_MANY_TCBS = 155; + /// The recipient process has refused the signal. pub const SIGNAL_REFUSED = 156; + /// The segment is already discarded and cannot be locked. pub const DISCARDED = 157; + /// The segment is already unlocked. pub const NOT_LOCKED = 158; + /// The address for the thread ID is not correct. pub const BAD_THREADID_ADDR = 159; + /// One or more arguments are not correct. pub const BAD_ARGUMENTS = 160; + /// The specified path is invalid. pub const BAD_PATHNAME = 161; + /// A signal is already pending. pub const SIGNAL_PENDING = 162; + /// No more threads can be created in the system. pub const MAX_THRDS_REACHED = 164; + /// Unable to lock a region of a file. pub const LOCK_FAILED = 167; + /// The requested resource is in use. pub const BUSY = 170; + /// Device's command support detection is in progress. pub const DEVICE_SUPPORT_IN_PROGRESS = 171; + /// A lock request was not outstanding for the supplied cancel region. pub const CANCEL_VIOLATION = 173; + /// The file system does not support atomic changes to the lock type. pub const ATOMIC_LOCKS_NOT_SUPPORTED = 174; + /// The system detected a segment number that was not correct. pub const INVALID_SEGMENT_NUMBER = 180; + /// The operating system cannot run %1. pub const INVALID_ORDINAL = 182; + /// Cannot create a file when that file already exists. pub const ALREADY_EXISTS = 183; + /// The flag passed is not correct. pub const INVALID_FLAG_NUMBER = 186; + /// The specified system semaphore name was not found. pub const SEM_NOT_FOUND = 187; + /// The operating system cannot run %1. pub const INVALID_STARTING_CODESEG = 188; + /// The operating system cannot run %1. pub const INVALID_STACKSEG = 189; + /// The operating system cannot run %1. pub const INVALID_MODULETYPE = 190; + /// Cannot run %1 in Win32 mode. pub const INVALID_EXE_SIGNATURE = 191; + /// The operating system cannot run %1. pub const EXE_MARKED_INVALID = 192; + /// %1 is not a valid Win32 application. pub const BAD_EXE_FORMAT = 193; + /// The operating system cannot run %1. pub const ITERATED_DATA_EXCEEDS_64k = 194; + /// The operating system cannot run %1. pub const INVALID_MINALLOCSIZE = 195; + /// The operating system cannot run this application program. pub const DYNLINK_FROM_INVALID_RING = 196; + /// The operating system is not presently configured to run this application. pub const IOPL_NOT_ENABLED = 197; + /// The operating system cannot run %1. pub const INVALID_SEGDPL = 198; + /// The operating system cannot run this application program. pub const AUTODATASEG_EXCEEDS_64k = 199; + /// The code segment cannot be greater than or equal to 64K. pub const RING2SEG_MUST_BE_MOVABLE = 200; + /// The operating system cannot run %1. pub const RELOC_CHAIN_XEEDS_SEGLIM = 201; + /// The operating system cannot run %1. pub const INFLOOP_IN_RELOC_CHAIN = 202; + /// The system could not find the environment option that was entered. pub const ENVVAR_NOT_FOUND = 203; + /// No process in the command subtree has a signal handler. pub const NO_SIGNAL_SENT = 205; + /// The filename or extension is too long. pub const FILENAME_EXCED_RANGE = 206; + /// The ring 2 stack is in use. pub const RING2_STACK_IN_USE = 207; + /// The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified. pub const META_EXPANSION_TOO_LONG = 208; + /// The signal being posted is not correct. pub const INVALID_SIGNAL_NUMBER = 209; + /// The signal handler cannot be set. pub const THREAD_1_INACTIVE = 210; + /// The segment is locked and cannot be reallocated. pub const LOCKED = 212; + /// Too many dynamic-link modules are attached to this program or dynamic-link module. pub const TOO_MANY_MODULES = 214; + /// Cannot nest calls to LoadModule. pub const NESTING_NOT_ALLOWED = 215; + /// This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher. pub const EXE_MACHINE_TYPE_MISMATCH = 216; + /// The image file %1 is signed, unable to modify. pub const EXE_CANNOT_MODIFY_SIGNED_BINARY = 217; + /// The image file %1 is strong signed, unable to modify. pub const EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218; + /// This file is checked out or locked for editing by another user. pub const FILE_CHECKED_OUT = 220; + /// The file must be checked out before saving changes. pub const CHECKOUT_REQUIRED = 221; + /// The file type being saved or retrieved has been blocked. pub const BAD_FILE_TYPE = 222; + /// The file size exceeds the limit allowed and cannot be saved. pub const FILE_TOO_LARGE = 223; + /// Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically. pub const FORMS_AUTH_REQUIRED = 224; + /// Operation did not complete successfully because the file contains a virus or potentially unwanted software. pub const VIRUS_INFECTED = 225; + /// This file contains a virus or potentially unwanted software and cannot be opened. Due to the nature of this virus or potentially unwanted software, the file has been removed from this location. pub const VIRUS_DELETED = 226; + /// The pipe is local. pub const PIPE_LOCAL = 229; + /// The pipe state is invalid. pub const BAD_PIPE = 230; + /// All pipe instances are busy. pub const PIPE_BUSY = 231; + /// The pipe is being closed. pub const NO_DATA = 232; + /// No process is on the other end of the pipe. pub const PIPE_NOT_CONNECTED = 233; + /// More data is available. pub const MORE_DATA = 234; + /// The session was canceled. pub const VC_DISCONNECTED = 240; + /// The specified extended attribute name was invalid. pub const INVALID_EA_NAME = 254; + /// The extended attributes are inconsistent. pub const EA_LIST_INCONSISTENT = 255; + /// The wait operation timed out. pub const IMEOUT = 258; + /// No more data is available. pub const NO_MORE_ITEMS = 259; + /// The copy functions cannot be used. pub const CANNOT_COPY = 266; + /// The directory name is invalid. pub const DIRECTORY = 267; + /// The extended attributes did not fit in the buffer. pub const EAS_DIDNT_FIT = 275; + /// The extended attribute file on the mounted file system is corrupt. pub const EA_FILE_CORRUPT = 276; + /// The extended attribute table file is full. pub const EA_TABLE_FULL = 277; + /// The specified extended attribute handle is invalid. pub const INVALID_EA_HANDLE = 278; + /// The mounted file system does not support extended attributes. pub const EAS_NOT_SUPPORTED = 282; + /// Attempt to release mutex not owned by caller. pub const NOT_OWNER = 288; + /// Too many posts were made to a semaphore. pub const TOO_MANY_POSTS = 298; + /// Only part of a ReadProcessMemory or WriteProcessMemory request was completed. pub const PARTIAL_COPY = 299; + /// The oplock request is denied. pub const OPLOCK_NOT_GRANTED = 300; + /// An invalid oplock acknowledgment was received by the system. pub const INVALID_OPLOCK_PROTOCOL = 301; + /// The volume is too fragmented to complete this operation. pub const DISK_TOO_FRAGMENTED = 302; + /// The file cannot be opened because it is in the process of being deleted. pub const DELETE_PENDING = 303; + /// Short name settings may not be changed on this volume due to the global registry setting. pub const INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304; + /// Short names are not enabled on this volume. pub const SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305; + /// The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume. pub const SECURITY_STREAM_IS_INCONSISTENT = 306; + /// A requested file lock operation cannot be processed due to an invalid byte range. pub const INVALID_LOCK_RANGE = 307; + /// The subsystem needed to support the image type is not present. pub const IMAGE_SUBSYSTEM_NOT_PRESENT = 308; + /// The specified file already has a notification GUID associated with it. pub const NOTIFICATION_GUID_ALREADY_DEFINED = 309; + /// An invalid exception handler routine has been detected. pub const INVALID_EXCEPTION_HANDLER = 310; + /// Duplicate privileges were specified for the token. pub const DUPLICATE_PRIVILEGES = 311; + /// No ranges for the specified operation were able to be processed. pub const NO_RANGES_PROCESSED = 312; + /// Operation is not allowed on a file system internal file. pub const NOT_ALLOWED_ON_SYSTEM_FILE = 313; + /// The physical resources of this disk have been exhausted. pub const DISK_RESOURCES_EXHAUSTED = 314; + /// The token representing the data is invalid. pub const INVALID_TOKEN = 315; + /// The device does not support the command feature. pub const DEVICE_FEATURE_NOT_SUPPORTED = 316; + /// The system cannot find message text for message number 0x%1 in the message file for %2. pub const MR_MID_NOT_FOUND = 317; + /// The scope specified was not found. pub const SCOPE_NOT_FOUND = 318; + /// The Central Access Policy specified is not defined on the target machine. pub const UNDEFINED_SCOPE = 319; + /// The Central Access Policy obtained from Active Directory is invalid. pub const INVALID_CAP = 320; + /// The device is unreachable. pub const DEVICE_UNREACHABLE = 321; + /// The target device has insufficient resources to complete the operation. pub const DEVICE_NO_RESOURCES = 322; + /// A data integrity checksum error occurred. Data in the file stream is corrupt. pub const DATA_CHECKSUM_ERROR = 323; + /// An attempt was made to modify both a KERNEL and normal Extended Attribute (EA) in the same operation. pub const INTERMIXED_KERNEL_EA_OPERATION = 324; + /// Device does not support file-level TRIM. pub const FILE_LEVEL_TRIM_NOT_SUPPORTED = 326; + /// The command specified a data offset that does not align to the device's granularity/alignment. pub const OFFSET_ALIGNMENT_VIOLATION = 327; + /// The command specified an invalid field in its parameter list. pub const INVALID_FIELD_IN_PARAMETER_LIST = 328; + /// An operation is currently in progress with the device. pub const OPERATION_IN_PROGRESS = 329; + /// An attempt was made to send down the command via an invalid path to the target device. pub const BAD_DEVICE_PATH = 330; + /// The command specified a number of descriptors that exceeded the maximum supported by the device. pub const TOO_MANY_DESCRIPTORS = 331; + /// Scrub is disabled on the specified file. pub const SCRUB_DATA_DISABLED = 332; + /// The storage device does not provide redundancy. pub const NOT_REDUNDANT_STORAGE = 333; + /// An operation is not supported on a resident file. pub const RESIDENT_FILE_NOT_SUPPORTED = 334; + /// An operation is not supported on a compressed file. pub const COMPRESSED_FILE_NOT_SUPPORTED = 335; + /// An operation is not supported on a directory. pub const DIRECTORY_NOT_SUPPORTED = 336; + /// The specified copy of the requested data could not be read. pub const NOT_READ_FROM_COPY = 337; + /// No action was taken as a system reboot is required. pub const FAIL_NOACTION_REBOOT = 350; + /// The shutdown operation failed. pub const FAIL_SHUTDOWN = 351; + /// The restart operation failed. pub const FAIL_RESTART = 352; + /// The maximum number of sessions has been reached. pub const MAX_SESSIONS_REACHED = 353; + /// The thread is already in background processing mode. pub const THREAD_MODE_ALREADY_BACKGROUND = 400; + /// The thread is not in background processing mode. pub const THREAD_MODE_NOT_BACKGROUND = 401; + /// The process is already in background processing mode. pub const PROCESS_MODE_ALREADY_BACKGROUND = 402; + /// The process is not in background processing mode. pub const PROCESS_MODE_NOT_BACKGROUND = 403; + /// Attempt to access invalid address. pub const INVALID_ADDRESS = 487; + /// User profile cannot be loaded. pub const USER_PROFILE_LOAD = 500; + /// Arithmetic result exceeded 32 bits. pub const ARITHMETIC_OVERFLOW = 534; + /// There is a process on other end of the pipe. pub const PIPE_CONNECTED = 535; + /// Waiting for a process to open the other end of the pipe. pub const PIPE_LISTENING = 536; + /// Application verifier has found an error in the current process. pub const VERIFIER_STOP = 537; + /// An error occurred in the ABIOS subsystem. pub const ABIOS_ERROR = 538; + /// A warning occurred in the WX86 subsystem. pub const WX86_WARNING = 539; + /// An error occurred in the WX86 subsystem. pub const WX86_ERROR = 540; + /// An attempt was made to cancel or set a timer that has an associated APC and the subject thread is not the thread that originally set the timer with an associated APC routine. pub const TIMER_NOT_CANCELED = 541; + /// Unwind exception code. pub const UNWIND = 542; + /// An invalid or unaligned stack was encountered during an unwind operation. pub const BAD_STACK = 543; + /// An invalid unwind target was encountered during an unwind operation. pub const INVALID_UNWIND_TARGET = 544; + /// Invalid Object Attributes specified to NtCreatePort or invalid Port Attributes specified to NtConnectPort pub const INVALID_PORT_ATTRIBUTES = 545; + /// Length of message passed to NtRequestPort or NtRequestWaitReplyPort was longer than the maximum message allowed by the port. pub const PORT_MESSAGE_TOO_LONG = 546; + /// An attempt was made to lower a quota limit below the current usage. pub const INVALID_QUOTA_LOWER = 547; + /// An attempt was made to attach to a device that was already attached to another device. pub const DEVICE_ALREADY_ATTACHED = 548; + /// An attempt was made to execute an instruction at an unaligned address and the host system does not support unaligned instruction references. pub const INSTRUCTION_MISALIGNMENT = 549; + /// Profiling not started. pub const PROFILING_NOT_STARTED = 550; + /// Profiling not stopped. pub const PROFILING_NOT_STOPPED = 551; + /// The passed ACL did not contain the minimum required information. pub const COULD_NOT_INTERPRET = 552; + /// The number of active profiling objects is at the maximum and no more may be started. pub const PROFILING_AT_LIMIT = 553; + /// Used to indicate that an operation cannot continue without blocking for I/O. pub const CANT_WAIT = 554; + /// Indicates that a thread attempted to terminate itself by default (called NtTerminateThread with NULL) and it was the last thread in the current process. pub const CANT_TERMINATE_SELF = 555; + /// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception. pub const UNEXPECTED_MM_CREATE_ERR = 556; + /// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception. pub const UNEXPECTED_MM_MAP_ERROR = 557; + /// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception. pub const UNEXPECTED_MM_EXTEND_ERR = 558; + /// A malformed function table was encountered during an unwind operation. pub const BAD_FUNCTION_TABLE = 559; + /// Indicates that an attempt was made to assign protection to a file system file or directory and one of the SIDs in the security descriptor could not be translated into a GUID that could be stored by the file system. This causes the protection attempt to fail, which may cause a file creation attempt to fail. pub const NO_GUID_TRANSLATION = 560; + /// Indicates that an attempt was made to grow an LDT by setting its size, or that the size was not an even number of selectors. pub const INVALID_LDT_SIZE = 561; + /// Indicates that the starting value for the LDT information was not an integral multiple of the selector size. pub const INVALID_LDT_OFFSET = 563; + /// Indicates that the user supplied an invalid descriptor when trying to set up Ldt descriptors. pub const INVALID_LDT_DESCRIPTOR = 564; + /// Indicates a process has too many threads to perform the requested action. For example, assignment of a primary token may only be performed when a process has zero or one threads. pub const TOO_MANY_THREADS = 565; + /// An attempt was made to operate on a thread within a specific process, but the thread specified is not in the process specified. pub const THREAD_NOT_IN_PROCESS = 566; + /// Page file quota was exceeded. pub const PAGEFILE_QUOTA_EXCEEDED = 567; + /// The Netlogon service cannot start because another Netlogon service running in the domain conflicts with the specified role. pub const LOGON_SERVER_CONFLICT = 568; + /// The SAM database on a Windows Server is significantly out of synchronization with the copy on the Domain Controller. A complete synchronization is required. pub const SYNCHRONIZATION_REQUIRED = 569; + /// The NtCreateFile API failed. This error should never be returned to an application, it is a place holder for the Windows Lan Manager Redirector to use in its internal error mapping routines. pub const NET_OPEN_FAILED = 570; + /// {Privilege Failed} The I/O permissions for the process could not be changed. pub const IO_PRIVILEGE_FAILED = 571; + /// {Application Exit by CTRL+C} The application terminated as a result of a CTRL+C. pub const CONTROL_C_EXIT = 572; + /// {Missing System File} The required system file %hs is bad or missing. pub const MISSING_SYSTEMFILE = 573; + /// {Application Error} The exception %s (0x%08lx) occurred in the application at location 0x%08lx. pub const UNHANDLED_EXCEPTION = 574; + /// {Application Error} The application was unable to start correctly (0x%lx). Click OK to close the application. pub const APP_INIT_FAILURE = 575; + /// {Unable to Create Paging File} The creation of the paging file %hs failed (%lx). The requested size was %ld. pub const PAGEFILE_CREATE_FAILED = 576; + /// Windows cannot verify the digital signature for this file. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source. pub const INVALID_IMAGE_HASH = 577; + /// {No Paging File Specified} No paging file was specified in the system configuration. pub const NO_PAGEFILE = 578; + /// {EXCEPTION} A real-mode application issued a floating-point instruction and floating-point hardware is not present. pub const ILLEGAL_FLOAT_CONTEXT = 579; + /// An event pair synchronization operation was performed using the thread specific client/server event pair object, but no event pair object was associated with the thread. pub const NO_EVENT_PAIR = 580; + /// A Windows Server has an incorrect configuration. pub const DOMAIN_CTRLR_CONFIG_ERROR = 581; + /// An illegal character was encountered. For a multi-byte character set this includes a lead byte without a succeeding trail byte. For the Unicode character set this includes the characters 0xFFFF and 0xFFFE. pub const ILLEGAL_CHARACTER = 582; + /// The Unicode character is not defined in the Unicode character set installed on the system. pub const UNDEFINED_CHARACTER = 583; + /// The paging file cannot be created on a floppy diskette. pub const FLOPPY_VOLUME = 584; + /// The system BIOS failed to connect a system interrupt to the device or bus for which the device is connected. pub const BIOS_FAILED_TO_CONNECT_INTERRUPT = 585; + /// This operation is only allowed for the Primary Domain Controller of the domain. pub const BACKUP_CONTROLLER = 586; + /// An attempt was made to acquire a mutant such that its maximum count would have been exceeded. pub const MUTANT_LIMIT_EXCEEDED = 587; + /// A volume has been accessed for which a file system driver is required that has not yet been loaded. pub const FS_DRIVER_REQUIRED = 588; + /// {Registry File Failure} The registry cannot load the hive (file): %hs or its log or alternate. It is corrupt, absent, or not writable. pub const CANNOT_LOAD_REGISTRY_FILE = 589; + /// {Unexpected Failure in DebugActiveProcess} An unexpected failure occurred while processing a DebugActiveProcess API request. You may choose OK to terminate the process, or Cancel to ignore the error. pub const DEBUG_ATTACH_FAILED = 590; + /// {Fatal System Error} The %hs system process terminated unexpectedly with a status of 0x%08x (0x%08x 0x%08x). The system has been shut down. pub const SYSTEM_PROCESS_TERMINATED = 591; + /// {Data Not Accepted} The TDI client could not handle the data received during an indication. pub const DATA_NOT_ACCEPTED = 592; + /// NTVDM encountered a hard error. pub const VDM_HARD_ERROR = 593; + /// {Cancel Timeout} The driver %hs failed to complete a cancelled I/O request in the allotted time. pub const DRIVER_CANCEL_TIMEOUT = 594; + /// {Reply Message Mismatch} An attempt was made to reply to an LPC message, but the thread specified by the client ID in the message was not waiting on that message. pub const REPLY_MESSAGE_MISMATCH = 595; + /// {Delayed Write Failed} Windows was unable to save all the data for the file %hs. The data has been lost. This error may be caused by a failure of your computer hardware or network connection. Please try to save this file elsewhere. pub const LOST_WRITEBEHIND_DATA = 596; + /// The parameter(s) passed to the server in the client/server shared memory window were invalid. Too much data may have been put in the shared memory window. pub const CLIENT_SERVER_PARAMETERS_INVALID = 597; + /// The stream is not a tiny stream. pub const NOT_TINY_STREAM = 598; + /// The request must be handled by the stack overflow code. pub const STACK_OVERFLOW_READ = 599; + /// Internal OFS status codes indicating how an allocation operation is handled. Either it is retried after the containing onode is moved or the extent stream is converted to a large stream. pub const CONVERT_TO_LARGE = 600; + /// The attempt to find the object found an object matching by ID on the volume but it is out of the scope of the handle used for the operation. pub const FOUND_OUT_OF_SCOPE = 601; + /// The bucket array must be grown. Retry transaction after doing so. pub const ALLOCATE_BUCKET = 602; + /// The user/kernel marshalling buffer has overflowed. pub const MARSHALL_OVERFLOW = 603; + /// The supplied variant structure contains invalid data. pub const INVALID_VARIANT = 604; + /// The specified buffer contains ill-formed data. pub const BAD_COMPRESSION_BUFFER = 605; + /// {Audit Failed} An attempt to generate a security audit failed. pub const AUDIT_FAILED = 606; + /// The timer resolution was not previously set by the current process. pub const TIMER_RESOLUTION_NOT_SET = 607; + /// There is insufficient account information to log you on. pub const INSUFFICIENT_LOGON_INFO = 608; + /// {Invalid DLL Entrypoint} The dynamic link library %hs is not written correctly. The stack pointer has been left in an inconsistent state. The entrypoint should be declared as WINAPI or STDCALL. Select YES to fail the DLL load. Select NO to continue execution. Selecting NO may cause the application to operate incorrectly. pub const BAD_DLL_ENTRYPOINT = 609; + /// {Invalid Service Callback Entrypoint} The %hs service is not written correctly. The stack pointer has been left in an inconsistent state. The callback entrypoint should be declared as WINAPI or STDCALL. Selecting OK will cause the service to continue operation. However, the service process may operate incorrectly. pub const BAD_SERVICE_ENTRYPOINT = 610; + /// There is an IP address conflict with another system on the network. pub const IP_ADDRESS_CONFLICT1 = 611; + /// There is an IP address conflict with another system on the network. pub const IP_ADDRESS_CONFLICT2 = 612; + /// {Low On Registry Space} The system has reached the maximum size allowed for the system part of the registry. Additional storage requests will be ignored. pub const REGISTRY_QUOTA_LIMIT = 613; + /// A callback return system service cannot be executed when no callback is active. pub const NO_CALLBACK_ACTIVE = 614; + /// The password provided is too short to meet the policy of your user account. Please choose a longer password. pub const PWD_TOO_SHORT = 615; + /// The policy of your user account does not allow you to change passwords too frequently. This is done to prevent users from changing back to a familiar, but potentially discovered, password. If you feel your password has been compromised then please contact your administrator immediately to have a new one assigned. pub const PWD_TOO_RECENT = 616; + /// You have attempted to change your password to one that you have used in the past. The policy of your user account does not allow this. Please select a password that you have not previously used. pub const PWD_HISTORY_CONFLICT = 617; + /// The specified compression format is unsupported. pub const UNSUPPORTED_COMPRESSION = 618; + /// The specified hardware profile configuration is invalid. pub const INVALID_HW_PROFILE = 619; + /// The specified Plug and Play registry device path is invalid. pub const INVALID_PLUGPLAY_DEVICE_PATH = 620; + /// The specified quota list is internally inconsistent with its descriptor. pub const QUOTA_LIST_INCONSISTENT = 621; + /// {Windows Evaluation Notification} The evaluation period for this installation of Windows has expired. This system will shutdown in 1 hour. To restore access to this installation of Windows, please upgrade this installation using a licensed distribution of this product. pub const EVALUATION_EXPIRATION = 622; + /// {Illegal System DLL Relocation} The system DLL %hs was relocated in memory. The application will not run properly. The relocation occurred because the DLL %hs occupied an address range reserved for Windows system DLLs. The vendor supplying the DLL should be contacted for a new DLL. pub const ILLEGAL_DLL_RELOCATION = 623; + /// {DLL Initialization Failed} The application failed to initialize because the window station is shutting down. pub const DLL_INIT_FAILED_LOGOFF = 624; + /// The validation process needs to continue on to the next step. pub const VALIDATE_CONTINUE = 625; + /// There are no more matches for the current index enumeration. pub const NO_MORE_MATCHES = 626; + /// The range could not be added to the range list because of a conflict. pub const RANGE_LIST_CONFLICT = 627; + /// The server process is running under a SID different than that required by client. pub const SERVER_SID_MISMATCH = 628; + /// A group marked use for deny only cannot be enabled. pub const CANT_ENABLE_DENY_ONLY = 629; + /// {EXCEPTION} Multiple floating point faults. pub const FLOAT_MULTIPLE_FAULTS = 630; + /// {EXCEPTION} Multiple floating point traps. pub const FLOAT_MULTIPLE_TRAPS = 631; + /// The requested interface is not supported. pub const NOINTERFACE = 632; + /// {System Standby Failed} The driver %hs does not support standby mode. Updating this driver may allow the system to go to standby mode. pub const DRIVER_FAILED_SLEEP = 633; + /// The system file %1 has become corrupt and has been replaced. pub const CORRUPT_SYSTEM_FILE = 634; + /// {Virtual Memory Minimum Too Low} Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file. During this process, memory requests for some applications may be denied. For more information, see Help. pub const COMMITMENT_MINIMUM = 635; + /// A device was removed so enumeration must be restarted. pub const PNP_RESTART_ENUMERATION = 636; + /// {Fatal System Error} The system image %s is not properly signed. The file has been replaced with the signed file. The system has been shut down. pub const SYSTEM_IMAGE_BAD_SIGNATURE = 637; + /// Device will not start without a reboot. pub const PNP_REBOOT_REQUIRED = 638; + /// There is not enough power to complete the requested operation. pub const INSUFFICIENT_POWER = 639; + /// ERROR_MULTIPLE_FAULT_VIOLATION pub const MULTIPLE_FAULT_VIOLATION = 640; + /// The system is in the process of shutting down. pub const SYSTEM_SHUTDOWN = 641; + /// An attempt to remove a processes DebugPort was made, but a port was not already associated with the process. pub const PORT_NOT_SET = 642; + /// This version of Windows is not compatible with the behavior version of directory forest, domain or domain controller. pub const DS_VERSION_CHECK_FAILURE = 643; + /// The specified range could not be found in the range list. pub const RANGE_NOT_FOUND = 644; + /// The driver was not loaded because the system is booting into safe mode. pub const NOT_SAFE_MODE_DRIVER = 646; + /// The driver was not loaded because it failed its initialization call. pub const FAILED_DRIVER_ENTRY = 647; + /// The "%hs" encountered an error while applying power or reading the device configuration. This may be caused by a failure of your hardware or by a poor connection. pub const DEVICE_ENUMERATION_ERROR = 648; + /// The create operation failed because the name contained at least one mount point which resolves to a volume to which the specified device object is not attached. pub const MOUNT_POINT_NOT_RESOLVED = 649; + /// The device object parameter is either not a valid device object or is not attached to the volume specified by the file name. pub const INVALID_DEVICE_OBJECT_PARAMETER = 650; + /// A Machine Check Error has occurred. Please check the system eventlog for additional information. pub const MCA_OCCURED = 651; + /// There was error [%2] processing the driver database. pub const DRIVER_DATABASE_ERROR = 652; + /// System hive size has exceeded its limit. pub const SYSTEM_HIVE_TOO_LARGE = 653; + /// The driver could not be loaded because a previous version of the driver is still in memory. pub const DRIVER_FAILED_PRIOR_UNLOAD = 654; + /// {Volume Shadow Copy Service} Please wait while the Volume Shadow Copy Service prepares volume %hs for hibernation. pub const VOLSNAP_PREPARE_HIBERNATE = 655; + /// The system has failed to hibernate (The error code is %hs). Hibernation will be disabled until the system is restarted. pub const HIBERNATION_FAILURE = 656; + /// The password provided is too long to meet the policy of your user account. Please choose a shorter password. pub const PWD_TOO_LONG = 657; + /// The requested operation could not be completed due to a file system limitation. pub const FILE_SYSTEM_LIMITATION = 665; + /// An assertion failure has occurred. pub const ASSERTION_FAILURE = 668; + /// An error occurred in the ACPI subsystem. pub const ACPI_ERROR = 669; + /// WOW Assertion Error. pub const WOW_ASSERTION = 670; + /// A device is missing in the system BIOS MPS table. This device will not be used. Please contact your system vendor for system BIOS update. pub const PNP_BAD_MPS_TABLE = 671; + /// A translator failed to translate resources. pub const PNP_TRANSLATION_FAILED = 672; + /// A IRQ translator failed to translate resources. pub const PNP_IRQ_TRANSLATION_FAILED = 673; + /// Driver %2 returned invalid ID for a child device (%3). pub const PNP_INVALID_ID = 674; + /// {Kernel Debugger Awakened} the system debugger was awakened by an interrupt. pub const WAKE_SYSTEM_DEBUGGER = 675; + /// {Handles Closed} Handles to objects have been automatically closed as a result of the requested operation. pub const HANDLES_CLOSED = 676; + /// {Too Much Information} The specified access control list (ACL) contained more information than was expected. pub const EXTRANEOUS_INFORMATION = 677; + /// This warning level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has NOT been completed, but has not been rolled back either (so it may still be committed if desired). pub const RXACT_COMMIT_NECESSARY = 678; + /// {Media Changed} The media may have changed. pub const MEDIA_CHECK = 679; + /// {GUID Substitution} During the translation of a global identifier (GUID) to a Windows security ID (SID), no administratively-defined GUID prefix was found. A substitute prefix was used, which will not compromise system security. However, this may provide a more restrictive access than intended. pub const GUID_SUBSTITUTION_MADE = 680; + /// The create operation stopped after reaching a symbolic link. pub const STOPPED_ON_SYMLINK = 681; + /// A long jump has been executed. pub const LONGJUMP = 682; + /// The Plug and Play query operation was not successful. pub const PLUGPLAY_QUERY_VETOED = 683; + /// A frame consolidation has been executed. pub const UNWIND_CONSOLIDATE = 684; + /// {Registry Hive Recovered} Registry hive (file): %hs was corrupted and it has been recovered. Some data might have been lost. pub const REGISTRY_HIVE_RECOVERED = 685; + /// The application is attempting to run executable code from the module %hs. This may be insecure. An alternative, %hs, is available. Should the application use the secure module %hs? pub const DLL_MIGHT_BE_INSECURE = 686; + /// The application is loading executable code from the module %hs. This is secure, but may be incompatible with previous releases of the operating system. An alternative, %hs, is available. Should the application use the secure module %hs? pub const DLL_MIGHT_BE_INCOMPATIBLE = 687; + /// Debugger did not handle the exception. pub const DBG_EXCEPTION_NOT_HANDLED = 688; + /// Debugger will reply later. pub const DBG_REPLY_LATER = 689; + /// Debugger cannot provide handle. pub const DBG_UNABLE_TO_PROVIDE_HANDLE = 690; + /// Debugger terminated thread. pub const DBG_TERMINATE_THREAD = 691; + /// Debugger terminated process. pub const DBG_TERMINATE_PROCESS = 692; + /// Debugger got control C. pub const DBG_CONTROL_C = 693; + /// Debugger printed exception on control C. pub const DBG_PRINTEXCEPTION_C = 694; + /// Debugger received RIP exception. pub const DBG_RIPEXCEPTION = 695; + /// Debugger received control break. pub const DBG_CONTROL_BREAK = 696; + /// Debugger command communication exception. pub const DBG_COMMAND_EXCEPTION = 697; + /// {Object Exists} An attempt was made to create an object and the object name already existed. pub const OBJECT_NAME_EXISTS = 698; + /// {Thread Suspended} A thread termination occurred while the thread was suspended. The thread was resumed, and termination proceeded. pub const THREAD_WAS_SUSPENDED = 699; + /// {Image Relocated} An image file could not be mapped at the address specified in the image file. Local fixups must be performed on this image. pub const IMAGE_NOT_AT_BASE = 700; + /// This informational level status indicates that a specified registry sub-tree transaction state did not yet exist and had to be created. pub const RXACT_STATE_CREATED = 701; + /// {Segment Load} A virtual DOS machine (VDM) is loading, unloading, or moving an MS-DOS or Win16 program segment image. An exception is raised so a debugger can load, unload or track symbols and breakpoints within these 16-bit segments. pub const SEGMENT_NOTIFICATION = 702; + /// {Invalid Current Directory} The process cannot switch to the startup current directory %hs. Select OK to set current directory to %hs, or select CANCEL to exit. pub const BAD_CURRENT_DIRECTORY = 703; + /// {Redundant Read} To satisfy a read request, the NT fault-tolerant file system successfully read the requested data from a redundant copy. This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was unable to reassign the failing area of the device. pub const FT_READ_RECOVERY_FROM_BACKUP = 704; + /// {Redundant Write} To satisfy a write request, the NT fault-tolerant file system successfully wrote a redundant copy of the information. This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was not able to reassign the failing area of the device. pub const FT_WRITE_RECOVERY = 705; + /// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine. Select OK to continue, or CANCEL to fail the DLL load. pub const IMAGE_MACHINE_TYPE_MISMATCH = 706; + /// {Partial Data Received} The network transport returned partial data to its client. The remaining data will be sent later. pub const RECEIVE_PARTIAL = 707; + /// {Expedited Data Received} The network transport returned data to its client that was marked as expedited by the remote system. pub const RECEIVE_EXPEDITED = 708; + /// {Partial Expedited Data Received} The network transport returned partial data to its client and this data was marked as expedited by the remote system. The remaining data will be sent later. pub const RECEIVE_PARTIAL_EXPEDITED = 709; + /// {TDI Event Done} The TDI indication has completed successfully. pub const EVENT_DONE = 710; + /// {TDI Event Pending} The TDI indication has entered the pending state. pub const EVENT_PENDING = 711; + /// Checking file system on %wZ. pub const CHECKING_FILE_SYSTEM = 712; + /// {Fatal Application Exit} %hs. pub const FATAL_APP_EXIT = 713; + /// The specified registry key is referenced by a predefined handle. pub const PREDEFINED_HANDLE = 714; + /// {Page Unlocked} The page protection of a locked page was changed to 'No Access' and the page was unlocked from memory and from the process. pub const WAS_UNLOCKED = 715; + /// %hs pub const SERVICE_NOTIFICATION = 716; + /// {Page Locked} One of the pages to lock was already locked. pub const WAS_LOCKED = 717; + /// Application popup: %1 : %2 pub const LOG_HARD_ERROR = 718; + /// ERROR_ALREADY_WIN32 pub const ALREADY_WIN32 = 719; + /// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine. pub const IMAGE_MACHINE_TYPE_MISMATCH_EXE = 720; + /// A yield execution was performed and no thread was available to run. pub const NO_YIELD_PERFORMED = 721; + /// The resumable flag to a timer API was ignored. pub const TIMER_RESUME_IGNORED = 722; + /// The arbiter has deferred arbitration of these resources to its parent. pub const ARBITRATION_UNHANDLED = 723; + /// The inserted CardBus device cannot be started because of a configuration error on "%hs". pub const CARDBUS_NOT_SUPPORTED = 724; + /// The CPUs in this multiprocessor system are not all the same revision level. To use all processors the operating system restricts itself to the features of the least capable processor in the system. Should problems occur with this system, contact the CPU manufacturer to see if this mix of processors is supported. pub const MP_PROCESSOR_MISMATCH = 725; + /// The system was put into hibernation. pub const HIBERNATED = 726; + /// The system was resumed from hibernation. pub const RESUME_HIBERNATION = 727; + /// Windows has detected that the system firmware (BIOS) was updated [previous firmware date = %2, current firmware date %3]. pub const FIRMWARE_UPDATED = 728; + /// A device driver is leaking locked I/O pages causing system degradation. The system has automatically enabled tracking code in order to try and catch the culprit. pub const DRIVERS_LEAKING_LOCKED_PAGES = 729; + /// The system has awoken. pub const WAKE_SYSTEM = 730; + /// ERROR_WAIT_1 pub const WAIT_1 = 731; + /// ERROR_WAIT_2 pub const WAIT_2 = 732; + /// ERROR_WAIT_3 pub const WAIT_3 = 733; + /// ERROR_WAIT_63 pub const WAIT_63 = 734; + /// ERROR_ABANDONED_WAIT_0 pub const ABANDONED_WAIT_0 = 735; + /// ERROR_ABANDONED_WAIT_63 pub const ABANDONED_WAIT_63 = 736; + /// ERROR_USER_APC pub const USER_APC = 737; + /// ERROR_KERNEL_APC pub const KERNEL_APC = 738; + /// ERROR_ALERTED pub const ALERTED = 739; + /// The requested operation requires elevation. pub const ELEVATION_REQUIRED = 740; + /// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link. pub const REPARSE = 741; + /// An open/create operation completed while an oplock break is underway. pub const OPLOCK_BREAK_IN_PROGRESS = 742; + /// A new volume has been mounted by a file system. pub const VOLUME_MOUNTED = 743; + /// This success level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has now been completed. pub const RXACT_COMMITTED = 744; + /// This indicates that a notify change request has been completed due to closing the handle which made the notify change request. pub const NOTIFY_CLEANUP = 745; + /// {Connect Failure on Primary Transport} An attempt was made to connect to the remote server %hs on the primary transport, but the connection failed. The computer WAS able to connect on a secondary transport. pub const PRIMARY_TRANSPORT_CONNECT_FAILED = 746; + /// Page fault was a transition fault. pub const PAGE_FAULT_TRANSITION = 747; + /// Page fault was a demand zero fault. pub const PAGE_FAULT_DEMAND_ZERO = 748; + /// Page fault was a demand zero fault. pub const PAGE_FAULT_COPY_ON_WRITE = 749; + /// Page fault was a demand zero fault. pub const PAGE_FAULT_GUARD_PAGE = 750; + /// Page fault was satisfied by reading from a secondary storage device. pub const PAGE_FAULT_PAGING_FILE = 751; + /// Cached page was locked during operation. pub const CACHE_PAGE_LOCKED = 752; + /// Crash dump exists in paging file. pub const CRASH_DUMP = 753; + /// Specified buffer contains all zeros. pub const BUFFER_ALL_ZEROS = 754; + /// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link. pub const REPARSE_OBJECT = 755; + /// The device has succeeded a query-stop and its resource requirements have changed. pub const RESOURCE_REQUIREMENTS_CHANGED = 756; + /// The translator has translated these resources into the global space and no further translations should be performed. pub const TRANSLATION_COMPLETE = 757; + /// A process being terminated has no threads to terminate. pub const NOTHING_TO_TERMINATE = 758; + /// The specified process is not part of a job. pub const PROCESS_NOT_IN_JOB = 759; + /// The specified process is part of a job. pub const PROCESS_IN_JOB = 760; + /// {Volume Shadow Copy Service} The system is now ready for hibernation. pub const VOLSNAP_HIBERNATE_READY = 761; + /// A file system or file system filter driver has successfully completed an FsFilter operation. pub const FSFILTER_OP_COMPLETED_SUCCESSFULLY = 762; + /// The specified interrupt vector was already connected. pub const INTERRUPT_VECTOR_ALREADY_CONNECTED = 763; + /// The specified interrupt vector is still connected. pub const INTERRUPT_STILL_CONNECTED = 764; + /// An operation is blocked waiting for an oplock. pub const WAIT_FOR_OPLOCK = 765; + /// Debugger handled exception. pub const DBG_EXCEPTION_HANDLED = 766; + /// Debugger continued. pub const DBG_CONTINUE = 767; + /// An exception occurred in a user mode callback and the kernel callback frame should be removed. pub const CALLBACK_POP_STACK = 768; + /// Compression is disabled for this volume. pub const COMPRESSION_DISABLED = 769; + /// The data provider cannot fetch backwards through a result set. pub const CANTFETCHBACKWARDS = 770; + /// The data provider cannot scroll backwards through a result set. pub const CANTSCROLLBACKWARDS = 771; + /// The data provider requires that previously fetched data is released before asking for more data. pub const ROWSNOTRELEASED = 772; + /// The data provider was not able to interpret the flags set for a column binding in an accessor. pub const BAD_ACCESSOR_FLAGS = 773; + /// One or more errors occurred while processing the request. pub const ERRORS_ENCOUNTERED = 774; + /// The implementation is not capable of performing the request. pub const NOT_CAPABLE = 775; + /// The client of a component requested an operation which is not valid given the state of the component instance. pub const REQUEST_OUT_OF_SEQUENCE = 776; + /// A version number could not be parsed. pub const VERSION_PARSE_ERROR = 777; + /// The iterator's start position is invalid. pub const BADSTARTPOSITION = 778; + /// The hardware has reported an uncorrectable memory error. pub const MEMORY_HARDWARE = 779; + /// The attempted operation required self healing to be enabled. pub const DISK_REPAIR_DISABLED = 780; + /// The Desktop heap encountered an error while allocating session memory. There is more information in the system event log. pub const INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE = 781; + /// The system power state is transitioning from %2 to %3. pub const SYSTEM_POWERSTATE_TRANSITION = 782; + /// The system power state is transitioning from %2 to %3 but could enter %4. pub const SYSTEM_POWERSTATE_COMPLEX_TRANSITION = 783; + /// A thread is getting dispatched with MCA EXCEPTION because of MCA. pub const MCA_EXCEPTION = 784; + /// Access to %1 is monitored by policy rule %2. pub const ACCESS_AUDIT_BY_POLICY = 785; + /// Access to %1 has been restricted by your Administrator by policy rule %2. pub const ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 786; + /// A valid hibernation file has been invalidated and should be abandoned. pub const ABANDON_HIBERFILE = 787; + /// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused by network connectivity issues. Please try to save this file elsewhere. pub const LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED = 788; + /// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error was returned by the server on which the file exists. Please try to save this file elsewhere. pub const LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR = 789; + /// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused if the device has been removed or the media is write-protected. pub const LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR = 790; + /// The resources required for this device conflict with the MCFG table. pub const BAD_MCFG_TABLE = 791; + /// The volume repair could not be performed while it is online. Please schedule to take the volume offline so that it can be repaired. pub const DISK_REPAIR_REDIRECTED = 792; + /// The volume repair was not successful. pub const DISK_REPAIR_UNSUCCESSFUL = 793; + /// One of the volume corruption logs is full. Further corruptions that may be detected won't be logged. pub const CORRUPT_LOG_OVERFULL = 794; + /// One of the volume corruption logs is internally corrupted and needs to be recreated. The volume may contain undetected corruptions and must be scanned. pub const CORRUPT_LOG_CORRUPTED = 795; + /// One of the volume corruption logs is unavailable for being operated on. pub const CORRUPT_LOG_UNAVAILABLE = 796; + /// One of the volume corruption logs was deleted while still having corruption records in them. The volume contains detected corruptions and must be scanned. pub const CORRUPT_LOG_DELETED_FULL = 797; + /// One of the volume corruption logs was cleared by chkdsk and no longer contains real corruptions. pub const CORRUPT_LOG_CLEARED = 798; + /// Orphaned files exist on the volume but could not be recovered because no more new names could be created in the recovery directory. Files must be moved from the recovery directory. pub const ORPHAN_NAME_EXHAUSTED = 799; + /// The oplock that was associated with this handle is now associated with a different handle. pub const OPLOCK_SWITCHED_TO_NEW_HANDLE = 800; + /// An oplock of the requested level cannot be granted. An oplock of a lower level may be available. pub const CANNOT_GRANT_REQUESTED_OPLOCK = 801; + /// The operation did not complete successfully because it would cause an oplock to be broken. The caller has requested that existing oplocks not be broken. pub const CANNOT_BREAK_OPLOCK = 802; + /// The handle with which this oplock was associated has been closed. The oplock is now broken. pub const OPLOCK_HANDLE_CLOSED = 803; + /// The specified access control entry (ACE) does not contain a condition. pub const NO_ACE_CONDITION = 804; + /// The specified access control entry (ACE) contains an invalid condition. pub const INVALID_ACE_CONDITION = 805; + /// Access to the specified file handle has been revoked. pub const FILE_HANDLE_REVOKED = 806; + /// An image file was mapped at a different address from the one specified in the image file but fixups will still be automatically performed on the image. pub const IMAGE_AT_DIFFERENT_BASE = 807; + /// Access to the extended attribute was denied. pub const EA_ACCESS_DENIED = 994; + /// The I/O operation has been aborted because of either a thread exit or an application request. pub const OPERATION_ABORTED = 995; + /// Overlapped I/O event is not in a signaled state. pub const IO_INCOMPLETE = 996; + /// Overlapped I/O operation is in progress. pub const IO_PENDING = 997; + /// Invalid access to memory location. pub const NOACCESS = 998; + /// Error performing inpage operation. pub const SWAPERROR = 999; + /// Recursion too deep; the stack overflowed. pub const STACK_OVERFLOW = 1001; + /// The window cannot act on the sent message. pub const INVALID_MESSAGE = 1002; + /// Cannot complete this function. pub const CAN_NOT_COMPLETE = 1003; + /// Invalid flags. pub const INVALID_FLAGS = 1004; + /// The volume does not contain a recognized file system. Please make sure that all required file system drivers are loaded and that the volume is not corrupted. pub const UNRECOGNIZED_VOLUME = 1005; + /// The volume for a file has been externally altered so that the opened file is no longer valid. pub const FILE_INVALID = 1006; + /// The requested operation cannot be performed in full-screen mode. pub const FULLSCREEN_MODE = 1007; + /// An attempt was made to reference a token that does not exist. pub const NO_TOKEN = 1008; + /// The configuration registry database is corrupt. pub const BADDB = 1009; + /// The configuration registry key is invalid. pub const BADKEY = 1010; + /// The configuration registry key could not be opened. pub const CANTOPEN = 1011; + /// The configuration registry key could not be read. pub const CANTREAD = 1012; + /// The configuration registry key could not be written. pub const CANTWRITE = 1013; + /// One of the files in the registry database had to be recovered by use of a log or alternate copy. The recovery was successful. pub const REGISTRY_RECOVERED = 1014; + /// The registry is corrupted. The structure of one of the files containing registry data is corrupted, or the system's memory image of the file is corrupted, or the file could not be recovered because the alternate copy or log was absent or corrupted. pub const REGISTRY_CORRUPT = 1015; + /// An I/O operation initiated by the registry failed unrecoverably. The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry. pub const REGISTRY_IO_FAILED = 1016; + /// The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format. pub const NOT_REGISTRY_FILE = 1017; + /// Illegal operation attempted on a registry key that has been marked for deletion. pub const KEY_DELETED = 1018; + /// System could not allocate the required space in a registry log. pub const NO_LOG_SPACE = 1019; + /// Cannot create a symbolic link in a registry key that already has subkeys or values. pub const KEY_HAS_CHILDREN = 1020; + /// Cannot create a stable subkey under a volatile parent key. pub const CHILD_MUST_BE_VOLATILE = 1021; + /// A notify change request is being completed and the information is not being returned in the caller's buffer. The caller now needs to enumerate the files to find the changes. pub const NOTIFY_ENUM_DIR = 1022; + /// A stop control has been sent to a service that other running services are dependent on. pub const DEPENDENT_SERVICES_RUNNING = 1051; + /// The requested control is not valid for this service. pub const INVALID_SERVICE_CONTROL = 1052; + /// The service did not respond to the start or control request in a timely fashion. pub const SERVICE_REQUEST_TIMEOUT = 1053; + /// A thread could not be created for the service. pub const SERVICE_NO_THREAD = 1054; + /// The service database is locked. pub const SERVICE_DATABASE_LOCKED = 1055; + /// An instance of the service is already running. pub const SERVICE_ALREADY_RUNNING = 1056; + /// The account name is invalid or does not exist, or the password is invalid for the account name specified. pub const INVALID_SERVICE_ACCOUNT = 1057; + /// The service cannot be started, either because it is disabled or because it has no enabled devices associated with it. pub const SERVICE_DISABLED = 1058; + /// Circular service dependency was specified. pub const CIRCULAR_DEPENDENCY = 1059; + /// The specified service does not exist as an installed service. pub const SERVICE_DOES_NOT_EXIST = 1060; + /// The service cannot accept control messages at this time. pub const SERVICE_CANNOT_ACCEPT_CTRL = 1061; + /// The service has not been started. pub const SERVICE_NOT_ACTIVE = 1062; + /// The service process could not connect to the service controller. pub const FAILED_SERVICE_CONTROLLER_CONNECT = 1063; + /// An exception occurred in the service when handling the control request. pub const EXCEPTION_IN_SERVICE = 1064; + /// The database specified does not exist. pub const DATABASE_DOES_NOT_EXIST = 1065; + /// The service has returned a service-specific error code. pub const SERVICE_SPECIFIC_ERROR = 1066; + /// The process terminated unexpectedly. pub const PROCESS_ABORTED = 1067; + /// The dependency service or group failed to start. pub const SERVICE_DEPENDENCY_FAIL = 1068; + /// The service did not start due to a logon failure. pub const SERVICE_LOGON_FAILED = 1069; + /// After starting, the service hung in a start-pending state. pub const SERVICE_START_HANG = 1070; + /// The specified service database lock is invalid. pub const INVALID_SERVICE_LOCK = 1071; + /// The specified service has been marked for deletion. pub const SERVICE_MARKED_FOR_DELETE = 1072; + /// The specified service already exists. pub const SERVICE_EXISTS = 1073; + /// The system is currently running with the last-known-good configuration. pub const ALREADY_RUNNING_LKG = 1074; + /// The dependency service does not exist or has been marked for deletion. pub const SERVICE_DEPENDENCY_DELETED = 1075; + /// The current boot has already been accepted for use as the last-known-good control set. pub const BOOT_ALREADY_ACCEPTED = 1076; + /// No attempts to start the service have been made since the last boot. pub const SERVICE_NEVER_STARTED = 1077; + /// The name is already in use as either a service name or a service display name. pub const DUPLICATE_SERVICE_NAME = 1078; + /// The account specified for this service is different from the account specified for other services running in the same process. pub const DIFFERENT_SERVICE_ACCOUNT = 1079; + /// Failure actions can only be set for Win32 services, not for drivers. pub const CANNOT_DETECT_DRIVER_FAILURE = 1080; + /// This service runs in the same process as the service control manager. Therefore, the service control manager cannot take action if this service's process terminates unexpectedly. pub const CANNOT_DETECT_PROCESS_ABORT = 1081; + /// No recovery program has been configured for this service. pub const NO_RECOVERY_PROGRAM = 1082; + /// The executable program that this service is configured to run in does not implement the service. pub const SERVICE_NOT_IN_EXE = 1083; + /// This service cannot be started in Safe Mode. pub const NOT_SAFEBOOT_SERVICE = 1084; + /// The physical end of the tape has been reached. pub const END_OF_MEDIA = 1100; + /// A tape access reached a filemark. pub const FILEMARK_DETECTED = 1101; + /// The beginning of the tape or a partition was encountered. pub const BEGINNING_OF_MEDIA = 1102; + /// A tape access reached the end of a set of files. pub const SETMARK_DETECTED = 1103; + /// No more data is on the tape. pub const NO_DATA_DETECTED = 1104; + /// Tape could not be partitioned. pub const PARTITION_FAILURE = 1105; + /// When accessing a new tape of a multivolume partition, the current block size is incorrect. pub const INVALID_BLOCK_LENGTH = 1106; + /// Tape partition information could not be found when loading a tape. pub const DEVICE_NOT_PARTITIONED = 1107; + /// Unable to lock the media eject mechanism. pub const UNABLE_TO_LOCK_MEDIA = 1108; + /// Unable to unload the media. pub const UNABLE_TO_UNLOAD_MEDIA = 1109; + /// The media in the drive may have changed. pub const MEDIA_CHANGED = 1110; + /// The I/O bus was reset. pub const BUS_RESET = 1111; + /// No media in drive. pub const NO_MEDIA_IN_DRIVE = 1112; + /// No mapping for the Unicode character exists in the target multi-byte code page. pub const NO_UNICODE_TRANSLATION = 1113; + /// A dynamic link library (DLL) initialization routine failed. pub const DLL_INIT_FAILED = 1114; + /// A system shutdown is in progress. pub const SHUTDOWN_IN_PROGRESS = 1115; + /// Unable to abort the system shutdown because no shutdown was in progress. pub const NO_SHUTDOWN_IN_PROGRESS = 1116; + /// The request could not be performed because of an I/O device error. pub const IO_DEVICE = 1117; + /// No serial device was successfully initialized. The serial driver will unload. pub const SERIAL_NO_DEVICE = 1118; + /// Unable to open a device that was sharing an interrupt request (IRQ) with other devices. At least one other device that uses that IRQ was already opened. pub const IRQ_BUSY = 1119; + /// A serial I/O operation was completed by another write to the serial port. The IOCTL_SERIAL_XOFF_COUNTER reached zero.) pub const MORE_WRITES = 1120; + /// A serial I/O operation completed because the timeout period expired. The IOCTL_SERIAL_XOFF_COUNTER did not reach zero.) pub const COUNTER_TIMEOUT = 1121; + /// No ID address mark was found on the floppy disk. pub const FLOPPY_ID_MARK_NOT_FOUND = 1122; + /// Mismatch between the floppy disk sector ID field and the floppy disk controller track address. pub const FLOPPY_WRONG_CYLINDER = 1123; + /// The floppy disk controller reported an error that is not recognized by the floppy disk driver. pub const FLOPPY_UNKNOWN_ERROR = 1124; + /// The floppy disk controller returned inconsistent results in its registers. pub const FLOPPY_BAD_REGISTERS = 1125; + /// While accessing the hard disk, a recalibrate operation failed, even after retries. pub const DISK_RECALIBRATE_FAILED = 1126; + /// While accessing the hard disk, a disk operation failed even after retries. pub const DISK_OPERATION_FAILED = 1127; + /// While accessing the hard disk, a disk controller reset was needed, but even that failed. pub const DISK_RESET_FAILED = 1128; + /// Physical end of tape encountered. pub const EOM_OVERFLOW = 1129; + /// Not enough server storage is available to process this command. pub const NOT_ENOUGH_SERVER_MEMORY = 1130; + /// A potential deadlock condition has been detected. pub const POSSIBLE_DEADLOCK = 1131; + /// The base address or the file offset specified does not have the proper alignment. pub const MAPPED_ALIGNMENT = 1132; + /// An attempt to change the system power state was vetoed by another application or driver. pub const SET_POWER_STATE_VETOED = 1140; + /// The system BIOS failed an attempt to change the system power state. pub const SET_POWER_STATE_FAILED = 1141; + /// An attempt was made to create more links on a file than the file system supports. pub const TOO_MANY_LINKS = 1142; + /// The specified program requires a newer version of Windows. pub const OLD_WIN_VERSION = 1150; + /// The specified program is not a Windows or MS-DOS program. pub const APP_WRONG_OS = 1151; + /// Cannot start more than one instance of the specified program. pub const SINGLE_INSTANCE_APP = 1152; + /// The specified program was written for an earlier version of Windows. pub const RMODE_APP = 1153; + /// One of the library files needed to run this application is damaged. pub const INVALID_DLL = 1154; + /// No application is associated with the specified file for this operation. pub const NO_ASSOCIATION = 1155; + /// An error occurred in sending the command to the application. pub const DDE_FAIL = 1156; + /// One of the library files needed to run this application cannot be found. pub const DLL_NOT_FOUND = 1157; + /// The current process has used all of its system allowance of handles for Window Manager objects. pub const NO_MORE_USER_HANDLES = 1158; + /// The message can be used only with synchronous operations. pub const MESSAGE_SYNC_ONLY = 1159; + /// The indicated source element has no media. pub const SOURCE_ELEMENT_EMPTY = 1160; + /// The indicated destination element already contains media. pub const DESTINATION_ELEMENT_FULL = 1161; + /// The indicated element does not exist. pub const ILLEGAL_ELEMENT_ADDRESS = 1162; + /// The indicated element is part of a magazine that is not present. pub const MAGAZINE_NOT_PRESENT = 1163; + /// The indicated device requires reinitialization due to hardware errors. pub const DEVICE_REINITIALIZATION_NEEDED = 1164; + /// The device has indicated that cleaning is required before further operations are attempted. pub const DEVICE_REQUIRES_CLEANING = 1165; + /// The device has indicated that its door is open. pub const DEVICE_DOOR_OPEN = 1166; + /// The device is not connected. pub const DEVICE_NOT_CONNECTED = 1167; + /// Element not found. pub const NOT_FOUND = 1168; + /// There was no match for the specified key in the index. pub const NO_MATCH = 1169; + /// The property set specified does not exist on the object. pub const SET_NOT_FOUND = 1170; + /// The point passed to GetMouseMovePoints is not in the buffer. pub const POINT_NOT_FOUND = 1171; + /// The tracking (workstation) service is not running. pub const NO_TRACKING_SERVICE = 1172; + /// The Volume ID could not be found. pub const NO_VOLUME_ID = 1173; + /// Unable to remove the file to be replaced. pub const UNABLE_TO_REMOVE_REPLACED = 1175; + /// Unable to move the replacement file to the file to be replaced. The file to be replaced has retained its original name. pub const UNABLE_TO_MOVE_REPLACEMENT = 1176; + /// Unable to move the replacement file to the file to be replaced. The file to be replaced has been renamed using the backup name. pub const UNABLE_TO_MOVE_REPLACEMENT_2 = 1177; + /// The volume change journal is being deleted. pub const JOURNAL_DELETE_IN_PROGRESS = 1178; + /// The volume change journal is not active. pub const JOURNAL_NOT_ACTIVE = 1179; + /// A file was found, but it may not be the correct file. pub const POTENTIAL_FILE_FOUND = 1180; + /// The journal entry has been deleted from the journal. pub const JOURNAL_ENTRY_DELETED = 1181; + /// A system shutdown has already been scheduled. pub const SHUTDOWN_IS_SCHEDULED = 1190; + /// The system shutdown cannot be initiated because there are other users logged on to the computer. pub const SHUTDOWN_USERS_LOGGED_ON = 1191; + /// The specified device name is invalid. pub const BAD_DEVICE = 1200; + /// The device is not currently connected but it is a remembered connection. pub const CONNECTION_UNAVAIL = 1201; + /// The local device name has a remembered connection to another network resource. pub const DEVICE_ALREADY_REMEMBERED = 1202; + /// The network path was either typed incorrectly, does not exist, or the network provider is not currently available. Please try retyping the path or contact your network administrator. pub const NO_NET_OR_BAD_PATH = 1203; + /// The specified network provider name is invalid. pub const BAD_PROVIDER = 1204; + /// Unable to open the network connection profile. pub const CANNOT_OPEN_PROFILE = 1205; + /// The network connection profile is corrupted. pub const BAD_PROFILE = 1206; + /// Cannot enumerate a noncontainer. pub const NOT_CONTAINER = 1207; + /// An extended error has occurred. pub const EXTENDED_ERROR = 1208; + /// The format of the specified group name is invalid. pub const INVALID_GROUPNAME = 1209; + /// The format of the specified computer name is invalid. pub const INVALID_COMPUTERNAME = 1210; + /// The format of the specified event name is invalid. pub const INVALID_EVENTNAME = 1211; + /// The format of the specified domain name is invalid. pub const INVALID_DOMAINNAME = 1212; + /// The format of the specified service name is invalid. pub const INVALID_SERVICENAME = 1213; + /// The format of the specified network name is invalid. pub const INVALID_NETNAME = 1214; + /// The format of the specified share name is invalid. pub const INVALID_SHARENAME = 1215; + /// The format of the specified password is invalid. pub const INVALID_PASSWORDNAME = 1216; + /// The format of the specified message name is invalid. pub const INVALID_MESSAGENAME = 1217; + /// The format of the specified message destination is invalid. pub const INVALID_MESSAGEDEST = 1218; + /// Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again. pub const SESSION_CREDENTIAL_CONFLICT = 1219; + /// An attempt was made to establish a session to a network server, but there are already too many sessions established to that server. pub const REMOTE_SESSION_LIMIT_EXCEEDED = 1220; + /// The workgroup or domain name is already in use by another computer on the network. pub const DUP_DOMAINNAME = 1221; + /// The network is not present or not started. pub const NO_NETWORK = 1222; + /// The operation was canceled by the user. pub const CANCELLED = 1223; + /// The requested operation cannot be performed on a file with a user-mapped section open. pub const USER_MAPPED_FILE = 1224; + /// The remote computer refused the network connection. pub const CONNECTION_REFUSED = 1225; + /// The network connection was gracefully closed. pub const GRACEFUL_DISCONNECT = 1226; + /// The network transport endpoint already has an address associated with it. pub const ADDRESS_ALREADY_ASSOCIATED = 1227; + /// An address has not yet been associated with the network endpoint. pub const ADDRESS_NOT_ASSOCIATED = 1228; + /// An operation was attempted on a nonexistent network connection. pub const CONNECTION_INVALID = 1229; + /// An invalid operation was attempted on an active network connection. pub const CONNECTION_ACTIVE = 1230; + /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const NETWORK_UNREACHABLE = 1231; + /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const HOST_UNREACHABLE = 1232; + /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const PROTOCOL_UNREACHABLE = 1233; + /// No service is operating at the destination network endpoint on the remote system. pub const PORT_UNREACHABLE = 1234; + /// The request was aborted. pub const REQUEST_ABORTED = 1235; + /// The network connection was aborted by the local system. pub const CONNECTION_ABORTED = 1236; + /// The operation could not be completed. A retry should be performed. pub const RETRY = 1237; + /// A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached. pub const CONNECTION_COUNT_LIMIT = 1238; + /// Attempting to log in during an unauthorized time of day for this account. pub const LOGIN_TIME_RESTRICTION = 1239; + /// The account is not authorized to log in from this station. pub const LOGIN_WKSTA_RESTRICTION = 1240; + /// The network address could not be used for the operation requested. pub const INCORRECT_ADDRESS = 1241; + /// The service is already registered. pub const ALREADY_REGISTERED = 1242; + /// The specified service does not exist. pub const SERVICE_NOT_FOUND = 1243; + /// The operation being requested was not performed because the user has not been authenticated. pub const NOT_AUTHENTICATED = 1244; + /// The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist. pub const NOT_LOGGED_ON = 1245; + /// Continue with work in progress. pub const CONTINUE = 1246; + /// An attempt was made to perform an initialization operation when initialization has already been completed. pub const ALREADY_INITIALIZED = 1247; + /// No more local devices. pub const NO_MORE_DEVICES = 1248; + /// The specified site does not exist. pub const NO_SUCH_SITE = 1249; + /// A domain controller with the specified name already exists. pub const DOMAIN_CONTROLLER_EXISTS = 1250; + /// This operation is supported only when you are connected to the server. pub const ONLY_IF_CONNECTED = 1251; + /// The group policy framework should call the extension even if there are no changes. pub const OVERRIDE_NOCHANGES = 1252; + /// The specified user does not have a valid profile. pub const BAD_USER_PROFILE = 1253; + /// This operation is not supported on a computer running Windows Server 2003 for Small Business Server. pub const NOT_SUPPORTED_ON_SBS = 1254; + /// The server machine is shutting down. pub const SERVER_SHUTDOWN_IN_PROGRESS = 1255; + /// The remote system is not available. For information about network troubleshooting, see Windows Help. pub const HOST_DOWN = 1256; + /// The security identifier provided is not from an account domain. pub const NON_ACCOUNT_SID = 1257; + /// The security identifier provided does not have a domain component. pub const NON_DOMAIN_SID = 1258; + /// AppHelp dialog canceled thus preventing the application from starting. pub const APPHELP_BLOCK = 1259; + /// This program is blocked by group policy. For more information, contact your system administrator. pub const ACCESS_DISABLED_BY_POLICY = 1260; + /// A program attempt to use an invalid register value. Normally caused by an uninitialized register. This error is Itanium specific. pub const REG_NAT_CONSUMPTION = 1261; + /// The share is currently offline or does not exist. pub const CSCSHARE_OFFLINE = 1262; + /// The Kerberos protocol encountered an error while validating the KDC certificate during smartcard logon. There is more information in the system event log. pub const PKINIT_FAILURE = 1263; + /// The Kerberos protocol encountered an error while attempting to utilize the smartcard subsystem. pub const SMARTCARD_SUBSYSTEM_FAILURE = 1264; + /// The system cannot contact a domain controller to service the authentication request. Please try again later. pub const DOWNGRADE_DETECTED = 1265; + /// The machine is locked and cannot be shut down without the force option. pub const MACHINE_LOCKED = 1271; + /// An application-defined callback gave invalid data when called. pub const CALLBACK_SUPPLIED_INVALID_DATA = 1273; + /// The group policy framework should call the extension in the synchronous foreground policy refresh. pub const SYNC_FOREGROUND_REFRESH_REQUIRED = 1274; + /// This driver has been blocked from loading. pub const DRIVER_BLOCKED = 1275; + /// A dynamic link library (DLL) referenced a module that was neither a DLL nor the process's executable image. pub const INVALID_IMPORT_OF_NON_DLL = 1276; + /// Windows cannot open this program since it has been disabled. pub const ACCESS_DISABLED_WEBBLADE = 1277; + /// Windows cannot open this program because the license enforcement system has been tampered with or become corrupted. pub const ACCESS_DISABLED_WEBBLADE_TAMPER = 1278; + /// A transaction recover failed. pub const RECOVERY_FAILURE = 1279; + /// The current thread has already been converted to a fiber. pub const ALREADY_FIBER = 1280; + /// The current thread has already been converted from a fiber. pub const ALREADY_THREAD = 1281; + /// The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application. pub const STACK_BUFFER_OVERRUN = 1282; + /// Data present in one of the parameters is more than the function can operate on. pub const PARAMETER_QUOTA_EXCEEDED = 1283; + /// An attempt to do an operation on a debug object failed because the object is in the process of being deleted. pub const DEBUGGER_INACTIVE = 1284; + /// An attempt to delay-load a .dll or get a function address in a delay-loaded .dll failed. pub const DELAY_LOAD_FAILED = 1285; + /// %1 is a 16-bit application. You do not have permissions to execute 16-bit applications. Check your permissions with your system administrator. pub const VDM_DISALLOWED = 1286; + /// Insufficient information exists to identify the cause of failure. pub const UNIDENTIFIED_ERROR = 1287; + /// The parameter passed to a C runtime function is incorrect. pub const INVALID_CRUNTIME_PARAMETER = 1288; + /// The operation occurred beyond the valid data length of the file. pub const BEYOND_VDL = 1289; + /// The service start failed since one or more services in the same process have an incompatible service SID type setting. A service with restricted service SID type can only coexist in the same process with other services with a restricted SID type. If the service SID type for this service was just configured, the hosting process must be restarted in order to start this service. /// On Windows Server 2003 and Windows XP, an unrestricted service cannot coexist in the same process with other services. The service with the unrestricted service SID type must be moved to an owned process in order to start this service. pub const INCOMPATIBLE_SERVICE_SID_TYPE = 1290; + /// The process hosting the driver for this device has been terminated. pub const DRIVER_PROCESS_TERMINATED = 1291; + /// An operation attempted to exceed an implementation-defined limit. pub const IMPLEMENTATION_LIMIT = 1292; + /// Either the target process, or the target thread's containing process, is a protected process. pub const PROCESS_IS_PROTECTED = 1293; + /// The service notification client is lagging too far behind the current state of services in the machine. pub const SERVICE_NOTIFY_CLIENT_LAGGING = 1294; + /// The requested file operation failed because the storage quota was exceeded. To free up disk space, move files to a different location or delete unnecessary files. For more information, contact your system administrator. pub const DISK_QUOTA_EXCEEDED = 1295; + /// The requested file operation failed because the storage policy blocks that type of file. For more information, contact your system administrator. pub const CONTENT_BLOCKED = 1296; + /// A privilege that the service requires to function properly does not exist in the service account configuration. You may use the Services Microsoft Management Console (MMC) snap-in (services.msc) and the Local Security Settings MMC snap-in (secpol.msc) to view the service configuration and the account configuration. pub const INCOMPATIBLE_SERVICE_PRIVILEGE = 1297; + /// A thread involved in this operation appears to be unresponsive. pub const APP_HANG = 1298; + /// Indicates a particular Security ID may not be assigned as the label of an object. pub const INVALID_LABEL = 1299; + /// Not all privileges or groups referenced are assigned to the caller. pub const NOT_ALL_ASSIGNED = 1300; + /// Some mapping between account names and security IDs was not done. pub const SOME_NOT_MAPPED = 1301; + /// No system quota limits are specifically set for this account. pub const NO_QUOTAS_FOR_ACCOUNT = 1302; + /// No encryption key is available. A well-known encryption key was returned. pub const LOCAL_USER_SESSION_KEY = 1303; + /// The password is too complex to be converted to a LAN Manager password. The LAN Manager password returned is a NULL string. pub const NULL_LM_PASSWORD = 1304; + /// The revision level is unknown. pub const UNKNOWN_REVISION = 1305; + /// Indicates two revision levels are incompatible. pub const REVISION_MISMATCH = 1306; + /// This security ID may not be assigned as the owner of this object. pub const INVALID_OWNER = 1307; + /// This security ID may not be assigned as the primary group of an object. pub const INVALID_PRIMARY_GROUP = 1308; + /// An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client. pub const NO_IMPERSONATION_TOKEN = 1309; + /// The group may not be disabled. pub const CANT_DISABLE_MANDATORY = 1310; + /// There are currently no logon servers available to service the logon request. pub const NO_LOGON_SERVERS = 1311; + /// A specified logon session does not exist. It may already have been terminated. pub const NO_SUCH_LOGON_SESSION = 1312; + /// A specified privilege does not exist. pub const NO_SUCH_PRIVILEGE = 1313; + /// A required privilege is not held by the client. pub const PRIVILEGE_NOT_HELD = 1314; + /// The name provided is not a properly formed account name. pub const INVALID_ACCOUNT_NAME = 1315; + /// The specified account already exists. pub const USER_EXISTS = 1316; + /// The specified account does not exist. pub const NO_SUCH_USER = 1317; + /// The specified group already exists. pub const GROUP_EXISTS = 1318; + /// The specified group does not exist. pub const NO_SUCH_GROUP = 1319; + /// Either the specified user account is already a member of the specified group, or the specified group cannot be deleted because it contains a member. pub const MEMBER_IN_GROUP = 1320; + /// The specified user account is not a member of the specified group account. pub const MEMBER_NOT_IN_GROUP = 1321; + /// This operation is disallowed as it could result in an administration account being disabled, deleted or unable to log on. pub const LAST_ADMIN = 1322; + /// Unable to update the password. The value provided as the current password is incorrect. pub const WRONG_PASSWORD = 1323; + /// Unable to update the password. The value provided for the new password contains values that are not allowed in passwords. pub const ILL_FORMED_PASSWORD = 1324; + /// Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain. pub const PASSWORD_RESTRICTION = 1325; + /// The user name or password is incorrect. pub const LOGON_FAILURE = 1326; + /// Account restrictions are preventing this user from signing in. For example: blank passwords aren't allowed, sign-in times are limited, or a policy restriction has been enforced. pub const ACCOUNT_RESTRICTION = 1327; + /// Your account has time restrictions that keep you from signing in right now. pub const INVALID_LOGON_HOURS = 1328; + /// This user isn't allowed to sign in to this computer. pub const INVALID_WORKSTATION = 1329; + /// The password for this account has expired. pub const PASSWORD_EXPIRED = 1330; + /// This user can't sign in because this account is currently disabled. pub const ACCOUNT_DISABLED = 1331; + /// No mapping between account names and security IDs was done. pub const NONE_MAPPED = 1332; + /// Too many local user identifiers (LUIDs) were requested at one time. pub const TOO_MANY_LUIDS_REQUESTED = 1333; + /// No more local user identifiers (LUIDs) are available. pub const LUIDS_EXHAUSTED = 1334; + /// The subauthority part of a security ID is invalid for this particular use. pub const INVALID_SUB_AUTHORITY = 1335; + /// The access control list (ACL) structure is invalid. pub const INVALID_ACL = 1336; + /// The security ID structure is invalid. pub const INVALID_SID = 1337; + /// The security descriptor structure is invalid. pub const INVALID_SECURITY_DESCR = 1338; + /// The inherited access control list (ACL) or access control entry (ACE) could not be built. pub const BAD_INHERITANCE_ACL = 1340; + /// The server is currently disabled. pub const SERVER_DISABLED = 1341; + /// The server is currently enabled. pub const SERVER_NOT_DISABLED = 1342; + /// The value provided was an invalid value for an identifier authority. pub const INVALID_ID_AUTHORITY = 1343; + /// No more memory is available for security information updates. pub const ALLOTTED_SPACE_EXCEEDED = 1344; + /// The specified attributes are invalid, or incompatible with the attributes for the group as a whole. pub const INVALID_GROUP_ATTRIBUTES = 1345; + /// Either a required impersonation level was not provided, or the provided impersonation level is invalid. pub const BAD_IMPERSONATION_LEVEL = 1346; + /// Cannot open an anonymous level security token. pub const CANT_OPEN_ANONYMOUS = 1347; + /// The validation information class requested was invalid. pub const BAD_VALIDATION_CLASS = 1348; + /// The type of the token is inappropriate for its attempted use. pub const BAD_TOKEN_TYPE = 1349; + /// Unable to perform a security operation on an object that has no associated security. pub const NO_SECURITY_ON_OBJECT = 1350; + /// Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied. pub const CANT_ACCESS_DOMAIN_INFO = 1351; + /// The security account manager (SAM) or local security authority (LSA) server was in the wrong state to perform the security operation. pub const INVALID_SERVER_STATE = 1352; + /// The domain was in the wrong state to perform the security operation. pub const INVALID_DOMAIN_STATE = 1353; + /// This operation is only allowed for the Primary Domain Controller of the domain. pub const INVALID_DOMAIN_ROLE = 1354; + /// The specified domain either does not exist or could not be contacted. pub const NO_SUCH_DOMAIN = 1355; + /// The specified domain already exists. pub const DOMAIN_EXISTS = 1356; + /// An attempt was made to exceed the limit on the number of domains per server. pub const DOMAIN_LIMIT_EXCEEDED = 1357; + /// Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk. pub const INTERNAL_DB_CORRUPTION = 1358; + /// An internal error occurred. pub const INTERNAL_ERROR = 1359; + /// Generic access types were contained in an access mask which should already be mapped to nongeneric types. pub const GENERIC_NOT_MAPPED = 1360; + /// A security descriptor is not in the right format (absolute or self-relative). pub const BAD_DESCRIPTOR_FORMAT = 1361; + /// The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process. pub const NOT_LOGON_PROCESS = 1362; + /// Cannot start a new logon session with an ID that is already in use. pub const LOGON_SESSION_EXISTS = 1363; + /// A specified authentication package is unknown. pub const NO_SUCH_PACKAGE = 1364; + /// The logon session is not in a state that is consistent with the requested operation. pub const BAD_LOGON_SESSION_STATE = 1365; + /// The logon session ID is already in use. pub const LOGON_SESSION_COLLISION = 1366; + /// A logon request contained an invalid logon type value. pub const INVALID_LOGON_TYPE = 1367; + /// Unable to impersonate using a named pipe until data has been read from that pipe. pub const CANNOT_IMPERSONATE = 1368; + /// The transaction state of a registry subtree is incompatible with the requested operation. pub const RXACT_INVALID_STATE = 1369; + /// An internal security database corruption has been encountered. pub const RXACT_COMMIT_FAILURE = 1370; + /// Cannot perform this operation on built-in accounts. pub const SPECIAL_ACCOUNT = 1371; + /// Cannot perform this operation on this built-in special group. pub const SPECIAL_GROUP = 1372; + /// Cannot perform this operation on this built-in special user. pub const SPECIAL_USER = 1373; + /// The user cannot be removed from a group because the group is currently the user's primary group. pub const MEMBERS_PRIMARY_GROUP = 1374; + /// The token is already in use as a primary token. pub const TOKEN_ALREADY_IN_USE = 1375; + /// The specified local group does not exist. pub const NO_SUCH_ALIAS = 1376; + /// The specified account name is not a member of the group. pub const MEMBER_NOT_IN_ALIAS = 1377; + /// The specified account name is already a member of the group. pub const MEMBER_IN_ALIAS = 1378; + /// The specified local group already exists. pub const ALIAS_EXISTS = 1379; + /// Logon failure: the user has not been granted the requested logon type at this computer. pub const LOGON_NOT_GRANTED = 1380; + /// The maximum number of secrets that may be stored in a single system has been exceeded. pub const TOO_MANY_SECRETS = 1381; + /// The length of a secret exceeds the maximum length allowed. pub const SECRET_TOO_LONG = 1382; + /// The local security authority database contains an internal inconsistency. pub const INTERNAL_DB_ERROR = 1383; + /// During a logon attempt, the user's security context accumulated too many security IDs. pub const TOO_MANY_CONTEXT_IDS = 1384; + /// Logon failure: the user has not been granted the requested logon type at this computer. pub const LOGON_TYPE_NOT_GRANTED = 1385; + /// A cross-encrypted password is necessary to change a user password. pub const NT_CROSS_ENCRYPTION_REQUIRED = 1386; + /// A member could not be added to or removed from the local group because the member does not exist. pub const NO_SUCH_MEMBER = 1387; + /// A new member could not be added to a local group because the member has the wrong account type. pub const INVALID_MEMBER = 1388; + /// Too many security IDs have been specified. pub const TOO_MANY_SIDS = 1389; + /// A cross-encrypted password is necessary to change this user password. pub const LM_CROSS_ENCRYPTION_REQUIRED = 1390; + /// Indicates an ACL contains no inheritable components. pub const NO_INHERITANCE = 1391; + /// The file or directory is corrupted and unreadable. pub const FILE_CORRUPT = 1392; + /// The disk structure is corrupted and unreadable. pub const DISK_CORRUPT = 1393; + /// There is no user session key for the specified logon session. pub const NO_USER_SESSION_KEY = 1394; + /// The service being accessed is licensed for a particular number of connections. No more connections can be made to the service at this time because there are already as many connections as the service can accept. pub const LICENSE_QUOTA_EXCEEDED = 1395; + /// The target account name is incorrect. pub const WRONG_TARGET_NAME = 1396; + /// Mutual Authentication failed. The server's password is out of date at the domain controller. pub const MUTUAL_AUTH_FAILED = 1397; + /// There is a time and/or date difference between the client and server. pub const TIME_SKEW = 1398; + /// This operation cannot be performed on the current domain. pub const CURRENT_DOMAIN_NOT_ALLOWED = 1399; + /// Invalid window handle. pub const INVALID_WINDOW_HANDLE = 1400; + /// Invalid menu handle. pub const INVALID_MENU_HANDLE = 1401; + /// Invalid cursor handle. pub const INVALID_CURSOR_HANDLE = 1402; + /// Invalid accelerator table handle. pub const INVALID_ACCEL_HANDLE = 1403; + /// Invalid hook handle. pub const INVALID_HOOK_HANDLE = 1404; + /// Invalid handle to a multiple-window position structure. pub const INVALID_DWP_HANDLE = 1405; + /// Cannot create a top-level child window. pub const TLW_WITH_WSCHILD = 1406; + /// Cannot find window class. pub const CANNOT_FIND_WND_CLASS = 1407; + /// Invalid window; it belongs to other thread. pub const WINDOW_OF_OTHER_THREAD = 1408; + /// Hot key is already registered. pub const HOTKEY_ALREADY_REGISTERED = 1409; + /// Class already exists. pub const CLASS_ALREADY_EXISTS = 1410; + /// Class does not exist. pub const CLASS_DOES_NOT_EXIST = 1411; + /// Class still has open windows. pub const CLASS_HAS_WINDOWS = 1412; + /// Invalid index. pub const INVALID_INDEX = 1413; + /// Invalid icon handle. pub const INVALID_ICON_HANDLE = 1414; + /// Using private DIALOG window words. pub const PRIVATE_DIALOG_INDEX = 1415; + /// The list box identifier was not found. pub const LISTBOX_ID_NOT_FOUND = 1416; + /// No wildcards were found. pub const NO_WILDCARD_CHARACTERS = 1417; + /// Thread does not have a clipboard open. pub const CLIPBOARD_NOT_OPEN = 1418; + /// Hot key is not registered. pub const HOTKEY_NOT_REGISTERED = 1419; + /// The window is not a valid dialog window. pub const WINDOW_NOT_DIALOG = 1420; + /// Control ID not found. pub const CONTROL_ID_NOT_FOUND = 1421; + /// Invalid message for a combo box because it does not have an edit control. pub const INVALID_COMBOBOX_MESSAGE = 1422; + /// The window is not a combo box. pub const WINDOW_NOT_COMBOBOX = 1423; + /// Height must be less than 256. pub const INVALID_EDIT_HEIGHT = 1424; + /// Invalid device context (DC) handle. pub const DC_NOT_FOUND = 1425; + /// Invalid hook procedure type. pub const INVALID_HOOK_FILTER = 1426; + /// Invalid hook procedure. pub const INVALID_FILTER_PROC = 1427; + /// Cannot set nonlocal hook without a module handle. pub const HOOK_NEEDS_HMOD = 1428; + /// This hook procedure can only be set globally. pub const GLOBAL_ONLY_HOOK = 1429; + /// The journal hook procedure is already installed. pub const JOURNAL_HOOK_SET = 1430; + /// The hook procedure is not installed. pub const HOOK_NOT_INSTALLED = 1431; + /// Invalid message for single-selection list box. pub const INVALID_LB_MESSAGE = 1432; + /// LB_SETCOUNT sent to non-lazy list box. pub const SETCOUNT_ON_BAD_LB = 1433; + /// This list box does not support tab stops. pub const LB_WITHOUT_TABSTOPS = 1434; + /// Cannot destroy object created by another thread. pub const DESTROY_OBJECT_OF_OTHER_THREAD = 1435; + /// Child windows cannot have menus. pub const CHILD_WINDOW_MENU = 1436; + /// The window does not have a system menu. pub const NO_SYSTEM_MENU = 1437; + /// Invalid message box style. pub const INVALID_MSGBOX_STYLE = 1438; + /// Invalid system-wide (SPI_*) parameter. pub const INVALID_SPI_VALUE = 1439; + /// Screen already locked. pub const SCREEN_ALREADY_LOCKED = 1440; + /// All handles to windows in a multiple-window position structure must have the same parent. pub const HWNDS_HAVE_DIFF_PARENT = 1441; + /// The window is not a child window. pub const NOT_CHILD_WINDOW = 1442; + /// Invalid GW_* command. pub const INVALID_GW_COMMAND = 1443; + /// Invalid thread identifier. pub const INVALID_THREAD_ID = 1444; + /// Cannot process a message from a window that is not a multiple document interface (MDI) window. pub const NON_MDICHILD_WINDOW = 1445; + /// Popup menu already active. pub const POPUP_ALREADY_ACTIVE = 1446; + /// The window does not have scroll bars. pub const NO_SCROLLBARS = 1447; + /// Scroll bar range cannot be greater than MAXLONG. pub const INVALID_SCROLLBAR_RANGE = 1448; + /// Cannot show or remove the window in the way specified. pub const INVALID_SHOWWIN_COMMAND = 1449; + /// Insufficient system resources exist to complete the requested service. pub const NO_SYSTEM_RESOURCES = 1450; + /// Insufficient system resources exist to complete the requested service. pub const NONPAGED_SYSTEM_RESOURCES = 1451; + /// Insufficient system resources exist to complete the requested service. pub const PAGED_SYSTEM_RESOURCES = 1452; + /// Insufficient quota to complete the requested service. pub const WORKING_SET_QUOTA = 1453; + /// Insufficient quota to complete the requested service. pub const PAGEFILE_QUOTA = 1454; + /// The paging file is too small for this operation to complete. pub const COMMITMENT_LIMIT = 1455; + /// A menu item was not found. pub const MENU_ITEM_NOT_FOUND = 1456; + /// Invalid keyboard layout handle. pub const INVALID_KEYBOARD_HANDLE = 1457; + /// Hook type not allowed. pub const HOOK_TYPE_NOT_ALLOWED = 1458; + /// This operation requires an interactive window station. pub const REQUIRES_INTERACTIVE_WINDOWSTATION = 1459; + /// This operation returned because the timeout period expired. pub const TIMEOUT = 1460; + /// Invalid monitor handle. pub const INVALID_MONITOR_HANDLE = 1461; + /// Incorrect size argument. pub const INCORRECT_SIZE = 1462; + /// The symbolic link cannot be followed because its type is disabled. pub const SYMLINK_CLASS_DISABLED = 1463; + /// This application does not support the current operation on symbolic links. pub const SYMLINK_NOT_SUPPORTED = 1464; + /// Windows was unable to parse the requested XML data. pub const XML_PARSE_ERROR = 1465; + /// An error was encountered while processing an XML digital signature. pub const XMLDSIG_ERROR = 1466; + /// This application must be restarted. pub const RESTART_APPLICATION = 1467; + /// The caller made the connection request in the wrong routing compartment. pub const WRONG_COMPARTMENT = 1468; + /// There was an AuthIP failure when attempting to connect to the remote host. pub const AUTHIP_FAILURE = 1469; + /// Insufficient NVRAM resources exist to complete the requested service. A reboot might be required. pub const NO_NVRAM_RESOURCES = 1470; + /// Unable to finish the requested operation because the specified process is not a GUI process. pub const NOT_GUI_PROCESS = 1471; + /// The event log file is corrupted. pub const EVENTLOG_FILE_CORRUPT = 1500; + /// No event log file could be opened, so the event logging service did not start. pub const EVENTLOG_CANT_START = 1501; + /// The event log file is full. pub const LOG_FILE_FULL = 1502; + /// The event log file has changed between read operations. pub const EVENTLOG_FILE_CHANGED = 1503; + /// The specified task name is invalid. pub const INVALID_TASK_NAME = 1550; + /// The specified task index is invalid. pub const INVALID_TASK_INDEX = 1551; + /// The specified thread is already joining a task. pub const THREAD_ALREADY_IN_TASK = 1552; + /// The Windows Installer Service could not be accessed. This can occur if the Windows Installer is not correctly installed. Contact your support personnel for assistance. pub const INSTALL_SERVICE_FAILURE = 1601; + /// User cancelled installation. pub const INSTALL_USEREXIT = 1602; + /// Fatal error during installation. pub const INSTALL_FAILURE = 1603; + /// Installation suspended, incomplete. pub const INSTALL_SUSPEND = 1604; + /// This action is only valid for products that are currently installed. pub const UNKNOWN_PRODUCT = 1605; + /// Feature ID not registered. pub const UNKNOWN_FEATURE = 1606; + /// Component ID not registered. pub const UNKNOWN_COMPONENT = 1607; + /// Unknown property. pub const UNKNOWN_PROPERTY = 1608; + /// Handle is in an invalid state. pub const INVALID_HANDLE_STATE = 1609; + /// The configuration data for this product is corrupt. Contact your support personnel. pub const BAD_CONFIGURATION = 1610; + /// Component qualifier not present. pub const INDEX_ABSENT = 1611; + /// The installation source for this product is not available. Verify that the source exists and that you can access it. pub const INSTALL_SOURCE_ABSENT = 1612; + /// This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service. pub const INSTALL_PACKAGE_VERSION = 1613; + /// Product is uninstalled. pub const PRODUCT_UNINSTALLED = 1614; + /// SQL query syntax invalid or unsupported. pub const BAD_QUERY_SYNTAX = 1615; + /// Record field does not exist. pub const INVALID_FIELD = 1616; + /// The device has been removed. pub const DEVICE_REMOVED = 1617; + /// Another installation is already in progress. Complete that installation before proceeding with this install. pub const INSTALL_ALREADY_RUNNING = 1618; + /// This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package. pub const INSTALL_PACKAGE_OPEN_FAILED = 1619; + /// This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package. pub const INSTALL_PACKAGE_INVALID = 1620; + /// There was an error starting the Windows Installer service user interface. Contact your support personnel. pub const INSTALL_UI_FAILURE = 1621; + /// Error opening installation log file. Verify that the specified log file location exists and that you can write to it. pub const INSTALL_LOG_FAILURE = 1622; + /// The language of this installation package is not supported by your system. pub const INSTALL_LANGUAGE_UNSUPPORTED = 1623; + /// Error applying transforms. Verify that the specified transform paths are valid. pub const INSTALL_TRANSFORM_FAILURE = 1624; + /// This installation is forbidden by system policy. Contact your system administrator. pub const INSTALL_PACKAGE_REJECTED = 1625; + /// Function could not be executed. pub const FUNCTION_NOT_CALLED = 1626; + /// Function failed during execution. pub const FUNCTION_FAILED = 1627; + /// Invalid or unknown table specified. pub const INVALID_TABLE = 1628; + /// Data supplied is of wrong type. pub const DATATYPE_MISMATCH = 1629; + /// Data of this type is not supported. pub const UNSUPPORTED_TYPE = 1630; + /// The Windows Installer service failed to start. Contact your support personnel. pub const CREATE_FAILED = 1631; + /// The Temp folder is on a drive that is full or is inaccessible. Free up space on the drive or verify that you have write permission on the Temp folder. pub const INSTALL_TEMP_UNWRITABLE = 1632; + /// This installation package is not supported by this processor type. Contact your product vendor. pub const INSTALL_PLATFORM_UNSUPPORTED = 1633; + /// Component not used on this computer. pub const INSTALL_NOTUSED = 1634; + /// This update package could not be opened. Verify that the update package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer update package. pub const PATCH_PACKAGE_OPEN_FAILED = 1635; + /// This update package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer update package. pub const PATCH_PACKAGE_INVALID = 1636; + /// This update package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service. pub const PATCH_PACKAGE_UNSUPPORTED = 1637; + /// Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel. pub const PRODUCT_VERSION = 1638; + /// Invalid command line argument. Consult the Windows Installer SDK for detailed command line help. pub const INVALID_COMMAND_LINE = 1639; + /// Only administrators have permission to add, remove, or configure server software during a Terminal services remote session. If you want to install or configure software on the server, contact your network administrator. pub const INSTALL_REMOTE_DISALLOWED = 1640; + /// The requested operation completed successfully. The system will be restarted so the changes can take effect. pub const SUCCESS_REBOOT_INITIATED = 1641; + /// The upgrade cannot be installed by the Windows Installer service because the program to be upgraded may be missing, or the upgrade may update a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade. pub const PATCH_TARGET_NOT_FOUND = 1642; + /// The update package is not permitted by software restriction policy. pub const PATCH_PACKAGE_REJECTED = 1643; + /// One or more customizations are not permitted by software restriction policy. pub const INSTALL_TRANSFORM_REJECTED = 1644; + /// The Windows Installer does not permit installation from a Remote Desktop Connection. pub const INSTALL_REMOTE_PROHIBITED = 1645; + /// Uninstallation of the update package is not supported. pub const PATCH_REMOVAL_UNSUPPORTED = 1646; + /// The update is not applied to this product. pub const UNKNOWN_PATCH = 1647; + /// No valid sequence could be found for the set of updates. pub const PATCH_NO_SEQUENCE = 1648; + /// Update removal was disallowed by policy. pub const PATCH_REMOVAL_DISALLOWED = 1649; + /// The XML update data is invalid. pub const INVALID_PATCH_XML = 1650; + /// Windows Installer does not permit updating of managed advertised products. At least one feature of the product must be installed before applying the update. pub const PATCH_MANAGED_ADVERTISED_PRODUCT = 1651; + /// The Windows Installer service is not accessible in Safe Mode. Please try again when your computer is not in Safe Mode or you can use System Restore to return your machine to a previous good state. pub const INSTALL_SERVICE_SAFEBOOT = 1652; + /// A fail fast exception occurred. Exception handlers will not be invoked and the process will be terminated immediately. pub const FAIL_FAST_EXCEPTION = 1653; + /// The app that you are trying to run is not supported on this version of Windows. pub const INSTALL_REJECTED = 1654; + /// The string binding is invalid. pub const RPC_S_INVALID_STRING_BINDING = 1700; + /// The binding handle is not the correct type. pub const RPC_S_WRONG_KIND_OF_BINDING = 1701; + /// The binding handle is invalid. pub const RPC_S_INVALID_BINDING = 1702; + /// The RPC protocol sequence is not supported. pub const RPC_S_PROTSEQ_NOT_SUPPORTED = 1703; + /// The RPC protocol sequence is invalid. pub const RPC_S_INVALID_RPC_PROTSEQ = 1704; + /// The string universal unique identifier (UUID) is invalid. pub const RPC_S_INVALID_STRING_UUID = 1705; + /// The endpoint format is invalid. pub const RPC_S_INVALID_ENDPOINT_FORMAT = 1706; + /// The network address is invalid. pub const RPC_S_INVALID_NET_ADDR = 1707; + /// No endpoint was found. pub const RPC_S_NO_ENDPOINT_FOUND = 1708; + /// The timeout value is invalid. pub const RPC_S_INVALID_TIMEOUT = 1709; + /// The object universal unique identifier (UUID) was not found. pub const RPC_S_OBJECT_NOT_FOUND = 1710; + /// The object universal unique identifier (UUID) has already been registered. pub const RPC_S_ALREADY_REGISTERED = 1711; + /// The type universal unique identifier (UUID) has already been registered. pub const RPC_S_TYPE_ALREADY_REGISTERED = 1712; + /// The RPC server is already listening. pub const RPC_S_ALREADY_LISTENING = 1713; + /// No protocol sequences have been registered. pub const RPC_S_NO_PROTSEQS_REGISTERED = 1714; + /// The RPC server is not listening. pub const RPC_S_NOT_LISTENING = 1715; + /// The manager type is unknown. pub const RPC_S_UNKNOWN_MGR_TYPE = 1716; + /// The interface is unknown. pub const RPC_S_UNKNOWN_IF = 1717; + /// There are no bindings. pub const RPC_S_NO_BINDINGS = 1718; + /// There are no protocol sequences. pub const RPC_S_NO_PROTSEQS = 1719; + /// The endpoint cannot be created. pub const RPC_S_CANT_CREATE_ENDPOINT = 1720; + /// Not enough resources are available to complete this operation. pub const RPC_S_OUT_OF_RESOURCES = 1721; + /// The RPC server is unavailable. pub const RPC_S_SERVER_UNAVAILABLE = 1722; + /// The RPC server is too busy to complete this operation. pub const RPC_S_SERVER_TOO_BUSY = 1723; + /// The network options are invalid. pub const RPC_S_INVALID_NETWORK_OPTIONS = 1724; + /// There are no remote procedure calls active on this thread. pub const RPC_S_NO_CALL_ACTIVE = 1725; + /// The remote procedure call failed. pub const RPC_S_CALL_FAILED = 1726; + /// The remote procedure call failed and did not execute. pub const RPC_S_CALL_FAILED_DNE = 1727; + /// A remote procedure call (RPC) protocol error occurred. pub const RPC_S_PROTOCOL_ERROR = 1728; + /// Access to the HTTP proxy is denied. pub const RPC_S_PROXY_ACCESS_DENIED = 1729; + /// The transfer syntax is not supported by the RPC server. pub const RPC_S_UNSUPPORTED_TRANS_SYN = 1730; + /// The universal unique identifier (UUID) type is not supported. pub const RPC_S_UNSUPPORTED_TYPE = 1732; + /// The tag is invalid. pub const RPC_S_INVALID_TAG = 1733; + /// The array bounds are invalid. pub const RPC_S_INVALID_BOUND = 1734; + /// The binding does not contain an entry name. pub const RPC_S_NO_ENTRY_NAME = 1735; + /// The name syntax is invalid. pub const RPC_S_INVALID_NAME_SYNTAX = 1736; + /// The name syntax is not supported. pub const RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737; + /// No network address is available to use to construct a universal unique identifier (UUID). pub const RPC_S_UUID_NO_ADDRESS = 1739; + /// The endpoint is a duplicate. pub const RPC_S_DUPLICATE_ENDPOINT = 1740; + /// The authentication type is unknown. pub const RPC_S_UNKNOWN_AUTHN_TYPE = 1741; + /// The maximum number of calls is too small. pub const RPC_S_MAX_CALLS_TOO_SMALL = 1742; + /// The string is too long. pub const RPC_S_STRING_TOO_LONG = 1743; + /// The RPC protocol sequence was not found. pub const RPC_S_PROTSEQ_NOT_FOUND = 1744; + /// The procedure number is out of range. pub const RPC_S_PROCNUM_OUT_OF_RANGE = 1745; + /// The binding does not contain any authentication information. pub const RPC_S_BINDING_HAS_NO_AUTH = 1746; + /// The authentication service is unknown. pub const RPC_S_UNKNOWN_AUTHN_SERVICE = 1747; + /// The authentication level is unknown. pub const RPC_S_UNKNOWN_AUTHN_LEVEL = 1748; + /// The security context is invalid. pub const RPC_S_INVALID_AUTH_IDENTITY = 1749; + /// The authorization service is unknown. pub const RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750; + /// The entry is invalid. pub const EPT_S_INVALID_ENTRY = 1751; + /// The server endpoint cannot perform the operation. pub const EPT_S_CANT_PERFORM_OP = 1752; + /// There are no more endpoints available from the endpoint mapper. pub const EPT_S_NOT_REGISTERED = 1753; + /// No interfaces have been exported. pub const RPC_S_NOTHING_TO_EXPORT = 1754; + /// The entry name is incomplete. pub const RPC_S_INCOMPLETE_NAME = 1755; + /// The version option is invalid. pub const RPC_S_INVALID_VERS_OPTION = 1756; + /// There are no more members. pub const RPC_S_NO_MORE_MEMBERS = 1757; + /// There is nothing to unexport. pub const RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758; + /// The interface was not found. pub const RPC_S_INTERFACE_NOT_FOUND = 1759; + /// The entry already exists. pub const RPC_S_ENTRY_ALREADY_EXISTS = 1760; + /// The entry is not found. pub const RPC_S_ENTRY_NOT_FOUND = 1761; + /// The name service is unavailable. pub const RPC_S_NAME_SERVICE_UNAVAILABLE = 1762; + /// The network address family is invalid. pub const RPC_S_INVALID_NAF_ID = 1763; + /// The requested operation is not supported. pub const RPC_S_CANNOT_SUPPORT = 1764; + /// No security context is available to allow impersonation. pub const RPC_S_NO_CONTEXT_AVAILABLE = 1765; + /// An internal error occurred in a remote procedure call (RPC). pub const RPC_S_INTERNAL_ERROR = 1766; + /// The RPC server attempted an integer division by zero. pub const RPC_S_ZERO_DIVIDE = 1767; + /// An addressing error occurred in the RPC server. pub const RPC_S_ADDRESS_ERROR = 1768; + /// A floating-point operation at the RPC server caused a division by zero. pub const RPC_S_FP_DIV_ZERO = 1769; + /// A floating-point underflow occurred at the RPC server. pub const RPC_S_FP_UNDERFLOW = 1770; + /// A floating-point overflow occurred at the RPC server. pub const RPC_S_FP_OVERFLOW = 1771; + /// The list of RPC servers available for the binding of auto handles has been exhausted. pub const RPC_X_NO_MORE_ENTRIES = 1772; + /// Unable to open the character translation table file. pub const RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773; + /// The file containing the character translation table has fewer than 512 bytes. pub const RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774; + /// A null context handle was passed from the client to the host during a remote procedure call. pub const RPC_X_SS_IN_NULL_CONTEXT = 1775; + /// The context handle changed during a remote procedure call. pub const RPC_X_SS_CONTEXT_DAMAGED = 1777; + /// The binding handles passed to a remote procedure call do not match. pub const RPC_X_SS_HANDLES_MISMATCH = 1778; + /// The stub is unable to get the remote procedure call handle. pub const RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779; + /// A null reference pointer was passed to the stub. pub const RPC_X_NULL_REF_POINTER = 1780; + /// The enumeration value is out of range. pub const RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781; + /// The byte count is too small. pub const RPC_X_BYTE_COUNT_TOO_SMALL = 1782; + /// The stub received bad data. pub const RPC_X_BAD_STUB_DATA = 1783; + /// The supplied user buffer is not valid for the requested operation. pub const INVALID_USER_BUFFER = 1784; + /// The disk media is not recognized. It may not be formatted. pub const UNRECOGNIZED_MEDIA = 1785; + /// The workstation does not have a trust secret. pub const NO_TRUST_LSA_SECRET = 1786; + /// The security database on the server does not have a computer account for this workstation trust relationship. pub const NO_TRUST_SAM_ACCOUNT = 1787; + /// The trust relationship between the primary domain and the trusted domain failed. pub const TRUSTED_DOMAIN_FAILURE = 1788; + /// The trust relationship between this workstation and the primary domain failed. pub const TRUSTED_RELATIONSHIP_FAILURE = 1789; + /// The network logon failed. pub const TRUST_FAILURE = 1790; + /// A remote procedure call is already in progress for this thread. pub const RPC_S_CALL_IN_PROGRESS = 1791; + /// An attempt was made to logon, but the network logon service was not started. pub const NETLOGON_NOT_STARTED = 1792; + /// The user's account has expired. pub const ACCOUNT_EXPIRED = 1793; + /// The redirector is in use and cannot be unloaded. pub const REDIRECTOR_HAS_OPEN_HANDLES = 1794; + /// The specified printer driver is already installed. pub const PRINTER_DRIVER_ALREADY_INSTALLED = 1795; + /// The specified port is unknown. pub const UNKNOWN_PORT = 1796; + /// The printer driver is unknown. pub const UNKNOWN_PRINTER_DRIVER = 1797; + /// The print processor is unknown. pub const UNKNOWN_PRINTPROCESSOR = 1798; + /// The specified separator file is invalid. pub const INVALID_SEPARATOR_FILE = 1799; + /// The specified priority is invalid. pub const INVALID_PRIORITY = 1800; + /// The printer name is invalid. pub const INVALID_PRINTER_NAME = 1801; + /// The printer already exists. pub const PRINTER_ALREADY_EXISTS = 1802; + /// The printer command is invalid. pub const INVALID_PRINTER_COMMAND = 1803; + /// The specified datatype is invalid. pub const INVALID_DATATYPE = 1804; + /// The environment specified is invalid. pub const INVALID_ENVIRONMENT = 1805; + /// There are no more bindings. pub const RPC_S_NO_MORE_BINDINGS = 1806; + /// The account used is an interdomain trust account. Use your global user account or local user account to access this server. pub const NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807; + /// The account used is a computer account. Use your global user account or local user account to access this server. pub const NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808; + /// The account used is a server trust account. Use your global user account or local user account to access this server. pub const NOLOGON_SERVER_TRUST_ACCOUNT = 1809; + /// The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain. pub const DOMAIN_TRUST_INCONSISTENT = 1810; + /// The server is in use and cannot be unloaded. pub const SERVER_HAS_OPEN_HANDLES = 1811; + /// The specified image file did not contain a resource section. pub const RESOURCE_DATA_NOT_FOUND = 1812; + /// The specified resource type cannot be found in the image file. pub const RESOURCE_TYPE_NOT_FOUND = 1813; + /// The specified resource name cannot be found in the image file. pub const RESOURCE_NAME_NOT_FOUND = 1814; + /// The specified resource language ID cannot be found in the image file. pub const RESOURCE_LANG_NOT_FOUND = 1815; + /// Not enough quota is available to process this command. pub const NOT_ENOUGH_QUOTA = 1816; + /// No interfaces have been registered. pub const RPC_S_NO_INTERFACES = 1817; + /// The remote procedure call was cancelled. pub const RPC_S_CALL_CANCELLED = 1818; + /// The binding handle does not contain all required information. pub const RPC_S_BINDING_INCOMPLETE = 1819; + /// A communications failure occurred during a remote procedure call. pub const RPC_S_COMM_FAILURE = 1820; + /// The requested authentication level is not supported. pub const RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821; + /// No principal name registered. pub const RPC_S_NO_PRINC_NAME = 1822; + /// The error specified is not a valid Windows RPC error code. pub const RPC_S_NOT_RPC_ERROR = 1823; + /// A UUID that is valid only on this computer has been allocated. pub const RPC_S_UUID_LOCAL_ONLY = 1824; + /// A security package specific error occurred. pub const RPC_S_SEC_PKG_ERROR = 1825; + /// Thread is not canceled. pub const RPC_S_NOT_CANCELLED = 1826; + /// Invalid operation on the encoding/decoding handle. pub const RPC_X_INVALID_ES_ACTION = 1827; + /// Incompatible version of the serializing package. pub const RPC_X_WRONG_ES_VERSION = 1828; + /// Incompatible version of the RPC stub. pub const RPC_X_WRONG_STUB_VERSION = 1829; + /// The RPC pipe object is invalid or corrupted. pub const RPC_X_INVALID_PIPE_OBJECT = 1830; + /// An invalid operation was attempted on an RPC pipe object. pub const RPC_X_WRONG_PIPE_ORDER = 1831; + /// Unsupported RPC pipe version. pub const RPC_X_WRONG_PIPE_VERSION = 1832; + /// HTTP proxy server rejected the connection because the cookie authentication failed. pub const RPC_S_COOKIE_AUTH_FAILED = 1833; + /// The group member was not found. pub const RPC_S_GROUP_MEMBER_NOT_FOUND = 1898; + /// The endpoint mapper database entry could not be created. pub const EPT_S_CANT_CREATE = 1899; + /// The object universal unique identifier (UUID) is the nil UUID. pub const RPC_S_INVALID_OBJECT = 1900; + /// The specified time is invalid. pub const INVALID_TIME = 1901; + /// The specified form name is invalid. pub const INVALID_FORM_NAME = 1902; + /// The specified form size is invalid. pub const INVALID_FORM_SIZE = 1903; + /// The specified printer handle is already being waited on. pub const ALREADY_WAITING = 1904; + /// The specified printer has been deleted. pub const PRINTER_DELETED = 1905; + /// The state of the printer is invalid. pub const INVALID_PRINTER_STATE = 1906; + /// The user's password must be changed before signing in. pub const PASSWORD_MUST_CHANGE = 1907; + /// Could not find the domain controller for this domain. pub const DOMAIN_CONTROLLER_NOT_FOUND = 1908; + /// The referenced account is currently locked out and may not be logged on to. pub const ACCOUNT_LOCKED_OUT = 1909; + /// The object exporter specified was not found. pub const OR_INVALID_OXID = 1910; + /// The object specified was not found. pub const OR_INVALID_OID = 1911; + /// The object resolver set specified was not found. pub const OR_INVALID_SET = 1912; + /// Some data remains to be sent in the request buffer. pub const RPC_S_SEND_INCOMPLETE = 1913; + /// Invalid asynchronous remote procedure call handle. pub const RPC_S_INVALID_ASYNC_HANDLE = 1914; + /// Invalid asynchronous RPC call handle for this operation. pub const RPC_S_INVALID_ASYNC_CALL = 1915; + /// The RPC pipe object has already been closed. pub const RPC_X_PIPE_CLOSED = 1916; + /// The RPC call completed before all pipes were processed. pub const RPC_X_PIPE_DISCIPLINE_ERROR = 1917; + /// No more data is available from the RPC pipe. pub const RPC_X_PIPE_EMPTY = 1918; + /// No site name is available for this machine. pub const NO_SITENAME = 1919; + /// The file cannot be accessed by the system. pub const CANT_ACCESS_FILE = 1920; + /// The name of the file cannot be resolved by the system. pub const CANT_RESOLVE_FILENAME = 1921; + /// The entry is not of the expected type. pub const RPC_S_ENTRY_TYPE_MISMATCH = 1922; + /// Not all object UUIDs could be exported to the specified entry. pub const RPC_S_NOT_ALL_OBJS_EXPORTED = 1923; + /// Interface could not be exported to the specified entry. pub const RPC_S_INTERFACE_NOT_EXPORTED = 1924; + /// The specified profile entry could not be added. pub const RPC_S_PROFILE_NOT_ADDED = 1925; + /// The specified profile element could not be added. pub const RPC_S_PRF_ELT_NOT_ADDED = 1926; + /// The specified profile element could not be removed. pub const RPC_S_PRF_ELT_NOT_REMOVED = 1927; + /// The group element could not be added. pub const RPC_S_GRP_ELT_NOT_ADDED = 1928; + /// The group element could not be removed. pub const RPC_S_GRP_ELT_NOT_REMOVED = 1929; + /// The printer driver is not compatible with a policy enabled on your computer that blocks NT 4.0 drivers. pub const KM_DRIVER_BLOCKED = 1930; + /// The context has expired and can no longer be used. pub const CONTEXT_EXPIRED = 1931; + /// The current user's delegated trust creation quota has been exceeded. pub const PER_USER_TRUST_QUOTA_EXCEEDED = 1932; + /// The total delegated trust creation quota has been exceeded. pub const ALL_USER_TRUST_QUOTA_EXCEEDED = 1933; + /// The current user's delegated trust deletion quota has been exceeded. pub const USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934; + /// The computer you are signing into is protected by an authentication firewall. The specified account is not allowed to authenticate to the computer. pub const AUTHENTICATION_FIREWALL_FAILED = 1935; + /// Remote connections to the Print Spooler are blocked by a policy set on your machine. pub const REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936; + /// Authentication failed because NTLM authentication has been disabled. pub const NTLM_BLOCKED = 1937; + /// Logon Failure: EAS policy requires that the user change their password before this operation can be performed. pub const PASSWORD_CHANGE_REQUIRED = 1938; + /// The pixel format is invalid. pub const INVALID_PIXEL_FORMAT = 2000; + /// The specified driver is invalid. pub const BAD_DRIVER = 2001; + /// The window style or class attribute is invalid for this operation. pub const INVALID_WINDOW_STYLE = 2002; + /// The requested metafile operation is not supported. pub const METAFILE_NOT_SUPPORTED = 2003; + /// The requested transformation operation is not supported. pub const TRANSFORM_NOT_SUPPORTED = 2004; + /// The requested clipping operation is not supported. pub const CLIPPING_NOT_SUPPORTED = 2005; + /// The specified color management module is invalid. pub const INVALID_CMM = 2010; + /// The specified color profile is invalid. pub const INVALID_PROFILE = 2011; + /// The specified tag was not found. pub const TAG_NOT_FOUND = 2012; + /// A required tag is not present. pub const TAG_NOT_PRESENT = 2013; + /// The specified tag is already present. pub const DUPLICATE_TAG = 2014; + /// The specified color profile is not associated with the specified device. pub const PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015; + /// The specified color profile was not found. pub const PROFILE_NOT_FOUND = 2016; + /// The specified color space is invalid. pub const INVALID_COLORSPACE = 2017; + /// Image Color Management is not enabled. pub const ICM_NOT_ENABLED = 2018; + /// There was an error while deleting the color transform. pub const DELETING_ICM_XFORM = 2019; + /// The specified color transform is invalid. pub const INVALID_TRANSFORM = 2020; + /// The specified transform does not match the bitmap's color space. pub const COLORSPACE_MISMATCH = 2021; + /// The specified named color index is not present in the profile. pub const INVALID_COLORINDEX = 2022; + /// The specified profile is intended for a device of a different type than the specified device. pub const PROFILE_DOES_NOT_MATCH_DEVICE = 2023; + /// The network connection was made successfully, but the user had to be prompted for a password other than the one originally specified. pub const CONNECTED_OTHER_PASSWORD = 2108; + /// The network connection was made successfully using default credentials. pub const CONNECTED_OTHER_PASSWORD_DEFAULT = 2109; + /// The specified username is invalid. pub const BAD_USERNAME = 2202; + /// This network connection does not exist. pub const NOT_CONNECTED = 2250; + /// This network connection has files open or requests pending. pub const OPEN_FILES = 2401; + /// Active connections still exist. pub const ACTIVE_CONNECTIONS = 2402; + /// The device is in use by an active process and cannot be disconnected. pub const DEVICE_IN_USE = 2404; + /// The specified print monitor is unknown. pub const UNKNOWN_PRINT_MONITOR = 3000; + /// The specified printer driver is currently in use. pub const PRINTER_DRIVER_IN_USE = 3001; + /// The spool file was not found. pub const SPOOL_FILE_NOT_FOUND = 3002; + /// A StartDocPrinter call was not issued. pub const SPL_NO_STARTDOC = 3003; + /// An AddJob call was not issued. pub const SPL_NO_ADDJOB = 3004; + /// The specified print processor has already been installed. pub const PRINT_PROCESSOR_ALREADY_INSTALLED = 3005; + /// The specified print monitor has already been installed. pub const PRINT_MONITOR_ALREADY_INSTALLED = 3006; + /// The specified print monitor does not have the required functions. pub const INVALID_PRINT_MONITOR = 3007; + /// The specified print monitor is currently in use. pub const PRINT_MONITOR_IN_USE = 3008; + /// The requested operation is not allowed when there are jobs queued to the printer. pub const PRINTER_HAS_JOBS_QUEUED = 3009; + /// The requested operation is successful. Changes will not be effective until the system is rebooted. pub const SUCCESS_REBOOT_REQUIRED = 3010; + /// The requested operation is successful. Changes will not be effective until the service is restarted. pub const SUCCESS_RESTART_REQUIRED = 3011; + /// No printers were found. pub const PRINTER_NOT_FOUND = 3012; + /// The printer driver is known to be unreliable. pub const PRINTER_DRIVER_WARNED = 3013; + /// The printer driver is known to harm the system. pub const PRINTER_DRIVER_BLOCKED = 3014; + /// The specified printer driver package is currently in use. pub const PRINTER_DRIVER_PACKAGE_IN_USE = 3015; + /// Unable to find a core driver package that is required by the printer driver package. pub const CORE_DRIVER_PACKAGE_NOT_FOUND = 3016; + /// The requested operation failed. A system reboot is required to roll back changes made. pub const FAIL_REBOOT_REQUIRED = 3017; + /// The requested operation failed. A system reboot has been initiated to roll back changes made. pub const FAIL_REBOOT_INITIATED = 3018; + /// The specified printer driver was not found on the system and needs to be downloaded. pub const PRINTER_DRIVER_DOWNLOAD_NEEDED = 3019; + /// The requested print job has failed to print. A print system update requires the job to be resubmitted. pub const PRINT_JOB_RESTART_REQUIRED = 3020; + /// The printer driver does not contain a valid manifest, or contains too many manifests. pub const INVALID_PRINTER_DRIVER_MANIFEST = 3021; + /// The specified printer cannot be shared. pub const PRINTER_NOT_SHAREABLE = 3022; + /// The operation was paused. pub const REQUEST_PAUSED = 3050; + /// Reissue the given operation as a cached IO operation. pub const IO_REISSUE_AS_CACHED = 3950; diff --git a/std/os/windows/index.zig b/std/os/windows/index.zig index e13ed0f131..426514f7d7 100644 --- a/std/os/windows/index.zig +++ b/std/os/windows/index.zig @@ -1,33 +1,59 @@ pub const ERROR = @import("error.zig"); -pub extern "advapi32" stdcallcc fn CryptAcquireContextA(phProv: &HCRYPTPROV, pszContainer: ?LPCSTR, - pszProvider: ?LPCSTR, dwProvType: DWORD, dwFlags: DWORD) BOOL; +pub extern "advapi32" stdcallcc fn CryptAcquireContextA( + phProv: &HCRYPTPROV, + pszContainer: ?LPCSTR, + pszProvider: ?LPCSTR, + dwProvType: DWORD, + dwFlags: DWORD, +) BOOL; pub extern "advapi32" stdcallcc fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) BOOL; pub extern "advapi32" stdcallcc fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: &BYTE) BOOL; - pub extern "kernel32" stdcallcc fn CloseHandle(hObject: HANDLE) BOOL; -pub extern "kernel32" stdcallcc fn CreateDirectoryA(lpPathName: LPCSTR, - lpSecurityAttributes: ?&SECURITY_ATTRIBUTES) BOOL; +pub extern "kernel32" stdcallcc fn CreateDirectoryA( + lpPathName: LPCSTR, + lpSecurityAttributes: ?&SECURITY_ATTRIBUTES, +) BOOL; -pub extern "kernel32" stdcallcc fn CreateFileA(lpFileName: LPCSTR, dwDesiredAccess: DWORD, - dwShareMode: DWORD, lpSecurityAttributes: ?LPSECURITY_ATTRIBUTES, dwCreationDisposition: DWORD, - dwFlagsAndAttributes: DWORD, hTemplateFile: ?HANDLE) HANDLE; +pub extern "kernel32" stdcallcc fn CreateFileA( + lpFileName: LPCSTR, + dwDesiredAccess: DWORD, + dwShareMode: DWORD, + lpSecurityAttributes: ?LPSECURITY_ATTRIBUTES, + dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, + hTemplateFile: ?HANDLE, +) HANDLE; -pub extern "kernel32" stdcallcc fn CreatePipe(hReadPipe: &HANDLE, hWritePipe: &HANDLE, - lpPipeAttributes: &const SECURITY_ATTRIBUTES, nSize: DWORD) BOOL; +pub extern "kernel32" stdcallcc fn CreatePipe( + hReadPipe: &HANDLE, + hWritePipe: &HANDLE, + lpPipeAttributes: &const SECURITY_ATTRIBUTES, + nSize: DWORD, +) BOOL; -pub extern "kernel32" stdcallcc fn CreateProcessA(lpApplicationName: ?LPCSTR, lpCommandLine: LPSTR, - lpProcessAttributes: ?&SECURITY_ATTRIBUTES, lpThreadAttributes: ?&SECURITY_ATTRIBUTES, bInheritHandles: BOOL, - dwCreationFlags: DWORD, lpEnvironment: ?&c_void, lpCurrentDirectory: ?LPCSTR, lpStartupInfo: &STARTUPINFOA, - lpProcessInformation: &PROCESS_INFORMATION) BOOL; - -pub extern "kernel32" stdcallcc fn CreateSymbolicLinkA(lpSymlinkFileName: LPCSTR, lpTargetFileName: LPCSTR, - dwFlags: DWORD) BOOLEAN; +pub extern "kernel32" stdcallcc fn CreateProcessA( + lpApplicationName: ?LPCSTR, + lpCommandLine: LPSTR, + lpProcessAttributes: ?&SECURITY_ATTRIBUTES, + lpThreadAttributes: ?&SECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: ?&c_void, + lpCurrentDirectory: ?LPCSTR, + lpStartupInfo: &STARTUPINFOA, + lpProcessInformation: &PROCESS_INFORMATION, +) BOOL; +pub extern "kernel32" stdcallcc fn CreateSymbolicLinkA( + lpSymlinkFileName: LPCSTR, + lpTargetFileName: LPCSTR, + dwFlags: DWORD, +) BOOLEAN; pub extern "kernel32" stdcallcc fn CreateThread(lpThreadAttributes: ?LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: ?LPVOID, dwCreationFlags: DWORD, lpThreadId: ?LPDWORD) ?HANDLE; @@ -55,12 +81,19 @@ pub extern "kernel32" stdcallcc fn GetModuleFileNameA(hModule: ?HMODULE, lpFilen pub extern "kernel32" stdcallcc fn GetLastError() DWORD; -pub extern "kernel32" stdcallcc fn GetFileInformationByHandleEx(in_hFile: HANDLE, - in_FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, out_lpFileInformation: &c_void, - in_dwBufferSize: DWORD) BOOL; +pub extern "kernel32" stdcallcc fn GetFileInformationByHandleEx( + in_hFile: HANDLE, + in_FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, + out_lpFileInformation: &c_void, + in_dwBufferSize: DWORD, +) BOOL; -pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA(hFile: HANDLE, lpszFilePath: LPSTR, - cchFilePath: DWORD, dwFlags: DWORD) DWORD; +pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA( + hFile: HANDLE, + lpszFilePath: LPSTR, + cchFilePath: DWORD, + dwFlags: DWORD, +) DWORD; pub extern "kernel32" stdcallcc fn GetProcessHeap() ?HANDLE; @@ -80,21 +113,32 @@ pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBy pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void) BOOL; -pub extern "kernel32" stdcallcc fn MoveFileExA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, - dwFlags: DWORD) BOOL; - +pub extern "kernel32" stdcallcc fn MoveFileExA( + lpExistingFileName: LPCSTR, + lpNewFileName: LPCSTR, + dwFlags: DWORD, +) BOOL; + pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: &LARGE_INTEGER) BOOL; pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: &LARGE_INTEGER) BOOL; pub extern "kernel32" stdcallcc fn PathFileExists(pszPath: ?LPCTSTR) BOOL; -pub extern "kernel32" stdcallcc fn ReadFile(in_hFile: HANDLE, out_lpBuffer: &c_void, - in_nNumberOfBytesToRead: DWORD, out_lpNumberOfBytesRead: &DWORD, - in_out_lpOverlapped: ?&OVERLAPPED) BOOL; +pub extern "kernel32" stdcallcc fn ReadFile( + in_hFile: HANDLE, + out_lpBuffer: &c_void, + in_nNumberOfBytesToRead: DWORD, + out_lpNumberOfBytesRead: &DWORD, + in_out_lpOverlapped: ?&OVERLAPPED, +) BOOL; -pub extern "kernel32" stdcallcc fn SetFilePointerEx(in_fFile: HANDLE, in_liDistanceToMove: LARGE_INTEGER, - out_opt_ldNewFilePointer: ?&LARGE_INTEGER, in_dwMoveMethod: DWORD) BOOL; +pub extern "kernel32" stdcallcc fn SetFilePointerEx( + in_fFile: HANDLE, + in_liDistanceToMove: LARGE_INTEGER, + out_opt_ldNewFilePointer: ?&LARGE_INTEGER, + in_dwMoveMethod: DWORD, +) BOOL; pub extern "kernel32" stdcallcc fn SetHandleInformation(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD) BOOL; @@ -104,14 +148,18 @@ pub extern "kernel32" stdcallcc fn TerminateProcess(hProcess: HANDLE, uExitCode: pub extern "kernel32" stdcallcc fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) DWORD; -pub extern "kernel32" stdcallcc fn WriteFile(in_hFile: HANDLE, in_lpBuffer: &const c_void, - in_nNumberOfBytesToWrite: DWORD, out_lpNumberOfBytesWritten: ?&DWORD, - in_out_lpOverlapped: ?&OVERLAPPED) BOOL; +pub extern "kernel32" stdcallcc fn WriteFile( + in_hFile: HANDLE, + in_lpBuffer: &const c_void, + in_nNumberOfBytesToWrite: DWORD, + out_lpNumberOfBytesWritten: ?&DWORD, + in_out_lpOverlapped: ?&OVERLAPPED, +) BOOL; //TODO: call unicode versions instead of relying on ANSI code page pub extern "kernel32" stdcallcc fn LoadLibraryA(lpLibFileName: LPCSTR) ?HMODULE; -pub extern "kernel32" stdcallcc fn FreeLibrary(hModule: HMODULE) BOOL; +pub extern "kernel32" stdcallcc fn FreeLibrary(hModule: HMODULE) BOOL; pub extern "user32" stdcallcc fn MessageBoxA(hWnd: ?HANDLE, lpText: ?LPCTSTR, lpCaption: ?LPCTSTR, uType: UINT) c_int; @@ -176,49 +224,51 @@ pub const MAX_PATH = 260; // TODO issue #305 pub const FILE_INFO_BY_HANDLE_CLASS = u32; -pub const FileBasicInfo = 0; -pub const FileStandardInfo = 1; -pub const FileNameInfo = 2; -pub const FileRenameInfo = 3; -pub const FileDispositionInfo = 4; -pub const FileAllocationInfo = 5; -pub const FileEndOfFileInfo = 6; -pub const FileStreamInfo = 7; -pub const FileCompressionInfo = 8; -pub const FileAttributeTagInfo = 9; -pub const FileIdBothDirectoryInfo = 10; -pub const FileIdBothDirectoryRestartInfo = 11; -pub const FileIoPriorityHintInfo = 12; -pub const FileRemoteProtocolInfo = 13; -pub const FileFullDirectoryInfo = 14; -pub const FileFullDirectoryRestartInfo = 15; -pub const FileStorageInfo = 16; -pub const FileAlignmentInfo = 17; -pub const FileIdInfo = 18; -pub const FileIdExtdDirectoryInfo = 19; -pub const FileIdExtdDirectoryRestartInfo = 20; +pub const FileBasicInfo = 0; +pub const FileStandardInfo = 1; +pub const FileNameInfo = 2; +pub const FileRenameInfo = 3; +pub const FileDispositionInfo = 4; +pub const FileAllocationInfo = 5; +pub const FileEndOfFileInfo = 6; +pub const FileStreamInfo = 7; +pub const FileCompressionInfo = 8; +pub const FileAttributeTagInfo = 9; +pub const FileIdBothDirectoryInfo = 10; +pub const FileIdBothDirectoryRestartInfo = 11; +pub const FileIoPriorityHintInfo = 12; +pub const FileRemoteProtocolInfo = 13; +pub const FileFullDirectoryInfo = 14; +pub const FileFullDirectoryRestartInfo = 15; +pub const FileStorageInfo = 16; +pub const FileAlignmentInfo = 17; +pub const FileIdInfo = 18; +pub const FileIdExtdDirectoryInfo = 19; +pub const FileIdExtdDirectoryRestartInfo = 20; pub const FILE_NAME_INFO = extern struct { FileNameLength: DWORD, FileName: [1]WCHAR, }; - /// Return the normalized drive name. This is the default. pub const FILE_NAME_NORMALIZED = 0x0; + /// Return the opened file name (not normalized). pub const FILE_NAME_OPENED = 0x8; /// Return the path with the drive letter. This is the default. pub const VOLUME_NAME_DOS = 0x0; + /// Return the path with a volume GUID path instead of the drive name. pub const VOLUME_NAME_GUID = 0x1; + /// Return the path with no drive information. pub const VOLUME_NAME_NONE = 0x4; + /// Return the path with the volume device path. pub const VOLUME_NAME_NT = 0x2; - pub const SECURITY_ATTRIBUTES = extern struct { nLength: DWORD, lpSecurityDescriptor: ?&c_void, @@ -227,7 +277,6 @@ pub const SECURITY_ATTRIBUTES = extern struct { pub const PSECURITY_ATTRIBUTES = &SECURITY_ATTRIBUTES; pub const LPSECURITY_ATTRIBUTES = &SECURITY_ATTRIBUTES; - pub const GENERIC_READ = 0x80000000; pub const GENERIC_WRITE = 0x40000000; pub const GENERIC_EXECUTE = 0x20000000; @@ -243,7 +292,6 @@ pub const OPEN_ALWAYS = 4; pub const OPEN_EXISTING = 3; pub const TRUNCATE_EXISTING = 5; - pub const FILE_ATTRIBUTE_ARCHIVE = 0x20; pub const FILE_ATTRIBUTE_ENCRYPTED = 0x4000; pub const FILE_ATTRIBUTE_HIDDEN = 0x2; diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index 5af318b7b0..7b7fdfae08 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -7,7 +7,7 @@ const mem = std.mem; const BufMap = std.BufMap; const cstr = std.cstr; -pub const WaitError = error { +pub const WaitError = error{ WaitAbandoned, WaitTimeOut, Unexpected, @@ -33,7 +33,7 @@ pub fn windowsClose(handle: windows.HANDLE) void { assert(windows.CloseHandle(handle) != 0); } -pub const WriteError = error { +pub const WriteError = error{ SystemResources, OperationAborted, IoPending, @@ -68,20 +68,18 @@ pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool { const size = @sizeOf(windows.FILE_NAME_INFO); var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = []u8{0} ** (size + windows.MAX_PATH); - if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, - @ptrCast(&c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) - { + if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, @ptrCast(&c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) { return true; } const name_info = @ptrCast(&const windows.FILE_NAME_INFO, &name_info_bytes[0]); const name_bytes = name_info_bytes[size..size + usize(name_info.FileNameLength)]; - const name_wide = ([]u16)(name_bytes); - return mem.indexOf(u16, name_wide, []u16{'m','s','y','s','-'}) != null or - mem.indexOf(u16, name_wide, []u16{'-','p','t','y'}) != null; + const name_wide = ([]u16)(name_bytes); + return mem.indexOf(u16, name_wide, []u16{ 'm', 's', 'y', 's', '-' }) != null or + mem.indexOf(u16, name_wide, []u16{ '-', 'p', 't', 'y' }) != null; } -pub const OpenError = error { +pub const OpenError = error{ SharingViolation, PathAlreadyExists, FileNotFound, @@ -92,15 +90,18 @@ pub const OpenError = error { }; /// `file_path` needs to be copied in memory to add a null terminating byte, hence the allocator. -pub fn windowsOpen(allocator: &mem.Allocator, file_path: []const u8, desired_access: windows.DWORD, share_mode: windows.DWORD, - creation_disposition: windows.DWORD, flags_and_attrs: windows.DWORD) - OpenError!windows.HANDLE -{ +pub fn windowsOpen( + allocator: &mem.Allocator, + file_path: []const u8, + desired_access: windows.DWORD, + share_mode: windows.DWORD, + creation_disposition: windows.DWORD, + flags_and_attrs: windows.DWORD, +) OpenError!windows.HANDLE { const path_with_null = try cstr.addNullByte(allocator, file_path); defer allocator.free(path_with_null); - const result = windows.CreateFileA(path_with_null.ptr, desired_access, share_mode, null, creation_disposition, - flags_and_attrs, null); + const result = windows.CreateFileA(path_with_null.ptr, desired_access, share_mode, null, creation_disposition, flags_and_attrs, null); if (result == windows.INVALID_HANDLE_VALUE) { const err = windows.GetLastError(); @@ -156,18 +157,16 @@ pub fn windowsLoadDll(allocator: &mem.Allocator, dll_path: []const u8) !windows. } pub fn windowsUnloadDll(hModule: windows.HMODULE) void { - assert(windows.FreeLibrary(hModule)!= 0); + assert(windows.FreeLibrary(hModule) != 0); } - test "InvalidDll" { if (builtin.os != builtin.Os.windows) return; const DllName = "asdf.dll"; const allocator = std.debug.global_allocator; - const handle = os.windowsLoadDll(allocator, DllName) catch |err| { + const handle = os.windowsLoadDll(allocator, DllName) catch |err| { assert(err == error.DllNotFound); return; }; } - diff --git a/std/os/zen.zig b/std/os/zen.zig index 51528ca391..7517cc0d69 100644 --- a/std/os/zen.zig +++ b/std/os/zen.zig @@ -3,35 +3,35 @@ ////////////////////////// pub const Message = struct { - sender: MailboxId, + sender: MailboxId, receiver: MailboxId, - type: usize, - payload: usize, + type: usize, + payload: usize, pub fn from(mailbox_id: &const MailboxId) Message { - return Message { - .sender = MailboxId.Undefined, + return Message{ + .sender = MailboxId.Undefined, .receiver = *mailbox_id, - .type = 0, - .payload = 0, + .type = 0, + .payload = 0, }; } pub fn to(mailbox_id: &const MailboxId, msg_type: usize) Message { - return Message { - .sender = MailboxId.This, + return Message{ + .sender = MailboxId.This, .receiver = *mailbox_id, - .type = msg_type, - .payload = 0, + .type = msg_type, + .payload = 0, }; } pub fn withData(mailbox_id: &const MailboxId, msg_type: usize, payload: usize) Message { - return Message { - .sender = MailboxId.This, + return Message{ + .sender = MailboxId.This, .receiver = *mailbox_id, - .type = msg_type, - .payload = payload, + .type = msg_type, + .payload = payload, }; } }; @@ -40,27 +40,25 @@ pub const MailboxId = union(enum) { Undefined, This, Kernel, - Port: u16, + Port: u16, Thread: u16, }; - ////////////////////////////////////// //// Ports reserved for servers //// ////////////////////////////////////// pub const Server = struct { - pub const Keyboard = MailboxId { .Port = 0 }; - pub const Terminal = MailboxId { .Port = 1 }; + pub const Keyboard = MailboxId{ .Port = 0 }; + pub const Terminal = MailboxId{ .Port = 1 }; }; - //////////////////////// //// POSIX things //// //////////////////////// // Standard streams. -pub const STDIN_FILENO = 0; +pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; @@ -101,26 +99,24 @@ pub fn write(fd: i32, buf: &const u8, count: usize) usize { return count; } - /////////////////////////// //// Syscall numbers //// /////////////////////////// pub const Syscall = enum(usize) { - exit = 0, - createPort = 1, - send = 2, - receive = 3, - subscribeIRQ = 4, - inb = 5, - map = 6, - createThread = 7, + exit = 0, + createPort = 1, + send = 2, + receive = 3, + subscribeIRQ = 4, + inb = 5, + map = 6, + createThread = 7, createProcess = 8, - wait = 9, - portReady = 10, + wait = 9, + portReady = 10, }; - //////////////////// //// Syscalls //// //////////////////// @@ -157,7 +153,7 @@ pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool { return syscall4(Syscall.map, v_addr, p_addr, size, usize(writable)) != 0; } -pub fn createThread(function: fn()void) u16 { +pub fn createThread(function: fn() void) u16 { return u16(syscall1(Syscall.createThread, @ptrToInt(function))); } @@ -180,66 +176,84 @@ pub fn portReady(port: u16) bool { inline fn syscall0(number: Syscall) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number)); + : [number] "{eax}" (number) + ); } inline fn syscall1(number: Syscall, arg1: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1)); + [arg1] "{ecx}" (arg1) + ); } inline fn syscall2(number: Syscall, arg1: usize, arg2: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2) + ); } inline fn syscall3(number: Syscall, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2), + [arg3] "{ebx}" (arg3) + ); } inline fn syscall4(number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2), + [arg3] "{ebx}" (arg3), + [arg4] "{esi}" (arg4) + ); } -inline fn syscall5(number: Syscall, arg1: usize, arg2: usize, arg3: usize, - arg4: usize, arg5: usize) usize -{ +inline fn syscall5( + number: Syscall, + arg1: usize, + arg2: usize, + arg3: usize, + arg4: usize, + arg5: usize, +) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4), - [arg5] "{edi}" (arg5)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2), + [arg3] "{ebx}" (arg3), + [arg4] "{esi}" (arg4), + [arg5] "{edi}" (arg5) + ); } -inline fn syscall6(number: Syscall, arg1: usize, arg2: usize, arg3: usize, - arg4: usize, arg5: usize, arg6: usize) usize -{ +inline fn syscall6( + number: Syscall, + arg1: usize, + arg2: usize, + arg3: usize, + arg4: usize, + arg5: usize, + arg6: usize, +) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4), - [arg5] "{edi}" (arg5), - [arg6] "{ebp}" (arg6)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2), + [arg3] "{ebx}" (arg3), + [arg4] "{esi}" (arg4), + [arg5] "{edi}" (arg5), + [arg6] "{ebp}" (arg6) + ); } diff --git a/std/rand/index.zig b/std/rand/index.zig index bd6209009e..68e6d3cb4d 100644 --- a/std/rand/index.zig +++ b/std/rand/index.zig @@ -69,7 +69,7 @@ pub const Random = struct { break :x start; } else x: { // Can't overflow because the range is over signed ints - break :x math.negateCast(value - end_uint) catch unreachable; + break :x math.negateCast(value - end_uint) catch unreachable; }; return result; } else { @@ -156,7 +156,7 @@ const SplitMix64 = struct { s: u64, pub fn init(seed: u64) SplitMix64 { - return SplitMix64 { .s = seed }; + return SplitMix64{ .s = seed }; } pub fn next(self: &SplitMix64) u64 { @@ -172,7 +172,7 @@ const SplitMix64 = struct { test "splitmix64 sequence" { var r = SplitMix64.init(0xaeecf86f7878dd75); - const seq = []const u64 { + const seq = []const u64{ 0x5dbd39db0178eb44, 0xa9900fb66b397da3, 0x5c1a28b1aeebcf5c, @@ -198,8 +198,8 @@ pub const Pcg = struct { i: u64, pub fn init(init_s: u64) Pcg { - var pcg = Pcg { - .random = Random { .fillFn = fill }, + var pcg = Pcg{ + .random = Random{ .fillFn = fill }, .s = undefined, .i = undefined, }; @@ -265,7 +265,7 @@ test "pcg sequence" { const s1: u64 = 0x84e9c579ef59bbf7; r.seedTwo(s0, s1); - const seq = []const u32 { + const seq = []const u32{ 2881561918, 3063928540, 1199791034, @@ -288,8 +288,8 @@ pub const Xoroshiro128 = struct { s: [2]u64, pub fn init(init_s: u64) Xoroshiro128 { - var x = Xoroshiro128 { - .random = Random { .fillFn = fill }, + var x = Xoroshiro128{ + .random = Random{ .fillFn = fill }, .s = undefined, }; @@ -314,9 +314,9 @@ pub const Xoroshiro128 = struct { var s0: u64 = 0; var s1: u64 = 0; - const table = []const u64 { + const table = []const u64{ 0xbeac0467eba5facb, - 0xd86b048b86aa9922 + 0xd86b048b86aa9922, }; inline for (table) |entry| { @@ -374,7 +374,7 @@ test "xoroshiro sequence" { r.s[0] = 0xaeecf86f7878dd75; r.s[1] = 0x01cd153642e72622; - const seq1 = []const u64 { + const seq1 = []const u64{ 0xb0ba0da5bb600397, 0x18a08afde614dccc, 0xa2635b956a31b929, @@ -387,10 +387,9 @@ test "xoroshiro sequence" { std.debug.assert(s == r.next()); } - r.jump(); - const seq2 = []const u64 { + const seq2 = []const u64{ 0x95344a13556d3e22, 0xb4fb32dafa4d00df, 0xb2011d9ccdcfe2dd, @@ -421,8 +420,8 @@ pub const Isaac64 = struct { i: usize, pub fn init(init_s: u64) Isaac64 { - var isaac = Isaac64 { - .random = Random { .fillFn = fill }, + var isaac = Isaac64{ + .random = Random{ .fillFn = fill }, .r = undefined, .m = undefined, .a = undefined, @@ -456,20 +455,20 @@ pub const Isaac64 = struct { { var i: usize = 0; while (i < midpoint) : (i += 4) { - self.step( ~(self.a ^ (self.a << 21)), i + 0, 0, midpoint); - self.step( self.a ^ (self.a >> 5) , i + 1, 0, midpoint); - self.step( self.a ^ (self.a << 12) , i + 2, 0, midpoint); - self.step( self.a ^ (self.a >> 33) , i + 3, 0, midpoint); + self.step(~(self.a ^ (self.a << 21)), i + 0, 0, midpoint); + self.step(self.a ^ (self.a >> 5), i + 1, 0, midpoint); + self.step(self.a ^ (self.a << 12), i + 2, 0, midpoint); + self.step(self.a ^ (self.a >> 33), i + 3, 0, midpoint); } } { var i: usize = 0; while (i < midpoint) : (i += 4) { - self.step( ~(self.a ^ (self.a << 21)), i + 0, midpoint, 0); - self.step( self.a ^ (self.a >> 5) , i + 1, midpoint, 0); - self.step( self.a ^ (self.a << 12) , i + 2, midpoint, 0); - self.step( self.a ^ (self.a >> 33) , i + 3, midpoint, 0); + self.step(~(self.a ^ (self.a << 21)), i + 0, midpoint, 0); + self.step(self.a ^ (self.a >> 5), i + 1, midpoint, 0); + self.step(self.a ^ (self.a << 12), i + 2, midpoint, 0); + self.step(self.a ^ (self.a >> 33), i + 3, midpoint, 0); } } @@ -493,7 +492,7 @@ pub const Isaac64 = struct { self.m[0] = init_s; // prescrambled golden ratio constants - var a = []const u64 { + var a = []const u64{ 0x647c4677a2884b7c, 0xb9f8b322c73ac862, 0x8c0ea5053d4712a0, @@ -513,14 +512,30 @@ pub const Isaac64 = struct { a[x1] +%= self.m[j + x1]; } - a[0] -%= a[4]; a[5] ^= a[7] >> 9; a[7] +%= a[0]; - a[1] -%= a[5]; a[6] ^= a[0] << 9; a[0] +%= a[1]; - a[2] -%= a[6]; a[7] ^= a[1] >> 23; a[1] +%= a[2]; - a[3] -%= a[7]; a[0] ^= a[2] << 15; a[2] +%= a[3]; - a[4] -%= a[0]; a[1] ^= a[3] >> 14; a[3] +%= a[4]; - a[5] -%= a[1]; a[2] ^= a[4] << 20; a[4] +%= a[5]; - a[6] -%= a[2]; a[3] ^= a[5] >> 17; a[5] +%= a[6]; - a[7] -%= a[3]; a[4] ^= a[6] << 14; a[6] +%= a[7]; + a[0] -%= a[4]; + a[5] ^= a[7] >> 9; + a[7] +%= a[0]; + a[1] -%= a[5]; + a[6] ^= a[0] << 9; + a[0] +%= a[1]; + a[2] -%= a[6]; + a[7] ^= a[1] >> 23; + a[1] +%= a[2]; + a[3] -%= a[7]; + a[0] ^= a[2] << 15; + a[2] +%= a[3]; + a[4] -%= a[0]; + a[1] ^= a[3] >> 14; + a[3] +%= a[4]; + a[5] -%= a[1]; + a[2] ^= a[4] << 20; + a[4] +%= a[5]; + a[6] -%= a[2]; + a[3] ^= a[5] >> 17; + a[5] +%= a[6]; + a[7] -%= a[3]; + a[4] ^= a[6] << 14; + a[6] +%= a[7]; comptime var x2: usize = 0; inline while (x2 < 8) : (x2 += 1) { @@ -533,7 +548,7 @@ pub const Isaac64 = struct { self.a = 0; self.b = 0; self.c = 0; - self.i = self.r.len; // trigger refill on first value + self.i = self.r.len; // trigger refill on first value } fn fill(r: &Random, buf: []u8) void { @@ -567,7 +582,7 @@ test "isaac64 sequence" { var r = Isaac64.init(0); // from reference implementation - const seq = []const u64 { + const seq = []const u64{ 0xf67dfba498e4937c, 0x84a5066a9204f380, 0xfee34bd5f5514dbb, @@ -609,7 +624,7 @@ test "Random float" { test "Random scalar" { var prng = DefaultPrng.init(0); - const s = prng .random.scalar(u64); + const s = prng.random.scalar(u64); } test "Random bytes" { @@ -621,8 +636,8 @@ test "Random bytes" { test "Random shuffle" { var prng = DefaultPrng.init(0); - var seq = []const u8 { 0, 1, 2, 3, 4 }; - var seen = []bool {false} ** 5; + var seq = []const u8{ 0, 1, 2, 3, 4 }; + var seen = []bool{false} ** 5; var i: usize = 0; while (i < 1000) : (i += 1) { @@ -639,7 +654,8 @@ test "Random shuffle" { fn sumArray(s: []const u8) u32 { var r: u32 = 0; - for (s) |e| r += e; + for (s) |e| + r += e; return r; } diff --git a/std/rand/ziggurat.zig b/std/rand/ziggurat.zig index 7790b71d26..404687ad0c 100644 --- a/std/rand/ziggurat.zig +++ b/std/rand/ziggurat.zig @@ -64,8 +64,14 @@ pub const ZigTable = struct { }; // zigNorInit -fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn(f64) f64, - comptime f_inv: fn(f64) f64, comptime zero_case: fn(&Random, f64) f64) ZigTable { +fn ZigTableGen( + comptime is_symmetric: bool, + comptime r: f64, + comptime v: f64, + comptime f: fn(f64) f64, + comptime f_inv: fn(f64) f64, + comptime zero_case: fn(&Random, f64) f64, +) ZigTable { var tables: ZigTable = undefined; tables.is_symmetric = is_symmetric; @@ -98,8 +104,12 @@ pub const NormDist = blk: { const norm_r = 3.6541528853610088; const norm_v = 0.00492867323399; -fn norm_f(x: f64) f64 { return math.exp(-x * x / 2.0); } -fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); } +fn norm_f(x: f64) f64 { + return math.exp(-x * x / 2.0); +} +fn norm_f_inv(y: f64) f64 { + return math.sqrt(-2.0 * math.ln(y)); +} fn norm_zero_case(random: &Random, u: f64) f64 { var x: f64 = 1; var y: f64 = 0; @@ -133,9 +143,15 @@ pub const ExpDist = blk: { const exp_r = 7.69711747013104972; const exp_v = 0.0039496598225815571993; -fn exp_f(x: f64) f64 { return math.exp(-x); } -fn exp_f_inv(y: f64) f64 { return -math.ln(y); } -fn exp_zero_case(random: &Random, _: f64) f64 { return exp_r - math.ln(random.float(f64)); } +fn exp_f(x: f64) f64 { + return math.exp(-x); +} +fn exp_f_inv(y: f64) f64 { + return -math.ln(y); +} +fn exp_zero_case(random: &Random, _: f64) f64 { + return exp_r - math.ln(random.float(f64)); +} test "ziggurant exp dist sanity" { var prng = std.rand.DefaultPrng.init(0); diff --git a/std/segmented_list.zig b/std/segmented_list.zig index 098378de4e..d755135fe8 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -5,7 +5,7 @@ const Allocator = std.mem.Allocator; // Imagine that `fn at(self: &Self, index: usize) &T` is a customer asking for a box // from a warehouse, based on a flat array, boxes ordered from 0 to N - 1. // But the warehouse actually stores boxes in shelves of increasing powers of 2 sizes. -// So when the customer requests a box index, we have to translate it to shelf index +// So when the customer requests a box index, we have to translate it to shelf index // and box index within that shelf. Illustration: // // customer indexes: @@ -37,14 +37,14 @@ const Allocator = std.mem.Allocator; // Now we complicate it a little bit further by adding a preallocated shelf, which must be // a power of 2: // prealloc=4 -// +// // customer indexes: // prealloc: 0 1 2 3 // shelf 0: 4 5 6 7 8 9 10 11 // shelf 1: 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // shelf 2: 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 // ... -// +// // warehouse indexes: // prealloc: 0 1 2 3 // shelf 0: 0 1 2 3 4 5 6 7 diff --git a/std/sort.zig b/std/sort.zig index 4cc7ad503a..5596c9063d 100644 --- a/std/sort.zig +++ b/std/sort.zig @@ -317,7 +317,6 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // 6. merge each A block with any B values that follow, using the cache or the second internal buffer // 7. sort the second internal buffer if it exists // 8. redistribute the two internal buffers back into the items - var block_size: usize = math.sqrt(iterator.length()); var buffer_size = iterator.length() / block_size + 1; diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index 056ab35003..c10f4aa806 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -27,10 +27,14 @@ extern fn zen_start() noreturn { nakedcc fn _start() noreturn { switch (builtin.arch) { builtin.Arch.x86_64 => { - argc_ptr = asm ("lea (%%rsp), %[argc]" : [argc] "=r" (-> &usize)); + argc_ptr = asm ("lea (%%rsp), %[argc]" + : [argc] "=r" (-> &usize) + ); }, builtin.Arch.i386 => { - argc_ptr = asm ("lea (%%esp), %[argc]" : [argc] "=r" (-> &usize)); + argc_ptr = asm ("lea (%%esp), %[argc]" + : [argc] "=r" (-> &usize) + ); }, else => @compileError("unsupported arch"), } diff --git a/std/special/bootstrap_lib.zig b/std/special/bootstrap_lib.zig index f55aaed96a..f029495cb0 100644 --- a/std/special/bootstrap_lib.zig +++ b/std/special/bootstrap_lib.zig @@ -7,8 +7,10 @@ comptime { @export("_DllMainCRTStartup", _DllMainCRTStartup, builtin.GlobalLinkage.Strong); } -stdcallcc fn _DllMainCRTStartup(hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD, - lpReserved: std.os.windows.LPVOID) std.os.windows.BOOL -{ +stdcallcc fn _DllMainCRTStartup( + hinstDLL: std.os.windows.HINSTANCE, + fdwReason: std.os.windows.DWORD, + lpReserved: std.os.windows.LPVOID, +) std.os.windows.BOOL { return std.os.windows.TRUE; } diff --git a/std/special/build_runner.zig b/std/special/build_runner.zig index e1a35f6648..cf8f19d49e 100644 --- a/std/special/build_runner.zig +++ b/std/special/build_runner.zig @@ -24,7 +24,6 @@ pub fn main() !void { const allocator = &arena.allocator; - // skip my own exe name _ = arg_it.skip(); @@ -175,8 +174,7 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void { try out_stream.print(" (none)\n"); } else { for (builder.available_options_list.toSliceConst()) |option| { - const name = try fmt.allocPrint(allocator, - " -D{}=[{}]", option.name, Builder.typeIdName(option.type_id)); + const name = try fmt.allocPrint(allocator, " -D{}=[{}]", option.name, Builder.typeIdName(option.type_id)); defer allocator.free(name); try out_stream.print("{s24} {}\n", name, option.description); } @@ -202,7 +200,7 @@ fn usageAndErr(builder: &Builder, already_ran_build: bool, out_stream: var) erro return error.InvalidArgs; } -const UnwrapArgError = error {OutOfMemory}; +const UnwrapArgError = error{OutOfMemory}; fn unwrapArg(arg: UnwrapArgError![]u8) UnwrapArgError![]u8 { return arg catch |err| { diff --git a/std/special/builtin.zig b/std/special/builtin.zig index a5126bc4f3..63149d5161 100644 --- a/std/special/builtin.zig +++ b/std/special/builtin.zig @@ -56,7 +56,8 @@ export fn memmove(dest: ?&u8, src: ?&const u8, n: usize) ?&u8 { comptime { if (builtin.mode != builtin.Mode.ReleaseFast and builtin.mode != builtin.Mode.ReleaseSmall and - builtin.os != builtin.Os.windows) { + builtin.os != builtin.Os.windows) + { @export("__stack_chk_fail", __stack_chk_fail, builtin.GlobalLinkage.Strong); } if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) { @@ -101,15 +102,27 @@ nakedcc fn clone() void { const math = @import("../math/index.zig"); -export fn fmodf(x: f32, y: f32) f32 { return generic_fmod(f32, x, y); } -export fn fmod(x: f64, y: f64) f64 { return generic_fmod(f64, x, y); } +export fn fmodf(x: f32, y: f32) f32 { + return generic_fmod(f32, x, y); +} +export fn fmod(x: f64, y: f64) f64 { + return generic_fmod(f64, x, y); +} // TODO add intrinsics for these (and probably the double version too) // and have the math stuff use the intrinsic. same as @mod and @rem -export fn floorf(x: f32) f32 { return math.floor(x); } -export fn ceilf(x: f32) f32 { return math.ceil(x); } -export fn floor(x: f64) f64 { return math.floor(x); } -export fn ceil(x: f64) f64 { return math.ceil(x); } +export fn floorf(x: f32) f32 { + return math.floor(x); +} +export fn ceilf(x: f32) f32 { + return math.ceil(x); +} +export fn floor(x: f64) f64 { + return math.floor(x); +} +export fn ceil(x: f64) f64 { + return math.ceil(x); +} fn generic_fmod(comptime T: type, x: T, y: T) T { @setRuntimeSafety(false); @@ -139,7 +152,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { // normalize x and y if (ex == 0) { i = ux << exp_bits; - while (i >> bits_minus_1 == 0) : (b: {ex -= 1; break :b i <<= 1;}) {} + while (i >> bits_minus_1 == 0) : (b: { + ex -= 1; + i <<= 1; + }) {} ux <<= log2uint(@bitCast(u32, -ex + 1)); } else { ux &= @maxValue(uint) >> exp_bits; @@ -147,7 +163,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { } if (ey == 0) { i = uy << exp_bits; - while (i >> bits_minus_1 == 0) : (b: {ey -= 1; break :b i <<= 1;}) {} + while (i >> bits_minus_1 == 0) : (b: { + ey -= 1; + i <<= 1; + }) {} uy <<= log2uint(@bitCast(u32, -ey + 1)); } else { uy &= @maxValue(uint) >> exp_bits; @@ -170,7 +189,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { return 0 * x; ux = i; } - while (ux >> digits == 0) : (b: {ux <<= 1; break :b ex -= 1;}) {} + while (ux >> digits == 0) : (b: { + ux <<= 1; + ex -= 1; + }) {} // scale result up if (ex > 0) { @@ -298,7 +320,7 @@ export fn sqrt(x: f64) f64 { // rounding direction if (ix0 | ix1 != 0) { - var z = 1.0 - tiny; // raise inexact + var z = 1.0 - tiny; // raise inexact if (z >= 1.0) { z = 1.0 + tiny; if (q1 == 0xFFFFFFFF) { @@ -336,13 +358,13 @@ export fn sqrtf(x: f32) f32 { var ix: i32 = @bitCast(i32, x); if ((ix & 0x7F800000) == 0x7F800000) { - return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan + return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan } // zero if (ix <= 0) { if (ix & ~sign == 0) { - return x; // sqrt (+-0) = +-0 + return x; // sqrt (+-0) = +-0 } if (ix < 0) { return math.snan(f32); @@ -360,20 +382,20 @@ export fn sqrtf(x: f32) f32 { m -= i - 1; } - m -= 127; // unbias exponent + m -= 127; // unbias exponent ix = (ix & 0x007FFFFF) | 0x00800000; - if (m & 1 != 0) { // odd m, double x to even + if (m & 1 != 0) { // odd m, double x to even ix += ix; } - m >>= 1; // m = [m / 2] + m >>= 1; // m = [m / 2] // sqrt(x) bit by bit ix += ix; - var q: i32 = 0; // q = sqrt(x) + var q: i32 = 0; // q = sqrt(x) var s: i32 = 0; - var r: i32 = 0x01000000; // r = moving bit right -> left + var r: i32 = 0x01000000; // r = moving bit right -> left while (r != 0) { const t = s + r; @@ -388,7 +410,7 @@ export fn sqrtf(x: f32) f32 { // floating add to find rounding direction if (ix != 0) { - var z = 1.0 - tiny; // inexact + var z = 1.0 - tiny; // inexact if (z >= 1.0) { z = 1.0 + tiny; if (z > 1.0) { diff --git a/std/special/compiler_rt/comparetf2.zig b/std/special/compiler_rt/comparetf2.zig index 760c3689c0..d63b7a7c92 100644 --- a/std/special/compiler_rt/comparetf2.zig +++ b/std/special/compiler_rt/comparetf2.zig @@ -38,25 +38,22 @@ pub extern fn __letf2(a: f128, b: f128) c_int { // If at least one of a and b is positive, we get the same result comparing // a and b as signed integers as we would with a floating-point compare. - return if ((aInt & bInt) >= 0) - if (aInt < bInt) - LE_LESS - else if (aInt == bInt) - LE_EQUAL - else - LE_GREATER + return if ((aInt & bInt) >= 0) if (aInt < bInt) + LE_LESS + else if (aInt == bInt) + LE_EQUAL else - // Otherwise, both are negative, so we need to flip the sense of the - // comparison to get the correct result. (This assumes a twos- or ones- - // complement integer representation; if integers are represented in a - // sign-magnitude representation, then this flip is incorrect). - if (aInt > bInt) - LE_LESS - else if (aInt == bInt) - LE_EQUAL - else - LE_GREATER - ; + LE_GREATER else + // Otherwise, both are negative, so we need to flip the sense of the + // comparison to get the correct result. (This assumes a twos- or ones- + // complement integer representation; if integers are represented in a + // sign-magnitude representation, then this flip is incorrect). + if (aInt > bInt) + LE_LESS + else if (aInt == bInt) + LE_EQUAL + else + LE_GREATER; } // TODO https://github.com/ziglang/zig/issues/305 @@ -76,21 +73,17 @@ pub extern fn __getf2(a: f128, b: f128) c_int { if (aAbs > infRep or bAbs > infRep) return GE_UNORDERED; if ((aAbs | bAbs) == 0) return GE_EQUAL; - return if ((aInt & bInt) >= 0) - if (aInt < bInt) - GE_LESS - else if (aInt == bInt) - GE_EQUAL - else - GE_GREATER + return if ((aInt & bInt) >= 0) if (aInt < bInt) + GE_LESS + else if (aInt == bInt) + GE_EQUAL else - if (aInt > bInt) - GE_LESS - else if (aInt == bInt) - GE_EQUAL - else - GE_GREATER - ; + GE_GREATER else if (aInt > bInt) + GE_LESS + else if (aInt == bInt) + GE_EQUAL + else + GE_GREATER; } pub extern fn __unordtf2(a: f128, b: f128) c_int { diff --git a/std/special/compiler_rt/fixunsdfti_test.zig b/std/special/compiler_rt/fixunsdfti_test.zig index 7283b35c0e..7f7b083d19 100644 --- a/std/special/compiler_rt/fixunsdfti_test.zig +++ b/std/special/compiler_rt/fixunsdfti_test.zig @@ -44,4 +44,3 @@ test "fixunsdfti" { test__fixunsdfti(-0x1.FFFFFFFFFFFFFp+62, 0); test__fixunsdfti(-0x1.FFFFFFFFFFFFEp+62, 0); } - diff --git a/std/special/compiler_rt/index.zig b/std/special/compiler_rt/index.zig index b051ccfc9d..3e014d4d16 100644 --- a/std/special/compiler_rt/index.zig +++ b/std/special/compiler_rt/index.zig @@ -92,10 +92,10 @@ pub fn setXmm0(comptime T: type, value: T) void { const aligned_value: T align(16) = value; asm volatile ( \\movaps (%[ptr]), %%xmm0 - - : + : : [ptr] "r" (&aligned_value) - : "xmm0"); + : "xmm0" + ); } extern fn __udivdi3(a: u64, b: u64) u64 { @@ -159,7 +159,8 @@ fn isArmArch() bool { builtin.Arch.armebv6t2, builtin.Arch.armebv5, builtin.Arch.armebv5te, - builtin.Arch.armebv4t => true, + builtin.Arch.armebv4t, + => true, else => false, }; } @@ -174,7 +175,10 @@ nakedcc fn __aeabi_uidivmod() void { \\ ldr r1, [sp] \\ add sp, sp, #4 \\ pop { pc } - ::: "r2", "r1"); + : + : + : "r2", "r1" + ); } // _chkstk (_alloca) routine - probe stack between %esp and (%esp-%eax) in 4k increments, diff --git a/std/unicode.zig b/std/unicode.zig index 300e129647..8bcc2705dd 100644 --- a/std/unicode.zig +++ b/std/unicode.zig @@ -58,6 +58,7 @@ pub fn utf8Encode(c: u32, out: []u8) !u3 { } const Utf8DecodeError = Utf8Decode2Error || Utf8Decode3Error || Utf8Decode4Error; + /// Decodes the UTF-8 codepoint encoded in the given slice of bytes. /// bytes.len must be equal to utf8ByteSequenceLength(bytes[0]) catch unreachable. /// If you already know the length at comptime, you can call one of @@ -150,7 +151,9 @@ pub fn utf8ValidateSlice(s: []const u8) bool { return false; } - if (utf8Decode(s[i..i+cp_len])) |_| {} else |_| { return false; } + if (utf8Decode(s[i..i + cp_len])) |_| {} else |_| { + return false; + } i += cp_len; } else |err| { return false; @@ -179,9 +182,7 @@ pub const Utf8View = struct { } pub fn initUnchecked(s: []const u8) Utf8View { - return Utf8View { - .bytes = s, - }; + return Utf8View{ .bytes = s }; } pub fn initComptime(comptime s: []const u8) Utf8View { @@ -191,12 +192,12 @@ pub const Utf8View = struct { error.InvalidUtf8 => { @compileError("invalid utf8"); unreachable; - } + }, } } pub fn iterator(s: &const Utf8View) Utf8Iterator { - return Utf8Iterator { + return Utf8Iterator{ .bytes = s.bytes, .i = 0, }; @@ -215,7 +216,7 @@ const Utf8Iterator = struct { const cp_len = utf8ByteSequenceLength(it.bytes[it.i]) catch unreachable; it.i += cp_len; - return it.bytes[it.i-cp_len..it.i]; + return it.bytes[it.i - cp_len..it.i]; } pub fn nextCodepoint(it: &Utf8Iterator) ?u32 { @@ -304,9 +305,12 @@ test "utf8 view bad" { fn testUtf8ViewBad() void { // Compile-time error. // const s3 = Utf8View.initComptime("\xfe\xf2"); - const s = Utf8View.init("hel\xadlo"); - if (s) |_| { unreachable; } else |err| { debug.assert(err == error.InvalidUtf8); } + if (s) |_| { + unreachable; + } else |err| { + debug.assert(err == error.InvalidUtf8); + } } test "utf8 view ok" { diff --git a/std/zig/ast.zig b/std/zig/ast.zig index e86c40e310..3e1b4fe16a 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -388,7 +388,8 @@ pub const Node = struct { Id.SwitchElse, Id.FieldInitializer, Id.DocComment, - Id.TestDecl => return false, + Id.TestDecl, + => return false, Id.While => { const while_node = @fieldParentPtr(While, "base", n); if (while_node.@"else") |@"else"| { @@ -608,8 +609,7 @@ pub const Node = struct { if (i < 1) return t; i -= 1; }, - InitArg.None, - InitArg.Enum => {}, + InitArg.None, InitArg.Enum => {}, } if (i < self.fields_and_decls.len) return self.fields_and_decls.at(i).*; @@ -1475,7 +1475,8 @@ pub const Node = struct { Op.Range, Op.Sub, Op.SubWrap, - Op.UnwrapMaybe => {}, + Op.UnwrapMaybe, + => {}, } if (i < 1) return self.rhs; diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 1bc64c3ddb..05554f5d34 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -81,10 +81,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try root_node.decls.push(&test_node.base); try stack.append(State{ .Block = block }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.LBrace, - .ptr = &block.lbrace, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &block.lbrace, + }, + }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &test_node.name } }); continue; }, @@ -95,13 +97,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, Token.Id.Keyword_pub => { stack.append(State.TopLevel) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &root_node.decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &root_node.decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, Token.Id.Keyword_comptime => { @@ -122,22 +126,26 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State.TopLevel) catch unreachable; try stack.append(State{ .Block = block }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.LBrace, - .ptr = &block.lbrace, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &block.lbrace, + }, + }); continue; }, else => { prevToken(&tok_it, &tree); stack.append(State.TopLevel) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &root_node.decls, - .visib_token = null, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &root_node.decls, + .visib_token = null, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, } @@ -147,31 +155,34 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_export, - Token.Id.Keyword_inline => { - stack.append(State{ .TopLevelDecl = TopLevelDeclCtx{ - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = AnnotatedToken{ - .index = token_index, - .ptr = token_ptr, + Token.Id.Keyword_export, Token.Id.Keyword_inline => { + stack.append(State{ + .TopLevelDecl = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = AnnotatedToken{ + .index = token_index, + .ptr = token_ptr, + }, + .lib_name = null, + .comments = ctx.comments, }, - .lib_name = null, - .comments = ctx.comments, - } }) catch unreachable; + }) catch unreachable; continue; }, Token.Id.Keyword_extern => { - stack.append(State{ .TopLevelLibname = TopLevelDeclCtx{ - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = AnnotatedToken{ - .index = token_index, - .ptr = token_ptr, + stack.append(State{ + .TopLevelLibname = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = AnnotatedToken{ + .index = token_index, + .ptr = token_ptr, + }, + .lib_name = null, + .comments = ctx.comments, }, - .lib_name = null, - .comments = ctx.comments, - } }) catch unreachable; + }) catch unreachable; continue; }, else => { @@ -192,13 +203,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }; }; - stack.append(State{ .TopLevelDecl = TopLevelDeclCtx{ - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = ctx.extern_export_inline_token, - .lib_name = lib_name, - .comments = ctx.comments, - } }) catch unreachable; + stack.append(State{ + .TopLevelDecl = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = ctx.extern_export_inline_token, + .lib_name = lib_name, + .comments = ctx.comments, + }, + }) catch unreachable; continue; }, State.TopLevelDecl => |ctx| { @@ -222,15 +235,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try ctx.decls.push(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Semicolon, - .ptr = &node.semicolon_token, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Semicolon, + .ptr = &node.semicolon_token, + }, + }) catch unreachable; try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); continue; }, - Token.Id.Keyword_var, - Token.Id.Keyword_const => { + Token.Id.Keyword_var, Token.Id.Keyword_const => { if (ctx.extern_export_inline_token) |annotated_token| { if (annotated_token.ptr.id == Token.Id.Keyword_inline) { ((try tree.errors.addOne())).* = Error{ .InvalidToken = Error.InvalidToken{ .token = annotated_token.index } }; @@ -238,21 +252,20 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } } - try stack.append(State{ .VarDecl = VarDeclCtx{ - .comments = ctx.comments, - .visib_token = ctx.visib_token, - .lib_name = ctx.lib_name, - .comptime_token = null, - .extern_export_token = if (ctx.extern_export_inline_token) |at| at.index else null, - .mut_token = token_index, - .list = ctx.decls, - } }); + try stack.append(State{ + .VarDecl = VarDeclCtx{ + .comments = ctx.comments, + .visib_token = ctx.visib_token, + .lib_name = ctx.lib_name, + .comptime_token = null, + .extern_export_token = if (ctx.extern_export_inline_token) |at| at.index else null, + .mut_token = token_index, + .list = ctx.decls, + }, + }); continue; }, - Token.Id.Keyword_fn, - Token.Id.Keyword_nakedcc, - Token.Id.Keyword_stdcallcc, - Token.Id.Keyword_async => { + Token.Id.Keyword_fn, Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc, Token.Id.Keyword_async => { const fn_proto = try arena.construct(ast.Node.FnProto{ .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = ctx.comments, @@ -274,13 +287,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .FnProto = fn_proto }); switch (token_ptr.id) { - Token.Id.Keyword_nakedcc, - Token.Id.Keyword_stdcallcc => { + Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => { fn_proto.cc_token = token_index; - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + }, + }); continue; }, Token.Id.Keyword_async => { @@ -292,10 +306,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); fn_proto.async_attr = async_node; - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + }, + }); try stack.append(State{ .AsyncAllocator = async_node }); continue; }, @@ -331,13 +347,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } stack.append(State{ .ContainerDecl = ctx.container_decl }) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &ctx.container_decl.fields_and_decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = null, - .lib_name = null, - .comments = ctx.comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &ctx.container_decl.fields_and_decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = null, + .lib_name = null, + .comments = ctx.comments, + }, + }); continue; }, @@ -361,9 +379,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .base = ast.Node{ .id = ast.Node.Id.ContainerDecl }, .layout_token = ctx.layout_token, .kind_token = switch (token_ptr.id) { - Token.Id.Keyword_struct, - Token.Id.Keyword_union, - Token.Id.Keyword_enum => token_index, + Token.Id.Keyword_struct, Token.Id.Keyword_union, Token.Id.Keyword_enum => token_index, else => { ((try tree.errors.addOne())).* = Error{ .ExpectedAggregateKw = Error.ExpectedAggregateKw{ .token = token_index } }; return tree; @@ -377,10 +393,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { ctx.opt_ctx.store(&node.base); stack.append(State{ .ContainerDecl = node }) catch unreachable; - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.LBrace, - .ptr = &node.lbrace_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &node.lbrace_token, + }, + }); try stack.append(State{ .ContainerInitArgStart = node }); continue; }, @@ -481,35 +499,41 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_pub => { switch (tree.tokens.at(container_decl.kind_token).id) { Token.Id.Keyword_struct => { - try stack.append(State{ .TopLevelExternOrField = TopLevelExternOrFieldCtx{ - .visib_token = token_index, - .container_decl = container_decl, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExternOrField = TopLevelExternOrFieldCtx{ + .visib_token = token_index, + .container_decl = container_decl, + .comments = comments, + }, + }); continue; }, else => { stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &container_decl.fields_and_decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, } }, Token.Id.Keyword_export => { stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &container_decl.fields_and_decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, Token.Id.RBrace => { @@ -523,13 +547,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { else => { prevToken(&tok_it, &tree); stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &container_decl.fields_and_decls, - .visib_token = null, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = null, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, } @@ -557,10 +583,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .VarDeclAlign = var_decl }); try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &var_decl.type_node } }); try stack.append(State{ .IfToken = Token.Id.Colon }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Identifier, - .ptr = &var_decl.name_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Identifier, + .ptr = &var_decl.name_token, + }, + }); continue; }, State.VarDeclAlign => |var_decl| { @@ -605,10 +633,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const semicolon_token = nextToken(&tok_it, &tree); if (semicolon_token.ptr.id != Token.Id.Semicolon) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = semicolon_token.index, - .expected_id = Token.Id.Semicolon, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = semicolon_token.index, + .expected_id = Token.Id.Semicolon, + }, + }; return tree; } @@ -713,10 +743,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try fn_proto.params.push(¶m_decl.base); - stack.append(State{ .ParamDeclEnd = ParamDeclEndCtx{ - .param_decl = param_decl, - .fn_proto = fn_proto, - } }) catch unreachable; + stack.append(State{ + .ParamDeclEnd = ParamDeclEndCtx{ + .param_decl = param_decl, + .fn_proto = fn_proto, + }, + }) catch unreachable; try stack.append(State{ .ParamDeclName = param_decl }); try stack.append(State{ .ParamDeclAliasOrComptime = param_decl }); continue; @@ -769,10 +801,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { State.MaybeLabeledExpression => |ctx| { if (eatToken(&tok_it, &tree, Token.Id.Colon)) |_| { - stack.append(State{ .LabeledExpression = LabelCtx{ - .label = ctx.label, - .opt_ctx = ctx.opt_ctx, - } }) catch unreachable; + stack.append(State{ + .LabeledExpression = LabelCtx{ + .label = ctx.label, + .opt_ctx = ctx.opt_ctx, + }, + }) catch unreachable; continue; } @@ -797,21 +831,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_while => { - stack.append(State{ .While = LoopCtx{ - .label = ctx.label, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .While = LoopCtx{ + .label = ctx.label, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, Token.Id.Keyword_for => { - stack.append(State{ .For = LoopCtx{ - .label = ctx.label, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .For = LoopCtx{ + .label = ctx.label, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, Token.Id.Keyword_suspend => { @@ -828,11 +866,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_inline => { - stack.append(State{ .Inline = InlineCtx{ - .label = ctx.label, - .inline_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .Inline = InlineCtx{ + .label = ctx.label, + .inline_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, else => { @@ -852,21 +892,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Keyword_while => { - stack.append(State{ .While = LoopCtx{ - .inline_token = ctx.inline_token, - .label = ctx.label, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .While = LoopCtx{ + .inline_token = ctx.inline_token, + .label = ctx.label, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, Token.Id.Keyword_for => { - stack.append(State{ .For = LoopCtx{ - .inline_token = ctx.inline_token, - .label = ctx.label, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .For = LoopCtx{ + .inline_token = ctx.inline_token, + .label = ctx.label, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, else => { @@ -971,27 +1015,29 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Keyword_comptime => { - stack.append(State{ .ComptimeStatement = ComptimeStatementCtx{ - .comptime_token = token_index, - .block = block, - } }) catch unreachable; + stack.append(State{ + .ComptimeStatement = ComptimeStatementCtx{ + .comptime_token = token_index, + .block = block, + }, + }) catch unreachable; continue; }, - Token.Id.Keyword_var, - Token.Id.Keyword_const => { - stack.append(State{ .VarDecl = VarDeclCtx{ - .comments = null, - .visib_token = null, - .comptime_token = null, - .extern_export_token = null, - .lib_name = null, - .mut_token = token_index, - .list = &block.statements, - } }) catch unreachable; + Token.Id.Keyword_var, Token.Id.Keyword_const => { + stack.append(State{ + .VarDecl = VarDeclCtx{ + .comments = null, + .visib_token = null, + .comptime_token = null, + .extern_export_token = null, + .lib_name = null, + .mut_token = token_index, + .list = &block.statements, + }, + }) catch unreachable; continue; }, - Token.Id.Keyword_defer, - Token.Id.Keyword_errdefer => { + Token.Id.Keyword_defer, Token.Id.Keyword_errdefer => { const node = try arena.construct(ast.Node.Defer{ .base = ast.Node{ .id = ast.Node.Id.Defer }, .defer_token = token_index, @@ -1036,17 +1082,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_var, - Token.Id.Keyword_const => { - stack.append(State{ .VarDecl = VarDeclCtx{ - .comments = null, - .visib_token = null, - .comptime_token = ctx.comptime_token, - .extern_export_token = null, - .lib_name = null, - .mut_token = token_index, - .list = &ctx.block.statements, - } }) catch unreachable; + Token.Id.Keyword_var, Token.Id.Keyword_const => { + stack.append(State{ + .VarDecl = VarDeclCtx{ + .comments = null, + .visib_token = null, + .comptime_token = ctx.comptime_token, + .extern_export_token = null, + .lib_name = null, + .mut_token = token_index, + .list = &ctx.block.statements, + }, + }) catch unreachable; continue; }, else => { @@ -1089,10 +1136,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .AsmOutputItems = items }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.Comma }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RParen, - .ptr = &node.rparen, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + }, + }); try stack.append(State{ .AsmOutputReturnOrType = node }); try stack.append(State{ .ExpectToken = Token.Id.LParen }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } }); @@ -1141,10 +1190,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .AsmInputItems = items }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.Comma }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RParen, - .ptr = &node.rparen, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + }, + }); try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); try stack.append(State{ .ExpectToken = Token.Id.LParen }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } }); @@ -1203,14 +1254,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .FieldInitListCommaOrEnd = list_state }) catch unreachable; try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); try stack.append(State{ .ExpectToken = Token.Id.Equal }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Identifier, - .ptr = &node.name_token, - } }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Period, - .ptr = &node.period_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Identifier, + .ptr = &node.name_token, + }, + }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Period, + .ptr = &node.period_token, + }, + }); continue; }, State.FieldInitListCommaOrEnd => |list_state| { @@ -1320,10 +1375,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try switch_case.items.push(&else_node.base); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.EqualAngleBracketRight, - .ptr = &switch_case.arrow_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.EqualAngleBracketRight, + .ptr = &switch_case.arrow_token, + }, + }); continue; } else { prevToken(&tok_it, &tree); @@ -1374,10 +1431,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } async_node.rangle_bracket = TokenIndex(0); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.AngleBracketRight, - .ptr = &??async_node.rangle_bracket, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.AngleBracketRight, + .ptr = &??async_node.rangle_bracket, + }, + }); try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &async_node.allocator_type } }); continue; }, @@ -1430,10 +1489,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - stack.append(State{ .ContainerKind = ContainerKindCtx{ - .opt_ctx = ctx.opt_ctx, - .layout_token = ctx.extern_token, - } }) catch unreachable; + stack.append(State{ + .ContainerKind = ContainerKindCtx{ + .opt_ctx = ctx.opt_ctx, + .layout_token = ctx.extern_token, + }, + }) catch unreachable; continue; }, State.SliceOrArrayAccess => |node| { @@ -1443,15 +1504,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { switch (token_ptr.id) { Token.Id.Ellipsis2 => { const start = node.op.ArrayAccess; - node.op = ast.Node.SuffixOp.Op{ .Slice = ast.Node.SuffixOp.Op.Slice{ - .start = start, - .end = null, - } }; + node.op = ast.Node.SuffixOp.Op{ + .Slice = ast.Node.SuffixOp.Op.Slice{ + .start = start, + .end = null, + }, + }; - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RBracket, - .ptr = &node.rtoken, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RBracket, + .ptr = &node.rtoken, + }, + }) catch unreachable; try stack.append(State{ .Expression = OptionalCtx{ .Optional = &node.op.Slice.end } }); continue; }, @@ -1467,11 +1532,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.SliceOrArrayType => |node| { if (eatToken(&tok_it, &tree, Token.Id.RBracket)) |_| { - node.op = ast.Node.PrefixOp.Op{ .SliceType = ast.Node.PrefixOp.AddrOfInfo{ - .align_info = null, - .const_token = null, - .volatile_token = null, - } }; + node.op = ast.Node.PrefixOp.Op{ + .SliceType = ast.Node.PrefixOp.AddrOfInfo{ + .align_info = null, + .const_token = null, + .volatile_token = null, + }, + }; stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable; try stack.append(State{ .AddrOfModifiers = &node.op.SliceType }); continue; @@ -1495,7 +1562,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { ((try tree.errors.addOne())).* = Error{ .ExtraAlignQualifier = Error.ExtraAlignQualifier{ .token = token_index } }; return tree; } - addr_of_info.align_info = ast.Node.PrefixOp.AddrOfInfo.Align { + addr_of_info.align_info = ast.Node.PrefixOp.AddrOfInfo.Align{ .node = undefined, .bit_range = null, }; @@ -1548,9 +1615,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.RParen => continue, else => { (try tree.errors.addOne()).* = Error{ - .ExpectedColonOrRParen = Error.ExpectedColonOrRParen{ - .token = token.index, - } + .ExpectedColonOrRParen = Error.ExpectedColonOrRParen{ .token = token.index }, }; return tree; }, @@ -1563,10 +1628,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = Token.Id.Pipe, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + }, + }; return tree; } @@ -1582,10 +1649,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + }, + }) catch unreachable; try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.error_symbol } }); continue; }, @@ -1595,10 +1664,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = Token.Id.Pipe, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + }, + }; return tree; } @@ -1615,15 +1686,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + }, + }); try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } }); - try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ - .id = Token.Id.Asterisk, - .ptr = &node.ptr_token, - } }); + try stack.append(State{ + .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Asterisk, + .ptr = &node.ptr_token, + }, + }); continue; }, State.PointerIndexPayload => |opt_ctx| { @@ -1632,10 +1707,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = Token.Id.Pipe, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + }, + }; return tree; } @@ -1653,17 +1730,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + }, + }) catch unreachable; try stack.append(State{ .Identifier = OptionalCtx{ .RequiredNull = &node.index_symbol } }); try stack.append(State{ .IfToken = Token.Id.Comma }); try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } }); - try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ - .id = Token.Id.Asterisk, - .ptr = &node.ptr_token, - } }); + try stack.append(State{ + .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Asterisk, + .ptr = &node.ptr_token, + }, + }); continue; }, @@ -1672,9 +1753,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_return, - Token.Id.Keyword_break, - Token.Id.Keyword_continue => { + Token.Id.Keyword_return, Token.Id.Keyword_break, Token.Id.Keyword_continue => { const node = try arena.construct(ast.Node.ControlFlowExpression{ .base = ast.Node{ .id = ast.Node.Id.ControlFlowExpression }, .ltoken = token_index, @@ -1703,9 +1782,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } continue; }, - Token.Id.Keyword_try, - Token.Id.Keyword_cancel, - Token.Id.Keyword_resume => { + Token.Id.Keyword_try, Token.Id.Keyword_cancel, Token.Id.Keyword_resume => { const node = try arena.construct(ast.Node.PrefixOp{ .base = ast.Node{ .id = ast.Node.Id.PrefixOp }, .op_token = token_index, @@ -2078,10 +2155,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.LBrace }); - try stack.append(State{ .FieldInitListItemOrEnd = ListSave(@typeOf(node.op.StructInitializer)){ - .list = &node.op.StructInitializer, - .ptr = &node.rtoken, - } }); + try stack.append(State{ + .FieldInitListItemOrEnd = ListSave(@typeOf(node.op.StructInitializer)){ + .list = &node.op.StructInitializer, + .ptr = &node.rtoken, + }, + }); continue; } @@ -2094,11 +2173,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { opt_ctx.store(&node.base); stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.LBrace }); - try stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ - .list = &node.op.ArrayInitializer, - .end = Token.Id.RBrace, - .ptr = &node.rtoken, - } }); + try stack.append(State{ + .ExprListItemOrEnd = ExprListCtx{ + .list = &node.op.ArrayInitializer, + .end = Token.Id.RBrace, + .ptr = &node.rtoken, + }, + }); continue; }, @@ -2171,10 +2252,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .allocator_type = null, .rangle_bracket = null, }); - stack.append(State{ .AsyncEnd = AsyncEndCtx{ - .ctx = opt_ctx, - .attribute = async_node, - } }) catch unreachable; + stack.append(State{ + .AsyncEnd = AsyncEndCtx{ + .ctx = opt_ctx, + .attribute = async_node, + }, + }) catch unreachable; try stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }); try stack.append(State{ .PrimaryExpression = opt_ctx.toRequired() }); try stack.append(State{ .AsyncAllocator = async_node }); @@ -2197,20 +2280,24 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const node = try arena.construct(ast.Node.SuffixOp{ .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, .lhs = lhs, - .op = ast.Node.SuffixOp.Op{ .Call = ast.Node.SuffixOp.Op.Call{ - .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena), - .async_attr = null, - } }, + .op = ast.Node.SuffixOp.Op{ + .Call = ast.Node.SuffixOp.Op.Call{ + .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena), + .async_attr = null, + }, + }, .rtoken = undefined, }); opt_ctx.store(&node.base); stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ - .list = &node.op.Call.params, - .end = Token.Id.RParen, - .ptr = &node.rtoken, - } }); + try stack.append(State{ + .ExprListItemOrEnd = ExprListCtx{ + .list = &node.op.Call.params, + .end = Token.Id.RParen, + .ptr = &node.rtoken, + }, + }); continue; }, Token.Id.LBracket => { @@ -2278,8 +2365,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.UndefinedLiteral, token.index); continue; }, - Token.Id.Keyword_true, - Token.Id.Keyword_false => { + Token.Id.Keyword_true, Token.Id.Keyword_false => { _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.BoolLiteral, token.index); continue; }, @@ -2321,8 +2407,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .Expression = OptionalCtx{ .Required = return_type_ptr } }); continue; }, - Token.Id.StringLiteral, - Token.Id.MultilineStringLiteralLine => { + Token.Id.StringLiteral, Token.Id.MultilineStringLiteralLine => { opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) ?? unreachable); continue; }, @@ -2335,10 +2420,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RParen, - .ptr = &node.rparen, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + }, + }) catch unreachable; try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); continue; }, @@ -2351,11 +2438,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ - .list = &node.params, - .end = Token.Id.RParen, - .ptr = &node.rparen_token, - } }) catch unreachable; + stack.append(State{ + .ExprListItemOrEnd = ExprListCtx{ + .list = &node.params, + .end = Token.Id.RParen, + .ptr = &node.rparen_token, + }, + }) catch unreachable; try stack.append(State{ .ExpectToken = Token.Id.LParen }); continue; }, @@ -2372,42 +2461,50 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_error => { - stack.append(State{ .ErrorTypeOrSetDecl = ErrorTypeOrSetDeclCtx{ - .error_token = token.index, - .opt_ctx = opt_ctx, - } }) catch unreachable; + stack.append(State{ + .ErrorTypeOrSetDecl = ErrorTypeOrSetDeclCtx{ + .error_token = token.index, + .opt_ctx = opt_ctx, + }, + }) catch unreachable; continue; }, Token.Id.Keyword_packed => { - stack.append(State{ .ContainerKind = ContainerKindCtx{ - .opt_ctx = opt_ctx, - .layout_token = token.index, - } }) catch unreachable; + stack.append(State{ + .ContainerKind = ContainerKindCtx{ + .opt_ctx = opt_ctx, + .layout_token = token.index, + }, + }) catch unreachable; continue; }, Token.Id.Keyword_extern => { - stack.append(State{ .ExternType = ExternTypeCtx{ - .opt_ctx = opt_ctx, - .extern_token = token.index, - .comments = null, - } }) catch unreachable; + stack.append(State{ + .ExternType = ExternTypeCtx{ + .opt_ctx = opt_ctx, + .extern_token = token.index, + .comments = null, + }, + }) catch unreachable; continue; }, - Token.Id.Keyword_struct, - Token.Id.Keyword_union, - Token.Id.Keyword_enum => { + Token.Id.Keyword_struct, Token.Id.Keyword_union, Token.Id.Keyword_enum => { prevToken(&tok_it, &tree); - stack.append(State{ .ContainerKind = ContainerKindCtx{ - .opt_ctx = opt_ctx, - .layout_token = null, - } }) catch unreachable; + stack.append(State{ + .ContainerKind = ContainerKindCtx{ + .opt_ctx = opt_ctx, + .layout_token = null, + }, + }) catch unreachable; continue; }, Token.Id.Identifier => { - stack.append(State{ .MaybeLabeledExpression = MaybeLabeledExpressionCtx{ - .label = token.index, - .opt_ctx = opt_ctx, - } }) catch unreachable; + stack.append(State{ + .MaybeLabeledExpression = MaybeLabeledExpressionCtx{ + .label = token.index, + .opt_ctx = opt_ctx, + }, + }) catch unreachable; continue; }, Token.Id.Keyword_fn => { @@ -2431,8 +2528,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .FnProto = fn_proto }) catch unreachable; continue; }, - Token.Id.Keyword_nakedcc, - Token.Id.Keyword_stdcallcc => { + Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => { const fn_proto = try arena.construct(ast.Node.FnProto{ .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = null, @@ -2451,10 +2547,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&fn_proto.base); stack.append(State{ .FnProto = fn_proto }) catch unreachable; - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + }, + }); continue; }, Token.Id.Keyword_asm => { @@ -2470,10 +2568,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RParen, - .ptr = &node.rparen, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + }, + }) catch unreachable; try stack.append(State{ .AsmClobberItems = &node.clobbers }); try stack.append(State{ .IfToken = Token.Id.Colon }); try stack.append(State{ .AsmInputItems = &node.inputs }); @@ -2482,17 +2582,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .IfToken = Token.Id.Colon }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.template } }); try stack.append(State{ .ExpectToken = Token.Id.LParen }); - try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ - .id = Token.Id.Keyword_volatile, - .ptr = &node.volatile_token, - } }); + try stack.append(State{ + .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Keyword_volatile, + .ptr = &node.volatile_token, + }, + }); }, Token.Id.Keyword_inline => { - stack.append(State{ .Inline = InlineCtx{ - .label = null, - .inline_token = token.index, - .opt_ctx = opt_ctx, - } }) catch unreachable; + stack.append(State{ + .Inline = InlineCtx{ + .label = null, + .inline_token = token.index, + .opt_ctx = opt_ctx, + }, + }) catch unreachable; continue; }, else => { @@ -2522,10 +2626,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); ctx.opt_ctx.store(&node.base); - stack.append(State{ .ErrorTagListItemOrEnd = ListSave(@typeOf(node.decls)){ - .list = &node.decls, - .ptr = &node.rbrace_token, - } }) catch unreachable; + stack.append(State{ + .ErrorTagListItemOrEnd = ListSave(@typeOf(node.decls)){ + .list = &node.decls, + .ptr = &node.rbrace_token, + }, + }) catch unreachable; continue; }, State.StringLiteral => |opt_ctx| { @@ -2553,10 +2659,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = Token.Id.Identifier, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Identifier, + }, + }; return tree; } }, @@ -2567,10 +2675,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const ident_token_index = ident_token.index; const ident_token_ptr = ident_token.ptr; if (ident_token_ptr.id != Token.Id.Identifier) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = ident_token_index, - .expected_id = Token.Id.Identifier, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = ident_token_index, + .expected_id = Token.Id.Identifier, + }, + }; return tree; } @@ -2588,10 +2698,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (token_ptr.id != token_id) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = token_id, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = token_id, + }, + }; return tree; } continue; @@ -2601,10 +2713,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (token_ptr.id != expect_token_save.id) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = expect_token_save.id, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = expect_token_save.id, + }, + }; return tree; } expect_token_save.ptr.* = token_index; @@ -2997,21 +3111,25 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con return true; }, Token.Id.Keyword_while => { - stack.append(State{ .While = LoopCtx{ - .label = null, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.*, - } }) catch unreachable; + stack.append(State{ + .While = LoopCtx{ + .label = null, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.*, + }, + }) catch unreachable; return true; }, Token.Id.Keyword_for => { - stack.append(State{ .For = LoopCtx{ - .label = null, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.*, - } }) catch unreachable; + stack.append(State{ + .For = LoopCtx{ + .label = null, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.*, + }, + }) catch unreachable; return true; }, Token.Id.Keyword_switch => { @@ -3024,10 +3142,12 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con }); ctx.store(&node.base); - stack.append(State{ .SwitchCaseOrEnd = ListSave(@typeOf(node.cases)){ - .list = &node.cases, - .ptr = &node.rbrace, - } }) catch unreachable; + stack.append(State{ + .SwitchCaseOrEnd = ListSave(@typeOf(node.cases)){ + .list = &node.cases, + .ptr = &node.rbrace, + }, + }) catch unreachable; try stack.append(State{ .ExpectToken = Token.Id.LBrace }); try stack.append(State{ .ExpectToken = Token.Id.RParen }); try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); @@ -3080,10 +3200,14 @@ fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end: return ExpectCommaOrEndResult{ .end_token = token_index }; } - return ExpectCommaOrEndResult{ .parse_error = Error{ .ExpectedCommaOrEnd = Error.ExpectedCommaOrEnd{ - .token = token_index, - .end_id = end, - } } }; + return ExpectCommaOrEndResult{ + .parse_error = Error{ + .ExpectedCommaOrEnd = Error.ExpectedCommaOrEnd{ + .token = token_index, + .end_id = end, + }, + }, + }; }, } } @@ -3167,13 +3291,14 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op { Token.Id.Tilde => ast.Node.PrefixOp.Op{ .BitNot = void{} }, Token.Id.Minus => ast.Node.PrefixOp.Op{ .Negation = void{} }, Token.Id.MinusPercent => ast.Node.PrefixOp.Op{ .NegationWrap = void{} }, - Token.Id.Asterisk, - Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .PointerType = void{} }, - Token.Id.Ampersand => ast.Node.PrefixOp.Op{ .AddrOf = ast.Node.PrefixOp.AddrOfInfo{ - .align_info = null, - .const_token = null, - .volatile_token = null, - } }, + Token.Id.Asterisk, Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .PointerType = void{} }, + Token.Id.Ampersand => ast.Node.PrefixOp.Op{ + .AddrOf = ast.Node.PrefixOp.AddrOfInfo{ + .align_info = null, + .const_token = null, + .volatile_token = null, + }, + }, Token.Id.QuestionMark => ast.Node.PrefixOp.Op{ .MaybeType = void{} }, Token.Id.QuestionMarkQuestionMark => ast.Node.PrefixOp.Op{ .UnwrapMaybe = void{} }, Token.Id.Keyword_await => ast.Node.PrefixOp.Op{ .Await = void{} }, diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 1f60fae270..75ba9e61d7 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1021,7 +1021,7 @@ test "zig fmt: extern declaration" { } test "zig fmt: alignment" { - try testCanonical( + try testCanonical( \\var foo: c_int align(1); \\ ); @@ -1070,7 +1070,7 @@ test "zig fmt: slice attributes" { } test "zig fmt: test declaration" { - try testCanonical( + try testCanonical( \\test "test name" { \\ const a = 1; \\ var b = 1; @@ -1312,7 +1312,7 @@ test "zig fmt: struct declaration" { } test "zig fmt: enum declaration" { - try testCanonical( + try testCanonical( \\const E = enum { \\ Ok, \\ SomethingElse = 0, @@ -1340,7 +1340,7 @@ test "zig fmt: enum declaration" { } test "zig fmt: union declaration" { - try testCanonical( + try testCanonical( \\const U = union { \\ Int: u8, \\ Float: f32, @@ -1860,10 +1860,15 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void { } else |err| switch (err) { error.OutOfMemory => { if (failing_allocator.allocated_bytes != failing_allocator.freed_bytes) { - warn("\nfail_index: {}/{}\nallocated bytes: {}\nfreed bytes: {}\nallocations: {}\ndeallocations: {}\n", - fail_index, needed_alloc_count, - failing_allocator.allocated_bytes, failing_allocator.freed_bytes, - failing_allocator.index, failing_allocator.deallocations); + warn( + "\nfail_index: {}/{}\nallocated bytes: {}\nfreed bytes: {}\nallocations: {}\ndeallocations: {}\n", + fail_index, + needed_alloc_count, + failing_allocator.allocated_bytes, + failing_allocator.freed_bytes, + failing_allocator.index, + failing_allocator.deallocations, + ); return error.MemoryLeakDetected; } }, @@ -1876,4 +1881,3 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void { fn testCanonical(source: []const u8) !void { return testTransform(source, source); } - diff --git a/std/zig/render.zig b/std/zig/render.zig index dce659f1ef..e3bf5fe38e 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -161,7 +161,15 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i } } -fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node, space: Space,) (@typeOf(stream).Child.Error || Error)!void { +fn renderExpression( + allocator: &mem.Allocator, + stream: var, + tree: &ast.Tree, + indent: usize, + start_col: &usize, + base: &ast.Node, + space: Space, +) (@typeOf(stream).Child.Error || Error)!void { switch (base.id) { ast.Node.Id.Identifier => { const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base); @@ -259,8 +267,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExpression(allocator, stream, tree, indent, start_col, infix_op_node.lhs, op_space); const after_op_space = blk: { - const loc = tree.tokenLocation(tree.tokens.at(infix_op_node.op_token).end, - tree.nextToken(infix_op_node.op_token)); + const loc = tree.tokenLocation(tree.tokens.at(infix_op_node.op_token).end, tree.nextToken(infix_op_node.op_token)); break :blk if (loc.line == 0) op_space else Space.Newline; }; @@ -367,14 +374,16 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.PrefixOp.Op.NegationWrap, ast.Node.PrefixOp.Op.UnwrapMaybe, ast.Node.PrefixOp.Op.MaybeType, - ast.Node.PrefixOp.Op.PointerType => { + ast.Node.PrefixOp.Op.PointerType, + => { try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); }, ast.Node.PrefixOp.Op.Try, ast.Node.PrefixOp.Op.Await, ast.Node.PrefixOp.Op.Cancel, - ast.Node.PrefixOp.Op.Resume => { + ast.Node.PrefixOp.Op.Resume, + => { try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.Space); }, } @@ -1568,13 +1577,19 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.VarDecl, ast.Node.Id.Use, ast.Node.Id.TestDecl, - ast.Node.Id.ParamDecl => unreachable, + ast.Node.Id.ParamDecl, + => unreachable, } } -fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, - var_decl: &ast.Node.VarDecl,) (@typeOf(stream).Child.Error || Error)!void -{ +fn renderVarDecl( + allocator: &mem.Allocator, + stream: var, + tree: &ast.Tree, + indent: usize, + start_col: &usize, + var_decl: &ast.Node.VarDecl, +) (@typeOf(stream).Child.Error || Error)!void { if (var_decl.visib_token) |visib_token| { try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub } @@ -1623,7 +1638,15 @@ fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent try renderToken(tree, stream, var_decl.semicolon_token, indent, start_col, Space.Newline); } -fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node, space: Space,) (@typeOf(stream).Child.Error || Error)!void { +fn renderParamDecl( + allocator: &mem.Allocator, + stream: var, + tree: &ast.Tree, + indent: usize, + start_col: &usize, + base: &ast.Node, + space: Space, +) (@typeOf(stream).Child.Error || Error)!void { const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base); if (param_decl.comptime_token) |comptime_token| { @@ -1643,7 +1666,14 @@ fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, inde } } -fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node,) (@typeOf(stream).Child.Error || Error)!void { +fn renderStatement( + allocator: &mem.Allocator, + stream: var, + tree: &ast.Tree, + indent: usize, + start_col: &usize, + base: &ast.Node, +) (@typeOf(stream).Child.Error || Error)!void { switch (base.id) { ast.Node.Id.VarDecl => { const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base); @@ -1840,7 +1870,13 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } } -fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize, start_col: &usize,) (@typeOf(stream).Child.Error || Error)!void { +fn renderDocComments( + tree: &ast.Tree, + stream: var, + node: var, + indent: usize, + start_col: &usize, +) (@typeOf(stream).Child.Error || Error)!void { const comment = node.doc_comments ?? return; var it = comment.lines.iterator(0); const first_token = node.firstToken(); diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig index b90a40108f..4881e952b7 100644 --- a/std/zig/tokenizer.zig +++ b/std/zig/tokenizer.zig @@ -11,55 +11,55 @@ pub const Token = struct { id: Id, }; - pub const keywords = []Keyword { - Keyword{.bytes="align", .id = Id.Keyword_align}, - Keyword{.bytes="and", .id = Id.Keyword_and}, - Keyword{.bytes="asm", .id = Id.Keyword_asm}, - Keyword{.bytes="async", .id = Id.Keyword_async}, - Keyword{.bytes="await", .id = Id.Keyword_await}, - Keyword{.bytes="break", .id = Id.Keyword_break}, - Keyword{.bytes="catch", .id = Id.Keyword_catch}, - Keyword{.bytes="cancel", .id = Id.Keyword_cancel}, - Keyword{.bytes="comptime", .id = Id.Keyword_comptime}, - Keyword{.bytes="const", .id = Id.Keyword_const}, - Keyword{.bytes="continue", .id = Id.Keyword_continue}, - Keyword{.bytes="defer", .id = Id.Keyword_defer}, - Keyword{.bytes="else", .id = Id.Keyword_else}, - Keyword{.bytes="enum", .id = Id.Keyword_enum}, - Keyword{.bytes="errdefer", .id = Id.Keyword_errdefer}, - Keyword{.bytes="error", .id = Id.Keyword_error}, - Keyword{.bytes="export", .id = Id.Keyword_export}, - Keyword{.bytes="extern", .id = Id.Keyword_extern}, - Keyword{.bytes="false", .id = Id.Keyword_false}, - Keyword{.bytes="fn", .id = Id.Keyword_fn}, - Keyword{.bytes="for", .id = Id.Keyword_for}, - Keyword{.bytes="if", .id = Id.Keyword_if}, - Keyword{.bytes="inline", .id = Id.Keyword_inline}, - Keyword{.bytes="nakedcc", .id = Id.Keyword_nakedcc}, - Keyword{.bytes="noalias", .id = Id.Keyword_noalias}, - Keyword{.bytes="null", .id = Id.Keyword_null}, - Keyword{.bytes="or", .id = Id.Keyword_or}, - Keyword{.bytes="packed", .id = Id.Keyword_packed}, - Keyword{.bytes="promise", .id = Id.Keyword_promise}, - Keyword{.bytes="pub", .id = Id.Keyword_pub}, - Keyword{.bytes="resume", .id = Id.Keyword_resume}, - Keyword{.bytes="return", .id = Id.Keyword_return}, - Keyword{.bytes="section", .id = Id.Keyword_section}, - Keyword{.bytes="stdcallcc", .id = Id.Keyword_stdcallcc}, - Keyword{.bytes="struct", .id = Id.Keyword_struct}, - Keyword{.bytes="suspend", .id = Id.Keyword_suspend}, - Keyword{.bytes="switch", .id = Id.Keyword_switch}, - Keyword{.bytes="test", .id = Id.Keyword_test}, - Keyword{.bytes="this", .id = Id.Keyword_this}, - Keyword{.bytes="true", .id = Id.Keyword_true}, - Keyword{.bytes="try", .id = Id.Keyword_try}, - Keyword{.bytes="undefined", .id = Id.Keyword_undefined}, - Keyword{.bytes="union", .id = Id.Keyword_union}, - Keyword{.bytes="unreachable", .id = Id.Keyword_unreachable}, - Keyword{.bytes="use", .id = Id.Keyword_use}, - Keyword{.bytes="var", .id = Id.Keyword_var}, - Keyword{.bytes="volatile", .id = Id.Keyword_volatile}, - Keyword{.bytes="while", .id = Id.Keyword_while}, + pub const keywords = []Keyword{ + Keyword{ .bytes = "align", .id = Id.Keyword_align }, + Keyword{ .bytes = "and", .id = Id.Keyword_and }, + Keyword{ .bytes = "asm", .id = Id.Keyword_asm }, + Keyword{ .bytes = "async", .id = Id.Keyword_async }, + Keyword{ .bytes = "await", .id = Id.Keyword_await }, + Keyword{ .bytes = "break", .id = Id.Keyword_break }, + Keyword{ .bytes = "catch", .id = Id.Keyword_catch }, + Keyword{ .bytes = "cancel", .id = Id.Keyword_cancel }, + Keyword{ .bytes = "comptime", .id = Id.Keyword_comptime }, + Keyword{ .bytes = "const", .id = Id.Keyword_const }, + Keyword{ .bytes = "continue", .id = Id.Keyword_continue }, + Keyword{ .bytes = "defer", .id = Id.Keyword_defer }, + Keyword{ .bytes = "else", .id = Id.Keyword_else }, + Keyword{ .bytes = "enum", .id = Id.Keyword_enum }, + Keyword{ .bytes = "errdefer", .id = Id.Keyword_errdefer }, + Keyword{ .bytes = "error", .id = Id.Keyword_error }, + Keyword{ .bytes = "export", .id = Id.Keyword_export }, + Keyword{ .bytes = "extern", .id = Id.Keyword_extern }, + Keyword{ .bytes = "false", .id = Id.Keyword_false }, + Keyword{ .bytes = "fn", .id = Id.Keyword_fn }, + Keyword{ .bytes = "for", .id = Id.Keyword_for }, + Keyword{ .bytes = "if", .id = Id.Keyword_if }, + Keyword{ .bytes = "inline", .id = Id.Keyword_inline }, + Keyword{ .bytes = "nakedcc", .id = Id.Keyword_nakedcc }, + Keyword{ .bytes = "noalias", .id = Id.Keyword_noalias }, + Keyword{ .bytes = "null", .id = Id.Keyword_null }, + Keyword{ .bytes = "or", .id = Id.Keyword_or }, + Keyword{ .bytes = "packed", .id = Id.Keyword_packed }, + Keyword{ .bytes = "promise", .id = Id.Keyword_promise }, + Keyword{ .bytes = "pub", .id = Id.Keyword_pub }, + Keyword{ .bytes = "resume", .id = Id.Keyword_resume }, + Keyword{ .bytes = "return", .id = Id.Keyword_return }, + Keyword{ .bytes = "section", .id = Id.Keyword_section }, + Keyword{ .bytes = "stdcallcc", .id = Id.Keyword_stdcallcc }, + Keyword{ .bytes = "struct", .id = Id.Keyword_struct }, + Keyword{ .bytes = "suspend", .id = Id.Keyword_suspend }, + Keyword{ .bytes = "switch", .id = Id.Keyword_switch }, + Keyword{ .bytes = "test", .id = Id.Keyword_test }, + Keyword{ .bytes = "this", .id = Id.Keyword_this }, + Keyword{ .bytes = "true", .id = Id.Keyword_true }, + Keyword{ .bytes = "try", .id = Id.Keyword_try }, + Keyword{ .bytes = "undefined", .id = Id.Keyword_undefined }, + Keyword{ .bytes = "union", .id = Id.Keyword_union }, + Keyword{ .bytes = "unreachable", .id = Id.Keyword_unreachable }, + Keyword{ .bytes = "use", .id = Id.Keyword_use }, + Keyword{ .bytes = "var", .id = Id.Keyword_var }, + Keyword{ .bytes = "volatile", .id = Id.Keyword_volatile }, + Keyword{ .bytes = "while", .id = Id.Keyword_while }, }; // TODO perfect hash at comptime @@ -72,7 +72,10 @@ pub const Token = struct { return null; } - const StrLitKind = enum {Normal, C}; + const StrLitKind = enum { + Normal, + C, + }; pub const Id = union(enum) { Invalid, @@ -202,7 +205,7 @@ pub const Tokenizer = struct { } pub fn init(buffer: []const u8) Tokenizer { - return Tokenizer { + return Tokenizer{ .buffer = buffer, .index = 0, .pending_invalid_token = null, @@ -269,7 +272,7 @@ pub const Tokenizer = struct { } const start_index = self.index; var state = State.Start; - var result = Token { + var result = Token{ .id = Token.Id.Eof, .start = self.index, .end = undefined, @@ -290,7 +293,7 @@ pub const Tokenizer = struct { }, '"' => { state = State.StringLiteral; - result.id = Token.Id { .StringLiteral = Token.StrLitKind.Normal }; + result.id = Token.Id{ .StringLiteral = Token.StrLitKind.Normal }; }, '\'' => { state = State.CharLiteral; @@ -369,7 +372,7 @@ pub const Tokenizer = struct { }, '\\' => { state = State.Backslash; - result.id = Token.Id { .MultilineStringLiteralLine = Token.StrLitKind.Normal }; + result.id = Token.Id{ .MultilineStringLiteralLine = Token.StrLitKind.Normal }; }, '{' => { result.id = Token.Id.LBrace; @@ -455,7 +458,7 @@ pub const Tokenizer = struct { else => { result.id = Token.Id.Asterisk; break; - } + }, }, State.AsteriskPercent => switch (c) { @@ -467,7 +470,7 @@ pub const Tokenizer = struct { else => { result.id = Token.Id.AsteriskPercent; break; - } + }, }, State.QuestionMark => switch (c) { @@ -535,7 +538,7 @@ pub const Tokenizer = struct { else => { result.id = Token.Id.Caret; break; - } + }, }, State.Identifier => switch (c) { @@ -560,11 +563,11 @@ pub const Tokenizer = struct { State.C => switch (c) { '\\' => { state = State.Backslash; - result.id = Token.Id { .MultilineStringLiteralLine = Token.StrLitKind.C }; + result.id = Token.Id{ .MultilineStringLiteralLine = Token.StrLitKind.C }; }, '"' => { state = State.StringLiteral; - result.id = Token.Id { .StringLiteral = Token.StrLitKind.C }; + result.id = Token.Id{ .StringLiteral = Token.StrLitKind.C }; }, 'a'...'z', 'A'...'Z', '_', '0'...'9' => { state = State.Identifier; @@ -605,7 +608,7 @@ pub const Tokenizer = struct { } state = State.CharLiteralEnd; - } + }, }, State.CharLiteralBackslash => switch (c) { @@ -736,7 +739,7 @@ pub const Tokenizer = struct { else => { result.id = Token.Id.MinusPercent; break; - } + }, }, State.AngleBracketLeft => switch (c) { @@ -944,7 +947,7 @@ pub const Tokenizer = struct { // reinterpret as a normal exponent number self.index -= 1; state = State.FloatExponentNumber; - } + }, }, State.FloatExponentUnsignedHex => switch (c) { '+', '-' => { @@ -954,7 +957,7 @@ pub const Tokenizer = struct { // reinterpret as a normal exponent number self.index -= 1; state = State.FloatExponentNumberHex; - } + }, }, State.FloatExponentNumber => switch (c) { '0'...'9' => {}, @@ -978,15 +981,15 @@ pub const Tokenizer = struct { State.FloatExponentNumberHex, State.StringLiteral, // find this error later State.MultilineStringLiteralLine, - State.Builtin => {}, + State.Builtin, + => {}, State.Identifier => { if (Token.getKeyword(self.buffer[result.start..self.index])) |id| { result.id = id; } }, - State.LineCommentStart, - State.LineComment => { + State.LineCommentStart, State.LineComment => { result.id = Token.Id.LineComment; }, State.DocComment, State.DocCommentStart => { @@ -1004,7 +1007,8 @@ pub const Tokenizer = struct { State.CharLiteralEscape1, State.CharLiteralEscape2, State.CharLiteralEnd, - State.StringLiteralBackslash => { + State.StringLiteralBackslash, + => { result.id = Token.Id.Invalid; }, @@ -1089,7 +1093,7 @@ pub const Tokenizer = struct { if (self.pending_invalid_token != null) return; const invalid_length = self.getInvalidCharacterLength(); if (invalid_length == 0) return; - self.pending_invalid_token = Token { + self.pending_invalid_token = Token{ .id = Token.Id.Invalid, .start = self.index, .end = self.index + invalid_length, @@ -1134,23 +1138,18 @@ pub const Tokenizer = struct { } }; - - test "tokenizer" { - testTokenize("test", []Token.Id { - Token.Id.Keyword_test, - }); + testTokenize("test", []Token.Id{Token.Id.Keyword_test}); } test "tokenizer - char literal with hex escape" { - testTokenize( \\'\x1b' - , []Token.Id { - Token.Id.CharLiteral, - }); + testTokenize( + \\'\x1b' + , []Token.Id{Token.Id.CharLiteral}); } test "tokenizer - float literal e exponent" { - testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id { + testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id{ Token.Id.Identifier, Token.Id.Equal, Token.Id.FloatLiteral, @@ -1159,7 +1158,7 @@ test "tokenizer - float literal e exponent" { } test "tokenizer - float literal p exponent" { - testTokenize("a = 0x1.a827999fcef32p+1022;\n", []Token.Id { + testTokenize("a = 0x1.a827999fcef32p+1022;\n", []Token.Id{ Token.Id.Identifier, Token.Id.Equal, Token.Id.FloatLiteral, @@ -1168,31 +1167,31 @@ test "tokenizer - float literal p exponent" { } test "tokenizer - chars" { - testTokenize("'c'", []Token.Id {Token.Id.CharLiteral}); + testTokenize("'c'", []Token.Id{Token.Id.CharLiteral}); } test "tokenizer - invalid token characters" { testTokenize("#", []Token.Id{Token.Id.Invalid}); testTokenize("`", []Token.Id{Token.Id.Invalid}); - testTokenize("'c", []Token.Id {Token.Id.Invalid}); - testTokenize("'", []Token.Id {Token.Id.Invalid}); - testTokenize("''", []Token.Id {Token.Id.Invalid, Token.Id.Invalid}); + testTokenize("'c", []Token.Id{Token.Id.Invalid}); + testTokenize("'", []Token.Id{Token.Id.Invalid}); + testTokenize("''", []Token.Id{ Token.Id.Invalid, Token.Id.Invalid }); } test "tokenizer - invalid literal/comment characters" { - testTokenize("\"\x00\"", []Token.Id { - Token.Id { .StringLiteral = Token.StrLitKind.Normal }, + testTokenize("\"\x00\"", []Token.Id{ + Token.Id{ .StringLiteral = Token.StrLitKind.Normal }, Token.Id.Invalid, }); - testTokenize("//\x00", []Token.Id { + testTokenize("//\x00", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); - testTokenize("//\x1f", []Token.Id { + testTokenize("//\x1f", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); - testTokenize("//\x7f", []Token.Id { + testTokenize("//\x7f", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); @@ -1261,18 +1260,16 @@ test "tokenizer - illegal unicode codepoints" { test "tokenizer - string identifier and builtin fns" { testTokenize( \\const @"if" = @import("std"); - , - []Token.Id{ - Token.Id.Keyword_const, - Token.Id.Identifier, - Token.Id.Equal, - Token.Id.Builtin, - Token.Id.LParen, - Token.Id {.StringLiteral = Token.StrLitKind.Normal}, - Token.Id.RParen, - Token.Id.Semicolon, - } - ); + , []Token.Id{ + Token.Id.Keyword_const, + Token.Id.Identifier, + Token.Id.Equal, + Token.Id.Builtin, + Token.Id.LParen, + Token.Id{ .StringLiteral = Token.StrLitKind.Normal }, + Token.Id.RParen, + Token.Id.Semicolon, + }); } test "tokenizer - pipe and then invalid" { @@ -1314,7 +1311,10 @@ fn testTokenize(source: []const u8, expected_tokens: []const Token.Id) void { } switch (expected_token_id) { Token.Id.StringLiteral => |expected_kind| { - std.debug.assert(expected_kind == switch (token.id) { Token.Id.StringLiteral => |kind| kind, else => unreachable }); + std.debug.assert(expected_kind == switch (token.id) { + Token.Id.StringLiteral => |kind| kind, + else => unreachable, + }); }, else => {}, } diff --git a/test/cases/align.zig b/test/cases/align.zig index a1259e96bf..f82aa6cfc4 100644 --- a/test/cases/align.zig +++ b/test/cases/align.zig @@ -70,7 +70,7 @@ test "specifying alignment allows pointer cast" { testBytesAlign(0x33); } fn testBytesAlign(b: u8) void { - var bytes align(4) = []u8 { + var bytes align(4) = []u8{ b, b, b, @@ -84,7 +84,7 @@ test "specifying alignment allows slice cast" { testBytesAlignSlice(0x33); } fn testBytesAlignSlice(b: u8) void { - var bytes align(4) = []u8 { + var bytes align(4) = []u8{ b, b, b, @@ -107,7 +107,7 @@ fn expects4(x: &align(4) u32) void { } test "@alignCast slices" { - var array align(4) = []u32 { + var array align(4) = []u32{ 1, 1, }; @@ -169,7 +169,7 @@ test "@ptrCast preserves alignment of bigger source" { test "compile-time known array index has best alignment possible" { // take full advantage of over-alignment - var array align(4) = []u8 { + var array align(4) = []u8{ 1, 2, 3, @@ -181,7 +181,7 @@ test "compile-time known array index has best alignment possible" { assert(@typeOf(&array[3]) == &u8); // because align is too small but we still figure out to use 2 - var bigger align(2) = []u64 { + var bigger align(2) = []u64{ 1, 2, 3, @@ -193,7 +193,7 @@ test "compile-time known array index has best alignment possible" { assert(@typeOf(&bigger[3]) == &align(2) u64); // because pointer is align 2 and u32 align % 2 == 0 we can assume align 2 - var smaller align(2) = []u32 { + var smaller align(2) = []u32{ 1, 2, 3, diff --git a/test/cases/array.zig b/test/cases/array.zig index 0fb61b2a9f..9a405216d8 100644 --- a/test/cases/array.zig +++ b/test/cases/array.zig @@ -34,7 +34,7 @@ test "void arrays" { } test "array literal" { - const hex_mult = []u16 { + const hex_mult = []u16{ 4096, 256, 16, @@ -54,7 +54,7 @@ test "array dot len const expr" { const ArrayDotLenConstExpr = struct { y: [some_array.len]u8, }; -const some_array = []u8 { +const some_array = []u8{ 0, 1, 2, @@ -62,7 +62,7 @@ const some_array = []u8 { }; test "nested arrays" { - const array_of_strings = [][]const u8 { + const array_of_strings = [][]const u8{ "hello", "this", "is", @@ -86,9 +86,7 @@ const Str = struct { a: []Sub, }; test "set global var array via slice embedded in struct" { - var s = Str { - .a = s_array[0..], - }; + var s = Str{ .a = s_array[0..] }; s.a[0].b = 1; s.a[1].b = 2; @@ -100,7 +98,7 @@ test "set global var array via slice embedded in struct" { } test "array literal with specified size" { - var array = [2]u8 { + var array = [2]u8{ 1, 2, }; diff --git a/test/cases/bugs/394.zig b/test/cases/bugs/394.zig index a99bd18b28..b0afec2357 100644 --- a/test/cases/bugs/394.zig +++ b/test/cases/bugs/394.zig @@ -10,11 +10,9 @@ const S = struct { const assert = @import("std").debug.assert; test "bug 394 fixed" { - const x = S { + const x = S{ .x = 3, - .y = E { - .B = 1, - }, + .y = E{ .B = 1 }, }; assert(x.x == 3); } diff --git a/test/cases/bugs/656.zig b/test/cases/bugs/656.zig index 24a28bf411..a6035d51bb 100644 --- a/test/cases/bugs/656.zig +++ b/test/cases/bugs/656.zig @@ -14,10 +14,8 @@ test "nullable if after an if in a switch prong of a switch with 2 prongs in an } fn foo(a: bool, b: bool) void { - var prefix_op = PrefixOp { - .AddrOf = Value { - .align_expr = 1234, - }, + var prefix_op = PrefixOp{ + .AddrOf = Value{ .align_expr = 1234 }, }; if (a) {} else { switch (prefix_op) { diff --git a/test/cases/bugs/828.zig b/test/cases/bugs/828.zig index 8f329e4f82..10d7370b90 100644 --- a/test/cases/bugs/828.zig +++ b/test/cases/bugs/828.zig @@ -1,14 +1,10 @@ const CountBy = struct { a: usize, - const One = CountBy { - .a = 1, - }; + const One = CountBy{ .a = 1 }; pub fn counter(self: &const CountBy) Counter { - return Counter { - .i = 0, - }; + return Counter{ .i = 0 }; } }; diff --git a/test/cases/cast.zig b/test/cases/cast.zig index 8b6afb4310..e37451ea93 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -33,27 +33,21 @@ fn funcWithConstPtrPtr(x: &const &i32) void { } test "implicitly cast a container to a const pointer of it" { - const z = Struct(void) { - .x = void{}, - }; + const z = Struct(void){ .x = void{} }; assert(0 == @sizeOf(@typeOf(z))); assert(void{} == Struct(void).pointer(z).x); assert(void{} == Struct(void).pointer(&z).x); assert(void{} == Struct(void).maybePointer(z).x); assert(void{} == Struct(void).maybePointer(&z).x); assert(void{} == Struct(void).maybePointer(null).x); - const s = Struct(u8) { - .x = 42, - }; + const s = Struct(u8){ .x = 42 }; assert(0 != @sizeOf(@typeOf(s))); assert(42 == Struct(u8).pointer(s).x); assert(42 == Struct(u8).pointer(&s).x); assert(42 == Struct(u8).maybePointer(s).x); assert(42 == Struct(u8).maybePointer(&s).x); assert(0 == Struct(u8).maybePointer(null).x); - const u = Union { - .x = 42, - }; + const u = Union{ .x = 42 }; assert(42 == Union.pointer(u).x); assert(42 == Union.pointer(&u).x); assert(42 == Union.maybePointer(u).x); @@ -77,9 +71,7 @@ fn Struct(comptime T: type) type { } fn maybePointer(self: ?&const Self) Self { - const none = Self { - .x = if (T == void) void{} else 0, - }; + const none = Self{ .x = if (T == void) void{} else 0 }; return (self ?? &none).*; } }; @@ -93,9 +85,7 @@ const Union = union { } fn maybePointer(self: ?&const Union) Union { - const none = Union { - .x = 0, - }; + const none = Union{ .x = 0 }; return (self ?? &none).*; } }; @@ -130,9 +120,7 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" { return ((??p).*.*).x; } }; - const s = S { - .x = 42, - }; + const s = S{ .x = 42 }; const p = &s; const q = &p; const r = &q; @@ -202,9 +190,7 @@ fn castToMaybeTypeError(z: i32) void { const f = z; const g: error!?i32 = f; - const a = A { - .a = z, - }; + const a = A{ .a = z }; const b: error!?A = a; assert((??(b catch unreachable)).a == 1); } @@ -343,7 +329,6 @@ test "peer type resolution: error and [N]T" { // TODO: implicit error!T to error!U where T can implicitly cast to U //assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK")); //comptime assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK")); - assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK")); comptime assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK")); } @@ -387,7 +372,7 @@ fn cast128Float(x: u128) f128 { } test "const slice widen cast" { - const bytes align(4) = []u8 { + const bytes align(4) = []u8{ 0x12, 0x12, 0x12, diff --git a/test/cases/const_slice_child.zig b/test/cases/const_slice_child.zig index 456b115234..a92c589186 100644 --- a/test/cases/const_slice_child.zig +++ b/test/cases/const_slice_child.zig @@ -4,7 +4,7 @@ const assert = debug.assert; var argv: &const &const u8 = undefined; test "const slice child" { - const strs = ([]&const u8) { + const strs = ([]&const u8){ c"one", c"two", c"three", diff --git a/test/cases/coroutines.zig b/test/cases/coroutines.zig index e983947a4c..8a0218aeb7 100644 --- a/test/cases/coroutines.zig +++ b/test/cases/coroutines.zig @@ -10,7 +10,6 @@ test "create a coroutine and cancel it" { cancel p; assert(x == 2); } - async fn simpleAsyncFn() void { x += 1; suspend; @@ -28,7 +27,6 @@ test "coroutine suspend, resume, cancel" { assert(std.mem.eql(u8, points, "abcdefg")); } - async fn testAsyncSeq() void { defer seq('e'); @@ -36,7 +34,7 @@ async fn testAsyncSeq() void { suspend; seq('d'); } -var points = []u8 {0} ** "abcdefg".len; +var points = []u8{0} ** "abcdefg".len; var index: usize = 0; fn seq(c: u8) void { @@ -54,7 +52,6 @@ test "coroutine suspend with block" { var a_promise: promise = undefined; var result = false; - async fn testSuspendBlock() void { suspend |p| { comptime assert(@typeOf(p) == promise->void); @@ -75,7 +72,6 @@ test "coroutine await" { assert(await_final_result == 1234); assert(std.mem.eql(u8, await_points, "abcdefghi")); } - async fn await_amain() void { await_seq('b'); const p = async await_another() catch unreachable; @@ -83,7 +79,6 @@ async fn await_amain() void { await_final_result = await p; await_seq('h'); } - async fn await_another() i32 { await_seq('c'); suspend |p| { @@ -94,7 +89,7 @@ async fn await_another() i32 { return 1234; } -var await_points = []u8 {0} ** "abcdefghi".len; +var await_points = []u8{0} ** "abcdefghi".len; var await_seq_index: usize = 0; fn await_seq(c: u8) void { @@ -111,7 +106,6 @@ test "coroutine await early return" { assert(early_final_result == 1234); assert(std.mem.eql(u8, early_points, "abcdef")); } - async fn early_amain() void { early_seq('b'); const p = async early_another() catch unreachable; @@ -119,13 +113,12 @@ async fn early_amain() void { early_final_result = await p; early_seq('e'); } - async fn early_another() i32 { early_seq('c'); return 1234; } -var early_points = []u8 {0} ** "abcdef".len; +var early_points = []u8{0} ** "abcdef".len; var early_seq_index: usize = 0; fn early_seq(c: u8) void { @@ -141,7 +134,6 @@ test "coro allocation failure" { error.OutOfMemory => {}, } } - async fn asyncFuncThatNeverGetsRun() void { @panic("coro frame allocation should fail"); } @@ -164,15 +156,12 @@ test "async fn pointer in a struct field" { const Foo = struct { bar: async<&std.mem.Allocator> fn(&i32) void, }; - var foo = Foo { - .bar = simpleAsyncFn2, - }; + var foo = Foo{ .bar = simpleAsyncFn2 }; const p = (async foo.bar(&data)) catch unreachable; assert(data == 2); cancel p; assert(data == 4); } - async<&std.mem.Allocator> fn simpleAsyncFn2(y: &i32) void { defer y.* += 2; y.* += 1; @@ -184,7 +173,6 @@ test "async fn with inferred error set" { resume p; cancel p; } - async fn failing() !void { suspend; return error.Fail; @@ -208,12 +196,10 @@ test "error return trace across suspend points - async return" { fn nonFailing() (promise->error!void) { return async suspendThenFail() catch unreachable; } - async fn suspendThenFail() error!void { suspend; return error.Fail; } - async fn printTrace(p: promise->error!void) void { (await p) catch |e| { std.debug.assert(e == error.Fail); @@ -234,7 +220,6 @@ test "break from suspend" { cancel p; std.debug.assert(my_result == 2); } - async fn testBreakFromSuspend(my_result: &i32) void { s: suspend |p| { break :s; diff --git a/test/cases/enum.zig b/test/cases/enum.zig index 1c46a3d9e0..cbcbc5e306 100644 --- a/test/cases/enum.zig +++ b/test/cases/enum.zig @@ -2,11 +2,9 @@ const assert = @import("std").debug.assert; const mem = @import("std").mem; test "enum type" { - const foo1 = Foo { - .One = 13, - }; - const foo2 = Foo { - .Two = Point { + const foo1 = Foo{ .One = 13 }; + const foo2 = Foo{ + .Two = Point{ .x = 1234, .y = 5678, }, @@ -48,18 +46,12 @@ const Bar = enum { }; fn returnAnInt(x: i32) Foo { - return Foo { - .One = x, - }; + return Foo{ .One = x }; } test "constant enum with payload" { - var empty = AnEnumWithPayload { - .Empty = {}, - }; - var full = AnEnumWithPayload { - .Full = 13, - }; + var empty = AnEnumWithPayload{ .Empty = {} }; + var full = AnEnumWithPayload{ .Full = 13 }; shouldBeEmpty(empty); shouldBeNotEmpty(full); } @@ -737,7 +729,7 @@ const BitFieldOfEnums = packed struct { c: C, }; -const bit_field_1 = BitFieldOfEnums { +const bit_field_1 = BitFieldOfEnums{ .a = A.Two, .b = B.Three3, .c = C.Four4, diff --git a/test/cases/enum_with_members.zig b/test/cases/enum_with_members.zig index 9e3e031f92..8fafa70b02 100644 --- a/test/cases/enum_with_members.zig +++ b/test/cases/enum_with_members.zig @@ -15,12 +15,8 @@ const ET = union(enum) { }; test "enum with members" { - const a = ET { - .SINT = -42, - }; - const b = ET { - .UINT = 42, - }; + const a = ET{ .SINT = -42 }; + const b = ET{ .UINT = 42 }; var buf: [20]u8 = undefined; assert((a.print(buf[0..]) catch unreachable) == 3); diff --git a/test/cases/error.zig b/test/cases/error.zig index 70d96e4d01..92b2a012bd 100644 --- a/test/cases/error.zig +++ b/test/cases/error.zig @@ -92,7 +92,7 @@ test "error set type " { comptime testErrorSetType(); } -const MyErrSet = error { +const MyErrSet = error{ OutOfMemory, FileNotFound, }; @@ -114,11 +114,11 @@ test "explicit error set cast" { comptime testExplicitErrorSetCast(Set1.A); } -const Set1 = error { +const Set1 = error{ A, B, }; -const Set2 = error { +const Set2 = error{ A, C, }; @@ -134,8 +134,7 @@ test "comptime test error for empty error set" { comptime testComptimeTestErrorEmptySet(1234); } -const EmptyErrorSet = error { -}; +const EmptyErrorSet = error{}; fn testComptimeTestErrorEmptySet(x: EmptyErrorSet!i32) void { if (x) |v| assert(v == 1234) else |err| @compileError("bad"); @@ -151,9 +150,10 @@ test "comptime err to int of error set with only 1 possible value" { testErrToIntWithOnePossibleValue(error.A, u32(error.A)); comptime testErrToIntWithOnePossibleValue(error.A, u32(error.A)); } -fn testErrToIntWithOnePossibleValue(x: error { - A, -}, comptime value: u32) void { +fn testErrToIntWithOnePossibleValue( + x: error{A}, + comptime value: u32, +) void { if (u32(x) != value) { @compileError("bad"); } @@ -197,16 +197,14 @@ fn foo2(f: fn() error!void) void { const x = f(); } -fn bar2() (error { -}!void) {} +fn bar2() (error{}!void) {} test "error: Zero sized error set returned with value payload crash" { _ = foo3(0); _ = comptime foo3(0); } -const Error = error { -}; +const Error = error{}; fn foo3(b: usize) Error!usize { return b; } diff --git a/test/cases/eval.zig b/test/cases/eval.zig index d7ad68b74e..3a1c67445a 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -72,12 +72,12 @@ const Point = struct { x: i32, y: i32, }; -const static_point_list = []Point { +const static_point_list = []Point{ makePoint(1, 2), makePoint(3, 4), }; fn makePoint(x: i32, y: i32) Point { - return Point { + return Point{ .x = x, .y = y, }; @@ -92,13 +92,11 @@ pub const Vec3 = struct { data: [3]f32, }; pub fn vec3(x: f32, y: f32, z: f32) Vec3 { - return Vec3 { - .data = []f32 { - x, - y, - z, - }, - }; + return Vec3{ .data = []f32{ + x, + y, + z, + } }; } test "constant expressions" { @@ -117,22 +115,22 @@ const Vertex = struct { g: f32, b: f32, }; -const vertices = []Vertex { - Vertex { +const vertices = []Vertex{ + Vertex{ .x = -0.6, .y = -0.4, .r = 1.0, .g = 0.0, .b = 0.0, }, - Vertex { + Vertex{ .x = 0.6, .y = -0.4, .r = 0.0, .g = 1.0, .b = 0.0, }, - Vertex { + Vertex{ .x = 0.0, .y = 0.6, .r = 0.0, @@ -149,7 +147,7 @@ const StInitStrFoo = struct { x: i32, y: bool, }; -var st_init_str_foo = StInitStrFoo { +var st_init_str_foo = StInitStrFoo{ .x = 13, .y = true, }; @@ -158,7 +156,7 @@ test "statically initalized array literal" { const y: [4]u8 = st_init_arr_lit_x; assert(y[3] == 4); } -const st_init_arr_lit_x = []u8 { +const st_init_arr_lit_x = []u8{ 1, 2, 3, @@ -220,16 +218,16 @@ const CmdFn = struct { func: fn(i32) i32, }; -const cmd_fns = []CmdFn { - CmdFn { +const cmd_fns = []CmdFn{ + CmdFn{ .name = "one", .func = one, }, - CmdFn { + CmdFn{ .name = "two", .func = two, }, - CmdFn { + CmdFn{ .name = "three", .func = three, }, @@ -289,9 +287,7 @@ const SimpleStruct = struct { } }; -var simple_struct = SimpleStruct { - .field = 1234, -}; +var simple_struct = SimpleStruct{ .field = 1234 }; const bound_fn = simple_struct.method; @@ -341,9 +337,7 @@ const Foo = struct { name: []const u8, }; -var foo_contents = Foo { - .name = "a", -}; +var foo_contents = Foo{ .name = "a" }; const foo_ref = &foo_contents; test "create global array with for loop" { @@ -529,9 +523,7 @@ const SingleFieldStruct = struct { }; test "const ptr to comptime mutable data is not memoized" { comptime { - var foo = SingleFieldStruct { - .x = 1, - }; + var foo = SingleFieldStruct{ .x = 1 }; assert(foo.read_x() == 1); foo.x = 2; assert(foo.read_x() == 2); @@ -574,9 +566,7 @@ pub const Info = struct { version: u8, }; -pub const diamond_info = Info { - .version = 0, -}; +pub const diamond_info = Info{ .version = 0 }; test "comptime modification of const struct field" { comptime { diff --git a/test/cases/field_parent_ptr.zig b/test/cases/field_parent_ptr.zig index 2e519098cc..1a7de9ce35 100644 --- a/test/cases/field_parent_ptr.zig +++ b/test/cases/field_parent_ptr.zig @@ -17,7 +17,7 @@ const Foo = struct { d: i32, }; -const foo = Foo { +const foo = Foo{ .a = true, .b = 0.123, .c = 1234, diff --git a/test/cases/fn.zig b/test/cases/fn.zig index 6d47dafad4..a0691fbffc 100644 --- a/test/cases/fn.zig +++ b/test/cases/fn.zig @@ -73,7 +73,7 @@ fn fnWithUnreachable() noreturn { } test "function pointers" { - const fns = []@typeOf(fn1) { + const fns = []@typeOf(fn1){ fn1, fn2, fn3, diff --git a/test/cases/fn_in_struct_in_comptime.zig b/test/cases/fn_in_struct_in_comptime.zig index 4f181d7ffb..51e494036b 100644 --- a/test/cases/fn_in_struct_in_comptime.zig +++ b/test/cases/fn_in_struct_in_comptime.zig @@ -1,6 +1,6 @@ const assert = @import("std").debug.assert; -fn get_foo() fn(&u8)usize { +fn get_foo() fn(&u8) usize { comptime { return struct { fn func(ptr: &u8) usize { diff --git a/test/cases/for.zig b/test/cases/for.zig index f13e6ec6e5..c624035708 100644 --- a/test/cases/for.zig +++ b/test/cases/for.zig @@ -3,7 +3,7 @@ const assert = std.debug.assert; const mem = std.mem; test "continue in for loop" { - const array = []i32 { + const array = []i32{ 1, 2, 3, @@ -35,7 +35,7 @@ fn mangleString(s: []u8) void { } test "basic for loop" { - const expected_result = []u8 { + const expected_result = []u8{ 9, 8, 7, @@ -57,7 +57,7 @@ test "basic for loop" { var buffer: [expected_result.len]u8 = undefined; var buf_index: usize = 0; - const array = []u8 { + const array = []u8{ 9, 8, 7, diff --git a/test/cases/generics.zig b/test/cases/generics.zig index 3fb33d0495..93fecc7295 100644 --- a/test/cases/generics.zig +++ b/test/cases/generics.zig @@ -81,11 +81,11 @@ test "function with return type type" { } test "generic struct" { - var a1 = GenNode(i32) { + var a1 = GenNode(i32){ .value = 13, .next = null, }; - var b1 = GenNode(bool) { + var b1 = GenNode(bool){ .value = true, .next = null, }; @@ -120,8 +120,8 @@ fn aGenericFn(comptime T: type, comptime a: T, b: T) T { } test "generic fn with implicit cast" { - assert(getFirstByte(u8, []u8 {13}) == 13); - assert(getFirstByte(u16, []u16 { + assert(getFirstByte(u8, []u8{13}) == 13); + assert(getFirstByte(u16, []u16{ 0, 13, }) == 0); @@ -133,7 +133,7 @@ fn getFirstByte(comptime T: type, mem: []const T) u8 { return getByte(@ptrCast(&const u8, &mem[0])); } -const foos = []fn(var) bool { +const foos = []fn(var) bool{ foo1, foo2, }; diff --git a/test/cases/incomplete_struct_param_tld.zig b/test/cases/incomplete_struct_param_tld.zig index a907ca748a..a2f57743d0 100644 --- a/test/cases/incomplete_struct_param_tld.zig +++ b/test/cases/incomplete_struct_param_tld.zig @@ -21,11 +21,9 @@ fn foo(a: &const A) i32 { } test "incomplete struct param top level declaration" { - const a = A { - .b = B { - .c = C { - .x = 13, - }, + const a = A{ + .b = B{ + .c = C{ .x = 13 }, }, }; assert(foo(a) == 13); diff --git a/test/cases/math.zig b/test/cases/math.zig index 3c6156a3ea..0b4622702f 100644 --- a/test/cases/math.zig +++ b/test/cases/math.zig @@ -197,7 +197,7 @@ fn test_u64_div() void { assert(result.remainder == 100663296); } fn divWithResult(a: u64, b: u64) DivResult { - return DivResult { + return DivResult{ .quotient = a / b, .remainder = a % b, }; diff --git a/test/cases/misc.zig b/test/cases/misc.zig index deeeca8c3a..42de163ea5 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -232,7 +232,7 @@ test "string escapes" { } test "multiline string" { - const s1 = + const s1 = \\one \\two) \\three @@ -242,7 +242,7 @@ test "multiline string" { } test "multiline C string" { - const s1 = + const s1 = c\\one c\\two) c\\three @@ -350,15 +350,13 @@ const Test3Point = struct { x: i32, y: i32, }; -const test3_foo = Test3Foo { - .Three = Test3Point { +const test3_foo = Test3Foo{ + .Three = Test3Point{ .x = 3, .y = 4, }, }; -const test3_bar = Test3Foo { - .Two = 13, -}; +const test3_bar = Test3Foo{ .Two = 13 }; fn test3_1(f: &const Test3Foo) void { switch (f.*) { Test3Foo.Three => |pt| { @@ -417,7 +415,7 @@ test "C string concatenation" { test "cast slice to u8 slice" { assert(@sizeOf(i32) == 4); - var big_thing_array = []i32 { + var big_thing_array = []i32{ 1, 2, 3, @@ -458,9 +456,9 @@ test "non const ptr to aliased type" { } test "array 2D const double ptr" { - const rect_2d_vertexes = [][1]f32 { - []f32 {1.0}, - []f32 {2.0}, + const rect_2d_vertexes = [][1]f32{ + []f32{1.0}, + []f32{2.0}, }; testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]); } @@ -565,7 +563,7 @@ test "volatile load and store" { test "slice string literal has type []const u8" { comptime { assert(@typeOf("aoeu"[0..]) == []const u8); - const array = []i32 { + const array = []i32{ 1, 2, 3, @@ -581,13 +579,9 @@ test "global variable initialized to global variable array element" { const GDTEntry = struct { field: i32, }; -var gdt = []GDTEntry { - GDTEntry { - .field = 1, - }, - GDTEntry { - .field = 2, - }, +var gdt = []GDTEntry{ + GDTEntry{ .field = 1 }, + GDTEntry{ .field = 2 }, }; var global_ptr = &gdt[0]; @@ -648,9 +642,7 @@ fn testStructInFn() void { kind: BlockKind, }; - var block = Block { - .kind = 1234, - }; + var block = Block{ .kind = 1234 }; block.kind += 1; @@ -694,12 +686,10 @@ const PackedEnum = packed enum { }; test "packed struct, enum, union parameters in extern function" { - testPackedStuff(PackedStruct { + testPackedStuff(PackedStruct{ .a = 1, .b = 2, - }, PackedUnion { - .a = 1, - }, PackedEnum.A); + }, PackedUnion{ .a = 1 }, PackedEnum.A); } export fn testPackedStuff(a: &const PackedStruct, b: &const PackedUnion, c: PackedEnum) void {} diff --git a/test/cases/null.zig b/test/cases/null.zig index 96a62ab1ed..936e5fafbd 100644 --- a/test/cases/null.zig +++ b/test/cases/null.zig @@ -58,7 +58,7 @@ fn foo(x: ?i32) ?bool { } test "if var maybe pointer" { - assert(shouldBeAPlus1(Particle { + assert(shouldBeAPlus1(Particle{ .a = 14, .b = 1, .c = 1, @@ -92,9 +92,7 @@ test "null literal outside function" { const SillyStruct = struct { context: ?i32, }; -const here_is_a_null_literal = SillyStruct { - .context = null, -}; +const here_is_a_null_literal = SillyStruct{ .context = null }; test "test null runtime" { testTestNullRuntime(null); diff --git a/test/cases/reflection.zig b/test/cases/reflection.zig index f9b64c80eb..b82ce6340f 100644 --- a/test/cases/reflection.zig +++ b/test/cases/reflection.zig @@ -59,7 +59,7 @@ test "reflection: enum member types and names" { } test "reflection: @field" { - var f = Foo { + var f = Foo{ .one = 42, .two = true, .three = void{}, diff --git a/test/cases/slice.zig b/test/cases/slice.zig index 4ca194672c..eae6fa895e 100644 --- a/test/cases/slice.zig +++ b/test/cases/slice.zig @@ -18,7 +18,7 @@ test "slice child property" { } test "runtime safety lets us slice from len..len" { - var an_array = []u8 { + var an_array = []u8{ 1, 2, 3, diff --git a/test/cases/struct.zig b/test/cases/struct.zig index c474d99f2b..37b0e497f0 100644 --- a/test/cases/struct.zig +++ b/test/cases/struct.zig @@ -27,7 +27,7 @@ test "invake static method in global scope" { } test "void struct fields" { - const foo = VoidStructFieldsFoo { + const foo = VoidStructFieldsFoo{ .a = void{}, .b = 1, .c = void{}, @@ -96,16 +96,12 @@ test "struct byval assign" { } fn structInitializer() void { - const val = Val { - .x = 42, - }; + const val = Val{ .x = 42 }; assert(val.x == 42); } test "fn call of struct field" { - assert(callStructField(Foo { - .ptr = aFunc, - }) == 13); + assert(callStructField(Foo{ .ptr = aFunc }) == 13); } const Foo = struct { @@ -121,9 +117,7 @@ fn callStructField(foo: &const Foo) i32 { } test "store member function in variable" { - const instance = MemberFnTestFoo { - .x = 1234, - }; + const instance = MemberFnTestFoo{ .x = 1234 }; const memberFn = MemberFnTestFoo.member; const result = memberFn(instance); assert(result == 1234); @@ -136,17 +130,13 @@ const MemberFnTestFoo = struct { }; test "call member function directly" { - const instance = MemberFnTestFoo { - .x = 1234, - }; + const instance = MemberFnTestFoo{ .x = 1234 }; const result = MemberFnTestFoo.member(instance); assert(result == 1234); } test "member functions" { - const r = MemberFnRand { - .seed = 1234, - }; + const r = MemberFnRand{ .seed = 1234 }; assert(r.getSeed() == 1234); } const MemberFnRand = struct { @@ -165,7 +155,7 @@ const Bar = struct { y: i32, }; fn makeBar(x: i32, y: i32) Bar { - return Bar { + return Bar{ .x = x, .y = y, }; @@ -190,7 +180,7 @@ fn testReturnEmptyStructFromFn() EmptyStruct2 { } test "pass slice of empty struct to fn" { - assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2 {EmptyStruct2{}}) == 1); + assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2{EmptyStruct2{}}) == 1); } fn testPassSliceOfEmptyStructToFn(slice: []const EmptyStruct2) usize { return slice.len; @@ -202,7 +192,7 @@ const APackedStruct = packed struct { }; test "packed struct" { - var foo = APackedStruct { + var foo = APackedStruct{ .x = 1, .y = 2, }; @@ -217,7 +207,7 @@ const BitField1 = packed struct { c: u2, }; -const bit_field_1 = BitField1 { +const bit_field_1 = BitField1{ .a = 1, .b = 2, .c = 3, @@ -267,7 +257,7 @@ test "packed struct 24bits" { assert(@sizeOf(Foo96Bits) == 12); } - var value = Foo96Bits { + var value = Foo96Bits{ .a = 0, .b = 0, .c = 0, @@ -310,7 +300,7 @@ test "packed array 24bits" { assert(@sizeOf(FooArray24Bits) == 2 + 2 * 3 + 2); } - var bytes = []u8 {0} ** (@sizeOf(FooArray24Bits) + 1); + var bytes = []u8{0} ** (@sizeOf(FooArray24Bits) + 1); bytes[bytes.len - 1] = 0xaa; const ptr = &([]FooArray24Bits)(bytes[0..bytes.len - 1])[0]; assert(ptr.a == 0); @@ -360,7 +350,7 @@ test "aligned array of packed struct" { assert(@sizeOf(FooArrayOfAligned) == 2 * 2); } - var bytes = []u8 {0xbb} ** @sizeOf(FooArrayOfAligned); + var bytes = []u8{0xbb} ** @sizeOf(FooArrayOfAligned); const ptr = &([]FooArrayOfAligned)(bytes[0..bytes.len])[0]; assert(ptr.a[0].a == 0xbb); @@ -370,11 +360,11 @@ test "aligned array of packed struct" { } test "runtime struct initialization of bitfield" { - const s1 = Nibbles { + const s1 = Nibbles{ .x = x1, .y = x1, }; - const s2 = Nibbles { + const s2 = Nibbles{ .x = u4(x2), .y = u4(x2), }; diff --git a/test/cases/struct_contains_slice_of_itself.zig b/test/cases/struct_contains_slice_of_itself.zig index ee34c16baf..07987ae32b 100644 --- a/test/cases/struct_contains_slice_of_itself.zig +++ b/test/cases/struct_contains_slice_of_itself.zig @@ -6,31 +6,31 @@ const Node = struct { }; test "struct contains slice of itself" { - var other_nodes = []Node { - Node { + var other_nodes = []Node{ + Node{ .payload = 31, .children = []Node{}, }, - Node { + Node{ .payload = 32, .children = []Node{}, }, }; - var nodes = []Node { - Node { + var nodes = []Node{ + Node{ .payload = 1, .children = []Node{}, }, - Node { + Node{ .payload = 2, .children = []Node{}, }, - Node { + Node{ .payload = 3, .children = other_nodes[0..], }, }; - const root = Node { + const root = Node{ .payload = 1234, .children = nodes[0..], }; diff --git a/test/cases/switch.zig b/test/cases/switch.zig index b870297f18..495fa9f3ed 100644 --- a/test/cases/switch.zig +++ b/test/cases/switch.zig @@ -6,10 +6,7 @@ test "switch with numbers" { fn testSwitchWithNumbers(x: u32) void { const result = switch (x) { - 1, - 2, - 3, - 4 ... 8 => false, + 1, 2, 3, 4...8 => false, 13 => true, else => false, }; @@ -25,9 +22,9 @@ test "switch with all ranges" { fn testSwitchWithAllRanges(x: u32, y: u32) u32 { return switch (x) { - 0 ... 100 => 1, - 101 ... 200 => 2, - 201 ... 300 => 3, + 0...100 => 1, + 101...200 => 2, + 201...300 => 3, else => y, }; } @@ -37,10 +34,8 @@ test "implicit comptime switch" { const result = switch (x) { 3 => 10, 4 => 11, - 5, - 6 => 12, - 7, - 8 => 13, + 5, 6 => 12, + 7, 8 => 13, else => 14, }; @@ -86,15 +81,9 @@ const SwitchStatmentFoo = enum { }; test "switch prong with variable" { - switchProngWithVarFn(SwitchProngWithVarEnum { - .One = 13, - }); - switchProngWithVarFn(SwitchProngWithVarEnum { - .Two = 13.0, - }); - switchProngWithVarFn(SwitchProngWithVarEnum { - .Meh = {}, - }); + switchProngWithVarFn(SwitchProngWithVarEnum{ .One = 13 }); + switchProngWithVarFn(SwitchProngWithVarEnum{ .Two = 13.0 }); + switchProngWithVarFn(SwitchProngWithVarEnum{ .Meh = {} }); } const SwitchProngWithVarEnum = union(enum) { One: i32, @@ -121,9 +110,7 @@ test "switch on enum using pointer capture" { } fn testSwitchEnumPtrCapture() void { - var value = SwitchProngWithVarEnum { - .One = 1234, - }; + var value = SwitchProngWithVarEnum{ .One = 1234 }; switch (value) { SwitchProngWithVarEnum.One => |*x| x.* += 1, else => unreachable, @@ -136,12 +123,8 @@ fn testSwitchEnumPtrCapture() void { test "switch with multiple expressions" { const x = switch (returnsFive()) { - 1, - 2, - 3 => 1, - 4, - 5, - 6 => 2, + 1, 2, 3 => 1, + 4, 5, 6 => 2, else => i32(3), }; assert(x == 2); @@ -156,9 +139,7 @@ const Number = union(enum) { Three: f32, }; -const number = Number { - .Three = 1.23, -}; +const number = Number{ .Three = 1.23 }; fn returnsFalse() bool { switch (number) { @@ -212,12 +193,11 @@ fn testSwitchHandleAllCasesExhaustive(x: u2) u2 { fn testSwitchHandleAllCasesRange(x: u8) u8 { return switch (x) { - 0 ... 100 => u8(0), - 101 ... 200 => 1, - 201, - 203 => 2, + 0...100 => u8(0), + 101...200 => 1, + 201, 203 => 2, 202 => 4, - 204 ... 255 => 3, + 204...255 => 3, }; } diff --git a/test/cases/switch_prong_err_enum.zig b/test/cases/switch_prong_err_enum.zig index 2d28d2f4c7..f060ac2c57 100644 --- a/test/cases/switch_prong_err_enum.zig +++ b/test/cases/switch_prong_err_enum.zig @@ -14,9 +14,7 @@ const FormValue = union(enum) { fn doThing(form_id: u64) error!FormValue { return switch (form_id) { - 17 => FormValue { - .Address = try readOnce(), - }, + 17 => FormValue{ .Address = try readOnce() }, else => error.InvalidDebugInfo, }; } diff --git a/test/cases/switch_prong_implicit_cast.zig b/test/cases/switch_prong_implicit_cast.zig index 3d80f3fdb2..56d37e290f 100644 --- a/test/cases/switch_prong_implicit_cast.zig +++ b/test/cases/switch_prong_implicit_cast.zig @@ -7,12 +7,8 @@ const FormValue = union(enum) { fn foo(id: u64) !FormValue { return switch (id) { - 2 => FormValue { - .Two = true, - }, - 1 => FormValue { - .One = {}, - }, + 2 => FormValue{ .Two = true }, + 1 => FormValue{ .One = {} }, else => return error.Whatever, }; } diff --git a/test/cases/this.zig b/test/cases/this.zig index 8ed5e1ae1a..5e433b5037 100644 --- a/test/cases/this.zig +++ b/test/cases/this.zig @@ -29,7 +29,7 @@ test "this refer to module call private fn" { } test "this refer to container" { - var pt = Point(i32) { + var pt = Point(i32){ .x = 12, .y = 34, }; diff --git a/test/cases/try.zig b/test/cases/try.zig index 483bf6a915..cf5fa5862a 100644 --- a/test/cases/try.zig +++ b/test/cases/try.zig @@ -7,8 +7,7 @@ test "try on error union" { fn tryOnErrorUnionImpl() void { const x = if (returnsTen()) |val| val + 1 else |err| switch (err) { - error.ItBroke, - error.NoMem => 1, + error.ItBroke, error.NoMem => 1, error.CrappedOut => i32(2), else => unreachable, }; diff --git a/test/cases/type_info.zig b/test/cases/type_info.zig index 7bf1e68180..eee5d1f2ca 100644 --- a/test/cases/type_info.zig +++ b/test/cases/type_info.zig @@ -103,7 +103,7 @@ test "type info: error set, error union info" { } fn testErrorSet() void { - const TestErrorSet = error { + const TestErrorSet = error{ First, Second, Third, @@ -196,7 +196,7 @@ fn testStruct() void { assert(!struct_info.Struct.defs[0].data.Fn.is_extern); assert(struct_info.Struct.defs[0].data.Fn.lib_name == null); assert(struct_info.Struct.defs[0].data.Fn.return_type == void); - assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn(&const TestStruct)void); + assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn(&const TestStruct) void); } const TestStruct = packed struct { diff --git a/test/cases/union.zig b/test/cases/union.zig index 93b5f740be..005ad08e6a 100644 --- a/test/cases/union.zig +++ b/test/cases/union.zig @@ -50,10 +50,10 @@ test "basic unions" { test "comptime union field access" { comptime { - var foo = Foo { .int = 0 }; + var foo = Foo{ .int = 0 }; assert(foo.int == 0); - foo = Foo { .float = 42.42 }; + foo = Foo{ .float = 42.42 }; assert(foo.float == 42.42); } } @@ -286,7 +286,6 @@ const PartialInstWithPayload = union(enum) { Compiled: i32, }; - test "access a member of tagged union with conflicting enum tag name" { const Bar = union(enum) { A: A, diff --git a/test/cases/var_args.zig b/test/cases/var_args.zig index 81f800568c..ec4d2059f3 100644 --- a/test/cases/var_args.zig +++ b/test/cases/var_args.zig @@ -58,7 +58,7 @@ fn extraFn(extra: u32, args: ...) usize { return args.len; } -const foos = []fn(...) bool { +const foos = []fn(...) bool{ foo1, foo2, }; diff --git a/test/cases/void.zig b/test/cases/void.zig index f4d72209e4..ef91690878 100644 --- a/test/cases/void.zig +++ b/test/cases/void.zig @@ -8,7 +8,7 @@ const Foo = struct { test "compare void with void compile time known" { comptime { - const foo = Foo { + const foo = Foo{ .a = {}, .b = 1, .c = {}, diff --git a/test/cases/while.zig b/test/cases/while.zig index 574a7b7e76..a95481668d 100644 --- a/test/cases/while.zig +++ b/test/cases/while.zig @@ -151,7 +151,7 @@ test "while on nullable with else result follow break prong" { test "while on error union with else result follow else prong" { const result = while (returnError()) |value| { break value; - } else|err| + } else |err| i32(2); assert(result == 2); } @@ -159,7 +159,7 @@ test "while on error union with else result follow else prong" { test "while on error union with else result follow break prong" { const result = while (returnSuccess(10)) |value| { break value; - } else|err| + } else |err| i32(2); assert(result == 10); } diff --git a/test/compare_output.zig b/test/compare_output.zig index 905ffd37a9..0170477b8b 100644 --- a/test/compare_output.zig +++ b/test/compare_output.zig @@ -475,7 +475,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\ ); - tc.setCommandLineArgs([][]const u8 { + tc.setCommandLineArgs([][]const u8{ "first arg", "'a' 'b' \\", "bare", @@ -516,7 +516,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\ ); - tc.setCommandLineArgs([][]const u8 { + tc.setCommandLineArgs([][]const u8{ "first arg", "'a' 'b' \\", "bare", diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 904ba6d9d8..5215953d0a 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1,7 +1,8 @@ const tests = @import("tests.zig"); pub fn addCases(cases: &tests.CompileErrorContext) void { - cases.add("invalid deref on switch target", + cases.add( + "invalid deref on switch target", \\comptime { \\ var tile = Tile.Empty; \\ switch (tile.*) { @@ -14,15 +15,19 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ Filled, \\}; , - ".tmp_source.zig:3:17: error: invalid deref on switch target"); + ".tmp_source.zig:3:17: error: invalid deref on switch target", + ); - cases.add("invalid field access in comptime", + cases.add( + "invalid field access in comptime", \\comptime { var x = doesnt_exist.whatever; } , - ".tmp_source.zig:1:20: error: use of undeclared identifier 'doesnt_exist'"); + ".tmp_source.zig:1:20: error: use of undeclared identifier 'doesnt_exist'", + ); - cases.add("suspend inside suspend block", - \\const std = @import("std"); + cases.add( + "suspend inside suspend block", + \\const std = @import("std",); \\ \\export fn entry() void { \\ var buf: [500]u8 = undefined; @@ -39,27 +44,32 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:12:9: error: cannot suspend inside suspend block", - ".tmp_source.zig:11:5: note: other suspend block here"); + ".tmp_source.zig:11:5: note: other suspend block here", + ); - cases.add("assign inline fn to non-comptime var", + cases.add( + "assign inline fn to non-comptime var", \\export fn entry() void { \\ var a = b; \\} \\inline fn b() void { } , ".tmp_source.zig:2:5: error: functions marked inline must be stored in const or comptime var", - ".tmp_source.zig:4:8: note: declared here"); + ".tmp_source.zig:4:8: note: declared here", + ); - cases.add("wrong type passed to @panic", + cases.add( + "wrong type passed to @panic", \\export fn entry() void { \\ var e = error.Foo; \\ @panic(e); \\} , - ".tmp_source.zig:3:12: error: expected type '[]const u8', found 'error{Foo}'"); + ".tmp_source.zig:3:12: error: expected type '[]const u8', found 'error{Foo}'", + ); - - cases.add("@tagName used on union with no associated enum tag", + cases.add( + "@tagName used on union with no associated enum tag", \\const FloatInt = extern union { \\ Float: f32, \\ Int: i32, @@ -70,10 +80,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:7:19: error: union has no associated enum", - ".tmp_source.zig:1:18: note: declared here"); + ".tmp_source.zig:1:18: note: declared here", + ); - cases.add("returning error from void async function", - \\const std = @import("std"); + cases.add( + "returning error from void async function", + \\const std = @import("std",); \\export fn entry() void { \\ const p = async amain() catch unreachable; \\} @@ -81,31 +93,39 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return error.ShouldBeCompileError; \\} , - ".tmp_source.zig:6:17: error: expected type 'void', found 'error{ShouldBeCompileError}'"); + ".tmp_source.zig:6:17: error: expected type 'void', found 'error{ShouldBeCompileError}'", + ); - cases.add("var not allowed in structs", + cases.add( + "var not allowed in structs", \\export fn entry() void { \\ var s = (struct{v: var}){.v=i32(10)}; \\} , - ".tmp_source.zig:2:23: error: invalid token: 'var'"); + ".tmp_source.zig:2:23: error: invalid token: 'var'", + ); - cases.add("@ptrCast discards const qualifier", + cases.add( + "@ptrCast discards const qualifier", \\export fn entry() void { \\ const x: i32 = 1234; \\ const y = @ptrCast(&i32, &x); \\} , - ".tmp_source.zig:3:15: error: cast discards const qualifier"); + ".tmp_source.zig:3:15: error: cast discards const qualifier", + ); - cases.add("comptime slice of undefined pointer non-zero len", + cases.add( + "comptime slice of undefined pointer non-zero len", \\export fn entry() void { \\ const slice = (&i32)(undefined)[0..1]; \\} , - ".tmp_source.zig:2:36: error: non-zero length slice of undefined pointer"); + ".tmp_source.zig:2:36: error: non-zero length slice of undefined pointer", + ); - cases.add("type checking function pointers", + cases.add( + "type checking function pointers", \\fn a(b: fn (&const u8) void) void { \\ b('a'); \\} @@ -116,9 +136,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ a(c); \\} , - ".tmp_source.zig:8:7: error: expected type 'fn(&const u8) void', found 'fn(u8) void'"); + ".tmp_source.zig:8:7: error: expected type 'fn(&const u8) void', found 'fn(u8) void'", + ); - cases.add("no else prong on switch on global error set", + cases.add( + "no else prong on switch on global error set", \\export fn entry() void { \\ foo(error.A); \\} @@ -128,18 +150,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:5:5: error: else prong required when switching on type 'error'"); + ".tmp_source.zig:5:5: error: else prong required when switching on type 'error'", + ); - cases.add("inferred error set with no returned error", + cases.add( + "inferred error set with no returned error", \\export fn entry() void { \\ foo() catch unreachable; \\} \\fn foo() !void { \\} , - ".tmp_source.zig:4:11: error: function with inferred error set must return at least one possible error"); + ".tmp_source.zig:4:11: error: function with inferred error set must return at least one possible error", + ); - cases.add("error not handled in switch", + cases.add( + "error not handled in switch", \\export fn entry() void { \\ foo(452) catch |err| switch (err) { \\ error.Foo => {}, @@ -155,9 +181,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:2:26: error: error.Baz not handled in switch", - ".tmp_source.zig:2:26: error: error.Bar not handled in switch"); + ".tmp_source.zig:2:26: error: error.Bar not handled in switch", + ); - cases.add("duplicate error in switch", + cases.add( + "duplicate error in switch", \\export fn entry() void { \\ foo(452) catch |err| switch (err) { \\ error.Foo => {}, @@ -175,9 +203,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:5:14: error: duplicate switch value: '@typeOf(foo).ReturnType.ErrorSet.Foo'", - ".tmp_source.zig:3:14: note: other value is here"); + ".tmp_source.zig:3:14: note: other value is here", + ); - cases.add("range operator in switch used on error set", + cases.add( + "range operator in switch used on error set", \\export fn entry() void { \\ try foo(452) catch |err| switch (err) { \\ error.A ... error.B => {}, @@ -192,31 +222,39 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:3:17: error: operator not allowed for errors"); + ".tmp_source.zig:3:17: error: operator not allowed for errors", + ); - cases.add("inferring error set of function pointer", + cases.add( + "inferring error set of function pointer", \\comptime { \\ const z: ?fn()!void = null; \\} , - ".tmp_source.zig:2:15: error: inferring error set of return type valid only for function definitions"); + ".tmp_source.zig:2:15: error: inferring error set of return type valid only for function definitions", + ); - cases.add("access non-existent member of error set", + cases.add( + "access non-existent member of error set", \\const Foo = error{A}; \\comptime { \\ const z = Foo.Bar; \\} , - ".tmp_source.zig:3:18: error: no error named 'Bar' in 'Foo'"); + ".tmp_source.zig:3:18: error: no error named 'Bar' in 'Foo'", + ); - cases.add("error union operator with non error set LHS", + cases.add( + "error union operator with non error set LHS", \\comptime { \\ const z = i32!i32; \\} , - ".tmp_source.zig:2:15: error: expected error set type, found type 'i32'"); + ".tmp_source.zig:2:15: error: expected error set type, found type 'i32'", + ); - cases.add("error equality but sets have no common members", + cases.add( + "error equality but sets have no common members", \\const Set1 = error{A, C}; \\const Set2 = error{B, D}; \\export fn entry() void { @@ -228,16 +266,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:7:11: error: error sets 'Set1' and 'Set2' have no common errors"); + ".tmp_source.zig:7:11: error: error sets 'Set1' and 'Set2' have no common errors", + ); - cases.add("only equality binary operator allowed for error sets", + cases.add( + "only equality binary operator allowed for error sets", \\comptime { \\ const z = error.A > error.B; \\} , - ".tmp_source.zig:2:23: error: operator not allowed for errors"); + ".tmp_source.zig:2:23: error: operator not allowed for errors", + ); - cases.add("explicit error set cast known at comptime violates error sets", + cases.add( + "explicit error set cast known at comptime violates error sets", \\const Set1 = error {A, B}; \\const Set2 = error {A, C}; \\comptime { @@ -245,9 +287,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var y = Set2(x); \\} , - ".tmp_source.zig:5:17: error: error.B not a member of error set 'Set2'"); + ".tmp_source.zig:5:17: error: error.B not a member of error set 'Set2'", + ); - cases.add("cast error union of global error set to error union of smaller error set", + cases.add( + "cast error union of global error set to error union of smaller error set", \\const SmallErrorSet = error{A}; \\export fn entry() void { \\ var x: SmallErrorSet!i32 = foo(); @@ -257,9 +301,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:35: error: expected 'SmallErrorSet!i32', found 'error!i32'", - ".tmp_source.zig:3:35: note: unable to cast global error set into smaller set"); + ".tmp_source.zig:3:35: note: unable to cast global error set into smaller set", + ); - cases.add("cast global error set to error set", + cases.add( + "cast global error set to error set", \\const SmallErrorSet = error{A}; \\export fn entry() void { \\ var x: SmallErrorSet = foo(); @@ -269,9 +315,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:31: error: expected 'SmallErrorSet', found 'error'", - ".tmp_source.zig:3:31: note: unable to cast global error set into smaller set"); + ".tmp_source.zig:3:31: note: unable to cast global error set into smaller set", + ); - cases.add("recursive inferred error set", + cases.add( + "recursive inferred error set", \\export fn entry() void { \\ foo() catch unreachable; \\} @@ -279,9 +327,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ try foo(); \\} , - ".tmp_source.zig:5:5: error: cannot resolve inferred error set '@typeOf(foo).ReturnType.ErrorSet': function 'foo' not fully analyzed yet"); + ".tmp_source.zig:5:5: error: cannot resolve inferred error set '@typeOf(foo).ReturnType.ErrorSet': function 'foo' not fully analyzed yet", + ); - cases.add("implicit cast of error set not a subset", + cases.add( + "implicit cast of error set not a subset", \\const Set1 = error{A, B}; \\const Set2 = error{A, C}; \\export fn entry() void { @@ -292,18 +342,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:7:19: error: expected 'Set2', found 'Set1'", - ".tmp_source.zig:1:23: note: 'error.B' not a member of destination error set"); + ".tmp_source.zig:1:23: note: 'error.B' not a member of destination error set", + ); - cases.add("int to err global invalid number", + cases.add( + "int to err global invalid number", \\const Set1 = error{A, B}; \\comptime { \\ var x: usize = 3; \\ var y = error(x); \\} , - ".tmp_source.zig:4:18: error: integer value 3 represents no error"); + ".tmp_source.zig:4:18: error: integer value 3 represents no error", + ); - cases.add("int to err non global invalid number", + cases.add( + "int to err non global invalid number", \\const Set1 = error{A, B}; \\const Set2 = error{A, C}; \\comptime { @@ -311,16 +365,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var y = Set2(x); \\} , - ".tmp_source.zig:5:17: error: integer value 2 represents no error in 'Set2'"); + ".tmp_source.zig:5:17: error: integer value 2 represents no error in 'Set2'", + ); - cases.add("@memberCount of error", + cases.add( + "@memberCount of error", \\comptime { \\ _ = @memberCount(error); \\} , - ".tmp_source.zig:2:9: error: global error set member count not available at comptime"); + ".tmp_source.zig:2:9: error: global error set member count not available at comptime", + ); - cases.add("duplicate error value in error set", + cases.add( + "duplicate error value in error set", \\const Foo = error { \\ Bar, \\ Bar, @@ -330,22 +388,30 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:5: error: duplicate error: 'Bar'", - ".tmp_source.zig:2:5: note: other error here"); + ".tmp_source.zig:2:5: note: other error here", + ); - cases.add("cast negative integer literal to usize", + cases.add( + "cast negative integer literal to usize", \\export fn entry() void { \\ const x = usize(-10); \\} - , ".tmp_source.zig:2:21: error: cannot cast negative value -10 to unsigned integer type 'usize'"); + , + ".tmp_source.zig:2:21: error: cannot cast negative value -10 to unsigned integer type 'usize'", + ); - cases.add("use invalid number literal as array index", + cases.add( + "use invalid number literal as array index", \\var v = 25; \\export fn entry() void { \\ var arr: [v]u8 = undefined; \\} - , ".tmp_source.zig:1:1: error: unable to infer variable type"); + , + ".tmp_source.zig:1:1: error: unable to infer variable type", + ); - cases.add("duplicate struct field", + cases.add( + "duplicate struct field", \\const Foo = struct { \\ Bar: i32, \\ Bar: usize, @@ -355,9 +421,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:5: error: duplicate struct field: 'Bar'", - ".tmp_source.zig:2:5: note: other field here"); + ".tmp_source.zig:2:5: note: other field here", + ); - cases.add("duplicate union field", + cases.add( + "duplicate union field", \\const Foo = union { \\ Bar: i32, \\ Bar: usize, @@ -367,9 +435,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:5: error: duplicate union field: 'Bar'", - ".tmp_source.zig:2:5: note: other field here"); + ".tmp_source.zig:2:5: note: other field here", + ); - cases.add("duplicate enum field", + cases.add( + "duplicate enum field", \\const Foo = enum { \\ Bar, \\ Bar, @@ -380,77 +450,108 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:5: error: duplicate enum field: 'Bar'", - ".tmp_source.zig:2:5: note: other field here"); + ".tmp_source.zig:2:5: note: other field here", + ); - cases.add("calling function with naked calling convention", + cases.add( + "calling function with naked calling convention", \\export fn entry() void { \\ foo(); \\} \\nakedcc fn foo() void { } , ".tmp_source.zig:2:5: error: unable to call function with naked calling convention", - ".tmp_source.zig:4:9: note: declared here"); + ".tmp_source.zig:4:9: note: declared here", + ); - cases.add("function with invalid return type", + cases.add( + "function with invalid return type", \\export fn foo() boid {} - , ".tmp_source.zig:1:17: error: use of undeclared identifier 'boid'"); + , + ".tmp_source.zig:1:17: error: use of undeclared identifier 'boid'", + ); - cases.add("function with non-extern non-packed enum parameter", + cases.add( + "function with non-extern non-packed enum parameter", \\const Foo = enum { A, B, C }; \\export fn entry(foo: Foo) void { } - , ".tmp_source.zig:2:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:2:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'", + ); - cases.add("function with non-extern non-packed struct parameter", + cases.add( + "function with non-extern non-packed struct parameter", \\const Foo = struct { \\ A: i32, \\ B: f32, \\ C: bool, \\}; \\export fn entry(foo: Foo) void { } - , ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'", + ); - cases.add("function with non-extern non-packed union parameter", + cases.add( + "function with non-extern non-packed union parameter", \\const Foo = union { \\ A: i32, \\ B: f32, \\ C: bool, \\}; \\export fn entry(foo: Foo) void { } - , ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'", + ); - cases.add("switch on enum with 1 field with no prongs", + cases.add( + "switch on enum with 1 field with no prongs", \\const Foo = enum { M }; \\ \\export fn entry() void { \\ var f = Foo.M; \\ switch (f) {} \\} - , ".tmp_source.zig:5:5: error: enumeration value 'Foo.M' not handled in switch"); + , + ".tmp_source.zig:5:5: error: enumeration value 'Foo.M' not handled in switch", + ); - cases.add("shift by negative comptime integer", + cases.add( + "shift by negative comptime integer", \\comptime { \\ var a = 1 >> -1; \\} - , ".tmp_source.zig:2:18: error: shift by negative value -1"); + , + ".tmp_source.zig:2:18: error: shift by negative value -1", + ); - cases.add("@panic called at compile time", + cases.add( + "@panic called at compile time", \\export fn entry() void { \\ comptime { - \\ @panic("aoeu"); + \\ @panic("aoeu",); \\ } \\} - , ".tmp_source.zig:3:9: error: encountered @panic at compile-time"); + , + ".tmp_source.zig:3:9: error: encountered @panic at compile-time", + ); - cases.add("wrong return type for main", + cases.add( + "wrong return type for main", \\pub fn main() f32 { } - , "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'"); + , + "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'", + ); - cases.add("double ?? on main return value", + cases.add( + "double ?? on main return value", \\pub fn main() ??void { \\} - , "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'"); + , + "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'", + ); - cases.add("bad identifier in function with struct defined inside function which references local const", + cases.add( + "bad identifier in function with struct defined inside function which references local const", \\export fn entry() void { \\ const BlockKind = u32; \\ @@ -460,9 +561,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\ bogus; \\} - , ".tmp_source.zig:8:5: error: use of undeclared identifier 'bogus'"); + , + ".tmp_source.zig:8:5: error: use of undeclared identifier 'bogus'", + ); - cases.add("labeled break not found", + cases.add( + "labeled break not found", \\export fn entry() void { \\ blah: while (true) { \\ while (true) { @@ -470,9 +574,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\ } \\} - , ".tmp_source.zig:4:13: error: label not found: 'outer'"); + , + ".tmp_source.zig:4:13: error: label not found: 'outer'", + ); - cases.add("labeled continue not found", + cases.add( + "labeled continue not found", \\export fn entry() void { \\ var i: usize = 0; \\ blah: while (i < 10) : (i += 1) { @@ -481,9 +588,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\ } \\} - , ".tmp_source.zig:5:13: error: labeled loop not found: 'outer'"); + , + ".tmp_source.zig:5:13: error: labeled loop not found: 'outer'", + ); - cases.add("attempt to use 0 bit type in extern fn", + cases.add( + "attempt to use 0 bit type in extern fn", \\extern fn foo(ptr: extern fn(&void) void) void; \\ \\export fn entry() void { @@ -491,390 +601,541 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\extern fn bar(x: &void) void { } - , ".tmp_source.zig:7:18: error: parameter of type '&void' has 0 bits; not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:7:18: error: parameter of type '&void' has 0 bits; not allowed in function with calling convention 'ccc'", + ); - cases.add("implicit semicolon - block statement", + cases.add( + "implicit semicolon - block statement", \\export fn entry() void { \\ {} \\ var good = {}; \\ ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - block expr", + cases.add( + "implicit semicolon - block expr", \\export fn entry() void { \\ _ = {}; \\ var good = {}; \\ _ = {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - comptime statement", + cases.add( + "implicit semicolon - comptime statement", \\export fn entry() void { \\ comptime {} \\ var good = {}; \\ comptime ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - comptime expression", + cases.add( + "implicit semicolon - comptime expression", \\export fn entry() void { \\ _ = comptime {}; \\ var good = {}; \\ _ = comptime {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - defer", + cases.add( + "implicit semicolon - defer", \\export fn entry() void { \\ defer {} \\ var good = {}; \\ defer ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if statement", + cases.add( + "implicit semicolon - if statement", \\export fn entry() void { \\ if(true) {} \\ var good = {}; \\ if(true) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if expression", + cases.add( + "implicit semicolon - if expression", \\export fn entry() void { \\ _ = if(true) {}; \\ var good = {}; \\ _ = if(true) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else statement", + cases.add( + "implicit semicolon - if-else statement", \\export fn entry() void { \\ if(true) {} else {} \\ var good = {}; \\ if(true) ({}) else ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else expression", + cases.add( + "implicit semicolon - if-else expression", \\export fn entry() void { \\ _ = if(true) {} else {}; \\ var good = {}; \\ _ = if(true) {} else {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else-if statement", + cases.add( + "implicit semicolon - if-else-if statement", \\export fn entry() void { \\ if(true) {} else if(true) {} \\ var good = {}; \\ if(true) ({}) else if(true) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else-if expression", + cases.add( + "implicit semicolon - if-else-if expression", \\export fn entry() void { \\ _ = if(true) {} else if(true) {}; \\ var good = {}; \\ _ = if(true) {} else if(true) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else-if-else statement", + cases.add( + "implicit semicolon - if-else-if-else statement", \\export fn entry() void { \\ if(true) {} else if(true) {} else {} \\ var good = {}; \\ if(true) ({}) else if(true) ({}) else ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else-if-else expression", + cases.add( + "implicit semicolon - if-else-if-else expression", \\export fn entry() void { \\ _ = if(true) {} else if(true) {} else {}; \\ var good = {}; \\ _ = if(true) {} else if(true) {} else {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - test statement", + cases.add( + "implicit semicolon - test statement", \\export fn entry() void { \\ if (foo()) |_| {} \\ var good = {}; \\ if (foo()) |_| ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - test expression", + cases.add( + "implicit semicolon - test expression", \\export fn entry() void { \\ _ = if (foo()) |_| {}; \\ var good = {}; \\ _ = if (foo()) |_| {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - while statement", + cases.add( + "implicit semicolon - while statement", \\export fn entry() void { \\ while(true) {} \\ var good = {}; \\ while(true) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - while expression", + cases.add( + "implicit semicolon - while expression", \\export fn entry() void { \\ _ = while(true) {}; \\ var good = {}; \\ _ = while(true) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - while-continue statement", + cases.add( + "implicit semicolon - while-continue statement", \\export fn entry() void { \\ while(true):({}) {} \\ var good = {}; \\ while(true):({}) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - while-continue expression", + cases.add( + "implicit semicolon - while-continue expression", \\export fn entry() void { \\ _ = while(true):({}) {}; \\ var good = {}; \\ _ = while(true):({}) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - for statement", + cases.add( + "implicit semicolon - for statement", \\export fn entry() void { \\ for(foo()) {} \\ var good = {}; \\ for(foo()) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - for expression", + cases.add( + "implicit semicolon - for expression", \\export fn entry() void { \\ _ = for(foo()) {}; \\ var good = {}; \\ _ = for(foo()) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("multiple function definitions", + cases.add( + "multiple function definitions", \\fn a() void {} \\fn a() void {} \\export fn entry() void { a(); } - , ".tmp_source.zig:2:1: error: redefinition of 'a'"); + , + ".tmp_source.zig:2:1: error: redefinition of 'a'", + ); - cases.add("unreachable with return", + cases.add( + "unreachable with return", \\fn a() noreturn {return;} \\export fn entry() void { a(); } - , ".tmp_source.zig:1:18: error: expected type 'noreturn', found 'void'"); + , + ".tmp_source.zig:1:18: error: expected type 'noreturn', found 'void'", + ); - cases.add("control reaches end of non-void function", + cases.add( + "control reaches end of non-void function", \\fn a() i32 {} \\export fn entry() void { _ = a(); } - , ".tmp_source.zig:1:12: error: expected type 'i32', found 'void'"); + , + ".tmp_source.zig:1:12: error: expected type 'i32', found 'void'", + ); - cases.add("undefined function call", + cases.add( + "undefined function call", \\export fn a() void { \\ b(); \\} - , ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'"); + , + ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'", + ); - cases.add("wrong number of arguments", + cases.add( + "wrong number of arguments", \\export fn a() void { \\ b(1); \\} \\fn b(a: i32, b: i32, c: i32) void { } - , ".tmp_source.zig:2:6: error: expected 3 arguments, found 1"); + , + ".tmp_source.zig:2:6: error: expected 3 arguments, found 1", + ); - cases.add("invalid type", + cases.add( + "invalid type", \\fn a() bogus {} \\export fn entry() void { _ = a(); } - , ".tmp_source.zig:1:8: error: use of undeclared identifier 'bogus'"); + , + ".tmp_source.zig:1:8: error: use of undeclared identifier 'bogus'", + ); - cases.add("pointer to noreturn", + cases.add( + "pointer to noreturn", \\fn a() &noreturn {} \\export fn entry() void { _ = a(); } - , ".tmp_source.zig:1:9: error: pointer to noreturn not allowed"); + , + ".tmp_source.zig:1:9: error: pointer to noreturn not allowed", + ); - cases.add("unreachable code", + cases.add( + "unreachable code", \\export fn a() void { \\ return; \\ b(); \\} \\ \\fn b() void {} - , ".tmp_source.zig:3:5: error: unreachable code"); + , + ".tmp_source.zig:3:5: error: unreachable code", + ); - cases.add("bad import", - \\const bogus = @import("bogus-does-not-exist.zig"); + cases.add( + "bad import", + \\const bogus = @import("bogus-does-not-exist.zig",); \\export fn entry() void { bogus.bogo(); } - , ".tmp_source.zig:1:15: error: unable to find 'bogus-does-not-exist.zig'"); + , + ".tmp_source.zig:1:15: error: unable to find 'bogus-does-not-exist.zig'", + ); - cases.add("undeclared identifier", + cases.add( + "undeclared identifier", \\export fn a() void { \\ return \\ b + \\ c; \\} , - ".tmp_source.zig:3:5: error: use of undeclared identifier 'b'", - ".tmp_source.zig:4:5: error: use of undeclared identifier 'c'"); + ".tmp_source.zig:3:5: error: use of undeclared identifier 'b'", + ".tmp_source.zig:4:5: error: use of undeclared identifier 'c'", + ); - cases.add("parameter redeclaration", + cases.add( + "parameter redeclaration", \\fn f(a : i32, a : i32) void { \\} \\export fn entry() void { f(1, 2); } - , ".tmp_source.zig:1:15: error: redeclaration of variable 'a'"); + , + ".tmp_source.zig:1:15: error: redeclaration of variable 'a'", + ); - cases.add("local variable redeclaration", + cases.add( + "local variable redeclaration", \\export fn f() void { \\ const a : i32 = 0; \\ const a = 0; \\} - , ".tmp_source.zig:3:5: error: redeclaration of variable 'a'"); + , + ".tmp_source.zig:3:5: error: redeclaration of variable 'a'", + ); - cases.add("local variable redeclares parameter", + cases.add( + "local variable redeclares parameter", \\fn f(a : i32) void { \\ const a = 0; \\} \\export fn entry() void { f(1); } - , ".tmp_source.zig:2:5: error: redeclaration of variable 'a'"); + , + ".tmp_source.zig:2:5: error: redeclaration of variable 'a'", + ); - cases.add("variable has wrong type", + cases.add( + "variable has wrong type", \\export fn f() i32 { \\ const a = c"a"; \\ return a; \\} - , ".tmp_source.zig:3:12: error: expected type 'i32', found '&const u8'"); + , + ".tmp_source.zig:3:12: error: expected type 'i32', found '&const u8'", + ); - cases.add("if condition is bool, not int", + cases.add( + "if condition is bool, not int", \\export fn f() void { \\ if (0) {} \\} - , ".tmp_source.zig:2:9: error: integer value 0 cannot be implicitly casted to type 'bool'"); + , + ".tmp_source.zig:2:9: error: integer value 0 cannot be implicitly casted to type 'bool'", + ); - cases.add("assign unreachable", + cases.add( + "assign unreachable", \\export fn f() void { \\ const a = return; \\} - , ".tmp_source.zig:2:5: error: unreachable code"); + , + ".tmp_source.zig:2:5: error: unreachable code", + ); - cases.add("unreachable variable", + cases.add( + "unreachable variable", \\export fn f() void { \\ const a: noreturn = {}; \\} - , ".tmp_source.zig:2:14: error: variable of type 'noreturn' not allowed"); + , + ".tmp_source.zig:2:14: error: variable of type 'noreturn' not allowed", + ); - cases.add("unreachable parameter", + cases.add( + "unreachable parameter", \\fn f(a: noreturn) void {} \\export fn entry() void { f(); } - , ".tmp_source.zig:1:9: error: parameter of type 'noreturn' not allowed"); + , + ".tmp_source.zig:1:9: error: parameter of type 'noreturn' not allowed", + ); - cases.add("bad assignment target", + cases.add( + "bad assignment target", \\export fn f() void { \\ 3 = 3; \\} - , ".tmp_source.zig:2:7: error: cannot assign to constant"); + , + ".tmp_source.zig:2:7: error: cannot assign to constant", + ); - cases.add("assign to constant variable", + cases.add( + "assign to constant variable", \\export fn f() void { \\ const a = 3; \\ a = 4; \\} - , ".tmp_source.zig:3:7: error: cannot assign to constant"); + , + ".tmp_source.zig:3:7: error: cannot assign to constant", + ); - cases.add("use of undeclared identifier", + cases.add( + "use of undeclared identifier", \\export fn f() void { \\ b = 3; \\} - , ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'"); + , + ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'", + ); - cases.add("const is a statement, not an expression", + cases.add( + "const is a statement, not an expression", \\export fn f() void { \\ (const a = 0); \\} - , ".tmp_source.zig:2:6: error: invalid token: 'const'"); + , + ".tmp_source.zig:2:6: error: invalid token: 'const'", + ); - cases.add("array access of undeclared identifier", + cases.add( + "array access of undeclared identifier", \\export fn f() void { \\ i[i] = i[i]; \\} - , ".tmp_source.zig:2:5: error: use of undeclared identifier 'i'", - ".tmp_source.zig:2:12: error: use of undeclared identifier 'i'"); + , + ".tmp_source.zig:2:5: error: use of undeclared identifier 'i'", + ".tmp_source.zig:2:12: error: use of undeclared identifier 'i'", + ); - cases.add("array access of non array", + cases.add( + "array access of non array", \\export fn f() void { \\ var bad : bool = undefined; \\ bad[bad] = bad[bad]; \\} - , ".tmp_source.zig:3:8: error: array access of non-array type 'bool'", - ".tmp_source.zig:3:19: error: array access of non-array type 'bool'"); + , + ".tmp_source.zig:3:8: error: array access of non-array type 'bool'", + ".tmp_source.zig:3:19: error: array access of non-array type 'bool'", + ); - cases.add("array access with non integer index", + cases.add( + "array access with non integer index", \\export fn f() void { \\ var array = "aoeu"; \\ var bad = false; \\ array[bad] = array[bad]; \\} - , ".tmp_source.zig:4:11: error: expected type 'usize', found 'bool'", - ".tmp_source.zig:4:24: error: expected type 'usize', found 'bool'"); + , + ".tmp_source.zig:4:11: error: expected type 'usize', found 'bool'", + ".tmp_source.zig:4:24: error: expected type 'usize', found 'bool'", + ); - cases.add("write to const global variable", + cases.add( + "write to const global variable", \\const x : i32 = 99; \\fn f() void { \\ x = 1; \\} \\export fn entry() void { f(); } - , ".tmp_source.zig:3:7: error: cannot assign to constant"); + , + ".tmp_source.zig:3:7: error: cannot assign to constant", + ); - - cases.add("missing else clause", + cases.add( + "missing else clause", \\fn f(b: bool) void { \\ const x : i32 = if (b) h: { break :h 1; }; \\ const y = if (b) h: { break :h i32(1); }; \\} \\export fn entry() void { f(true); } - , ".tmp_source.zig:2:42: error: integer value 1 cannot be implicitly casted to type 'void'", - ".tmp_source.zig:3:15: error: incompatible types: 'i32' and 'void'"); + , + ".tmp_source.zig:2:42: error: integer value 1 cannot be implicitly casted to type 'void'", + ".tmp_source.zig:3:15: error: incompatible types: 'i32' and 'void'", + ); - cases.add("direct struct loop", + cases.add( + "direct struct loop", \\const A = struct { a : A, }; \\export fn entry() usize { return @sizeOf(A); } - , ".tmp_source.zig:1:11: error: struct 'A' contains itself"); + , + ".tmp_source.zig:1:11: error: struct 'A' contains itself", + ); - cases.add("indirect struct loop", + cases.add( + "indirect struct loop", \\const A = struct { b : B, }; \\const B = struct { c : C, }; \\const C = struct { a : A, }; \\export fn entry() usize { return @sizeOf(A); } - , ".tmp_source.zig:1:11: error: struct 'A' contains itself"); + , + ".tmp_source.zig:1:11: error: struct 'A' contains itself", + ); - cases.add("invalid struct field", + cases.add( + "invalid struct field", \\const A = struct { x : i32, }; \\export fn f() void { \\ var a : A = undefined; @@ -882,27 +1143,37 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const y = a.bar; \\} , - ".tmp_source.zig:4:6: error: no member named 'foo' in struct 'A'", - ".tmp_source.zig:5:16: error: no member named 'bar' in struct 'A'"); + ".tmp_source.zig:4:6: error: no member named 'foo' in struct 'A'", + ".tmp_source.zig:5:16: error: no member named 'bar' in struct 'A'", + ); - cases.add("redefinition of struct", + cases.add( + "redefinition of struct", \\const A = struct { x : i32, }; \\const A = struct { y : i32, }; - , ".tmp_source.zig:2:1: error: redefinition of 'A'"); + , + ".tmp_source.zig:2:1: error: redefinition of 'A'", + ); - cases.add("redefinition of enums", + cases.add( + "redefinition of enums", \\const A = enum {}; \\const A = enum {}; - , ".tmp_source.zig:2:1: error: redefinition of 'A'"); + , + ".tmp_source.zig:2:1: error: redefinition of 'A'", + ); - cases.add("redefinition of global variables", + cases.add( + "redefinition of global variables", \\var a : i32 = 1; \\var a : i32 = 2; , - ".tmp_source.zig:2:1: error: redefinition of 'a'", - ".tmp_source.zig:1:1: note: previous definition is here"); + ".tmp_source.zig:2:1: error: redefinition of 'a'", + ".tmp_source.zig:1:1: note: previous definition is here", + ); - cases.add("duplicate field in struct value expression", + cases.add( + "duplicate field in struct value expression", \\const A = struct { \\ x : i32, \\ y : i32, @@ -916,9 +1187,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ .z = 4, \\ }; \\} - , ".tmp_source.zig:11:9: error: duplicate field"); + , + ".tmp_source.zig:11:9: error: duplicate field", + ); - cases.add("missing field in struct value expression", + cases.add( + "missing field in struct value expression", \\const A = struct { \\ x : i32, \\ y : i32, @@ -932,9 +1206,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ .y = 2, \\ }; \\} - , ".tmp_source.zig:9:17: error: missing field: 'x'"); + , + ".tmp_source.zig:9:17: error: missing field: 'x'", + ); - cases.add("invalid field in struct value expression", + cases.add( + "invalid field in struct value expression", \\const A = struct { \\ x : i32, \\ y : i32, @@ -947,66 +1224,95 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ .foo = 42, \\ }; \\} - , ".tmp_source.zig:10:9: error: no member named 'foo' in struct 'A'"); + , + ".tmp_source.zig:10:9: error: no member named 'foo' in struct 'A'", + ); - cases.add("invalid break expression", + cases.add( + "invalid break expression", \\export fn f() void { \\ break; \\} - , ".tmp_source.zig:2:5: error: break expression outside loop"); + , + ".tmp_source.zig:2:5: error: break expression outside loop", + ); - cases.add("invalid continue expression", + cases.add( + "invalid continue expression", \\export fn f() void { \\ continue; \\} - , ".tmp_source.zig:2:5: error: continue expression outside loop"); + , + ".tmp_source.zig:2:5: error: continue expression outside loop", + ); - cases.add("invalid maybe type", + cases.add( + "invalid maybe type", \\export fn f() void { \\ if (true) |x| { } \\} - , ".tmp_source.zig:2:9: error: expected nullable type, found 'bool'"); + , + ".tmp_source.zig:2:9: error: expected nullable type, found 'bool'", + ); - cases.add("cast unreachable", + cases.add( + "cast unreachable", \\fn f() i32 { \\ return i32(return 1); \\} \\export fn entry() void { _ = f(); } - , ".tmp_source.zig:2:15: error: unreachable code"); + , + ".tmp_source.zig:2:15: error: unreachable code", + ); - cases.add("invalid builtin fn", + cases.add( + "invalid builtin fn", \\fn f() @bogus(foo) { \\} \\export fn entry() void { _ = f(); } - , ".tmp_source.zig:1:8: error: invalid builtin function: 'bogus'"); + , + ".tmp_source.zig:1:8: error: invalid builtin function: 'bogus'", + ); - cases.add("top level decl dependency loop", + cases.add( + "top level decl dependency loop", \\const a : @typeOf(b) = 0; \\const b : @typeOf(a) = 0; \\export fn entry() void { \\ const c = a + b; \\} - , ".tmp_source.zig:1:1: error: 'a' depends on itself"); + , + ".tmp_source.zig:1:1: error: 'a' depends on itself", + ); - cases.add("noalias on non pointer param", + cases.add( + "noalias on non pointer param", \\fn f(noalias x: i32) void {} \\export fn entry() void { f(1234); } - , ".tmp_source.zig:1:6: error: noalias on non-pointer parameter"); + , + ".tmp_source.zig:1:6: error: noalias on non-pointer parameter", + ); - cases.add("struct init syntax for array", + cases.add( + "struct init syntax for array", \\const foo = []u16{.x = 1024,}; \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:1:18: error: type '[]u16' does not support struct initialization syntax"); + , + ".tmp_source.zig:1:18: error: type '[]u16' does not support struct initialization syntax", + ); - cases.add("type variables must be constant", + cases.add( + "type variables must be constant", \\var foo = u8; \\export fn entry() foo { \\ return 1; \\} - , ".tmp_source.zig:1:1: error: variable of type 'type' must be constant"); + , + ".tmp_source.zig:1:1: error: variable of type 'type' must be constant", + ); - - cases.add("variables shadowing types", + cases.add( + "variables shadowing types", \\const Foo = struct {}; \\const Bar = struct {}; \\ @@ -1018,12 +1324,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ f(1234); \\} , - ".tmp_source.zig:4:6: error: redefinition of 'Foo'", - ".tmp_source.zig:1:1: note: previous definition is here", - ".tmp_source.zig:5:5: error: redefinition of 'Bar'", - ".tmp_source.zig:2:1: note: previous definition is here"); + ".tmp_source.zig:4:6: error: redefinition of 'Foo'", + ".tmp_source.zig:1:1: note: previous definition is here", + ".tmp_source.zig:5:5: error: redefinition of 'Bar'", + ".tmp_source.zig:2:1: note: previous definition is here", + ); - cases.add("switch expression - missing enumeration prong", + cases.add( + "switch expression - missing enumeration prong", \\const Number = enum { \\ One, \\ Two, @@ -1039,9 +1347,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:8:5: error: enumeration value 'Number.Four' not handled in switch"); + , + ".tmp_source.zig:8:5: error: enumeration value 'Number.Four' not handled in switch", + ); - cases.add("switch expression - duplicate enumeration prong", + cases.add( + "switch expression - duplicate enumeration prong", \\const Number = enum { \\ One, \\ Two, @@ -1059,10 +1370,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:13:15: error: duplicate switch value", - ".tmp_source.zig:10:15: note: other value is here"); + , + ".tmp_source.zig:13:15: error: duplicate switch value", + ".tmp_source.zig:10:15: note: other value is here", + ); - cases.add("switch expression - duplicate enumeration prong when else present", + cases.add( + "switch expression - duplicate enumeration prong when else present", \\const Number = enum { \\ One, \\ Two, @@ -1081,10 +1395,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:13:15: error: duplicate switch value", - ".tmp_source.zig:10:15: note: other value is here"); + , + ".tmp_source.zig:13:15: error: duplicate switch value", + ".tmp_source.zig:10:15: note: other value is here", + ); - cases.add("switch expression - multiple else prongs", + cases.add( + "switch expression - multiple else prongs", \\fn f(x: u32) void { \\ const value: bool = switch (x) { \\ 1234 => false, @@ -1095,9 +1412,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry() void { \\ f(1234); \\} - , ".tmp_source.zig:5:9: error: multiple else prongs in switch expression"); + , + ".tmp_source.zig:5:9: error: multiple else prongs in switch expression", + ); - cases.add("switch expression - non exhaustive integer prongs", + cases.add( + "switch expression - non exhaustive integer prongs", \\fn foo(x: u8) void { \\ switch (x) { \\ 0 => {}, @@ -1105,9 +1425,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:2:5: error: switch must handle all possibilities"); + ".tmp_source.zig:2:5: error: switch must handle all possibilities", + ); - cases.add("switch expression - duplicate or overlapping integer value", + cases.add( + "switch expression - duplicate or overlapping integer value", \\fn foo(x: u8) u8 { \\ return switch (x) { \\ 0 ... 100 => u8(0), @@ -1119,9 +1441,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , ".tmp_source.zig:6:9: error: duplicate switch value", - ".tmp_source.zig:5:14: note: previous value is here"); + ".tmp_source.zig:5:14: note: previous value is here", + ); - cases.add("switch expression - switch on pointer type with no else", + cases.add( + "switch expression - switch on pointer type with no else", \\fn foo(x: &u8) void { \\ switch (x) { \\ &y => {}, @@ -1130,54 +1454,77 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\const y: u8 = 100; \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:2:5: error: else prong required when switching on type '&u8'"); + ".tmp_source.zig:2:5: error: else prong required when switching on type '&u8'", + ); - cases.add("global variable initializer must be constant expression", + cases.add( + "global variable initializer must be constant expression", \\extern fn foo() i32; \\const x = foo(); \\export fn entry() i32 { return x; } - , ".tmp_source.zig:2:11: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:2:11: error: unable to evaluate constant expression", + ); - cases.add("array concatenation with wrong type", + cases.add( + "array concatenation with wrong type", \\const src = "aoeu"; \\const derp = usize(1234); \\const a = derp ++ "foo"; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } - , ".tmp_source.zig:3:11: error: expected array or C string literal, found 'usize'"); + , + ".tmp_source.zig:3:11: error: expected array or C string literal, found 'usize'", + ); - cases.add("non compile time array concatenation", + cases.add( + "non compile time array concatenation", \\fn f() []u8 { \\ return s ++ "foo"; \\} \\var s: [10]u8 = undefined; \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:2:12: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:2:12: error: unable to evaluate constant expression", + ); - cases.add("@cImport with bogus include", + cases.add( + "@cImport with bogus include", \\const c = @cImport(@cInclude("bogus.h")); \\export fn entry() usize { return @sizeOf(@typeOf(c.bogo)); } - , ".tmp_source.zig:1:11: error: C import failed", - ".h:1:10: note: 'bogus.h' file not found"); + , + ".tmp_source.zig:1:11: error: C import failed", + ".h:1:10: note: 'bogus.h' file not found", + ); - cases.add("address of number literal", + cases.add( + "address of number literal", \\const x = 3; \\const y = &x; \\fn foo() &const i32 { return y; } \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:3:30: error: expected type '&const i32', found '&const (integer literal)'"); + , + ".tmp_source.zig:3:30: error: expected type '&const i32', found '&const (integer literal)'", + ); - cases.add("integer overflow error", + cases.add( + "integer overflow error", \\const x : u8 = 300; \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:1:16: error: integer value 300 cannot be implicitly casted to type 'u8'"); + , + ".tmp_source.zig:1:16: error: integer value 300 cannot be implicitly casted to type 'u8'", + ); - cases.add("incompatible number literals", + cases.add( + "incompatible number literals", \\const x = 2 == 2.0; \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:1:11: error: integer value 2 cannot be implicitly casted to type '(float literal)'"); + , + ".tmp_source.zig:1:11: error: integer value 2 cannot be implicitly casted to type '(float literal)'", + ); - cases.add("missing function call param", + cases.add( + "missing function call param", \\const Foo = struct { \\ a: i32, \\ b: i32, @@ -1201,58 +1548,73 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:20:34: error: expected 1 arguments, found 0"); + , + ".tmp_source.zig:20:34: error: expected 1 arguments, found 0", + ); - cases.add("missing function name and param name", + cases.add( + "missing function name and param name", \\fn () void {} \\fn f(i32) void {} \\export fn entry() usize { return @sizeOf(@typeOf(f)); } , - ".tmp_source.zig:1:1: error: missing function name", - ".tmp_source.zig:2:6: error: missing parameter name"); + ".tmp_source.zig:1:1: error: missing function name", + ".tmp_source.zig:2:6: error: missing parameter name", + ); - cases.add("wrong function type", + cases.add( + "wrong function type", \\const fns = []fn() void { a, b, c }; \\fn a() i32 {return 0;} \\fn b() i32 {return 1;} \\fn c() i32 {return 2;} \\export fn entry() usize { return @sizeOf(@typeOf(fns)); } - , ".tmp_source.zig:1:27: error: expected type 'fn() void', found 'fn() i32'"); + , + ".tmp_source.zig:1:27: error: expected type 'fn() void', found 'fn() i32'", + ); - cases.add("extern function pointer mismatch", + cases.add( + "extern function pointer mismatch", \\const fns = [](fn(i32)i32) { a, b, c }; \\pub fn a(x: i32) i32 {return x + 0;} \\pub fn b(x: i32) i32 {return x + 1;} \\export fn c(x: i32) i32 {return x + 2;} \\ \\export fn entry() usize { return @sizeOf(@typeOf(fns)); } - , ".tmp_source.zig:1:36: error: expected type 'fn(i32) i32', found 'extern fn(i32) i32'"); + , + ".tmp_source.zig:1:36: error: expected type 'fn(i32) i32', found 'extern fn(i32) i32'", + ); - - cases.add("implicit cast from f64 to f32", + cases.add( + "implicit cast from f64 to f32", \\const x : f64 = 1.0; \\const y : f32 = x; \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } - , ".tmp_source.zig:2:17: error: expected type 'f32', found 'f64'"); + , + ".tmp_source.zig:2:17: error: expected type 'f32', found 'f64'", + ); - - cases.add("colliding invalid top level functions", + cases.add( + "colliding invalid top level functions", \\fn func() bogus {} \\fn func() bogus {} \\export fn entry() usize { return @sizeOf(@typeOf(func)); } , - ".tmp_source.zig:2:1: error: redefinition of 'func'", - ".tmp_source.zig:1:11: error: use of undeclared identifier 'bogus'"); + ".tmp_source.zig:2:1: error: redefinition of 'func'", + ".tmp_source.zig:1:11: error: use of undeclared identifier 'bogus'", + ); - - cases.add("bogus compile var", + cases.add( + "bogus compile var", \\const x = @import("builtin").bogus; \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:1:29: error: no member named 'bogus' in '"); + , + ".tmp_source.zig:1:29: error: no member named 'bogus' in '", + ); - - cases.add("non constant expression in array size outside function", + cases.add( + "non constant expression in array size outside function", \\const Foo = struct { \\ y: [get()]u8, \\}; @@ -1261,22 +1623,25 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(Foo)); } , - ".tmp_source.zig:5:25: error: unable to evaluate constant expression", - ".tmp_source.zig:2:12: note: called from here", - ".tmp_source.zig:2:8: note: called from here"); + ".tmp_source.zig:5:25: error: unable to evaluate constant expression", + ".tmp_source.zig:2:12: note: called from here", + ".tmp_source.zig:2:8: note: called from here", + ); - - cases.add("addition with non numbers", + cases.add( + "addition with non numbers", \\const Foo = struct { \\ field: i32, \\}; \\const x = Foo {.field = 1} + Foo {.field = 2}; \\ \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:4:28: error: invalid operands to binary expression: 'Foo' and 'Foo'"); + , + ".tmp_source.zig:4:28: error: invalid operands to binary expression: 'Foo' and 'Foo'", + ); - - cases.add("division by zero", + cases.add( + "division by zero", \\const lit_int_x = 1 / 0; \\const lit_float_x = 1.0 / 0.0; \\const int_x = u32(1) / u32(0); @@ -1287,49 +1652,65 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry3() usize { return @sizeOf(@typeOf(int_x)); } \\export fn entry4() usize { return @sizeOf(@typeOf(float_x)); } , - ".tmp_source.zig:1:21: error: division by zero", - ".tmp_source.zig:2:25: error: division by zero", - ".tmp_source.zig:3:22: error: division by zero", - ".tmp_source.zig:4:26: error: division by zero"); + ".tmp_source.zig:1:21: error: division by zero", + ".tmp_source.zig:2:25: error: division by zero", + ".tmp_source.zig:3:22: error: division by zero", + ".tmp_source.zig:4:26: error: division by zero", + ); - - cases.add("normal string with newline", + cases.add( + "normal string with newline", \\const foo = "a \\b"; \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:1:13: error: newline not allowed in string literal"); + , + ".tmp_source.zig:1:13: error: newline not allowed in string literal", + ); - cases.add("invalid comparison for function pointers", + cases.add( + "invalid comparison for function pointers", \\fn foo() void {} \\const invalid = foo > foo; \\ \\export fn entry() usize { return @sizeOf(@typeOf(invalid)); } - , ".tmp_source.zig:2:21: error: operator not allowed for type 'fn() void'"); + , + ".tmp_source.zig:2:21: error: operator not allowed for type 'fn() void'", + ); - cases.add("generic function instance with non-constant expression", + cases.add( + "generic function instance with non-constant expression", \\fn foo(comptime x: i32, y: i32) i32 { return x + y; } \\fn test1(a: i32, b: i32) i32 { \\ return foo(a, b); \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(test1)); } - , ".tmp_source.zig:3:16: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:3:16: error: unable to evaluate constant expression", + ); - cases.add("assign null to non-nullable pointer", + cases.add( + "assign null to non-nullable pointer", \\const a: &u8 = null; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } - , ".tmp_source.zig:1:16: error: expected type '&u8', found '(null)'"); + , + ".tmp_source.zig:1:16: error: expected type '&u8', found '(null)'", + ); - cases.add("indexing an array of size zero", + cases.add( + "indexing an array of size zero", \\const array = []u8{}; \\export fn foo() void { \\ const pointer = &array[0]; \\} - , ".tmp_source.zig:3:27: error: index 0 outside array of size 0"); + , + ".tmp_source.zig:3:27: error: index 0 outside array of size 0", + ); - cases.add("compile time division by zero", + cases.add( + "compile time division by zero", \\const y = foo(0); \\fn foo(x: u32) u32 { \\ return 1 / x; @@ -1337,17 +1718,21 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:14: error: division by zero", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:14: error: division by zero", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("branch on undefined value", + cases.add( + "branch on undefined value", \\const x = if (undefined) true else false; \\ \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:1:15: error: use of undefined value"); + , + ".tmp_source.zig:1:15: error: use of undefined value", + ); - - cases.add("endless loop in function evaluation", + cases.add( + "endless loop in function evaluation", \\const seventh_fib_number = fibbonaci(7); \\fn fibbonaci(x: i32) i32 { \\ return fibbonaci(x - 1) + fibbonaci(x - 2); @@ -1355,16 +1740,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(seventh_fib_number)); } , - ".tmp_source.zig:3:21: error: evaluation exceeded 1000 backwards branches", - ".tmp_source.zig:3:21: note: called from here"); + ".tmp_source.zig:3:21: error: evaluation exceeded 1000 backwards branches", + ".tmp_source.zig:3:21: note: called from here", + ); - cases.add("@embedFile with bogus file", - \\const resource = @embedFile("bogus.txt"); + cases.add( + "@embedFile with bogus file", + \\const resource = @embedFile("bogus.txt",); \\ \\export fn entry() usize { return @sizeOf(@typeOf(resource)); } - , ".tmp_source.zig:1:29: error: unable to find '", "bogus.txt'"); + , + ".tmp_source.zig:1:29: error: unable to find '", + "bogus.txt'", + ); - cases.add("non-const expression in struct literal outside function", + cases.add( + "non-const expression in struct literal outside function", \\const Foo = struct { \\ x: i32, \\}; @@ -1372,9 +1763,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\extern fn get_it() i32; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } - , ".tmp_source.zig:4:21: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:4:21: error: unable to evaluate constant expression", + ); - cases.add("non-const expression function call with struct return value outside function", + cases.add( + "non-const expression function call with struct return value outside function", \\const Foo = struct { \\ x: i32, \\}; @@ -1387,19 +1781,24 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } , - ".tmp_source.zig:6:24: error: unable to evaluate constant expression", - ".tmp_source.zig:4:17: note: called from here"); + ".tmp_source.zig:6:24: error: unable to evaluate constant expression", + ".tmp_source.zig:4:17: note: called from here", + ); - cases.add("undeclared identifier error should mark fn as impure", + cases.add( + "undeclared identifier error should mark fn as impure", \\export fn foo() void { \\ test_a_thing(); \\} \\fn test_a_thing() void { \\ bad_fn_call(); \\} - , ".tmp_source.zig:5:5: error: use of undeclared identifier 'bad_fn_call'"); + , + ".tmp_source.zig:5:5: error: use of undeclared identifier 'bad_fn_call'", + ); - cases.add("illegal comparison of types", + cases.add( + "illegal comparison of types", \\fn bad_eql_1(a: []u8, b: []u8) bool { \\ return a == b; \\} @@ -1414,10 +1813,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry1() usize { return @sizeOf(@typeOf(bad_eql_1)); } \\export fn entry2() usize { return @sizeOf(@typeOf(bad_eql_2)); } , - ".tmp_source.zig:2:14: error: operator not allowed for type '[]u8'", - ".tmp_source.zig:9:16: error: operator not allowed for type 'EnumWithData'"); + ".tmp_source.zig:2:14: error: operator not allowed for type '[]u8'", + ".tmp_source.zig:9:16: error: operator not allowed for type 'EnumWithData'", + ); - cases.add("non-const switch number literal", + cases.add( + "non-const switch number literal", \\export fn foo() void { \\ const x = switch (bar()) { \\ 1, 2 => 1, @@ -1428,25 +1829,34 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\fn bar() i32 { \\ return 2; \\} - , ".tmp_source.zig:2:15: error: unable to infer expression type"); + , + ".tmp_source.zig:2:15: error: unable to infer expression type", + ); - cases.add("atomic orderings of cmpxchg - failure stricter than success", + cases.add( + "atomic orderings of cmpxchg - failure stricter than success", \\const AtomicOrder = @import("builtin").AtomicOrder; \\export fn f() void { \\ var x: i32 = 1234; \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Monotonic, AtomicOrder.SeqCst)) {} \\} - , ".tmp_source.zig:4:81: error: failure atomic ordering must be no stricter than success"); + , + ".tmp_source.zig:4:81: error: failure atomic ordering must be no stricter than success", + ); - cases.add("atomic orderings of cmpxchg - success Monotonic or stricter", + cases.add( + "atomic orderings of cmpxchg - success Monotonic or stricter", \\const AtomicOrder = @import("builtin").AtomicOrder; \\export fn f() void { \\ var x: i32 = 1234; \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Unordered, AtomicOrder.Unordered)) {} \\} - , ".tmp_source.zig:4:58: error: success atomic ordering must be Monotonic or stricter"); + , + ".tmp_source.zig:4:58: error: success atomic ordering must be Monotonic or stricter", + ); - cases.add("negation overflow in function evaluation", + cases.add( + "negation overflow in function evaluation", \\const y = neg(-128); \\fn neg(x: i8) i8 { \\ return -x; @@ -1454,10 +1864,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:12: error: negation caused overflow", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:12: error: negation caused overflow", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("add overflow in function evaluation", + cases.add( + "add overflow in function evaluation", \\const y = add(65530, 10); \\fn add(a: u16, b: u16) u16 { \\ return a + b; @@ -1465,11 +1877,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:14: error: operation caused overflow", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:14: error: operation caused overflow", + ".tmp_source.zig:1:14: note: called from here", + ); - - cases.add("sub overflow in function evaluation", + cases.add( + "sub overflow in function evaluation", \\const y = sub(10, 20); \\fn sub(a: u16, b: u16) u16 { \\ return a - b; @@ -1477,10 +1890,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:14: error: operation caused overflow", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:14: error: operation caused overflow", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("mul overflow in function evaluation", + cases.add( + "mul overflow in function evaluation", \\const y = mul(300, 6000); \\fn mul(a: u16, b: u16) u16 { \\ return a * b; @@ -1488,27 +1903,34 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:14: error: operation caused overflow", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:14: error: operation caused overflow", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("truncate sign mismatch", + cases.add( + "truncate sign mismatch", \\fn f() i8 { \\ const x: u32 = 10; \\ return @truncate(i8, x); \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:3:26: error: expected signed integer type, found 'u32'"); + , + ".tmp_source.zig:3:26: error: expected signed integer type, found 'u32'", + ); - cases.add("try in function with non error return type", + cases.add( + "try in function with non error return type", \\export fn f() void { \\ try something(); \\} \\fn something() error!void { } , - ".tmp_source.zig:2:5: error: expected type 'void', found 'error'"); + ".tmp_source.zig:2:5: error: expected type 'void', found 'error'", + ); - cases.add("invalid pointer for var type", + cases.add( + "invalid pointer for var type", \\extern fn ext() usize; \\var bytes: [ext()]u8 = undefined; \\export fn f() void { @@ -1516,30 +1938,42 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ b.* = u8(i); \\ } \\} - , ".tmp_source.zig:2:13: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:2:13: error: unable to evaluate constant expression", + ); - cases.add("export function with comptime parameter", + cases.add( + "export function with comptime parameter", \\export fn foo(comptime x: i32, y: i32) i32{ \\ return x + y; \\} - , ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'", + ); - cases.add("extern function with comptime parameter", + cases.add( + "extern function with comptime parameter", \\extern fn foo(comptime x: i32, y: i32) i32; \\fn f() i32 { \\ return foo(1, 2); \\} \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'", + ); - cases.add("convert fixed size array to slice with invalid size", + cases.add( + "convert fixed size array to slice with invalid size", \\export fn f() void { \\ var array: [5]u8 = undefined; \\ var foo = ([]const u32)(array)[0]; \\} - , ".tmp_source.zig:3:28: error: unable to convert [5]u8 to []const u32: size mismatch"); + , + ".tmp_source.zig:3:28: error: unable to convert [5]u8 to []const u32: size mismatch", + ); - cases.add("non-pure function returns type", + cases.add( + "non-pure function returns type", \\var a: u32 = 0; \\pub fn List(comptime T: type) type { \\ a += 1; @@ -1558,18 +1992,24 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var list: List(i32) = undefined; \\ list.length = 10; \\} - , ".tmp_source.zig:3:7: error: unable to evaluate constant expression", - ".tmp_source.zig:16:19: note: called from here"); + , + ".tmp_source.zig:3:7: error: unable to evaluate constant expression", + ".tmp_source.zig:16:19: note: called from here", + ); - cases.add("bogus method call on slice", + cases.add( + "bogus method call on slice", \\var self = "aoeu"; \\fn f(m: []const u8) void { \\ m.copy(u8, self[0..], m); \\} \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:3:6: error: no member named 'copy' in '[]const u8'"); + , + ".tmp_source.zig:3:6: error: no member named 'copy' in '[]const u8'", + ); - cases.add("wrong number of arguments for method fn call", + cases.add( + "wrong number of arguments for method fn call", \\const Foo = struct { \\ fn method(self: &const Foo, a: i32) void {} \\}; @@ -1578,34 +2018,49 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ foo.method(1, 2); \\} \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:6:15: error: expected 2 arguments, found 3"); + , + ".tmp_source.zig:6:15: error: expected 2 arguments, found 3", + ); - cases.add("assign through constant pointer", + cases.add( + "assign through constant pointer", \\export fn f() void { \\ var cstr = c"Hat"; \\ cstr[0] = 'W'; \\} - , ".tmp_source.zig:3:11: error: cannot assign to constant"); + , + ".tmp_source.zig:3:11: error: cannot assign to constant", + ); - cases.add("assign through constant slice", + cases.add( + "assign through constant slice", \\export fn f() void { \\ var cstr: []const u8 = "Hat"; \\ cstr[0] = 'W'; \\} - , ".tmp_source.zig:3:11: error: cannot assign to constant"); + , + ".tmp_source.zig:3:11: error: cannot assign to constant", + ); - cases.add("main function with bogus args type", + cases.add( + "main function with bogus args type", \\pub fn main(args: [][]bogus) !void {} - , ".tmp_source.zig:1:23: error: use of undeclared identifier 'bogus'"); + , + ".tmp_source.zig:1:23: error: use of undeclared identifier 'bogus'", + ); - cases.add("for loop missing element param", + cases.add( + "for loop missing element param", \\fn foo(blah: []u8) void { \\ for (blah) { } \\} \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:2:5: error: for loop expression missing element parameter"); + , + ".tmp_source.zig:2:5: error: for loop expression missing element parameter", + ); - cases.add("misspelled type with pointer only reference", + cases.add( + "misspelled type with pointer only reference", \\const JasonHM = u8; \\const JasonList = &JsonNode; \\ @@ -1636,9 +2091,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:5:16: error: use of undeclared identifier 'JsonList'"); + , + ".tmp_source.zig:5:16: error: use of undeclared identifier 'JsonList'", + ); - cases.add("method call with first arg type primitive", + cases.add( + "method call with first arg type primitive", \\const Foo = struct { \\ x: i32, \\ @@ -1654,9 +2112,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\ derp.init(); \\} - , ".tmp_source.zig:14:5: error: expected type 'i32', found '&const Foo'"); + , + ".tmp_source.zig:14:5: error: expected type 'i32', found '&const Foo'", + ); - cases.add("method call with first arg type wrong container", + cases.add( + "method call with first arg type wrong container", \\pub const List = struct { \\ len: usize, \\ allocator: &Allocator, @@ -1681,26 +2142,33 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = List.init(&global_allocator); \\ x.init(); \\} - , ".tmp_source.zig:23:5: error: expected type '&Allocator', found '&List'"); + , + ".tmp_source.zig:23:5: error: expected type '&Allocator', found '&List'", + ); - cases.add("binary not on number literal", + cases.add( + "binary not on number literal", \\const TINY_QUANTUM_SHIFT = 4; \\const TINY_QUANTUM_SIZE = 1 << TINY_QUANTUM_SHIFT; \\var block_aligned_stuff: usize = (4 + TINY_QUANTUM_SIZE) & ~(TINY_QUANTUM_SIZE - 1); \\ \\export fn entry() usize { return @sizeOf(@typeOf(block_aligned_stuff)); } - , ".tmp_source.zig:3:60: error: unable to perform binary not operation on type '(integer literal)'"); + , + ".tmp_source.zig:3:60: error: unable to perform binary not operation on type '(integer literal)'", + ); cases.addCase(x: { - const tc = cases.create("multiple files with private function error", - \\const foo = @import("foo.zig"); + const tc = cases.create( + "multiple files with private function error", + \\const foo = @import("foo.zig",); \\ \\export fn callPrivFunction() void { \\ foo.privateFunction(); \\} , ".tmp_source.zig:4:8: error: 'privateFunction' is private", - "foo.zig:1:1: note: declared here"); + "foo.zig:1:1: note: declared here", + ); tc.addSourceFile("foo.zig", \\fn privateFunction() void { } @@ -1709,14 +2177,18 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { break :x tc; }); - cases.add("container init with non-type", + cases.add( + "container init with non-type", \\const zero: i32 = 0; \\const a = zero{1}; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } - , ".tmp_source.zig:2:11: error: expected type, found 'i32'"); + , + ".tmp_source.zig:2:11: error: expected type, found 'i32'", + ); - cases.add("assign to constant field", + cases.add( + "assign to constant field", \\const Foo = struct { \\ field: i32, \\}; @@ -1724,9 +2196,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const f = Foo {.field = 1234,}; \\ f.field = 0; \\} - , ".tmp_source.zig:6:13: error: cannot assign to constant"); + , + ".tmp_source.zig:6:13: error: cannot assign to constant", + ); - cases.add("return from defer expression", + cases.add( + "return from defer expression", \\pub fn testTrickyDefer() !void { \\ defer canFail() catch {}; \\ @@ -1742,9 +2217,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(testTrickyDefer)); } - , ".tmp_source.zig:4:11: error: cannot return from defer expression"); + , + ".tmp_source.zig:4:11: error: cannot return from defer expression", + ); - cases.add("attempt to access var args out of bounds", + cases.add( + "attempt to access var args out of bounds", \\fn add(args: ...) i32 { \\ return args[0] + args[1]; \\} @@ -1755,10 +2233,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:2:26: error: index 1 outside argument list of size 1", - ".tmp_source.zig:6:15: note: called from here"); + ".tmp_source.zig:2:26: error: index 1 outside argument list of size 1", + ".tmp_source.zig:6:15: note: called from here", + ); - cases.add("pass integer literal to var args", + cases.add( + "pass integer literal to var args", \\fn add(args: ...) i32 { \\ var sum = i32(0); \\ {comptime var i: usize = 0; inline while (i < args.len) : (i += 1) { @@ -1772,32 +2252,44 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(bar)); } - , ".tmp_source.zig:10:16: error: compiler bug: integer and float literals in var args function must be casted"); + , + ".tmp_source.zig:10:16: error: compiler bug: integer and float literals in var args function must be casted", + ); - cases.add("assign too big number to u16", + cases.add( + "assign too big number to u16", \\export fn foo() void { \\ var vga_mem: u16 = 0xB8000; \\} - , ".tmp_source.zig:2:24: error: integer value 753664 cannot be implicitly casted to type 'u16'"); + , + ".tmp_source.zig:2:24: error: integer value 753664 cannot be implicitly casted to type 'u16'", + ); - cases.add("global variable alignment non power of 2", + cases.add( + "global variable alignment non power of 2", \\const some_data: [100]u8 align(3) = undefined; \\export fn entry() usize { return @sizeOf(@typeOf(some_data)); } - , ".tmp_source.zig:1:32: error: alignment value 3 is not a power of 2"); + , + ".tmp_source.zig:1:32: error: alignment value 3 is not a power of 2", + ); - cases.add("function alignment non power of 2", + cases.add( + "function alignment non power of 2", \\extern fn foo() align(3) void; \\export fn entry() void { return foo(); } - , ".tmp_source.zig:1:23: error: alignment value 3 is not a power of 2"); + , + ".tmp_source.zig:1:23: error: alignment value 3 is not a power of 2", + ); - cases.add("compile log", + cases.add( + "compile log", \\export fn foo() void { - \\ comptime bar(12, "hi"); + \\ comptime bar(12, "hi",); \\} \\fn bar(a: i32, b: []const u8) void { - \\ @compileLog("begin"); + \\ @compileLog("begin",); \\ @compileLog("a", a, "b", b); - \\ @compileLog("end"); + \\ @compileLog("end",); \\} , ".tmp_source.zig:5:5: error: found compile log statement", @@ -1805,9 +2297,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { ".tmp_source.zig:6:5: error: found compile log statement", ".tmp_source.zig:2:17: note: called from here", ".tmp_source.zig:7:5: error: found compile log statement", - ".tmp_source.zig:2:17: note: called from here"); + ".tmp_source.zig:2:17: note: called from here", + ); - cases.add("casting bit offset pointer to regular pointer", + cases.add( + "casting bit offset pointer to regular pointer", \\const BitField = packed struct { \\ a: u3, \\ b: u3, @@ -1823,9 +2317,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:8:26: error: expected type '&const u3', found '&align(1:3:6) const u3'"); + , + ".tmp_source.zig:8:26: error: expected type '&const u3', found '&align(1:3:6) const u3'", + ); - cases.add("referring to a struct that is invalid", + cases.add( + "referring to a struct that is invalid", \\const UsbDeviceRequest = struct { \\ Type: u8, \\}; @@ -1838,10 +2335,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ if (!ok) unreachable; \\} , - ".tmp_source.zig:10:14: error: unable to evaluate constant expression", - ".tmp_source.zig:6:20: note: called from here"); + ".tmp_source.zig:10:14: error: unable to evaluate constant expression", + ".tmp_source.zig:6:20: note: called from here", + ); - cases.add("control flow uses comptime var at runtime", + cases.add( + "control flow uses comptime var at runtime", \\export fn foo() void { \\ comptime var i = 0; \\ while (i < 5) : (i += 1) { @@ -1851,55 +2350,78 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\fn bar() void { } , - ".tmp_source.zig:3:5: error: control flow attempts to use compile-time variable at runtime", - ".tmp_source.zig:3:24: note: compile-time variable assigned here"); + ".tmp_source.zig:3:5: error: control flow attempts to use compile-time variable at runtime", + ".tmp_source.zig:3:24: note: compile-time variable assigned here", + ); - cases.add("ignored return value", + cases.add( + "ignored return value", \\export fn foo() void { \\ bar(); \\} \\fn bar() i32 { return 0; } - , ".tmp_source.zig:2:8: error: expression value is ignored"); + , + ".tmp_source.zig:2:8: error: expression value is ignored", + ); - cases.add("ignored assert-err-ok return value", + cases.add( + "ignored assert-err-ok return value", \\export fn foo() void { \\ bar() catch unreachable; \\} \\fn bar() error!i32 { return 0; } - , ".tmp_source.zig:2:11: error: expression value is ignored"); + , + ".tmp_source.zig:2:11: error: expression value is ignored", + ); - cases.add("ignored statement value", + cases.add( + "ignored statement value", \\export fn foo() void { \\ 1; \\} - , ".tmp_source.zig:2:5: error: expression value is ignored"); + , + ".tmp_source.zig:2:5: error: expression value is ignored", + ); - cases.add("ignored comptime statement value", + cases.add( + "ignored comptime statement value", \\export fn foo() void { \\ comptime {1;} \\} - , ".tmp_source.zig:2:15: error: expression value is ignored"); + , + ".tmp_source.zig:2:15: error: expression value is ignored", + ); - cases.add("ignored comptime value", + cases.add( + "ignored comptime value", \\export fn foo() void { \\ comptime 1; \\} - , ".tmp_source.zig:2:5: error: expression value is ignored"); + , + ".tmp_source.zig:2:5: error: expression value is ignored", + ); - cases.add("ignored defered statement value", + cases.add( + "ignored defered statement value", \\export fn foo() void { \\ defer {1;} \\} - , ".tmp_source.zig:2:12: error: expression value is ignored"); + , + ".tmp_source.zig:2:12: error: expression value is ignored", + ); - cases.add("ignored defered function call", + cases.add( + "ignored defered function call", \\export fn foo() void { \\ defer bar(); \\} \\fn bar() error!i32 { return 0; } - , ".tmp_source.zig:2:14: error: expression value is ignored"); + , + ".tmp_source.zig:2:14: error: expression value is ignored", + ); - cases.add("dereference an array", + cases.add( + "dereference an array", \\var s_buffer: [10]u8 = undefined; \\pub fn pass(in: []u8) []u8 { \\ var out = &s_buffer; @@ -1908,11 +2430,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(pass)); } - , ".tmp_source.zig:4:11: error: attempt to dereference non pointer type '[10]u8'"); + , + ".tmp_source.zig:4:11: error: attempt to dereference non pointer type '[10]u8'", + ); - cases.add("pass const ptr to mutable ptr fn", + cases.add( + "pass const ptr to mutable ptr fn", \\fn foo() bool { - \\ const a = ([]const u8)("a"); + \\ const a = ([]const u8)("a",); \\ const b = &a; \\ return ptrEql(b, b); \\} @@ -1921,18 +2446,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:4:19: error: expected type '&[]const u8', found '&const []const u8'"); + , + ".tmp_source.zig:4:19: error: expected type '&[]const u8', found '&const []const u8'", + ); cases.addCase(x: { - const tc = cases.create("export collision", - \\const foo = @import("foo.zig"); + const tc = cases.create( + "export collision", + \\const foo = @import("foo.zig",); \\ \\export fn bar() usize { \\ return foo.baz; \\} , "foo.zig:1:8: error: exported symbol collision: 'bar'", - ".tmp_source.zig:3:8: note: other symbol here"); + ".tmp_source.zig:3:8: note: other symbol here", + ); tc.addSourceFile("foo.zig", \\export fn bar() void {} @@ -1942,35 +2471,48 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { break :x tc; }); - cases.add("pass non-copyable type by value to function", + cases.add( + "pass non-copyable type by value to function", \\const Point = struct { x: i32, y: i32, }; \\fn foo(p: Point) void { } \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:2:11: error: type 'Point' is not copyable; cannot pass by value"); + , + ".tmp_source.zig:2:11: error: type 'Point' is not copyable; cannot pass by value", + ); - cases.add("implicit cast from array to mutable slice", + cases.add( + "implicit cast from array to mutable slice", \\var global_array: [10]i32 = undefined; \\fn foo(param: []i32) void {} \\export fn entry() void { \\ foo(global_array); \\} - , ".tmp_source.zig:4:9: error: expected type '[]i32', found '[10]i32'"); + , + ".tmp_source.zig:4:9: error: expected type '[]i32', found '[10]i32'", + ); - cases.add("ptrcast to non-pointer", + cases.add( + "ptrcast to non-pointer", \\export fn entry(a: &i32) usize { \\ return @ptrCast(usize, a); \\} - , ".tmp_source.zig:2:21: error: expected pointer, found 'usize'"); + , + ".tmp_source.zig:2:21: error: expected pointer, found 'usize'", + ); - cases.add("too many error values to cast to small integer", + cases.add( + "too many error values to cast to small integer", \\const Error = error { A, B, C, D, E, F, G, H }; \\fn foo(e: Error) u2 { \\ return u2(e); \\} \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:3:14: error: too many error values to fit in 'u2'"); + , + ".tmp_source.zig:3:14: error: too many error values to fit in 'u2'", + ); - cases.add("asm at compile time", + cases.add( + "asm at compile time", \\comptime { \\ doSomeAsm(); \\} @@ -1982,48 +2524,66 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\.set aoeu, derp; \\ ); \\} - , ".tmp_source.zig:6:5: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:6:5: error: unable to evaluate constant expression", + ); - cases.add("invalid member of builtin enum", - \\const builtin = @import("builtin"); + cases.add( + "invalid member of builtin enum", + \\const builtin = @import("builtin",); \\export fn entry() void { \\ const foo = builtin.Arch.x86; \\} - , ".tmp_source.zig:3:29: error: container 'Arch' has no member called 'x86'"); + , + ".tmp_source.zig:3:29: error: container 'Arch' has no member called 'x86'", + ); - cases.add("int to ptr of 0 bits", + cases.add( + "int to ptr of 0 bits", \\export fn foo() void { \\ var x: usize = 0x1000; \\ var y: &void = @intToPtr(&void, x); \\} - , ".tmp_source.zig:3:31: error: type '&void' has 0 bits and cannot store information"); + , + ".tmp_source.zig:3:31: error: type '&void' has 0 bits and cannot store information", + ); - cases.add("@fieldParentPtr - non struct", + cases.add( + "@fieldParentPtr - non struct", \\const Foo = i32; \\export fn foo(a: &i32) &Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} - , ".tmp_source.zig:3:28: error: expected struct type, found 'i32'"); + , + ".tmp_source.zig:3:28: error: expected struct type, found 'i32'", + ); - cases.add("@fieldParentPtr - bad field name", + cases.add( + "@fieldParentPtr - bad field name", \\const Foo = extern struct { \\ derp: i32, \\}; \\export fn foo(a: &i32) &Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} - , ".tmp_source.zig:5:33: error: struct 'Foo' has no field 'a'"); + , + ".tmp_source.zig:5:33: error: struct 'Foo' has no field 'a'", + ); - cases.add("@fieldParentPtr - field pointer is not pointer", + cases.add( + "@fieldParentPtr - field pointer is not pointer", \\const Foo = extern struct { \\ a: i32, \\}; \\export fn foo(a: i32) &Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} - , ".tmp_source.zig:5:38: error: expected pointer, found 'i32'"); + , + ".tmp_source.zig:5:38: error: expected pointer, found 'i32'", + ); - cases.add("@fieldParentPtr - comptime field ptr not based on struct", + cases.add( + "@fieldParentPtr - comptime field ptr not based on struct", \\const Foo = struct { \\ a: i32, \\ b: i32, @@ -2034,9 +2594,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const field_ptr = @intToPtr(&i32, 0x1234); \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", field_ptr); \\} - , ".tmp_source.zig:9:55: error: pointer value not based on parent struct"); + , + ".tmp_source.zig:9:55: error: pointer value not based on parent struct", + ); - cases.add("@fieldParentPtr - comptime wrong field index", + cases.add( + "@fieldParentPtr - comptime wrong field index", \\const Foo = struct { \\ a: i32, \\ b: i32, @@ -2046,76 +2609,100 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\comptime { \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", &foo.a); \\} - , ".tmp_source.zig:8:29: error: field 'b' has index 1 but pointer value is index 0 of struct 'Foo'"); + , + ".tmp_source.zig:8:29: error: field 'b' has index 1 but pointer value is index 0 of struct 'Foo'", + ); - cases.add("@offsetOf - non struct", + cases.add( + "@offsetOf - non struct", \\const Foo = i32; \\export fn foo() usize { - \\ return @offsetOf(Foo, "a"); + \\ return @offsetOf(Foo, "a",); \\} - , ".tmp_source.zig:3:22: error: expected struct type, found 'i32'"); + , + ".tmp_source.zig:3:22: error: expected struct type, found 'i32'", + ); - cases.add("@offsetOf - bad field name", + cases.add( + "@offsetOf - bad field name", \\const Foo = struct { \\ derp: i32, \\}; \\export fn foo() usize { - \\ return @offsetOf(Foo, "a"); + \\ return @offsetOf(Foo, "a",); \\} - , ".tmp_source.zig:5:27: error: struct 'Foo' has no field 'a'"); + , + ".tmp_source.zig:5:27: error: struct 'Foo' has no field 'a'", + ); - cases.addExe("missing main fn in executable", + cases.addExe( + "missing main fn in executable", \\ - , "error: no member named 'main' in '"); + , + "error: no member named 'main' in '", + ); - cases.addExe("private main fn", + cases.addExe( + "private main fn", \\fn main() void {} , "error: 'main' is private", - ".tmp_source.zig:1:1: note: declared here"); + ".tmp_source.zig:1:1: note: declared here", + ); - cases.add("setting a section on an extern variable", + cases.add( + "setting a section on an extern variable", \\extern var foo: i32 section(".text2"); \\export fn entry() i32 { \\ return foo; \\} , - ".tmp_source.zig:1:29: error: cannot set section of external variable 'foo'"); + ".tmp_source.zig:1:29: error: cannot set section of external variable 'foo'", + ); - cases.add("setting a section on a local variable", + cases.add( + "setting a section on a local variable", \\export fn entry() i32 { \\ var foo: i32 section(".text2") = 1234; \\ return foo; \\} , - ".tmp_source.zig:2:26: error: cannot set section of local variable 'foo'"); + ".tmp_source.zig:2:26: error: cannot set section of local variable 'foo'", + ); - cases.add("setting a section on an extern fn", + cases.add( + "setting a section on an extern fn", \\extern fn foo() section(".text2") void; \\export fn entry() void { \\ foo(); \\} , - ".tmp_source.zig:1:25: error: cannot set section of external function 'foo'"); + ".tmp_source.zig:1:25: error: cannot set section of external function 'foo'", + ); - cases.add("returning address of local variable - simple", + cases.add( + "returning address of local variable - simple", \\export fn foo() &i32 { \\ var a: i32 = undefined; \\ return &a; \\} , - ".tmp_source.zig:3:13: error: function returns address of local variable"); + ".tmp_source.zig:3:13: error: function returns address of local variable", + ); - cases.add("returning address of local variable - phi", + cases.add( + "returning address of local variable - phi", \\export fn foo(c: bool) &i32 { \\ var a: i32 = undefined; \\ var b: i32 = undefined; \\ return if (c) &a else &b; \\} , - ".tmp_source.zig:4:12: error: function returns address of local variable"); + ".tmp_source.zig:4:12: error: function returns address of local variable", + ); - cases.add("inner struct member shadowing outer struct member", + cases.add( + "inner struct member shadowing outer struct member", \\fn A() type { \\ return struct { \\ b: B(), @@ -2137,57 +2724,71 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:9:17: error: redefinition of 'Self'", - ".tmp_source.zig:5:9: note: previous definition is here"); + ".tmp_source.zig:5:9: note: previous definition is here", + ); - cases.add("while expected bool, got nullable", + cases.add( + "while expected bool, got nullable", \\export fn foo() void { \\ while (bar()) {} \\} \\fn bar() ?i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected type 'bool', found '?i32'"); + ".tmp_source.zig:2:15: error: expected type 'bool', found '?i32'", + ); - cases.add("while expected bool, got error union", + cases.add( + "while expected bool, got error union", \\export fn foo() void { \\ while (bar()) {} \\} \\fn bar() error!i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected type 'bool', found 'error!i32'"); + ".tmp_source.zig:2:15: error: expected type 'bool', found 'error!i32'", + ); - cases.add("while expected nullable, got bool", + cases.add( + "while expected nullable, got bool", \\export fn foo() void { \\ while (bar()) |x| {} \\} \\fn bar() bool { return true; } , - ".tmp_source.zig:2:15: error: expected nullable type, found 'bool'"); + ".tmp_source.zig:2:15: error: expected nullable type, found 'bool'", + ); - cases.add("while expected nullable, got error union", + cases.add( + "while expected nullable, got error union", \\export fn foo() void { \\ while (bar()) |x| {} \\} \\fn bar() error!i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected nullable type, found 'error!i32'"); + ".tmp_source.zig:2:15: error: expected nullable type, found 'error!i32'", + ); - cases.add("while expected error union, got bool", + cases.add( + "while expected error union, got bool", \\export fn foo() void { \\ while (bar()) |x| {} else |err| {} \\} \\fn bar() bool { return true; } , - ".tmp_source.zig:2:15: error: expected error union type, found 'bool'"); + ".tmp_source.zig:2:15: error: expected error union type, found 'bool'", + ); - cases.add("while expected error union, got nullable", + cases.add( + "while expected error union, got nullable", \\export fn foo() void { \\ while (bar()) |x| {} else |err| {} \\} \\fn bar() ?i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected error union type, found '?i32'"); + ".tmp_source.zig:2:15: error: expected error union type, found '?i32'", + ); - cases.add("inline fn calls itself indirectly", + cases.add( + "inline fn calls itself indirectly", \\export fn foo() void { \\ bar(); \\} @@ -2201,91 +2802,113 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\extern fn quux() void; , - ".tmp_source.zig:4:8: error: unable to inline function"); + ".tmp_source.zig:4:8: error: unable to inline function", + ); - cases.add("save reference to inline function", + cases.add( + "save reference to inline function", \\export fn foo() void { \\ quux(@ptrToInt(bar)); \\} \\inline fn bar() void { } \\extern fn quux(usize) void; , - ".tmp_source.zig:4:8: error: unable to inline function"); + ".tmp_source.zig:4:8: error: unable to inline function", + ); - cases.add("signed integer division", + cases.add( + "signed integer division", \\export fn foo(a: i32, b: i32) i32 { \\ return a / b; \\} , - ".tmp_source.zig:2:14: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact"); + ".tmp_source.zig:2:14: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact", + ); - cases.add("signed integer remainder division", + cases.add( + "signed integer remainder division", \\export fn foo(a: i32, b: i32) i32 { \\ return a % b; \\} , - ".tmp_source.zig:2:14: error: remainder division with 'i32' and 'i32': signed integers and floats must use @rem or @mod"); + ".tmp_source.zig:2:14: error: remainder division with 'i32' and 'i32': signed integers and floats must use @rem or @mod", + ); - cases.add("cast negative value to unsigned integer", + cases.add( + "cast negative value to unsigned integer", \\comptime { \\ const value: i32 = -1; \\ const unsigned = u32(value); \\} , - ".tmp_source.zig:3:25: error: attempt to cast negative value to unsigned integer"); + ".tmp_source.zig:3:25: error: attempt to cast negative value to unsigned integer", + ); - cases.add("compile-time division by zero", + cases.add( + "compile-time division by zero", \\comptime { \\ const a: i32 = 1; \\ const b: i32 = 0; \\ const c = a / b; \\} , - ".tmp_source.zig:4:17: error: division by zero"); + ".tmp_source.zig:4:17: error: division by zero", + ); - cases.add("compile-time remainder division by zero", + cases.add( + "compile-time remainder division by zero", \\comptime { \\ const a: i32 = 1; \\ const b: i32 = 0; \\ const c = a % b; \\} , - ".tmp_source.zig:4:17: error: division by zero"); + ".tmp_source.zig:4:17: error: division by zero", + ); - cases.add("compile-time integer cast truncates bits", + cases.add( + "compile-time integer cast truncates bits", \\comptime { \\ const spartan_count: u16 = 300; \\ const byte = u8(spartan_count); \\} , - ".tmp_source.zig:3:20: error: cast from 'u16' to 'u8' truncates bits"); + ".tmp_source.zig:3:20: error: cast from 'u16' to 'u8' truncates bits", + ); - cases.add("@setRuntimeSafety twice for same scope", + cases.add( + "@setRuntimeSafety twice for same scope", \\export fn foo() void { \\ @setRuntimeSafety(false); \\ @setRuntimeSafety(false); \\} , ".tmp_source.zig:3:5: error: runtime safety set twice for same scope", - ".tmp_source.zig:2:5: note: first set here"); + ".tmp_source.zig:2:5: note: first set here", + ); - cases.add("@setFloatMode twice for same scope", + cases.add( + "@setFloatMode twice for same scope", \\export fn foo() void { \\ @setFloatMode(this, @import("builtin").FloatMode.Optimized); \\ @setFloatMode(this, @import("builtin").FloatMode.Optimized); \\} , ".tmp_source.zig:3:5: error: float mode set twice for same scope", - ".tmp_source.zig:2:5: note: first set here"); + ".tmp_source.zig:2:5: note: first set here", + ); - cases.add("array access of type", + cases.add( + "array access of type", \\export fn foo() void { \\ var b: u8[40] = undefined; \\} , - ".tmp_source.zig:2:14: error: array access of non-array type 'type'"); + ".tmp_source.zig:2:14: error: array access of non-array type 'type'", + ); - cases.add("cannot break out of defer expression", + cases.add( + "cannot break out of defer expression", \\export fn foo() void { \\ while (true) { \\ defer { @@ -2294,9 +2917,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:4:13: error: cannot break out of defer expression"); + ".tmp_source.zig:4:13: error: cannot break out of defer expression", + ); - cases.add("cannot continue out of defer expression", + cases.add( + "cannot continue out of defer expression", \\export fn foo() void { \\ while (true) { \\ defer { @@ -2305,9 +2930,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:4:13: error: cannot continue out of defer expression"); + ".tmp_source.zig:4:13: error: cannot continue out of defer expression", + ); - cases.add("calling a var args function only known at runtime", + cases.add( + "calling a var args function only known at runtime", \\var foos = []fn(...) void { foo1, foo2 }; \\ \\fn foo1(args: ...) void {} @@ -2317,9 +2944,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ foos[0](); \\} , - ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value"); + ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value", + ); - cases.add("calling a generic function only known at runtime", + cases.add( + "calling a generic function only known at runtime", \\var foos = []fn(var) void { foo1, foo2 }; \\ \\fn foo1(arg: var) void {} @@ -2329,10 +2958,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ foos[0](true); \\} , - ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value"); + ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value", + ); - cases.add("@compileError shows traceback of references that caused it", - \\const foo = @compileError("aoeu"); + cases.add( + "@compileError shows traceback of references that caused it", + \\const foo = @compileError("aoeu",); \\ \\const bar = baz + foo; \\const baz = 1; @@ -2343,9 +2974,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:1:13: error: aoeu", ".tmp_source.zig:3:19: note: referenced here", - ".tmp_source.zig:7:12: note: referenced here"); + ".tmp_source.zig:7:12: note: referenced here", + ); - cases.add("instantiating an undefined value for an invalid struct that contains itself", + cases.add( + "instantiating an undefined value for an invalid struct that contains itself", \\const Foo = struct { \\ x: Foo, \\}; @@ -2356,73 +2989,93 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return @sizeOf(@typeOf(foo.x)); \\} , - ".tmp_source.zig:1:13: error: struct 'Foo' contains itself"); + ".tmp_source.zig:1:13: error: struct 'Foo' contains itself", + ); - cases.add("float literal too large error", + cases.add( + "float literal too large error", \\comptime { \\ const a = 0x1.0p16384; \\} , - ".tmp_source.zig:2:15: error: float literal out of range of any type"); + ".tmp_source.zig:2:15: error: float literal out of range of any type", + ); - cases.add("float literal too small error (denormal)", + cases.add( + "float literal too small error (denormal)", \\comptime { \\ const a = 0x1.0p-16384; \\} , - ".tmp_source.zig:2:15: error: float literal out of range of any type"); + ".tmp_source.zig:2:15: error: float literal out of range of any type", + ); - cases.add("explicit cast float literal to integer when there is a fraction component", + cases.add( + "explicit cast float literal to integer when there is a fraction component", \\export fn entry() i32 { \\ return i32(12.34); \\} , - ".tmp_source.zig:2:16: error: fractional component prevents float value 12.340000 from being casted to type 'i32'"); + ".tmp_source.zig:2:16: error: fractional component prevents float value 12.340000 from being casted to type 'i32'", + ); - cases.add("non pointer given to @ptrToInt", + cases.add( + "non pointer given to @ptrToInt", \\export fn entry(x: i32) usize { \\ return @ptrToInt(x); \\} , - ".tmp_source.zig:2:22: error: expected pointer, found 'i32'"); + ".tmp_source.zig:2:22: error: expected pointer, found 'i32'", + ); - cases.add("@shlExact shifts out 1 bits", + cases.add( + "@shlExact shifts out 1 bits", \\comptime { \\ const x = @shlExact(u8(0b01010101), 2); \\} , - ".tmp_source.zig:2:15: error: operation caused overflow"); + ".tmp_source.zig:2:15: error: operation caused overflow", + ); - cases.add("@shrExact shifts out 1 bits", + cases.add( + "@shrExact shifts out 1 bits", \\comptime { \\ const x = @shrExact(u8(0b10101010), 2); \\} , - ".tmp_source.zig:2:15: error: exact shift shifted out 1 bits"); + ".tmp_source.zig:2:15: error: exact shift shifted out 1 bits", + ); - cases.add("shifting without int type or comptime known", + cases.add( + "shifting without int type or comptime known", \\export fn entry(x: u8) u8 { \\ return 0x11 << x; \\} , - ".tmp_source.zig:2:17: error: LHS of shift must be an integer type, or RHS must be compile-time known"); + ".tmp_source.zig:2:17: error: LHS of shift must be an integer type, or RHS must be compile-time known", + ); - cases.add("shifting RHS is log2 of LHS int bit width", + cases.add( + "shifting RHS is log2 of LHS int bit width", \\export fn entry(x: u8, y: u8) u8 { \\ return x << y; \\} , - ".tmp_source.zig:2:17: error: expected type 'u3', found 'u8'"); + ".tmp_source.zig:2:17: error: expected type 'u3', found 'u8'", + ); - cases.add("globally shadowing a primitive type", + cases.add( + "globally shadowing a primitive type", \\const u16 = @intType(false, 8); \\export fn entry() void { \\ const a: u16 = 300; \\} , - ".tmp_source.zig:1:1: error: declaration shadows type 'u16'"); + ".tmp_source.zig:1:1: error: declaration shadows type 'u16'", + ); - cases.add("implicitly increasing pointer alignment", + cases.add( + "implicitly increasing pointer alignment", \\const Foo = packed struct { \\ a: u8, \\ b: u32, @@ -2437,9 +3090,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ x.* += 1; \\} , - ".tmp_source.zig:8:13: error: expected type '&u32', found '&align(1) u32'"); + ".tmp_source.zig:8:13: error: expected type '&u32', found '&align(1) u32'", + ); - cases.add("implicitly increasing slice alignment", + cases.add( + "implicitly increasing slice alignment", \\const Foo = packed struct { \\ a: u8, \\ b: u32, @@ -2455,9 +3110,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ x[0] += 1; \\} , - ".tmp_source.zig:9:17: error: expected type '[]u32', found '[]align(1) u32'"); + ".tmp_source.zig:9:17: error: expected type '[]u32', found '[]align(1) u32'", + ); - cases.add("increase pointer alignment in @ptrCast", + cases.add( + "increase pointer alignment in @ptrCast", \\export fn entry() u32 { \\ var bytes: [4]u8 = []u8{0x01, 0x02, 0x03, 0x04}; \\ const ptr = @ptrCast(&u32, &bytes[0]); @@ -2466,9 +3123,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:3:17: error: cast increases pointer alignment", ".tmp_source.zig:3:38: note: '&u8' has alignment 1", - ".tmp_source.zig:3:27: note: '&u32' has alignment 4"); + ".tmp_source.zig:3:27: note: '&u32' has alignment 4", + ); - cases.add("increase pointer alignment in slice resize", + cases.add( + "increase pointer alignment in slice resize", \\export fn entry() u32 { \\ var bytes = []u8{0x01, 0x02, 0x03, 0x04}; \\ return ([]u32)(bytes[0..])[0]; @@ -2476,16 +3135,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:3:19: error: cast increases pointer alignment", ".tmp_source.zig:3:19: note: '[]u8' has alignment 1", - ".tmp_source.zig:3:19: note: '[]u32' has alignment 4"); + ".tmp_source.zig:3:19: note: '[]u32' has alignment 4", + ); - cases.add("@alignCast expects pointer or slice", + cases.add( + "@alignCast expects pointer or slice", \\export fn entry() void { \\ @alignCast(4, u32(3)); \\} , - ".tmp_source.zig:2:22: error: expected pointer or slice, found 'u32'"); + ".tmp_source.zig:2:22: error: expected pointer or slice, found 'u32'", + ); - cases.add("passing an under-aligned function pointer", + cases.add( + "passing an under-aligned function pointer", \\export fn entry() void { \\ testImplicitlyDecreaseFnAlign(alignedSmall, 1234); \\} @@ -2494,9 +3157,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\fn alignedSmall() align(4) i32 { return 1234; } , - ".tmp_source.zig:2:35: error: expected type 'fn() align(8) i32', found 'fn() align(4) i32'"); + ".tmp_source.zig:2:35: error: expected type 'fn() align(8) i32', found 'fn() align(4) i32'", + ); - cases.add("passing a not-aligned-enough pointer to cmpxchg", + cases.add( + "passing a not-aligned-enough pointer to cmpxchg", \\const AtomicOrder = @import("builtin").AtomicOrder; \\export fn entry() bool { \\ var x: i32 align(1) = 1234; @@ -2504,16 +3169,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return x == 5678; \\} , - ".tmp_source.zig:4:32: error: expected type '&i32', found '&align(1) i32'"); + ".tmp_source.zig:4:32: error: expected type '&i32', found '&align(1) i32'", + ); - cases.add("wrong size to an array literal", + cases.add( + "wrong size to an array literal", \\comptime { \\ const array = [2]u8{1, 2, 3}; \\} , - ".tmp_source.zig:2:24: error: expected [2]u8 literal, found [3]u8 literal"); + ".tmp_source.zig:2:24: error: expected [2]u8 literal, found [3]u8 literal", + ); - cases.add("@setEvalBranchQuota in non-root comptime execution context", + cases.add( + "@setEvalBranchQuota in non-root comptime execution context", \\comptime { \\ foo(); \\} @@ -2523,9 +3192,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:5:5: error: @setEvalBranchQuota must be called from the top of the comptime stack", ".tmp_source.zig:2:8: note: called from here", - ".tmp_source.zig:1:10: note: called from here"); + ".tmp_source.zig:1:10: note: called from here", + ); - cases.add("wrong pointer implicitly casted to pointer to @OpaqueType()", + cases.add( + "wrong pointer implicitly casted to pointer to @OpaqueType()", \\const Derp = @OpaqueType(); \\extern fn bar(d: &Derp) void; \\export fn foo() void { @@ -2533,9 +3204,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ bar(@ptrCast(&c_void, &x)); \\} , - ".tmp_source.zig:5:9: error: expected type '&Derp', found '&c_void'"); + ".tmp_source.zig:5:9: error: expected type '&Derp', found '&c_void'", + ); - cases.add("non-const variables of things that require const variables", + cases.add( + "non-const variables of things that require const variables", \\const Opaque = @OpaqueType(); \\ \\export fn entry(opaque: &Opaque) void { @@ -2549,7 +3222,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var e = null; \\ var f = opaque.*; \\ var g = i32; - \\ var h = @import("std"); + \\ var h = @import("std",); \\ var i = (Foo {}).bar; \\ \\ var z: noreturn = return; @@ -2569,26 +3242,32 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { ".tmp_source.zig:13:4: error: variable of type 'type' must be const or comptime", ".tmp_source.zig:14:4: error: variable of type '(namespace)' must be const or comptime", ".tmp_source.zig:15:4: error: variable of type '(bound fn(&const Foo) void)' must be const or comptime", - ".tmp_source.zig:17:4: error: unreachable code"); + ".tmp_source.zig:17:4: error: unreachable code", + ); - cases.add("wrong types given to atomic order args in cmpxchg", + cases.add( + "wrong types given to atomic order args in cmpxchg", \\export fn entry() void { \\ var x: i32 = 1234; \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, u32(1234), u32(1234))) {} \\} , - ".tmp_source.zig:3:50: error: expected type 'AtomicOrder', found 'u32'"); + ".tmp_source.zig:3:50: error: expected type 'AtomicOrder', found 'u32'", + ); - cases.add("wrong types given to @export", + cases.add( + "wrong types given to @export", \\extern fn entry() void { } \\comptime { \\ @export("entry", entry, u32(1234)); \\} , - ".tmp_source.zig:3:32: error: expected type 'GlobalLinkage', found 'u32'"); + ".tmp_source.zig:3:32: error: expected type 'GlobalLinkage', found 'u32'", + ); - cases.add("struct with invalid field", - \\const std = @import("std"); + cases.add( + "struct with invalid field", + \\const std = @import("std",); \\const Allocator = std.mem.Allocator; \\const ArrayList = std.ArrayList; \\ @@ -2612,23 +3291,29 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ }; \\} , - ".tmp_source.zig:14:17: error: use of undeclared identifier 'HeaderValue'"); + ".tmp_source.zig:14:17: error: use of undeclared identifier 'HeaderValue'", + ); - cases.add("@setAlignStack outside function", + cases.add( + "@setAlignStack outside function", \\comptime { \\ @setAlignStack(16); \\} , - ".tmp_source.zig:2:5: error: @setAlignStack outside function"); + ".tmp_source.zig:2:5: error: @setAlignStack outside function", + ); - cases.add("@setAlignStack in naked function", + cases.add( + "@setAlignStack in naked function", \\export nakedcc fn entry() void { \\ @setAlignStack(16); \\} , - ".tmp_source.zig:2:5: error: @setAlignStack in naked function"); + ".tmp_source.zig:2:5: error: @setAlignStack in naked function", + ); - cases.add("@setAlignStack in inline function", + cases.add( + "@setAlignStack in inline function", \\export fn entry() void { \\ foo(); \\} @@ -2636,25 +3321,31 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ @setAlignStack(16); \\} , - ".tmp_source.zig:5:5: error: @setAlignStack in inline function"); + ".tmp_source.zig:5:5: error: @setAlignStack in inline function", + ); - cases.add("@setAlignStack set twice", + cases.add( + "@setAlignStack set twice", \\export fn entry() void { \\ @setAlignStack(16); \\ @setAlignStack(16); \\} , ".tmp_source.zig:3:5: error: alignstack set twice", - ".tmp_source.zig:2:5: note: first set here"); + ".tmp_source.zig:2:5: note: first set here", + ); - cases.add("@setAlignStack too big", + cases.add( + "@setAlignStack too big", \\export fn entry() void { \\ @setAlignStack(511 + 1); \\} , - ".tmp_source.zig:2:5: error: attempt to @setAlignStack(512); maximum is 256"); + ".tmp_source.zig:2:5: error: attempt to @setAlignStack(512); maximum is 256", + ); - cases.add("storing runtime value in compile time variable then using it", + cases.add( + "storing runtime value in compile time variable then using it", \\const Mode = @import("builtin").Mode; \\ \\fn Free(comptime filename: []const u8) TestCase { @@ -2697,9 +3388,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:37:16: error: cannot store runtime value in compile time variable"); + ".tmp_source.zig:37:16: error: cannot store runtime value in compile time variable", + ); - cases.add("field access of opaque type", + cases.add( + "field access of opaque type", \\const MyType = @OpaqueType(); \\ \\export fn entry() bool { @@ -2711,120 +3404,148 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return x.blah; \\} , - ".tmp_source.zig:9:13: error: type '&MyType' does not support field access"); + ".tmp_source.zig:9:13: error: type '&MyType' does not support field access", + ); - cases.add("carriage return special case", + cases.add( + "carriage return special case", "fn test() bool {\r\n" ++ - " true\r\n" ++ - "}\r\n" - , - ".tmp_source.zig:1:17: error: invalid carriage return, only '\\n' line endings are supported"); + " true\r\n" ++ + "}\r\n", + ".tmp_source.zig:1:17: error: invalid carriage return, only '\\n' line endings are supported", + ); - cases.add("non-printable invalid character", - "\xff\xfe" ++ - \\fn test() bool {\r - \\ true\r - \\} - , - ".tmp_source.zig:1:1: error: invalid character: '\\xff'"); + cases.add( + "non-printable invalid character", + "\xff\xfe" ++ + \\fn test() bool {\r + \\ true\r + \\} + , + ".tmp_source.zig:1:1: error: invalid character: '\\xff'", + ); - cases.add("non-printable invalid character with escape alternative", + cases.add( + "non-printable invalid character with escape alternative", "fn test() bool {\n" ++ - "\ttrue\n" ++ - "}\n" - , - ".tmp_source.zig:2:1: error: invalid character: '\\t'"); + "\ttrue\n" ++ + "}\n", + ".tmp_source.zig:2:1: error: invalid character: '\\t'", + ); - cases.add("@ArgType given non function parameter", + cases.add( + "@ArgType given non function parameter", \\comptime { \\ _ = @ArgType(i32, 3); \\} , - ".tmp_source.zig:2:18: error: expected function, found 'i32'"); + ".tmp_source.zig:2:18: error: expected function, found 'i32'", + ); - cases.add("@ArgType arg index out of bounds", + cases.add( + "@ArgType arg index out of bounds", \\comptime { \\ _ = @ArgType(@typeOf(add), 2); \\} \\fn add(a: i32, b: i32) i32 { return a + b; } , - ".tmp_source.zig:2:32: error: arg index 2 out of bounds; 'fn(i32, i32) i32' has 2 arguments"); + ".tmp_source.zig:2:32: error: arg index 2 out of bounds; 'fn(i32, i32) i32' has 2 arguments", + ); - cases.add("@memberType on unsupported type", + cases.add( + "@memberType on unsupported type", \\comptime { \\ _ = @memberType(i32, 0); \\} , - ".tmp_source.zig:2:21: error: type 'i32' does not support @memberType"); + ".tmp_source.zig:2:21: error: type 'i32' does not support @memberType", + ); - cases.add("@memberType on enum", + cases.add( + "@memberType on enum", \\comptime { \\ _ = @memberType(Foo, 0); \\} \\const Foo = enum {A,}; , - ".tmp_source.zig:2:21: error: type 'Foo' does not support @memberType"); + ".tmp_source.zig:2:21: error: type 'Foo' does not support @memberType", + ); - cases.add("@memberType struct out of bounds", + cases.add( + "@memberType struct out of bounds", \\comptime { \\ _ = @memberType(Foo, 0); \\} \\const Foo = struct {}; , - ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members"); + ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members", + ); - cases.add("@memberType union out of bounds", + cases.add( + "@memberType union out of bounds", \\comptime { \\ _ = @memberType(Foo, 1); \\} \\const Foo = union {A: void,}; , - ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members"); + ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members", + ); - cases.add("@memberName on unsupported type", + cases.add( + "@memberName on unsupported type", \\comptime { \\ _ = @memberName(i32, 0); \\} , - ".tmp_source.zig:2:21: error: type 'i32' does not support @memberName"); + ".tmp_source.zig:2:21: error: type 'i32' does not support @memberName", + ); - cases.add("@memberName struct out of bounds", + cases.add( + "@memberName struct out of bounds", \\comptime { \\ _ = @memberName(Foo, 0); \\} \\const Foo = struct {}; , - ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members"); + ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members", + ); - cases.add("@memberName enum out of bounds", + cases.add( + "@memberName enum out of bounds", \\comptime { \\ _ = @memberName(Foo, 1); \\} \\const Foo = enum {A,}; , - ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members"); + ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members", + ); - cases.add("@memberName union out of bounds", + cases.add( + "@memberName union out of bounds", \\comptime { \\ _ = @memberName(Foo, 1); \\} \\const Foo = union {A:i32,}; , - ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members"); + ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members", + ); - cases.add("calling var args extern function, passing array instead of pointer", + cases.add( + "calling var args extern function, passing array instead of pointer", \\export fn entry() void { - \\ foo("hello"); + \\ foo("hello",); \\} \\pub extern fn foo(format: &const u8, ...) void; , - ".tmp_source.zig:2:9: error: expected type '&const u8', found '[5]u8'"); + ".tmp_source.zig:2:9: error: expected type '&const u8', found '[5]u8'", + ); - cases.add("constant inside comptime function has compile error", + cases.add( + "constant inside comptime function has compile error", \\const ContextAllocator = MemoryPool(usize); \\ \\pub fn MemoryPool(comptime T: type) type { - \\ const free_list_t = @compileError("aoeu"); + \\ const free_list_t = @compileError("aoeu",); \\ \\ return struct { \\ free_list: free_list_t, @@ -2837,9 +3558,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:4:25: error: aoeu", ".tmp_source.zig:1:36: note: called from here", - ".tmp_source.zig:12:20: note: referenced here"); + ".tmp_source.zig:12:20: note: referenced here", + ); - cases.add("specify enum tag type that is too small", + cases.add( + "specify enum tag type that is too small", \\const Small = enum (u2) { \\ One, \\ Two, @@ -2852,9 +3575,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = Small.One; \\} , - ".tmp_source.zig:1:20: error: 'u2' too small to hold all bits; must be at least 'u3'"); + ".tmp_source.zig:1:20: error: 'u2' too small to hold all bits; must be at least 'u3'", + ); - cases.add("specify non-integer enum tag type", + cases.add( + "specify non-integer enum tag type", \\const Small = enum (f32) { \\ One, \\ Two, @@ -2865,9 +3590,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = Small.One; \\} , - ".tmp_source.zig:1:20: error: expected integer, found 'f32'"); + ".tmp_source.zig:1:20: error: expected integer, found 'f32'", + ); - cases.add("implicitly casting enum to tag type", + cases.add( + "implicitly casting enum to tag type", \\const Small = enum(u2) { \\ One, \\ Two, @@ -2879,9 +3606,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x: u2 = Small.Two; \\} , - ".tmp_source.zig:9:22: error: expected type 'u2', found 'Small'"); + ".tmp_source.zig:9:22: error: expected type 'u2', found 'Small'", + ); - cases.add("explicitly casting enum to non tag type", + cases.add( + "explicitly casting enum to non tag type", \\const Small = enum(u2) { \\ One, \\ Two, @@ -2893,9 +3622,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = u3(Small.Two); \\} , - ".tmp_source.zig:9:15: error: enum to integer cast to 'u3' instead of its tag type, 'u2'"); + ".tmp_source.zig:9:15: error: enum to integer cast to 'u3' instead of its tag type, 'u2'", + ); - cases.add("explicitly casting non tag type to enum", + cases.add( + "explicitly casting non tag type to enum", \\const Small = enum(u2) { \\ One, \\ Two, @@ -2908,9 +3639,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = Small(y); \\} , - ".tmp_source.zig:10:18: error: integer to enum cast from 'u3' instead of its tag type, 'u2'"); + ".tmp_source.zig:10:18: error: integer to enum cast from 'u3' instead of its tag type, 'u2'", + ); - cases.add("non unsigned integer enum tag type", + cases.add( + "non unsigned integer enum tag type", \\const Small = enum(i2) { \\ One, \\ Two, @@ -2922,9 +3655,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var y = Small.Two; \\} , - ".tmp_source.zig:1:19: error: expected unsigned integer, found 'i2'"); + ".tmp_source.zig:1:19: error: expected unsigned integer, found 'i2'", + ); - cases.add("struct fields with value assignments", + cases.add( + "struct fields with value assignments", \\const MultipleChoice = struct { \\ A: i32 = 20, \\}; @@ -2932,9 +3667,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x: MultipleChoice = undefined; \\} , - ".tmp_source.zig:2:14: error: enums, not structs, support field assignment"); + ".tmp_source.zig:2:14: error: enums, not structs, support field assignment", + ); - cases.add("union fields with value assignments", + cases.add( + "union fields with value assignments", \\const MultipleChoice = union { \\ A: i32 = 20, \\}; @@ -2943,25 +3680,31 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:2:14: error: non-enum union field assignment", - ".tmp_source.zig:1:24: note: consider 'union(enum)' here"); + ".tmp_source.zig:1:24: note: consider 'union(enum)' here", + ); - cases.add("enum with 0 fields", + cases.add( + "enum with 0 fields", \\const Foo = enum {}; \\export fn entry() usize { \\ return @sizeOf(Foo); \\} , - ".tmp_source.zig:1:13: error: enums must have 1 or more fields"); + ".tmp_source.zig:1:13: error: enums must have 1 or more fields", + ); - cases.add("union with 0 fields", + cases.add( + "union with 0 fields", \\const Foo = union {}; \\export fn entry() usize { \\ return @sizeOf(Foo); \\} , - ".tmp_source.zig:1:13: error: unions must have 1 or more fields"); + ".tmp_source.zig:1:13: error: unions must have 1 or more fields", + ); - cases.add("enum value already taken", + cases.add( + "enum value already taken", \\const MultipleChoice = enum(u32) { \\ A = 20, \\ B = 40, @@ -2974,9 +3717,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:6:9: error: enum tag value 60 already taken", - ".tmp_source.zig:4:9: note: other occurrence here"); + ".tmp_source.zig:4:9: note: other occurrence here", + ); - cases.add("union with specified enum omits field", + cases.add( + "union with specified enum omits field", \\const Letter = enum { \\ A, \\ B, @@ -2991,9 +3736,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:6:17: error: enum field missing: 'C'", - ".tmp_source.zig:4:5: note: declared here"); + ".tmp_source.zig:4:5: note: declared here", + ); - cases.add("@TagType when union has no attached enum", + cases.add( + "@TagType when union has no attached enum", \\const Foo = union { \\ A: i32, \\}; @@ -3002,9 +3749,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:5:24: error: union 'Foo' has no tag", - ".tmp_source.zig:1:13: note: consider 'union(enum)' here"); + ".tmp_source.zig:1:13: note: consider 'union(enum)' here", + ); - cases.add("non-integer tag type to automatic union enum", + cases.add( + "non-integer tag type to automatic union enum", \\const Foo = union(enum(f32)) { \\ A: i32, \\}; @@ -3012,9 +3761,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const x = @TagType(Foo); \\} , - ".tmp_source.zig:1:23: error: expected integer tag type, found 'f32'"); + ".tmp_source.zig:1:23: error: expected integer tag type, found 'f32'", + ); - cases.add("non-enum tag type passed to union", + cases.add( + "non-enum tag type passed to union", \\const Foo = union(u32) { \\ A: i32, \\}; @@ -3022,9 +3773,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const x = @TagType(Foo); \\} , - ".tmp_source.zig:1:18: error: expected enum tag type, found 'u32'"); + ".tmp_source.zig:1:18: error: expected enum tag type, found 'u32'", + ); - cases.add("union auto-enum value already taken", + cases.add( + "union auto-enum value already taken", \\const MultipleChoice = union(enum(u32)) { \\ A = 20, \\ B = 40, @@ -3037,9 +3790,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:6:9: error: enum tag value 60 already taken", - ".tmp_source.zig:4:9: note: other occurrence here"); + ".tmp_source.zig:4:9: note: other occurrence here", + ); - cases.add("union enum field does not match enum", + cases.add( + "union enum field does not match enum", \\const Letter = enum { \\ A, \\ B, @@ -3056,9 +3811,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:10:5: error: enum field not found: 'D'", - ".tmp_source.zig:1:16: note: enum declared here"); + ".tmp_source.zig:1:16: note: enum declared here", + ); - cases.add("field type supplied in an enum", + cases.add( + "field type supplied in an enum", \\const Letter = enum { \\ A: void, \\ B, @@ -3069,9 +3826,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:2:8: error: structs and unions, not enums, support field types", - ".tmp_source.zig:1:16: note: consider 'union(enum)' here"); + ".tmp_source.zig:1:16: note: consider 'union(enum)' here", + ); - cases.add("struct field missing type", + cases.add( + "struct field missing type", \\const Letter = struct { \\ A, \\}; @@ -3079,9 +3838,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var a = Letter { .A = {} }; \\} , - ".tmp_source.zig:2:5: error: struct field missing type"); + ".tmp_source.zig:2:5: error: struct field missing type", + ); - cases.add("extern union field missing type", + cases.add( + "extern union field missing type", \\const Letter = extern union { \\ A, \\}; @@ -3089,9 +3850,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var a = Letter { .A = {} }; \\} , - ".tmp_source.zig:2:5: error: union field missing type"); + ".tmp_source.zig:2:5: error: union field missing type", + ); - cases.add("extern union given enum tag type", + cases.add( + "extern union given enum tag type", \\const Letter = enum { \\ A, \\ B, @@ -3106,9 +3869,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var a = Payload { .A = 1234 }; \\} , - ".tmp_source.zig:6:29: error: extern union does not support enum tag type"); + ".tmp_source.zig:6:29: error: extern union does not support enum tag type", + ); - cases.add("packed union given enum tag type", + cases.add( + "packed union given enum tag type", \\const Letter = enum { \\ A, \\ B, @@ -3123,9 +3888,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var a = Payload { .A = 1234 }; \\} , - ".tmp_source.zig:6:29: error: packed union does not support enum tag type"); + ".tmp_source.zig:6:29: error: packed union does not support enum tag type", + ); - cases.add("switch on union with no attached enum", + cases.add( + "switch on union with no attached enum", \\const Payload = union { \\ A: i32, \\ B: f64, @@ -3143,9 +3910,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:11:14: error: switch on union which has no attached enum", - ".tmp_source.zig:1:17: note: consider 'union(enum)' here"); + ".tmp_source.zig:1:17: note: consider 'union(enum)' here", + ); - cases.add("enum in field count range but not matching tag", + cases.add( + "enum in field count range but not matching tag", \\const Foo = enum(u32) { \\ A = 10, \\ B = 11, @@ -3155,9 +3924,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:6:16: error: enum 'Foo' has no tag matching integer value 0", - ".tmp_source.zig:1:13: note: 'Foo' declared here"); + ".tmp_source.zig:1:13: note: 'Foo' declared here", + ); - cases.add("comptime cast enum to union but field has payload", + cases.add( + "comptime cast enum to union but field has payload", \\const Letter = enum { A, B, C }; \\const Value = union(Letter) { \\ A: i32, @@ -3169,9 +3940,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:8:26: error: cast to union 'Value' must initialize 'i32' field 'A'", - ".tmp_source.zig:3:5: note: field 'A' declared here"); + ".tmp_source.zig:3:5: note: field 'A' declared here", + ); - cases.add("runtime cast to union which has non-void fields", + cases.add( + "runtime cast to union which has non-void fields", \\const Letter = enum { A, B, C }; \\const Value = union(Letter) { \\ A: i32, @@ -3186,9 +3959,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:11:20: error: runtime cast to union 'Value' which has non-void fields", - ".tmp_source.zig:3:5: note: field 'A' has type 'i32'"); + ".tmp_source.zig:3:5: note: field 'A' has type 'i32'", + ); - cases.add("self-referencing function pointer field", + cases.add( + "self-referencing function pointer field", \\const S = struct { \\ f: fn(_: S) void, \\}; @@ -3198,19 +3973,23 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var _ = S { .f = f }; \\} , - ".tmp_source.zig:4:9: error: type 'S' is not copyable; cannot pass by value"); + ".tmp_source.zig:4:9: error: type 'S' is not copyable; cannot pass by value", + ); - cases.add("taking offset of void field in struct", + cases.add( + "taking offset of void field in struct", \\const Empty = struct { \\ val: void, \\}; \\export fn foo() void { - \\ const fieldOffset = @offsetOf(Empty, "val"); + \\ const fieldOffset = @offsetOf(Empty, "val",); \\} , - ".tmp_source.zig:5:42: error: zero-bit field 'val' in struct 'Empty' has no offset"); + ".tmp_source.zig:5:42: error: zero-bit field 'val' in struct 'Empty' has no offset", + ); - cases.add("invalid union field access in comptime", + cases.add( + "invalid union field access in comptime", \\const Foo = union { \\ Bar: u8, \\ Baz: void, @@ -3220,21 +3999,26 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const bar_val = foo.Bar; \\} , - ".tmp_source.zig:7:24: error: accessing union field 'Bar' while field 'Baz' is set"); + ".tmp_source.zig:7:24: error: accessing union field 'Bar' while field 'Baz' is set", + ); - cases.add("getting return type of generic function", + cases.add( + "getting return type of generic function", \\fn generic(a: var) void {} \\comptime { \\ _ = @typeOf(generic).ReturnType; \\} , - ".tmp_source.zig:3:25: error: ReturnType has not been resolved because 'fn(var)var' is generic"); + ".tmp_source.zig:3:25: error: ReturnType has not been resolved because 'fn(var)var' is generic", + ); - cases.add("getting @ArgType of generic function", + cases.add( + "getting @ArgType of generic function", \\fn generic(a: var) void {} \\comptime { \\ _ = @ArgType(@typeOf(generic), 0); \\} , - ".tmp_source.zig:3:36: error: @ArgType could not resolve the type of arg 0 because 'fn(var)var' is generic"); + ".tmp_source.zig:3:36: error: @ArgType could not resolve the type of arg 0 because 'fn(var)var' is generic", + ); } diff --git a/test/gen_h.zig b/test/gen_h.zig index 30d168cf2c..2def39bed7 100644 --- a/test/gen_h.zig +++ b/test/gen_h.zig @@ -76,5 +76,4 @@ pub fn addCases(cases: &tests.GenHContext) void { \\TEST_EXPORT void entry(struct Foo foo, uint8_t bar[]); \\ ); - } diff --git a/test/standalone/brace_expansion/main.zig b/test/standalone/brace_expansion/main.zig index 93089ae1ff..c96cc2cbb9 100644 --- a/test/standalone/brace_expansion/main.zig +++ b/test/standalone/brace_expansion/main.zig @@ -29,8 +29,7 @@ fn tokenize(input: []const u8) !ArrayList(Token) { for (input) |b, i| { switch (state) { State.Start => switch (b) { - 'a' ... 'z', - 'A' ... 'Z' => { + 'a'...'z', 'A'...'Z' => { state = State.Word; tok_begin = i; }, @@ -40,11 +39,8 @@ fn tokenize(input: []const u8) !ArrayList(Token) { else => return error.InvalidInput, }, State.Word => switch (b) { - 'a' ... 'z', - 'A' ... 'Z' => {}, - '{', - '}', - ',' => { + 'a'...'z', 'A'...'Z' => {}, + '{', '}', ',' => { try token_list.append(Token{ .Word = input[tok_begin..i] }); switch (b) { '{' => try token_list.append(Token.OpenBrace), @@ -103,8 +99,7 @@ fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node { }; switch (tokens.items[token_index.*]) { - Token.Word, - Token.OpenBrace => { + Token.Word, Token.OpenBrace => { const pair = try global_allocator.alloc(Node, 2); pair[0] = result_node; pair[1] = try parse(tokens, token_index); diff --git a/test/standalone/issue_339/test.zig b/test/standalone/issue_339/test.zig index f65b9f734e..da0747b8e6 100644 --- a/test/standalone/issue_339/test.zig +++ b/test/standalone/issue_339/test.zig @@ -1,5 +1,8 @@ const StackTrace = @import("builtin").StackTrace; -pub fn panic(msg: []const u8, stack_trace: ?&StackTrace) noreturn { @breakpoint(); while (true) {} } +pub fn panic(msg: []const u8, stack_trace: ?&StackTrace) noreturn { + @breakpoint(); + while (true) {} +} fn bar() error!void {} diff --git a/test/standalone/pkg_import/pkg.zig b/test/standalone/pkg_import/pkg.zig index abb977a2ef..19ab525b81 100644 --- a/test/standalone/pkg_import/pkg.zig +++ b/test/standalone/pkg_import/pkg.zig @@ -1 +1,3 @@ -pub fn add(a: i32, b: i32) i32 { return a + b; } +pub fn add(a: i32, b: i32) i32 { + return a + b; +} diff --git a/test/standalone/use_alias/main.zig b/test/standalone/use_alias/main.zig index 40cab9ad8a..873393cef7 100644 --- a/test/standalone/use_alias/main.zig +++ b/test/standalone/use_alias/main.zig @@ -2,7 +2,7 @@ const c = @import("c.zig"); const assert = @import("std").debug.assert; test "symbol exists" { - var foo = c.Foo { + var foo = c.Foo{ .a = 1, .b = 1, }; diff --git a/test/translate_c.zig b/test/translate_c.zig index 2054cfa246..4cf1e047fa 100644 --- a/test/translate_c.zig +++ b/test/translate_c.zig @@ -638,7 +638,6 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\} ); - cases.addC("c style cast", \\int float_to_int(float a) { \\ return (int)a; @@ -1289,29 +1288,29 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ } \\} , - \\pub fn switch_fn(i: c_int) c_int { - \\ var res: c_int = 0; - \\ __switch: { - \\ __case_2: { - \\ __default: { - \\ __case_1: { - \\ __case_0: { - \\ switch (i) { - \\ 0 => break :__case_0, - \\ 1 => break :__case_1, - \\ else => break :__default, - \\ 2 => break :__case_2, - \\ } - \\ } - \\ res = 1; - \\ } - \\ res = 2; - \\ } - \\ res = (3 * i); - \\ break :__switch; - \\ } - \\ res = 5; - \\ } - \\} + \\pub fn switch_fn(i: c_int) c_int { + \\ var res: c_int = 0; + \\ __switch: { + \\ __case_2: { + \\ __default: { + \\ __case_1: { + \\ __case_0: { + \\ switch (i) { + \\ 0 => break :__case_0, + \\ 1 => break :__case_1, + \\ else => break :__default, + \\ 2 => break :__case_2, + \\ } + \\ } + \\ res = 1; + \\ } + \\ res = 2; + \\ } + \\ res = (3 * i); + \\ break :__switch; + \\ } + \\ res = 5; + \\ } + \\} ); } From d172e3f3bbb61956d8d2202fd008b61f07eb3121 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 29 May 2018 17:38:50 -0400 Subject: [PATCH 71/75] fix AtomicFile for relative paths closes #1017 --- std/os/index.zig | 14 ++++++++++---- std/os/path.zig | 2 ++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/std/os/index.zig b/std/os/index.zig index db182ed669..645d993256 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -855,14 +855,20 @@ pub const AtomicFile = struct { const dirname = os.path.dirname(dest_path); var rand_buf: [12]u8 = undefined; - const tmp_path = try allocator.alloc(u8, dirname.len + 1 + base64.Base64Encoder.calcSize(rand_buf.len)); + + const dirname_component_len = if (dirname.len == 0) 0 else dirname.len + 1; + const tmp_path = try allocator.alloc(u8, dirname_component_len + + base64.Base64Encoder.calcSize(rand_buf.len)); errdefer allocator.free(tmp_path); - mem.copy(u8, tmp_path[0..], dirname); - tmp_path[dirname.len] = os.path.sep; + + if (dirname.len != 0) { + mem.copy(u8, tmp_path[0..], dirname); + tmp_path[dirname.len] = os.path.sep; + } while (true) { try getRandomBytes(rand_buf[0..]); - b64_fs_encoder.encode(tmp_path[dirname.len + 1..], rand_buf); + b64_fs_encoder.encode(tmp_path[dirname_component_len..], rand_buf); const file = os.File.openWriteNoClobber(allocator, tmp_path, mode) catch |err| switch (err) { error.PathAlreadyExists => continue, diff --git a/std/os/path.zig b/std/os/path.zig index 5b2b031aab..f2b3bb9b0a 100644 --- a/std/os/path.zig +++ b/std/os/path.zig @@ -647,6 +647,8 @@ fn testResolvePosix(paths: []const []const u8) []u8 { return resolvePosix(debug.global_allocator, paths) catch unreachable; } +/// If the path is a file in the current directory (no directory component) +/// then the returned slice has .len = 0. pub fn dirname(path: []const u8) []const u8 { if (is_windows) { return dirnameWindows(path); From b0eebfa560b7c05859a535bf46abd8b9cf9306b3 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 29 May 2018 18:10:36 -0400 Subject: [PATCH 72/75] fix syntax of std/json_test.zig See #663 --- std/json_test.zig | 36 +++++++++--------------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/std/json_test.zig b/std/json_test.zig index 60a5d1288c..cb054d8e4e 100644 --- a/std/json_test.zig +++ b/std/json_test.zig @@ -81,9 +81,7 @@ test "y_array_with_several_null" { } test "y_array_with_trailing_space" { - ok( - "[2] " - ); + ok("[2] "); } test "y_number_0e+1" { @@ -579,9 +577,7 @@ test "y_structure_true_in_array" { } test "y_structure_whitespace_array" { - ok( - " [] " - ); + ok(" [] "); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -696,7 +692,6 @@ test "n_array_newlines_unclosed" { ); } - test "n_array_number_and_comma" { err( \\[1,] @@ -971,7 +966,6 @@ test "n_number_invalid-utf-8-in-int" { ); } - test "n_number_++" { err( \\[++1234] @@ -1228,7 +1222,7 @@ test "n_object_unterminated-value" { err( \\{"a":"a ); - } +} test "n_object_with_single_string" { err( @@ -1243,9 +1237,7 @@ test "n_object_with_trailing_garbage" { } test "n_single_space" { - err( - " " - ); + err(" "); } test "n_string_1_surrogate_then_escape" { @@ -1279,9 +1271,7 @@ test "n_string_accentuated_char_no_quotes" { } test "n_string_backslash_00" { - err( - \\["\"] - ); + err("[\"\x00\"]"); } test "n_string_escaped_backslash_bad" { @@ -1291,9 +1281,7 @@ test "n_string_escaped_backslash_bad" { } test "n_string_escaped_ctrl_char_tab" { - err( - \\["\ "] - ); + err("\x5b\x22\x5c\x09\x22\x5d"); } test "n_string_escaped_emoji" { @@ -1416,9 +1404,7 @@ test "n_string_with_trailing_garbage" { } test "n_structure_100000_opening_arrays" { - err( - "[" ** 100000 - ); + err("[" ** 100000); } test "n_structure_angle_bracket_." { @@ -1558,9 +1544,7 @@ test "n_structure_open_array_comma" { } test "n_structure_open_array_object" { - err( - "[{\"\":" ** 50000 - ); + err("[{\"\":" ** 50000); } test "n_structure_open_array_open_object" { @@ -1900,9 +1884,7 @@ test "i_string_UTF8_surrogate_U+D800" { } test "i_structure_500_nested_arrays" { - any( - ("[" ** 500) ++ ("]" ** 500) - ); + any(("[" ** 500) ++ ("]" ** 500)); } test "i_structure_UTF-8_BOM_empty_object" { From 2b3af4ef6b79b8fe178656b069f837eff82ae8c3 Mon Sep 17 00:00:00 2001 From: Jimmi HC Date: Wed, 30 May 2018 10:30:09 +0200 Subject: [PATCH 73/75] fixed #1009 ir_make_type_info_defs already calls resolve_top_level_decl on all Tld when building the def array. This means, that there is no reason that analyze_fn_body is nessesary, as the fn type should have already been resolved completly. The only thing analyze_fn_body does here, is cause problems with generic functions. --- src/ir.cpp | 4 ---- test/cases/type_info.zig | 7 +++++++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index 440063d58d..5d182fe9b0 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -15982,10 +15982,6 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop FnTableEntry *fn_entry = ((TldFn *)curr_entry->value)->fn_entry; assert(!fn_entry->is_test); - analyze_fn_body(ira->codegen, fn_entry); - if (fn_entry->anal_state == FnAnalStateInvalid) - return; - AstNodeFnProto *fn_node = (AstNodeFnProto *)(fn_entry->proto_node); ConstExprValue *fn_def_val = create_const_vals(1); diff --git a/test/cases/type_info.zig b/test/cases/type_info.zig index eee5d1f2ca..05266feb9c 100644 --- a/test/cases/type_info.zig +++ b/test/cases/type_info.zig @@ -233,3 +233,10 @@ fn testFunction() void { fn foo(comptime a: usize, b: bool, args: ...) usize { return 0; } + +test "typeInfo with comptime parameter in struct fn def" { + const S = struct { + pub fn func(comptime x: f32) void {} + }; + comptime var info = @typeInfo(S); +} From 1b3aaacba260e4c8d89ac98ab856ff9b3c77dac4 Mon Sep 17 00:00:00 2001 From: Jimmi HC Date: Wed, 30 May 2018 10:34:20 +0200 Subject: [PATCH 74/75] Removed copy-pasted resolve_inferred_error_set both ir.cpp and analyze.cpp have a function resolve_inferred_error_set, which is a nearly exact copy-paste. This commit removes the one in ir.cpp and exposes then one in analyze.cpp. This also allows us to make analyze_fn_body local to analyze.cpp, as it is not used anywhere in ir.cpp after this change --- src/analyze.cpp | 7 +++--- src/analyze.hpp | 2 +- src/ir.cpp | 62 ++++++++++++++++--------------------------------- 3 files changed, 25 insertions(+), 46 deletions(-) diff --git a/src/analyze.cpp b/src/analyze.cpp index c59fde8ef6..b00e18a9a1 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -25,6 +25,7 @@ static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type); static void resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type); static void resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type); static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type); +static void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry); ErrorMsg *add_node_error(CodeGen *g, AstNode *node, Buf *msg) { if (node->owner->c_import_node != nullptr) { @@ -3880,7 +3881,7 @@ static void define_local_param_variables(CodeGen *g, FnTableEntry *fn_table_entr } } -static bool analyze_resolve_inferred_error_set(CodeGen *g, TypeTableEntry *err_set_type, AstNode *source_node) { +bool resolve_inferred_error_set(CodeGen *g, TypeTableEntry *err_set_type, AstNode *source_node) { FnTableEntry *infer_fn = err_set_type->data.error_set.infer_fn; if (infer_fn != nullptr) { if (infer_fn->anal_state == FnAnalStateInvalid) { @@ -3932,7 +3933,7 @@ void analyze_fn_ir(CodeGen *g, FnTableEntry *fn_table_entry, AstNode *return_typ } if (inferred_err_set_type->data.error_set.infer_fn != nullptr) { - if (!analyze_resolve_inferred_error_set(g, inferred_err_set_type, return_type_node)) { + if (!resolve_inferred_error_set(g, inferred_err_set_type, return_type_node)) { fn_table_entry->anal_state = FnAnalStateInvalid; return; } @@ -3962,7 +3963,7 @@ void analyze_fn_ir(CodeGen *g, FnTableEntry *fn_table_entry, AstNode *return_typ fn_table_entry->anal_state = FnAnalStateComplete; } -void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry) { +static void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry) { assert(fn_table_entry->anal_state != FnAnalStateProbing); if (fn_table_entry->anal_state != FnAnalStateReady) return; diff --git a/src/analyze.hpp b/src/analyze.hpp index 56ca21a93f..d538f042ce 100644 --- a/src/analyze.hpp +++ b/src/analyze.hpp @@ -191,7 +191,7 @@ void add_fn_export(CodeGen *g, FnTableEntry *fn_table_entry, Buf *symbol_name, G ConstExprValue *get_builtin_value(CodeGen *codegen, const char *name); TypeTableEntry *get_ptr_to_stack_trace_type(CodeGen *g); -void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry); +bool resolve_inferred_error_set(CodeGen *g, TypeTableEntry *err_set_type, AstNode *source_node); TypeTableEntry *get_auto_err_set_type(CodeGen *g, FnTableEntry *fn_entry); diff --git a/src/ir.cpp b/src/ir.cpp index 5d182fe9b0..8d32a81e25 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -7633,38 +7633,16 @@ static bool slice_is_const(TypeTableEntry *type) { return type->data.structure.fields[slice_ptr_index].type_entry->data.pointer.is_const; } -static bool resolve_inferred_error_set(IrAnalyze *ira, TypeTableEntry *err_set_type, AstNode *source_node) { - assert(err_set_type->id == TypeTableEntryIdErrorSet); - FnTableEntry *infer_fn = err_set_type->data.error_set.infer_fn; - if (infer_fn != nullptr) { - if (infer_fn->anal_state == FnAnalStateInvalid) { - return false; - } else if (infer_fn->anal_state == FnAnalStateReady) { - analyze_fn_body(ira->codegen, infer_fn); - if (err_set_type->data.error_set.infer_fn != nullptr) { - assert(ira->codegen->errors.length != 0); - return false; - } - } else { - ir_add_error_node(ira, source_node, - buf_sprintf("cannot resolve inferred error set '%s': function '%s' not fully analyzed yet", - buf_ptr(&err_set_type->name), buf_ptr(&err_set_type->data.error_set.infer_fn->symbol_name))); - return false; - } - } - return true; -} - static TypeTableEntry *get_error_set_intersection(IrAnalyze *ira, TypeTableEntry *set1, TypeTableEntry *set2, AstNode *source_node) { assert(set1->id == TypeTableEntryIdErrorSet); assert(set2->id == TypeTableEntryIdErrorSet); - if (!resolve_inferred_error_set(ira, set1, source_node)) { + if (!resolve_inferred_error_set(ira->codegen, set1, source_node)) { return ira->codegen->builtin_types.entry_invalid; } - if (!resolve_inferred_error_set(ira, set2, source_node)) { + if (!resolve_inferred_error_set(ira->codegen, set2, source_node)) { return ira->codegen->builtin_types.entry_invalid; } if (type_is_global_error_set(set1)) { @@ -7803,7 +7781,7 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, TypeTableEntry return result; } - if (!resolve_inferred_error_set(ira, contained_set, source_node)) { + if (!resolve_inferred_error_set(ira->codegen, contained_set, source_node)) { result.id = ConstCastResultIdUnresolvedInferredErrSet; return result; } @@ -8192,7 +8170,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod err_set_type = ira->codegen->builtin_types.entry_global_error_set; } else { err_set_type = prev_inst->value.type; - if (!resolve_inferred_error_set(ira, err_set_type, prev_inst->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, err_set_type, prev_inst->source_node)) { return ira->codegen->builtin_types.entry_invalid; } update_errors_helper(ira->codegen, &errors, &errors_count); @@ -8231,7 +8209,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod if (type_is_global_error_set(err_set_type)) { continue; } - if (!resolve_inferred_error_set(ira, cur_type, cur_inst->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, cur_type, cur_inst->source_node)) { return ira->codegen->builtin_types.entry_invalid; } if (type_is_global_error_set(cur_type)) { @@ -8297,7 +8275,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod continue; } TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type; - if (!resolve_inferred_error_set(ira, cur_err_set_type, cur_inst->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, cur_err_set_type, cur_inst->source_node)) { return ira->codegen->builtin_types.entry_invalid; } if (type_is_global_error_set(cur_err_set_type)) { @@ -8360,7 +8338,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod if (err_set_type != nullptr && type_is_global_error_set(err_set_type)) { continue; } - if (!resolve_inferred_error_set(ira, cur_type, cur_inst->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, cur_type, cur_inst->source_node)) { return ira->codegen->builtin_types.entry_invalid; } @@ -8417,11 +8395,11 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod TypeTableEntry *prev_err_set_type = (err_set_type == nullptr) ? prev_type->data.error_union.err_set_type : err_set_type; TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type; - if (!resolve_inferred_error_set(ira, prev_err_set_type, cur_inst->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, prev_err_set_type, cur_inst->source_node)) { return ira->codegen->builtin_types.entry_invalid; } - if (!resolve_inferred_error_set(ira, cur_err_set_type, cur_inst->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, cur_err_set_type, cur_inst->source_node)) { return ira->codegen->builtin_types.entry_invalid; } @@ -8531,7 +8509,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod { if (err_set_type != nullptr) { TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type; - if (!resolve_inferred_error_set(ira, cur_err_set_type, cur_inst->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, cur_err_set_type, cur_inst->source_node)) { return ira->codegen->builtin_types.entry_invalid; } if (type_is_global_error_set(cur_err_set_type) || type_is_global_error_set(err_set_type)) { @@ -9213,7 +9191,7 @@ static IrInstruction *ir_analyze_err_set_cast(IrAnalyze *ira, IrInstruction *sou if (!val) return ira->codegen->invalid_instruction; - if (!resolve_inferred_error_set(ira, wanted_type, source_instr->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, wanted_type, source_instr->source_node)) { return ira->codegen->invalid_instruction; } if (!type_is_global_error_set(wanted_type)) { @@ -9654,7 +9632,7 @@ static IrInstruction *ir_analyze_int_to_err(IrAnalyze *ira, IrInstruction *sourc IrInstruction *result = ir_create_const(&ira->new_irb, source_instr->scope, source_instr->source_node, wanted_type); - if (!resolve_inferred_error_set(ira, wanted_type, source_instr->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, wanted_type, source_instr->source_node)) { return ira->codegen->invalid_instruction; } @@ -9752,7 +9730,7 @@ static IrInstruction *ir_analyze_err_to_int(IrAnalyze *ira, IrInstruction *sourc zig_unreachable(); } if (!type_is_global_error_set(err_set_type)) { - if (!resolve_inferred_error_set(ira, err_set_type, source_instr->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, err_set_type, source_instr->source_node)) { return ira->codegen->invalid_instruction; } if (err_set_type->data.error_set.err_count == 0) { @@ -10647,7 +10625,7 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp return ira->codegen->builtin_types.entry_invalid; } - if (!resolve_inferred_error_set(ira, intersect_type, source_node)) { + if (!resolve_inferred_error_set(ira->codegen, intersect_type, source_node)) { return ira->codegen->builtin_types.entry_invalid; } @@ -11503,11 +11481,11 @@ static TypeTableEntry *ir_analyze_merge_error_sets(IrAnalyze *ira, IrInstruction return ira->codegen->builtin_types.entry_type; } - if (!resolve_inferred_error_set(ira, op1_type, instruction->op1->other->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, op1_type, instruction->op1->other->source_node)) { return ira->codegen->builtin_types.entry_invalid; } - if (!resolve_inferred_error_set(ira, op2_type, instruction->op2->other->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, op2_type, instruction->op2->other->source_node)) { return ira->codegen->builtin_types.entry_invalid; } @@ -13851,7 +13829,7 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru } err_set_type = err_entry->set_with_only_this_in_it; } else { - if (!resolve_inferred_error_set(ira, child_type, field_ptr_instruction->base.source_node)) { + if (!resolve_inferred_error_set(ira->codegen, child_type, field_ptr_instruction->base.source_node)) { return ira->codegen->builtin_types.entry_invalid; } err_entry = find_err_table_entry(child_type, field_name); @@ -17559,7 +17537,7 @@ static TypeTableEntry *ir_analyze_instruction_member_count(IrAnalyze *ira, IrIns } else if (container_type->id == TypeTableEntryIdUnion) { result = container_type->data.unionation.src_field_count; } else if (container_type->id == TypeTableEntryIdErrorSet) { - if (!resolve_inferred_error_set(ira, container_type, instruction->base.source_node)) { + if (!resolve_inferred_error_set(ira->codegen, container_type, instruction->base.source_node)) { return ira->codegen->builtin_types.entry_invalid; } if (type_is_global_error_set(container_type)) { @@ -17863,7 +17841,7 @@ static TypeTableEntry *ir_analyze_instruction_test_err(IrAnalyze *ira, IrInstruc } TypeTableEntry *err_set_type = type_entry->data.error_union.err_set_type; - if (!resolve_inferred_error_set(ira, err_set_type, instruction->base.source_node)) { + if (!resolve_inferred_error_set(ira->codegen, err_set_type, instruction->base.source_node)) { return ira->codegen->builtin_types.entry_invalid; } if (!type_is_global_error_set(err_set_type) && @@ -18131,7 +18109,7 @@ static TypeTableEntry *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira } } } else if (switch_type->id == TypeTableEntryIdErrorSet) { - if (!resolve_inferred_error_set(ira, switch_type, target_value->source_node)) { + if (!resolve_inferred_error_set(ira->codegen, switch_type, target_value->source_node)) { return ira->codegen->builtin_types.entry_invalid; } From 15302e84a45a04cfe94a8842318f02a608055962 Mon Sep 17 00:00:00 2001 From: Jimmi HC Date: Wed, 30 May 2018 11:51:46 +0200 Subject: [PATCH 75/75] Adding workaround for when the user tries to unwrap 'type' closes #1011 --- src/ir.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/ir.cpp b/src/ir.cpp index 8d32a81e25..6e944a8976 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -17914,6 +17914,15 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_err_payload(IrAnalyze *ira, return ira->codegen->builtin_types.entry_invalid; TypeTableEntry *ptr_type = value->value.type; + // Because we don't have Pointer Reform yet, we can't have a pointer to a 'type'. + // Therefor, we have to check for type 'type' here, so we can output a correct error + // without asserting the assert below. + if (ptr_type->id == TypeTableEntryIdMetaType) { + ir_add_error(ira, value, + buf_sprintf("expected error union type, found '%s'", buf_ptr(&ptr_type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + // This will be a pointer type because unwrap err payload IR instruction operates on a pointer to a thing. assert(ptr_type->id == TypeTableEntryIdPointer);