authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-02-02 23:45:23-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-02-03 00:06:11-07:00
log81c27c74bc8ccc8087b75c5d4eb1b350ad907cd0
tree9dc79bfecab52e844714bd81150368b40202f4c0
parent873bb29c984b976021fb9ca95ad3298e03a8b3ff

use build.zig.zon instead of build.zig.ini for the manifest file

* improve error message when build manifest file is missing * update std.zig.Ast to support ZON * Compilation.AllErrors.Message: make the notes field a const slice * move build manifest parsing logic into src/Manifest.zig and add more checks, and make the checks integrate into the standard error reporting code so that reported errors look sexy closes #14290

8 files changed, 665 insertions(+), 224 deletions(-)

lib/std/Build.zig+2-2
......@@ -1496,8 +1496,8 @@ pub fn dependency(b: *Build, name: []const u8, args: anytype) *Dependency {
14961496 }
14971497 }
14981498
1499 const full_path = b.pathFromRoot("build.zig.ini");
1500 std.debug.print("no dependency named '{s}' in '{s}'\n", .{ name, full_path });
1499 const full_path = b.pathFromRoot("build.zig.zon");
1500 std.debug.print("no dependency named '{s}' in '{s}'. All packages used in build.zig must be declared in this file.\n", .{ name, full_path });
15011501 std.process.exit(1);
15021502}
15031503
lib/std/array_hash_map.zig+2-1
......@@ -1145,7 +1145,8 @@ pub fn ArrayHashMapUnmanaged(
11451145 }
11461146
11471147 /// Create a copy of the hash map which can be modified separately.
1148 /// The copy uses the same context and allocator as this instance.
1148 /// The copy uses the same context as this instance, but is allocated
1149 /// with the provided allocator.
11491150 pub fn clone(self: Self, allocator: Allocator) !Self {
11501151 if (@sizeOf(ByIndexContext) != 0)
11511152 @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call cloneContext instead.");
lib/std/zig/Ast.zig+4
......@@ -1,4 +1,8 @@
11//! Abstract Syntax Tree for Zig source code.
2//! For Zig syntax, the root node is at nodes[0] and contains the list of
3//! sub-nodes.
4//! For Zon syntax, the root node is at nodes[0] and contains lhs as the node
5//! index of the main expression.
26
37/// Reference to externally-owned data.
48source: [:0]const u8,
lib/std/zig/Parse.zig+11-2
......@@ -181,17 +181,26 @@ pub fn parseRoot(p: *Parse) !void {
181181/// TODO: set a flag in Parse struct, and honor that flag
182182/// by emitting compilation errors when non-zon nodes are encountered.
183183pub fn parseZon(p: *Parse) !void {
184 const node_index = p.parseExpr() catch |err| switch (err) {
184 // We must use index 0 so that 0 can be used as null elsewhere.
185 p.nodes.appendAssumeCapacity(.{
186 .tag = .root,
187 .main_token = 0,
188 .data = undefined,
189 });
190 const node_index = p.expectExpr() catch |err| switch (err) {
185191 error.ParseError => {
186192 assert(p.errors.items.len > 0);
187193 return;
188194 },
189195 else => |e| return e,
190196 };
191 assert(node_index == 0);
192197 if (p.token_tags[p.tok_i] != .eof) {
193198 try p.warnExpected(.eof);
194199 }
200 p.nodes.items(.data)[0] = .{
201 .lhs = node_index,
202 .rhs = undefined,
203 };
195204}
196205
197206/// ContainerMembers <- ContainerDeclarations (ContainerField COMMA)* (ContainerField / ContainerDeclarations)
src/Compilation.zig+1-1
......@@ -385,7 +385,7 @@ pub const AllErrors = struct {
385385 count: u32 = 1,
386386 /// Does not include the trailing newline.
387387 source_line: ?[]const u8,
388 notes: []Message = &.{},
388 notes: []const Message = &.{},
389389 reference_trace: []Message = &.{},
390390
391391 /// Splits the error message up into lines to properly indent them
src/Manifest.zig created+499
......@@ -0,0 +1,499 @@
1pub const basename = "build.zig.zon";
2pub const Hash = std.crypto.hash.sha2.Sha256;
3
4pub const Dependency = struct {
5 url: []const u8,
6 url_tok: Ast.TokenIndex,
7 hash: ?[]const u8,
8 hash_tok: Ast.TokenIndex,
9};
10
11pub const ErrorMessage = struct {
12 msg: []const u8,
13 tok: Ast.TokenIndex,
14 off: u32,
15};
16
17pub const MultihashFunction = enum(u16) {
18 identity = 0x00,
19 sha1 = 0x11,
20 @"sha2-256" = 0x12,
21 @"sha2-512" = 0x13,
22 @"sha3-512" = 0x14,
23 @"sha3-384" = 0x15,
24 @"sha3-256" = 0x16,
25 @"sha3-224" = 0x17,
26 @"sha2-384" = 0x20,
27 @"sha2-256-trunc254-padded" = 0x1012,
28 @"sha2-224" = 0x1013,
29 @"sha2-512-224" = 0x1014,
30 @"sha2-512-256" = 0x1015,
31 @"blake2b-256" = 0xb220,
32 _,
33};
34
35pub const multihash_function: MultihashFunction = switch (Hash) {
36 std.crypto.hash.sha2.Sha256 => .@"sha2-256",
37 else => @compileError("unreachable"),
38};
39comptime {
40 // We avoid unnecessary uleb128 code in hexDigest by asserting here the
41 // values are small enough to be contained in the one-byte encoding.
42 assert(@enumToInt(multihash_function) < 127);
43 assert(Hash.digest_length < 127);
44}
45pub const multihash_len = 1 + 1 + Hash.digest_length;
46
47name: []const u8,
48version: std.SemanticVersion,
49dependencies: std.StringArrayHashMapUnmanaged(Dependency),
50
51errors: []ErrorMessage,
52arena_state: std.heap.ArenaAllocator.State,
53
54pub const Error = Allocator.Error;
55
56pub fn parse(gpa: Allocator, ast: std.zig.Ast) Error!Manifest {
57 const node_tags = ast.nodes.items(.tag);
58 const node_datas = ast.nodes.items(.data);
59 assert(node_tags[0] == .root);
60 const main_node_index = node_datas[0].lhs;
61
62 var arena_instance = std.heap.ArenaAllocator.init(gpa);
63 errdefer arena_instance.deinit();
64
65 var p: Parse = .{
66 .gpa = gpa,
67 .ast = ast,
68 .arena = arena_instance.allocator(),
69 .errors = .{},
70
71 .name = undefined,
72 .version = undefined,
73 .dependencies = .{},
74 .buf = .{},
75 };
76 defer p.buf.deinit(gpa);
77 defer p.errors.deinit(gpa);
78 defer p.dependencies.deinit(gpa);
79
80 p.parseRoot(main_node_index) catch |err| switch (err) {
81 error.ParseFailure => assert(p.errors.items.len > 0),
82 else => |e| return e,
83 };
84
85 return .{
86 .name = p.name,
87 .version = p.version,
88 .dependencies = try p.dependencies.clone(p.arena),
89 .errors = try p.arena.dupe(ErrorMessage, p.errors.items),
90 .arena_state = arena_instance.state,
91 };
92}
93
94pub fn deinit(man: *Manifest, gpa: Allocator) void {
95 man.arena_state.promote(gpa).deinit();
96 man.* = undefined;
97}
98
99const hex_charset = "0123456789abcdef";
100
101pub fn hex64(x: u64) [16]u8 {
102 var result: [16]u8 = undefined;
103 var i: usize = 0;
104 while (i < 8) : (i += 1) {
105 const byte = @truncate(u8, x >> @intCast(u6, 8 * i));
106 result[i * 2 + 0] = hex_charset[byte >> 4];
107 result[i * 2 + 1] = hex_charset[byte & 15];
108 }
109 return result;
110}
111
112test hex64 {
113 const s = "[" ++ hex64(0x12345678_abcdef00) ++ "]";
114 try std.testing.expectEqualStrings("[00efcdab78563412]", s);
115}
116
117pub fn hexDigest(digest: [Hash.digest_length]u8) [multihash_len * 2]u8 {
118 var result: [multihash_len * 2]u8 = undefined;
119
120 result[0] = hex_charset[@enumToInt(multihash_function) >> 4];
121 result[1] = hex_charset[@enumToInt(multihash_function) & 15];
122
123 result[2] = hex_charset[Hash.digest_length >> 4];
124 result[3] = hex_charset[Hash.digest_length & 15];
125
126 for (digest) |byte, i| {
127 result[4 + i * 2] = hex_charset[byte >> 4];
128 result[5 + i * 2] = hex_charset[byte & 15];
129 }
130 return result;
131}
132
133const Parse = struct {
134 gpa: Allocator,
135 ast: std.zig.Ast,
136 arena: Allocator,
137 buf: std.ArrayListUnmanaged(u8),
138 errors: std.ArrayListUnmanaged(ErrorMessage),
139
140 name: []const u8,
141 version: std.SemanticVersion,
142 dependencies: std.StringArrayHashMapUnmanaged(Dependency),
143
144 const InnerError = error{ ParseFailure, OutOfMemory };
145
146 fn parseRoot(p: *Parse, node: Ast.Node.Index) !void {
147 const ast = p.ast;
148 const main_tokens = ast.nodes.items(.main_token);
149 const main_token = main_tokens[node];
150
151 var buf: [2]Ast.Node.Index = undefined;
152 const struct_init = ast.fullStructInit(&buf, node) orelse {
153 return fail(p, main_token, "expected top level expression to be a struct", .{});
154 };
155
156 var have_name = false;
157 var have_version = false;
158
159 for (struct_init.ast.fields) |field_init| {
160 const name_token = ast.firstToken(field_init) - 2;
161 const field_name = try identifierTokenString(p, name_token);
162 // We could get fancy with reflection and comptime logic here but doing
163 // things manually provides an opportunity to do any additional verification
164 // that is desirable on a per-field basis.
165 if (mem.eql(u8, field_name, "dependencies")) {
166 try parseDependencies(p, field_init);
167 } else if (mem.eql(u8, field_name, "name")) {
168 p.name = try parseString(p, field_init);
169 have_name = true;
170 } else if (mem.eql(u8, field_name, "version")) {
171 const version_text = try parseString(p, field_init);
172 p.version = std.SemanticVersion.parse(version_text) catch |err| v: {
173 try appendError(p, main_tokens[field_init], "unable to parse semantic version: {s}", .{@errorName(err)});
174 break :v undefined;
175 };
176 have_version = true;
177 } else {
178 // Ignore unknown fields so that we can add fields in future zig
179 // versions without breaking older zig versions.
180 }
181 }
182
183 if (!have_name) {
184 try appendError(p, main_token, "missing top-level 'name' field", .{});
185 }
186
187 if (!have_version) {
188 try appendError(p, main_token, "missing top-level 'version' field", .{});
189 }
190 }
191
192 fn parseDependencies(p: *Parse, node: Ast.Node.Index) !void {
193 const ast = p.ast;
194 const main_tokens = ast.nodes.items(.main_token);
195
196 var buf: [2]Ast.Node.Index = undefined;
197 const struct_init = ast.fullStructInit(&buf, node) orelse {
198 const tok = main_tokens[node];
199 return fail(p, tok, "expected dependencies expression to be a struct", .{});
200 };
201
202 for (struct_init.ast.fields) |field_init| {
203 const name_token = ast.firstToken(field_init) - 2;
204 const dep_name = try identifierTokenString(p, name_token);
205 const dep = try parseDependency(p, field_init);
206 try p.dependencies.put(p.gpa, dep_name, dep);
207 }
208 }
209
210 fn parseDependency(p: *Parse, node: Ast.Node.Index) !Dependency {
211 const ast = p.ast;
212 const main_tokens = ast.nodes.items(.main_token);
213
214 var buf: [2]Ast.Node.Index = undefined;
215 const struct_init = ast.fullStructInit(&buf, node) orelse {
216 const tok = main_tokens[node];
217 return fail(p, tok, "expected dependency expression to be a struct", .{});
218 };
219
220 var dep: Dependency = .{
221 .url = undefined,
222 .url_tok = undefined,
223 .hash = null,
224 .hash_tok = undefined,
225 };
226 var have_url = false;
227
228 for (struct_init.ast.fields) |field_init| {
229 const name_token = ast.firstToken(field_init) - 2;
230 const field_name = try identifierTokenString(p, name_token);
231 // We could get fancy with reflection and comptime logic here but doing
232 // things manually provides an opportunity to do any additional verification
233 // that is desirable on a per-field basis.
234 if (mem.eql(u8, field_name, "url")) {
235 dep.url = parseString(p, field_init) catch |err| switch (err) {
236 error.ParseFailure => continue,
237 else => |e| return e,
238 };
239 dep.url_tok = main_tokens[field_init];
240 have_url = true;
241 } else if (mem.eql(u8, field_name, "hash")) {
242 dep.hash = parseHash(p, field_init) catch |err| switch (err) {
243 error.ParseFailure => continue,
244 else => |e| return e,
245 };
246 dep.hash_tok = main_tokens[field_init];
247 } else {
248 // Ignore unknown fields so that we can add fields in future zig
249 // versions without breaking older zig versions.
250 }
251 }
252
253 if (!have_url) {
254 try appendError(p, main_tokens[node], "dependency is missing 'url' field", .{});
255 }
256
257 return dep;
258 }
259
260 fn parseString(p: *Parse, node: Ast.Node.Index) ![]const u8 {
261 const ast = p.ast;
262 const node_tags = ast.nodes.items(.tag);
263 const main_tokens = ast.nodes.items(.main_token);
264 if (node_tags[node] != .string_literal) {
265 return fail(p, main_tokens[node], "expected string literal", .{});
266 }
267 const str_lit_token = main_tokens[node];
268 const token_bytes = ast.tokenSlice(str_lit_token);
269 p.buf.clearRetainingCapacity();
270 try parseStrLit(p, str_lit_token, &p.buf, token_bytes, 0);
271 const duped = try p.arena.dupe(u8, p.buf.items);
272 return duped;
273 }
274
275 fn parseHash(p: *Parse, node: Ast.Node.Index) ![]const u8 {
276 const ast = p.ast;
277 const main_tokens = ast.nodes.items(.main_token);
278 const tok = main_tokens[node];
279 const h = try parseString(p, node);
280
281 if (h.len >= 2) {
282 const their_multihash_func = std.fmt.parseInt(u8, h[0..2], 16) catch |err| {
283 return fail(p, tok, "invalid multihash value: unable to parse hash function: {s}", .{
284 @errorName(err),
285 });
286 };
287 if (@intToEnum(MultihashFunction, their_multihash_func) != multihash_function) {
288 return fail(p, tok, "unsupported hash function: only sha2-256 is supported", .{});
289 }
290 }
291
292 const hex_multihash_len = 2 * Manifest.multihash_len;
293 if (h.len != hex_multihash_len) {
294 return fail(p, tok, "wrong hash size. expected: {d}, found: {d}", .{
295 hex_multihash_len, h.len,
296 });
297 }
298
299 return h;
300 }
301
302 /// TODO: try to DRY this with AstGen.identifierTokenString
303 fn identifierTokenString(p: *Parse, token: Ast.TokenIndex) InnerError![]const u8 {
304 const ast = p.ast;
305 const token_tags = ast.tokens.items(.tag);
306 assert(token_tags[token] == .identifier);
307 const ident_name = ast.tokenSlice(token);
308 if (!mem.startsWith(u8, ident_name, "@")) {
309 return ident_name;
310 }
311 p.buf.clearRetainingCapacity();
312 try parseStrLit(p, token, &p.buf, ident_name, 1);
313 const duped = try p.arena.dupe(u8, p.buf.items);
314 return duped;
315 }
316
317 /// TODO: try to DRY this with AstGen.parseStrLit
318 fn parseStrLit(
319 p: *Parse,
320 token: Ast.TokenIndex,
321 buf: *std.ArrayListUnmanaged(u8),
322 bytes: []const u8,
323 offset: u32,
324 ) InnerError!void {
325 const raw_string = bytes[offset..];
326 var buf_managed = buf.toManaged(p.gpa);
327 const result = std.zig.string_literal.parseWrite(buf_managed.writer(), raw_string);
328 buf.* = buf_managed.moveToUnmanaged();
329 switch (try result) {
330 .success => {},
331 .failure => |err| try p.appendStrLitError(err, token, bytes, offset),
332 }
333 }
334
335 /// TODO: try to DRY this with AstGen.failWithStrLitError
336 fn appendStrLitError(
337 p: *Parse,
338 err: std.zig.string_literal.Error,
339 token: Ast.TokenIndex,
340 bytes: []const u8,
341 offset: u32,
342 ) Allocator.Error!void {
343 const raw_string = bytes[offset..];
344 switch (err) {
345 .invalid_escape_character => |bad_index| {
346 try p.appendErrorOff(
347 token,
348 offset + @intCast(u32, bad_index),
349 "invalid escape character: '{c}'",
350 .{raw_string[bad_index]},
351 );
352 },
353 .expected_hex_digit => |bad_index| {
354 try p.appendErrorOff(
355 token,
356 offset + @intCast(u32, bad_index),
357 "expected hex digit, found '{c}'",
358 .{raw_string[bad_index]},
359 );
360 },
361 .empty_unicode_escape_sequence => |bad_index| {
362 try p.appendErrorOff(
363 token,
364 offset + @intCast(u32, bad_index),
365 "empty unicode escape sequence",
366 .{},
367 );
368 },
369 .expected_hex_digit_or_rbrace => |bad_index| {
370 try p.appendErrorOff(
371 token,
372 offset + @intCast(u32, bad_index),
373 "expected hex digit or '}}', found '{c}'",
374 .{raw_string[bad_index]},
375 );
376 },
377 .invalid_unicode_codepoint => |bad_index| {
378 try p.appendErrorOff(
379 token,
380 offset + @intCast(u32, bad_index),
381 "unicode escape does not correspond to a valid codepoint",
382 .{},
383 );
384 },
385 .expected_lbrace => |bad_index| {
386 try p.appendErrorOff(
387 token,
388 offset + @intCast(u32, bad_index),
389 "expected '{{', found '{c}",
390 .{raw_string[bad_index]},
391 );
392 },
393 .expected_rbrace => |bad_index| {
394 try p.appendErrorOff(
395 token,
396 offset + @intCast(u32, bad_index),
397 "expected '}}', found '{c}",
398 .{raw_string[bad_index]},
399 );
400 },
401 .expected_single_quote => |bad_index| {
402 try p.appendErrorOff(
403 token,
404 offset + @intCast(u32, bad_index),
405 "expected single quote ('), found '{c}",
406 .{raw_string[bad_index]},
407 );
408 },
409 .invalid_character => |bad_index| {
410 try p.appendErrorOff(
411 token,
412 offset + @intCast(u32, bad_index),
413 "invalid byte in string or character literal: '{c}'",
414 .{raw_string[bad_index]},
415 );
416 },
417 }
418 }
419
420 fn fail(
421 p: *Parse,
422 tok: Ast.TokenIndex,
423 comptime fmt: []const u8,
424 args: anytype,
425 ) InnerError {
426 try appendError(p, tok, fmt, args);
427 return error.ParseFailure;
428 }
429
430 fn appendError(p: *Parse, tok: Ast.TokenIndex, comptime fmt: []const u8, args: anytype) !void {
431 return appendErrorOff(p, tok, 0, fmt, args);
432 }
433
434 fn appendErrorOff(
435 p: *Parse,
436 tok: Ast.TokenIndex,
437 byte_offset: u32,
438 comptime fmt: []const u8,
439 args: anytype,
440 ) Allocator.Error!void {
441 try p.errors.append(p.gpa, .{
442 .msg = try std.fmt.allocPrint(p.arena, fmt, args),
443 .tok = tok,
444 .off = byte_offset,
445 });
446 }
447};
448
449const Manifest = @This();
450const std = @import("std");
451const mem = std.mem;
452const Allocator = std.mem.Allocator;
453const assert = std.debug.assert;
454const Ast = std.zig.Ast;
455const testing = std.testing;
456
457test "basic" {
458 const gpa = testing.allocator;
459
460 const example =
461 \\.{
462 \\ .name = "foo",
463 \\ .version = "3.2.1",
464 \\ .dependencies = .{
465 \\ .bar = .{
466 \\ .url = "https://example.com/baz.tar.gz",
467 \\ .hash = "1220f1b680b6065fcfc94fe777f22e73bcb7e2767e5f4d99d4255fe76ded69c7a35f",
468 \\ },
469 \\ },
470 \\}
471 ;
472
473 var ast = try std.zig.Ast.parse(gpa, example, .zon);
474 defer ast.deinit(gpa);
475
476 try testing.expect(ast.errors.len == 0);
477
478 var manifest = try Manifest.parse(gpa, ast);
479 defer manifest.deinit(gpa);
480
481 try testing.expectEqualStrings("foo", manifest.name);
482
483 try testing.expectEqual(@as(std.SemanticVersion, .{
484 .major = 3,
485 .minor = 2,
486 .patch = 1,
487 }), manifest.version);
488
489 try testing.expect(manifest.dependencies.count() == 1);
490 try testing.expectEqualStrings("bar", manifest.dependencies.keys()[0]);
491 try testing.expectEqualStrings(
492 "https://example.com/baz.tar.gz",
493 manifest.dependencies.values()[0].url,
494 );
495 try testing.expectEqualStrings(
496 "1220f1b680b6065fcfc94fe777f22e73bcb7e2767e5f4d99d4255fe76ded69c7a35f",
497 manifest.dependencies.values()[0].hash orelse return error.TestFailed,
498 );
499}
src/Package.zig+136-211
......@@ -6,8 +6,8 @@ const fs = std.fs;
66const mem = std.mem;
77const Allocator = mem.Allocator;
88const assert = std.debug.assert;
9const Hash = std.crypto.hash.sha2.Sha256;
109const log = std.log.scoped(.package);
10const main = @import("main.zig");
1111
1212const Compilation = @import("Compilation.zig");
1313const Module = @import("Module.zig");
......@@ -15,6 +15,7 @@ const ThreadPool = @import("ThreadPool.zig");
1515const WaitGroup = @import("WaitGroup.zig");
1616const Cache = @import("Cache.zig");
1717const build_options = @import("build_options");
18const Manifest = @import("Manifest.zig");
1819
1920pub const Table = std.StringHashMapUnmanaged(*Package);
2021
......@@ -141,10 +142,10 @@ pub fn addAndAdopt(parent: *Package, gpa: Allocator, child: *Package) !void {
141142}
142143
143144pub const build_zig_basename = "build.zig";
144pub const ini_basename = build_zig_basename ++ ".ini";
145145
146146pub fn fetchAndAddDependencies(
147147 pkg: *Package,
148 arena: Allocator,
148149 thread_pool: *ThreadPool,
149150 http_client: *std.http.Client,
150151 directory: Compilation.Directory,
......@@ -153,89 +154,77 @@ pub fn fetchAndAddDependencies(
153154 dependencies_source: *std.ArrayList(u8),
154155 build_roots_source: *std.ArrayList(u8),
155156 name_prefix: []const u8,
157 color: main.Color,
156158) !void {
157159 const max_bytes = 10 * 1024 * 1024;
158160 const gpa = thread_pool.allocator;
159 const build_zig_ini = directory.handle.readFileAlloc(gpa, ini_basename, max_bytes) catch |err| switch (err) {
161 const build_zig_zon_bytes = directory.handle.readFileAllocOptions(
162 arena,
163 Manifest.basename,
164 max_bytes,
165 null,
166 1,
167 0,
168 ) catch |err| switch (err) {
160169 error.FileNotFound => {
161170 // Handle the same as no dependencies.
162171 return;
163172 },
164173 else => |e| return e,
165174 };
166 defer gpa.free(build_zig_ini);
167175
168 const ini: std.Ini = .{ .bytes = build_zig_ini };
169 var any_error = false;
170 var it = ini.iterateSection("\n[dependency]\n");
171 while (it.next()) |dep| {
172 var line_it = mem.split(u8, dep, "\n");
173 var opt_name: ?[]const u8 = null;
174 var opt_url: ?[]const u8 = null;
175 var expected_hash: ?[]const u8 = null;
176 while (line_it.next()) |kv| {
177 const eq_pos = mem.indexOfScalar(u8, kv, '=') orelse continue;
178 const key = kv[0..eq_pos];
179 const value = kv[eq_pos + 1 ..];
180 if (mem.eql(u8, key, "name")) {
181 opt_name = value;
182 } else if (mem.eql(u8, key, "url")) {
183 opt_url = value;
184 } else if (mem.eql(u8, key, "hash")) {
185 expected_hash = value;
186 } else {
187 const loc = std.zig.findLineColumn(ini.bytes, @ptrToInt(key.ptr) - @ptrToInt(ini.bytes.ptr));
188 std.log.warn("{s}/{s}:{d}:{d} unrecognized key: '{s}'", .{
189 directory.path orelse ".",
190 "build.zig.ini",
191 loc.line,
192 loc.column,
193 key,
194 });
195 }
196 }
176 var ast = try std.zig.Ast.parse(gpa, build_zig_zon_bytes, .zon);
177 defer ast.deinit(gpa);
197178
198 const name = opt_name orelse {
199 const loc = std.zig.findLineColumn(ini.bytes, @ptrToInt(dep.ptr) - @ptrToInt(ini.bytes.ptr));
200 std.log.err("{s}/{s}:{d}:{d} missing key: 'name'", .{
201 directory.path orelse ".",
202 "build.zig.ini",
203 loc.line,
204 loc.column,
205 });
206 any_error = true;
207 continue;
208 };
179 if (ast.errors.len > 0) {
180 const file_path = try directory.join(arena, &.{Manifest.basename});
181 try main.printErrsMsgToStdErr(gpa, arena, ast, file_path, color);
182 return error.PackageFetchFailed;
183 }
209184
210 const url = opt_url orelse {
211 const loc = std.zig.findLineColumn(ini.bytes, @ptrToInt(dep.ptr) - @ptrToInt(ini.bytes.ptr));
212 std.log.err("{s}/{s}:{d}:{d} missing key: 'name'", .{
213 directory.path orelse ".",
214 "build.zig.ini",
215 loc.line,
216 loc.column,
217 });
218 any_error = true;
219 continue;
185 var manifest = try Manifest.parse(gpa, ast);
186 defer manifest.deinit(gpa);
187
188 if (manifest.errors.len > 0) {
189 const ttyconf: std.debug.TTY.Config = switch (color) {
190 .auto => std.debug.detectTTYConfig(std.io.getStdErr()),
191 .on => .escape_codes,
192 .off => .no_color,
220193 };
194 const file_path = try directory.join(arena, &.{Manifest.basename});
195 for (manifest.errors) |msg| {
196 Report.renderErrorMessage(ast, file_path, ttyconf, msg, &.{});
197 }
198 return error.PackageFetchFailed;
199 }
200
201 const report: Report = .{
202 .ast = &ast,
203 .directory = directory,
204 .color = color,
205 .arena = arena,
206 };
207
208 var any_error = false;
209 const deps_list = manifest.dependencies.values();
210 for (manifest.dependencies.keys()) |name, i| {
211 const dep = deps_list[i];
221212
222 const sub_prefix = try std.fmt.allocPrint(gpa, "{s}{s}.", .{ name_prefix, name });
223 defer gpa.free(sub_prefix);
213 const sub_prefix = try std.fmt.allocPrint(arena, "{s}{s}.", .{ name_prefix, name });
224214 const fqn = sub_prefix[0 .. sub_prefix.len - 1];
225215
226216 const sub_pkg = try fetchAndUnpack(
227217 thread_pool,
228218 http_client,
229219 global_cache_directory,
230 url,
231 expected_hash,
232 ini,
233 directory,
220 dep,
221 report,
234222 build_roots_source,
235223 fqn,
236224 );
237225
238226 try pkg.fetchAndAddDependencies(
227 arena,
239228 thread_pool,
240229 http_client,
241230 sub_pkg.root_src_directory,
......@@ -244,6 +233,7 @@ pub fn fetchAndAddDependencies(
244233 dependencies_source,
245234 build_roots_source,
246235 sub_prefix,
236 color,
247237 );
248238
249239 try addAndAdopt(pkg, gpa, sub_pkg);
......@@ -253,7 +243,7 @@ pub fn fetchAndAddDependencies(
253243 });
254244 }
255245
256 if (any_error) return error.InvalidBuildZigIniFile;
246 if (any_error) return error.InvalidBuildManifestFile;
257247}
258248
259249pub fn createFilePkg(
......@@ -264,7 +254,7 @@ pub fn createFilePkg(
264254 contents: []const u8,
265255) !*Package {
266256 const rand_int = std.crypto.random.int(u64);
267 const tmp_dir_sub_path = "tmp" ++ fs.path.sep_str ++ hex64(rand_int);
257 const tmp_dir_sub_path = "tmp" ++ fs.path.sep_str ++ Manifest.hex64(rand_int);
268258 {
269259 var tmp_dir = try cache_directory.handle.makeOpenPath(tmp_dir_sub_path, .{});
270260 defer tmp_dir.close();
......@@ -282,14 +272,73 @@ pub fn createFilePkg(
282272 return createWithDir(gpa, name, cache_directory, o_dir_sub_path, basename);
283273}
284274
275const Report = struct {
276 ast: *const std.zig.Ast,
277 directory: Compilation.Directory,
278 color: main.Color,
279 arena: Allocator,
280
281 fn fail(
282 report: Report,
283 tok: std.zig.Ast.TokenIndex,
284 comptime fmt_string: []const u8,
285 fmt_args: anytype,
286 ) error{ PackageFetchFailed, OutOfMemory } {
287 return failWithNotes(report, &.{}, tok, fmt_string, fmt_args);
288 }
289
290 fn failWithNotes(
291 report: Report,
292 notes: []const Compilation.AllErrors.Message,
293 tok: std.zig.Ast.TokenIndex,
294 comptime fmt_string: []const u8,
295 fmt_args: anytype,
296 ) error{ PackageFetchFailed, OutOfMemory } {
297 const ttyconf: std.debug.TTY.Config = switch (report.color) {
298 .auto => std.debug.detectTTYConfig(std.io.getStdErr()),
299 .on => .escape_codes,
300 .off => .no_color,
301 };
302 const file_path = try report.directory.join(report.arena, &.{Manifest.basename});
303 renderErrorMessage(report.ast.*, file_path, ttyconf, .{
304 .tok = tok,
305 .off = 0,
306 .msg = try std.fmt.allocPrint(report.arena, fmt_string, fmt_args),
307 }, notes);
308 return error.PackageFetchFailed;
309 }
310
311 fn renderErrorMessage(
312 ast: std.zig.Ast,
313 file_path: []const u8,
314 ttyconf: std.debug.TTY.Config,
315 msg: Manifest.ErrorMessage,
316 notes: []const Compilation.AllErrors.Message,
317 ) void {
318 const token_starts = ast.tokens.items(.start);
319 const start_loc = ast.tokenLocation(0, msg.tok);
320 Compilation.AllErrors.Message.renderToStdErr(.{ .src = .{
321 .msg = msg.msg,
322 .src_path = file_path,
323 .line = @intCast(u32, start_loc.line),
324 .column = @intCast(u32, start_loc.column),
325 .span = .{
326 .start = token_starts[msg.tok],
327 .end = @intCast(u32, token_starts[msg.tok] + ast.tokenSlice(msg.tok).len),
328 .main = token_starts[msg.tok] + msg.off,
329 },
330 .source_line = ast.source[start_loc.line_start..start_loc.line_end],
331 .notes = notes,
332 } }, ttyconf);
333 }
334};
335
285336fn fetchAndUnpack(
286337 thread_pool: *ThreadPool,
287338 http_client: *std.http.Client,
288339 global_cache_directory: Compilation.Directory,
289 url: []const u8,
290 expected_hash: ?[]const u8,
291 ini: std.Ini,
292 comp_directory: Compilation.Directory,
340 dep: Manifest.Dependency,
341 report: Report,
293342 build_roots_source: *std.ArrayList(u8),
294343 fqn: []const u8,
295344) !*Package {
......@@ -298,37 +347,8 @@ fn fetchAndUnpack(
298347
299348 // Check if the expected_hash is already present in the global package
300349 // cache, and thereby avoid both fetching and unpacking.
301 if (expected_hash) |h| cached: {
302 const hex_multihash_len = 2 * multihash_len;
303 if (h.len >= 2) {
304 const their_multihash_func = std.fmt.parseInt(u8, h[0..2], 16) catch |err| {
305 return reportError(
306 ini,
307 comp_directory,
308 h.ptr,
309 "invalid multihash value: unable to parse hash function: {s}",
310 .{@errorName(err)},
311 );
312 };
313 if (@intToEnum(MultihashFunction, their_multihash_func) != multihash_function) {
314 return reportError(
315 ini,
316 comp_directory,
317 h.ptr,
318 "unsupported hash function: only sha2-256 is supported",
319 .{},
320 );
321 }
322 }
323 if (h.len != hex_multihash_len) {
324 return reportError(
325 ini,
326 comp_directory,
327 h.ptr,
328 "wrong hash size. expected: {d}, found: {d}",
329 .{ hex_multihash_len, h.len },
330 );
331 }
350 if (dep.hash) |h| cached: {
351 const hex_multihash_len = 2 * Manifest.multihash_len;
332352 const hex_digest = h[0..hex_multihash_len];
333353 const pkg_dir_sub_path = "p" ++ s ++ hex_digest;
334354 var pkg_dir = global_cache_directory.handle.openDir(pkg_dir_sub_path, .{}) catch |err| switch (err) {
......@@ -366,10 +386,10 @@ fn fetchAndUnpack(
366386 return ptr;
367387 }
368388
369 const uri = try std.Uri.parse(url);
389 const uri = try std.Uri.parse(dep.url);
370390
371391 const rand_int = std.crypto.random.int(u64);
372 const tmp_dir_sub_path = "tmp" ++ s ++ hex64(rand_int);
392 const tmp_dir_sub_path = "tmp" ++ s ++ Manifest.hex64(rand_int);
373393
374394 const actual_hash = a: {
375395 var tmp_directory: Compilation.Directory = d: {
......@@ -398,13 +418,9 @@ fn fetchAndUnpack(
398418 // by default, so the same logic applies for buffering the reader as for gzip.
399419 try unpackTarball(gpa, &req, tmp_directory.handle, std.compress.xz);
400420 } else {
401 return reportError(
402 ini,
403 comp_directory,
404 uri.path.ptr,
405 "unknown file extension for path '{s}'",
406 .{uri.path},
407 );
421 return report.fail(dep.url_tok, "unknown file extension for path '{s}'", .{
422 uri.path,
423 });
408424 }
409425
410426 // TODO: delete files not included in the package prior to computing the package hash.
......@@ -415,28 +431,21 @@ fn fetchAndUnpack(
415431 break :a try computePackageHash(thread_pool, .{ .dir = tmp_directory.handle });
416432 };
417433
418 const pkg_dir_sub_path = "p" ++ s ++ hexDigest(actual_hash);
434 const pkg_dir_sub_path = "p" ++ s ++ Manifest.hexDigest(actual_hash);
419435 try renameTmpIntoCache(global_cache_directory.handle, tmp_dir_sub_path, pkg_dir_sub_path);
420436
421 const actual_hex = hexDigest(actual_hash);
422 if (expected_hash) |h| {
437 const actual_hex = Manifest.hexDigest(actual_hash);
438 if (dep.hash) |h| {
423439 if (!mem.eql(u8, h, &actual_hex)) {
424 return reportError(
425 ini,
426 comp_directory,
427 h.ptr,
428 "hash mismatch: expected: {s}, found: {s}",
429 .{ h, actual_hex },
430 );
440 return report.fail(dep.hash_tok, "hash mismatch: expected: {s}, found: {s}", .{
441 h, actual_hex,
442 });
431443 }
432444 } else {
433 return reportError(
434 ini,
435 comp_directory,
436 url.ptr,
437 "url field is missing corresponding hash field: hash={s}",
438 .{&actual_hex},
439 );
445 const notes: [1]Compilation.AllErrors.Message = .{.{ .plain = .{
446 .msg = try std.fmt.allocPrint(report.arena, "expected .hash = \"{s}\",", .{&actual_hex}),
447 } }};
448 return report.failWithNotes(&notes, dep.url_tok, "url field is missing corresponding hash field", .{});
440449 }
441450
442451 const build_root = try global_cache_directory.join(gpa, &.{pkg_dir_sub_path});
......@@ -471,29 +480,9 @@ fn unpackTarball(
471480 });
472481}
473482
474fn reportError(
475 ini: std.Ini,
476 comp_directory: Compilation.Directory,
477 src_ptr: [*]const u8,
478 comptime fmt_string: []const u8,
479 fmt_args: anytype,
480) error{PackageFetchFailed} {
481 const loc = std.zig.findLineColumn(ini.bytes, @ptrToInt(src_ptr) - @ptrToInt(ini.bytes.ptr));
482 if (comp_directory.path) |p| {
483 std.debug.print("{s}{c}{s}:{d}:{d}: error: " ++ fmt_string ++ "\n", .{
484 p, fs.path.sep, ini_basename, loc.line + 1, loc.column + 1,
485 } ++ fmt_args);
486 } else {
487 std.debug.print("{s}:{d}:{d}: error: " ++ fmt_string ++ "\n", .{
488 ini_basename, loc.line + 1, loc.column + 1,
489 } ++ fmt_args);
490 }
491 return error.PackageFetchFailed;
492}
493
494483const HashedFile = struct {
495484 path: []const u8,
496 hash: [Hash.digest_length]u8,
485 hash: [Manifest.Hash.digest_length]u8,
497486 failure: Error!void,
498487
499488 const Error = fs.File.OpenError || fs.File.ReadError || fs.File.StatError;
......@@ -507,7 +496,7 @@ const HashedFile = struct {
507496fn computePackageHash(
508497 thread_pool: *ThreadPool,
509498 pkg_dir: fs.IterableDir,
510) ![Hash.digest_length]u8 {
499) ![Manifest.Hash.digest_length]u8 {
511500 const gpa = thread_pool.allocator;
512501
513502 // We'll use an arena allocator for the path name strings since they all
......@@ -550,7 +539,7 @@ fn computePackageHash(
550539
551540 std.sort.sort(*HashedFile, all_files.items, {}, HashedFile.lessThan);
552541
553 var hasher = Hash.init(.{});
542 var hasher = Manifest.Hash.init(.{});
554543 var any_failures = false;
555544 for (all_files.items) |hashed_file| {
556545 hashed_file.failure catch |err| {
......@@ -571,7 +560,7 @@ fn workerHashFile(dir: fs.Dir, hashed_file: *HashedFile, wg: *WaitGroup) void {
571560fn hashFileFallible(dir: fs.Dir, hashed_file: *HashedFile) HashedFile.Error!void {
572561 var buf: [8000]u8 = undefined;
573562 var file = try dir.openFile(hashed_file.path, .{});
574 var hasher = Hash.init(.{});
563 var hasher = Manifest.Hash.init(.{});
575564 hasher.update(hashed_file.path);
576565 hasher.update(&.{ 0, @boolToInt(try isExecutable(file)) });
577566 while (true) {
......@@ -595,52 +584,6 @@ fn isExecutable(file: fs.File) !bool {
595584 }
596585}
597586
598const hex_charset = "0123456789abcdef";
599
600fn hex64(x: u64) [16]u8 {
601 var result: [16]u8 = undefined;
602 var i: usize = 0;
603 while (i < 8) : (i += 1) {
604 const byte = @truncate(u8, x >> @intCast(u6, 8 * i));
605 result[i * 2 + 0] = hex_charset[byte >> 4];
606 result[i * 2 + 1] = hex_charset[byte & 15];
607 }
608 return result;
609}
610
611test hex64 {
612 const s = "[" ++ hex64(0x12345678_abcdef00) ++ "]";
613 try std.testing.expectEqualStrings("[00efcdab78563412]", s);
614}
615
616const multihash_function: MultihashFunction = switch (Hash) {
617 std.crypto.hash.sha2.Sha256 => .@"sha2-256",
618 else => @compileError("unreachable"),
619};
620comptime {
621 // We avoid unnecessary uleb128 code in hexDigest by asserting here the
622 // values are small enough to be contained in the one-byte encoding.
623 assert(@enumToInt(multihash_function) < 127);
624 assert(Hash.digest_length < 127);
625}
626const multihash_len = 1 + 1 + Hash.digest_length;
627
628fn hexDigest(digest: [Hash.digest_length]u8) [multihash_len * 2]u8 {
629 var result: [multihash_len * 2]u8 = undefined;
630
631 result[0] = hex_charset[@enumToInt(multihash_function) >> 4];
632 result[1] = hex_charset[@enumToInt(multihash_function) & 15];
633
634 result[2] = hex_charset[Hash.digest_length >> 4];
635 result[3] = hex_charset[Hash.digest_length & 15];
636
637 for (digest) |byte, i| {
638 result[4 + i * 2] = hex_charset[byte >> 4];
639 result[5 + i * 2] = hex_charset[byte & 15];
640 }
641 return result;
642}
643
644587fn renameTmpIntoCache(
645588 cache_dir: fs.Dir,
646589 tmp_dir_sub_path: []const u8,
......@@ -669,21 +612,3 @@ fn renameTmpIntoCache(
669612 break;
670613 }
671614}
672
673const MultihashFunction = enum(u16) {
674 identity = 0x00,
675 sha1 = 0x11,
676 @"sha2-256" = 0x12,
677 @"sha2-512" = 0x13,
678 @"sha3-512" = 0x14,
679 @"sha3-384" = 0x15,
680 @"sha3-256" = 0x16,
681 @"sha3-224" = 0x17,
682 @"sha2-384" = 0x20,
683 @"sha2-256-trunc254-padded" = 0x1012,
684 @"sha2-224" = 0x1013,
685 @"sha2-512-224" = 0x1014,
686 @"sha2-512-256" = 0x1015,
687 @"blake2b-256" = 0xb220,
688 _,
689};
src/main.zig+10-7
......@@ -3915,6 +3915,7 @@ pub const usage_build =
39153915;
39163916
39173917pub fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
3918 var color: Color = .auto;
39183919 var prominent_compile_errors: bool = false;
39193920
39203921 // We want to release all the locks before executing the child process, so we make a nice
......@@ -4117,6 +4118,7 @@ pub fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !voi
41174118 // Here we borrow main package's table and will replace it with a fresh
41184119 // one after this process completes.
41194120 main_pkg.fetchAndAddDependencies(
4121 arena,
41204122 &thread_pool,
41214123 &http_client,
41224124 build_directory,
......@@ -4125,6 +4127,7 @@ pub fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !voi
41254127 &dependencies_source,
41264128 &build_roots_source,
41274129 "",
4130 color,
41284131 ) catch |err| switch (err) {
41294132 error.PackageFetchFailed => process.exit(1),
41304133 else => |e| return e,
......@@ -4366,7 +4369,7 @@ pub fn cmdFmt(gpa: Allocator, arena: Allocator, args: []const []const u8) !void
43664369 };
43674370 defer tree.deinit(gpa);
43684371
4369 try printErrsMsgToStdErr(gpa, arena, tree.errors, tree, "<stdin>", color);
4372 try printErrsMsgToStdErr(gpa, arena, tree, "<stdin>", color);
43704373 var has_ast_error = false;
43714374 if (check_ast_flag) {
43724375 const Module = @import("Module.zig");
......@@ -4569,7 +4572,7 @@ fn fmtPathFile(
45694572 var tree = try Ast.parse(fmt.gpa, source_code, .zig);
45704573 defer tree.deinit(fmt.gpa);
45714574
4572 try printErrsMsgToStdErr(fmt.gpa, fmt.arena, tree.errors, tree, file_path, fmt.color);
4575 try printErrsMsgToStdErr(fmt.gpa, fmt.arena, tree, file_path, fmt.color);
45734576 if (tree.errors.len != 0) {
45744577 fmt.any_error = true;
45754578 return;
......@@ -4649,14 +4652,14 @@ fn fmtPathFile(
46494652 }
46504653}
46514654
4652fn printErrsMsgToStdErr(
4655pub fn printErrsMsgToStdErr(
46534656 gpa: mem.Allocator,
46544657 arena: mem.Allocator,
4655 parse_errors: []const Ast.Error,
46564658 tree: Ast,
46574659 path: []const u8,
46584660 color: Color,
46594661) !void {
4662 const parse_errors: []const Ast.Error = tree.errors;
46604663 var i: usize = 0;
46614664 while (i < parse_errors.len) : (i += 1) {
46624665 const parse_error = parse_errors[i];
......@@ -5316,7 +5319,7 @@ pub fn cmdAstCheck(
53165319 file.tree_loaded = true;
53175320 defer file.tree.deinit(gpa);
53185321
5319 try printErrsMsgToStdErr(gpa, arena, file.tree.errors, file.tree, file.sub_file_path, color);
5322 try printErrsMsgToStdErr(gpa, arena, file.tree, file.sub_file_path, color);
53205323 if (file.tree.errors.len != 0) {
53215324 process.exit(1);
53225325 }
......@@ -5442,7 +5445,7 @@ pub fn cmdChangelist(
54425445 file.tree_loaded = true;
54435446 defer file.tree.deinit(gpa);
54445447
5445 try printErrsMsgToStdErr(gpa, arena, file.tree.errors, file.tree, old_source_file, .auto);
5448 try printErrsMsgToStdErr(gpa, arena, file.tree, old_source_file, .auto);
54465449 if (file.tree.errors.len != 0) {
54475450 process.exit(1);
54485451 }
......@@ -5479,7 +5482,7 @@ pub fn cmdChangelist(
54795482 var new_tree = try Ast.parse(gpa, new_source, .zig);
54805483 defer new_tree.deinit(gpa);
54815484
5482 try printErrsMsgToStdErr(gpa, arena, new_tree.errors, new_tree, new_source_file, .auto);
5485 try printErrsMsgToStdErr(gpa, arena, new_tree, new_source_file, .auto);
54835486 if (new_tree.errors.len != 0) {
54845487 process.exit(1);
54855488 }